1 /******/ (function(modules) { // webpackBootstrap
2 /******/ // The module cache
3 /******/ var installedModules = {};
5 /******/ // The require function
6 /******/ function __webpack_require__(moduleId) {
8 /******/ // Check if module is in cache
9 /******/ if(installedModules[moduleId])
10 /******/ return installedModules[moduleId].exports;
12 /******/ // Create a new module (and put it into the cache)
13 /******/ var module = installedModules[moduleId] = {
15 /******/ id: moduleId,
16 /******/ loaded: false
19 /******/ // Execute the module function
20 /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
22 /******/ // Flag the module as loaded
23 /******/ module.loaded = true;
25 /******/ // Return the exports of the module
26 /******/ return module.exports;
30 /******/ // expose the modules object (__webpack_modules__)
31 /******/ __webpack_require__.m = modules;
33 /******/ // expose the module cache
34 /******/ __webpack_require__.c = installedModules;
36 /******/ // __webpack_public_path__
37 /******/ __webpack_require__.p = "";
39 /******/ // Load entry module and return exports
40 /******/ return __webpack_require__(0);
42 /************************************************************************/
45 /***/ function(module, exports, __webpack_require__) {
47 /* WEBPACK VAR INJECTION */(function(global) {module.exports = global["pdfMake"] = __webpack_require__(1);
48 /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }())))
52 /***/ function(module, exports, __webpack_require__) {
54 /* WEBPACK VAR INJECTION */(function(Buffer) {/* jslint node: true */
55 /* jslint browser: true */
56 /* global BlobBuilder */
59 var PdfPrinter = __webpack_require__(6);
60 var FileSaver = __webpack_require__(105);
61 var saveAs = FileSaver.saveAs;
63 var defaultClientFonts = {
65 normal: 'Roboto-Regular.ttf',
66 bold: 'Roboto-Medium.ttf',
67 italics: 'Roboto-Italic.ttf',
68 bolditalics: 'Roboto-Italic.ttf'
72 function Document(docDefinition, fonts, vfs) {
73 this.docDefinition = docDefinition;
74 this.fonts = fonts || defaultClientFonts;
78 Document.prototype._createDoc = function(options, callback) {
79 var printer = new PdfPrinter(this.fonts);
80 printer.fs.bindFS(this.vfs);
82 var doc = printer.createPdfKitDocument(this.docDefinition, options);
86 doc.on('data', function(chunk) {
89 doc.on('end', function() {
90 result = Buffer.concat(chunks);
91 callback(result, doc._pdfMakePages);
96 Document.prototype._getPages = function(options, cb){
97 if (!cb) throw 'getBuffer is an async method and needs a callback argument';
98 this._createDoc(options, function(ignoreBuffer, pages){
103 Document.prototype.open = function(message) {
104 // we have to open the window immediately and store the reference
105 // otherwise popup blockers will stop us
106 var win = window.open('', '_blank');
109 this.getDataUrl(function(result) {
110 win.location.href = result;
119 Document.prototype.print = function() {
120 this.getDataUrl(function(dataUrl) {
121 var iFrame = document.createElement('iframe');
122 iFrame.style.position = 'absolute';
123 iFrame.style.left = '-99999px';
124 iFrame.src = dataUrl;
125 iFrame.onload = function() {
126 function removeIFrame(){
127 document.body.removeChild(iFrame);
128 document.removeEventListener('click', removeIFrame);
130 document.addEventListener('click', removeIFrame, false);
133 document.body.appendChild(iFrame);
134 }, { autoPrint: true });
137 Document.prototype.download = function(defaultFileName, cb) {
138 if(typeof defaultFileName === "function") {
139 cb = defaultFileName;
140 defaultFileName = null;
143 defaultFileName = defaultFileName || 'file.pdf';
144 this.getBuffer(function (result) {
147 blob = new Blob([result], { type: 'application/pdf' });
150 // Old browser which can't handle it without making it an byte array (ie10)
151 if (e.name == "InvalidStateError") {
152 var byteArray = new Uint8Array(result);
153 blob = new Blob([byteArray.buffer], { type: 'application/pdf' });
157 saveAs(blob, defaultFileName);
160 throw 'Could not generate blob';
162 if (typeof cb === "function") {
168 Document.prototype.getBase64 = function(cb, options) {
169 if (!cb) throw 'getBase64 is an async method and needs a callback argument';
170 this._createDoc(options, function(buffer) {
171 cb(buffer.toString('base64'));
175 Document.prototype.getDataUrl = function(cb, options) {
176 if (!cb) throw 'getDataUrl is an async method and needs a callback argument';
177 this._createDoc(options, function(buffer) {
178 cb('data:application/pdf;base64,' + buffer.toString('base64'));
182 Document.prototype.getBuffer = function(cb, options) {
183 if (!cb) throw 'getBuffer is an async method and needs a callback argument';
184 this._createDoc(options, function(buffer){
190 createPdf: function(docDefinition) {
191 return new Document(docDefinition, window.pdfMake.fonts, window.pdfMake.vfs);
195 /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2).Buffer))
199 /***/ function(module, exports, __webpack_require__) {
201 /* WEBPACK VAR INJECTION */(function(Buffer, global) {/*!
202 * The buffer module from node.js, for the browser.
204 * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
207 /* eslint-disable no-proto */
209 var base64 = __webpack_require__(3)
210 var ieee754 = __webpack_require__(4)
211 var isArray = __webpack_require__(5)
213 exports.Buffer = Buffer
214 exports.SlowBuffer = SlowBuffer
215 exports.INSPECT_MAX_BYTES = 50
216 Buffer.poolSize = 8192 // not used by this implementation
221 * If `Buffer.TYPED_ARRAY_SUPPORT`:
222 * === true Use Uint8Array implementation (fastest)
223 * === false Use Object implementation (most compatible, even IE6)
225 * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
226 * Opera 11.6+, iOS 4.2+.
228 * Due to various browser bugs, sometimes the Object implementation will be used even
229 * when the browser supports typed arrays.
233 * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,
234 * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
236 * - Safari 5-7 lacks support for changing the `Object.prototype.constructor` property
239 * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
241 * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
242 * incorrect length in some situations.
244 * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they
245 * get the Object implementation, which is slower but behaves correctly.
247 Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined
248 ? global.TYPED_ARRAY_SUPPORT
249 : typedArraySupport()
251 function typedArraySupport () {
254 var arr = new Uint8Array(1)
255 arr.foo = function () { return 42 }
256 arr.constructor = Bar
257 return arr.foo() === 42 && // typed array instances can be augmented
258 arr.constructor === Bar && // constructor can be set
259 typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`
260 arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`
266 function kMaxLength () {
267 return Buffer.TYPED_ARRAY_SUPPORT
276 * The Buffer constructor returns instances of `Uint8Array` that are augmented
277 * with function properties for all the node `Buffer` API functions. We use
278 * `Uint8Array` so that square bracket notation works as expected -- it returns
281 * By augmenting the instances, we can avoid modifying the `Uint8Array`
284 function Buffer (arg) {
285 if (!(this instanceof Buffer)) {
286 // Avoid going through an ArgumentsAdaptorTrampoline in the common case.
287 if (arguments.length > 1) return new Buffer(arg, arguments[1])
288 return new Buffer(arg)
292 this.parent = undefined
295 if (typeof arg === 'number') {
296 return fromNumber(this, arg)
299 // Slightly less common case.
300 if (typeof arg === 'string') {
301 return fromString(this, arg, arguments.length > 1 ? arguments[1] : 'utf8')
305 return fromObject(this, arg)
308 function fromNumber (that, length) {
309 that = allocate(that, length < 0 ? 0 : checked(length) | 0)
310 if (!Buffer.TYPED_ARRAY_SUPPORT) {
311 for (var i = 0; i < length; i++) {
318 function fromString (that, string, encoding) {
319 if (typeof encoding !== 'string' || encoding === '') encoding = 'utf8'
321 // Assumption: byteLength() return value is always < kMaxLength.
322 var length = byteLength(string, encoding) | 0
323 that = allocate(that, length)
325 that.write(string, encoding)
329 function fromObject (that, object) {
330 if (Buffer.isBuffer(object)) return fromBuffer(that, object)
332 if (isArray(object)) return fromArray(that, object)
334 if (object == null) {
335 throw new TypeError('must start with number, buffer, array or string')
338 if (typeof ArrayBuffer !== 'undefined') {
339 if (object.buffer instanceof ArrayBuffer) {
340 return fromTypedArray(that, object)
342 if (object instanceof ArrayBuffer) {
343 return fromArrayBuffer(that, object)
347 if (object.length) return fromArrayLike(that, object)
349 return fromJsonObject(that, object)
352 function fromBuffer (that, buffer) {
353 var length = checked(buffer.length) | 0
354 that = allocate(that, length)
355 buffer.copy(that, 0, 0, length)
359 function fromArray (that, array) {
360 var length = checked(array.length) | 0
361 that = allocate(that, length)
362 for (var i = 0; i < length; i += 1) {
363 that[i] = array[i] & 255
368 // Duplicate of fromArray() to keep fromArray() monomorphic.
369 function fromTypedArray (that, array) {
370 var length = checked(array.length) | 0
371 that = allocate(that, length)
372 // Truncating the elements is probably not what people expect from typed
373 // arrays with BYTES_PER_ELEMENT > 1 but it's compatible with the behavior
374 // of the old Buffer constructor.
375 for (var i = 0; i < length; i += 1) {
376 that[i] = array[i] & 255
381 function fromArrayBuffer (that, array) {
382 if (Buffer.TYPED_ARRAY_SUPPORT) {
383 // Return an augmented `Uint8Array` instance, for best performance
385 that = Buffer._augment(new Uint8Array(array))
387 // Fallback: Return an object instance of the Buffer class
388 that = fromTypedArray(that, new Uint8Array(array))
393 function fromArrayLike (that, array) {
394 var length = checked(array.length) | 0
395 that = allocate(that, length)
396 for (var i = 0; i < length; i += 1) {
397 that[i] = array[i] & 255
402 // Deserialize { type: 'Buffer', data: [1,2,3,...] } into a Buffer object.
403 // Returns a zero-length buffer for inputs that don't conform to the spec.
404 function fromJsonObject (that, object) {
408 if (object.type === 'Buffer' && isArray(object.data)) {
410 length = checked(array.length) | 0
412 that = allocate(that, length)
414 for (var i = 0; i < length; i += 1) {
415 that[i] = array[i] & 255
420 if (Buffer.TYPED_ARRAY_SUPPORT) {
421 Buffer.prototype.__proto__ = Uint8Array.prototype
422 Buffer.__proto__ = Uint8Array
425 function allocate (that, length) {
426 if (Buffer.TYPED_ARRAY_SUPPORT) {
427 // Return an augmented `Uint8Array` instance, for best performance
428 that = Buffer._augment(new Uint8Array(length))
429 that.__proto__ = Buffer.prototype
431 // Fallback: Return an object instance of the Buffer class
433 that._isBuffer = true
436 var fromPool = length !== 0 && length <= Buffer.poolSize >>> 1
437 if (fromPool) that.parent = rootParent
442 function checked (length) {
443 // Note: cannot use `length < kMaxLength` here because that fails when
444 // length is NaN (which is otherwise coerced to zero.)
445 if (length >= kMaxLength()) {
446 throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
447 'size: 0x' + kMaxLength().toString(16) + ' bytes')
452 function SlowBuffer (subject, encoding) {
453 if (!(this instanceof SlowBuffer)) return new SlowBuffer(subject, encoding)
455 var buf = new Buffer(subject, encoding)
460 Buffer.isBuffer = function isBuffer (b) {
461 return !!(b != null && b._isBuffer)
464 Buffer.compare = function compare (a, b) {
465 if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
466 throw new TypeError('Arguments must be Buffers')
469 if (a === b) return 0
475 var len = Math.min(x, y)
477 if (a[i] !== b[i]) break
492 Buffer.isEncoding = function isEncoding (encoding) {
493 switch (String(encoding).toLowerCase()) {
511 Buffer.concat = function concat (list, length) {
512 if (!isArray(list)) throw new TypeError('list argument must be an Array of Buffers.')
514 if (list.length === 0) {
519 if (length === undefined) {
521 for (i = 0; i < list.length; i++) {
522 length += list[i].length
526 var buf = new Buffer(length)
528 for (i = 0; i < list.length; i++) {
536 function byteLength (string, encoding) {
537 if (typeof string !== 'string') string = '' + string
539 var len = string.length
540 if (len === 0) return 0
542 // Use a for loop to avoid recursion
543 var loweredCase = false
554 return utf8ToBytes(string).length
563 return base64ToBytes(string).length
565 if (loweredCase) return utf8ToBytes(string).length // assume utf8
566 encoding = ('' + encoding).toLowerCase()
571 Buffer.byteLength = byteLength
573 // pre-set for values that may exist in the future
574 Buffer.prototype.length = undefined
575 Buffer.prototype.parent = undefined
577 function slowToString (encoding, start, end) {
578 var loweredCase = false
581 end = end === undefined || end === Infinity ? this.length : end | 0
583 if (!encoding) encoding = 'utf8'
584 if (start < 0) start = 0
585 if (end > this.length) end = this.length
586 if (end <= start) return ''
591 return hexSlice(this, start, end)
595 return utf8Slice(this, start, end)
598 return asciiSlice(this, start, end)
601 return binarySlice(this, start, end)
604 return base64Slice(this, start, end)
610 return utf16leSlice(this, start, end)
613 if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
614 encoding = (encoding + '').toLowerCase()
620 Buffer.prototype.toString = function toString () {
621 var length = this.length | 0
622 if (length === 0) return ''
623 if (arguments.length === 0) return utf8Slice(this, 0, length)
624 return slowToString.apply(this, arguments)
627 Buffer.prototype.equals = function equals (b) {
628 if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
629 if (this === b) return true
630 return Buffer.compare(this, b) === 0
633 Buffer.prototype.inspect = function inspect () {
635 var max = exports.INSPECT_MAX_BYTES
636 if (this.length > 0) {
637 str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')
638 if (this.length > max) str += ' ... '
640 return '<Buffer ' + str + '>'
643 Buffer.prototype.compare = function compare (b) {
644 if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
645 if (this === b) return 0
646 return Buffer.compare(this, b)
649 Buffer.prototype.indexOf = function indexOf (val, byteOffset) {
650 if (byteOffset > 0x7fffffff) byteOffset = 0x7fffffff
651 else if (byteOffset < -0x80000000) byteOffset = -0x80000000
654 if (this.length === 0) return -1
655 if (byteOffset >= this.length) return -1
657 // Negative offsets start from the end of the buffer
658 if (byteOffset < 0) byteOffset = Math.max(this.length + byteOffset, 0)
660 if (typeof val === 'string') {
661 if (val.length === 0) return -1 // special case: looking for empty string always fails
662 return String.prototype.indexOf.call(this, val, byteOffset)
664 if (Buffer.isBuffer(val)) {
665 return arrayIndexOf(this, val, byteOffset)
667 if (typeof val === 'number') {
668 if (Buffer.TYPED_ARRAY_SUPPORT && Uint8Array.prototype.indexOf === 'function') {
669 return Uint8Array.prototype.indexOf.call(this, val, byteOffset)
671 return arrayIndexOf(this, [ val ], byteOffset)
674 function arrayIndexOf (arr, val, byteOffset) {
676 for (var i = 0; byteOffset + i < arr.length; i++) {
677 if (arr[byteOffset + i] === val[foundIndex === -1 ? 0 : i - foundIndex]) {
678 if (foundIndex === -1) foundIndex = i
679 if (i - foundIndex + 1 === val.length) return byteOffset + foundIndex
687 throw new TypeError('val must be string, number or Buffer')
690 // `get` is deprecated
691 Buffer.prototype.get = function get (offset) {
692 console.log('.get() is deprecated. Access using array indexes instead.')
693 return this.readUInt8(offset)
696 // `set` is deprecated
697 Buffer.prototype.set = function set (v, offset) {
698 console.log('.set() is deprecated. Access using array indexes instead.')
699 return this.writeUInt8(v, offset)
702 function hexWrite (buf, string, offset, length) {
703 offset = Number(offset) || 0
704 var remaining = buf.length - offset
708 length = Number(length)
709 if (length > remaining) {
714 // must be an even number of digits
715 var strLen = string.length
716 if (strLen % 2 !== 0) throw new Error('Invalid hex string')
718 if (length > strLen / 2) {
721 for (var i = 0; i < length; i++) {
722 var parsed = parseInt(string.substr(i * 2, 2), 16)
723 if (isNaN(parsed)) throw new Error('Invalid hex string')
724 buf[offset + i] = parsed
729 function utf8Write (buf, string, offset, length) {
730 return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
733 function asciiWrite (buf, string, offset, length) {
734 return blitBuffer(asciiToBytes(string), buf, offset, length)
737 function binaryWrite (buf, string, offset, length) {
738 return asciiWrite(buf, string, offset, length)
741 function base64Write (buf, string, offset, length) {
742 return blitBuffer(base64ToBytes(string), buf, offset, length)
745 function ucs2Write (buf, string, offset, length) {
746 return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
749 Buffer.prototype.write = function write (string, offset, length, encoding) {
750 // Buffer#write(string)
751 if (offset === undefined) {
755 // Buffer#write(string, encoding)
756 } else if (length === undefined && typeof offset === 'string') {
760 // Buffer#write(string, offset[, length][, encoding])
761 } else if (isFinite(offset)) {
763 if (isFinite(length)) {
765 if (encoding === undefined) encoding = 'utf8'
770 // legacy write(string, encoding, offset, length) - remove in v0.13
778 var remaining = this.length - offset
779 if (length === undefined || length > remaining) length = remaining
781 if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
782 throw new RangeError('attempt to write outside buffer bounds')
785 if (!encoding) encoding = 'utf8'
787 var loweredCase = false
791 return hexWrite(this, string, offset, length)
795 return utf8Write(this, string, offset, length)
798 return asciiWrite(this, string, offset, length)
801 return binaryWrite(this, string, offset, length)
804 // Warning: maxLength not taken into account in base64Write
805 return base64Write(this, string, offset, length)
811 return ucs2Write(this, string, offset, length)
814 if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
815 encoding = ('' + encoding).toLowerCase()
821 Buffer.prototype.toJSON = function toJSON () {
824 data: Array.prototype.slice.call(this._arr || this, 0)
828 function base64Slice (buf, start, end) {
829 if (start === 0 && end === buf.length) {
830 return base64.fromByteArray(buf)
832 return base64.fromByteArray(buf.slice(start, end))
836 function utf8Slice (buf, start, end) {
837 end = Math.min(buf.length, end)
842 var firstByte = buf[i]
844 var bytesPerSequence = (firstByte > 0xEF) ? 4
845 : (firstByte > 0xDF) ? 3
846 : (firstByte > 0xBF) ? 2
849 if (i + bytesPerSequence <= end) {
850 var secondByte, thirdByte, fourthByte, tempCodePoint
852 switch (bytesPerSequence) {
854 if (firstByte < 0x80) {
855 codePoint = firstByte
859 secondByte = buf[i + 1]
860 if ((secondByte & 0xC0) === 0x80) {
861 tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
862 if (tempCodePoint > 0x7F) {
863 codePoint = tempCodePoint
868 secondByte = buf[i + 1]
869 thirdByte = buf[i + 2]
870 if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
871 tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
872 if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
873 codePoint = tempCodePoint
878 secondByte = buf[i + 1]
879 thirdByte = buf[i + 2]
880 fourthByte = buf[i + 3]
881 if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
882 tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
883 if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
884 codePoint = tempCodePoint
890 if (codePoint === null) {
891 // we did not generate a valid codePoint so insert a
892 // replacement char (U+FFFD) and advance only 1 byte
895 } else if (codePoint > 0xFFFF) {
896 // encode to utf16 (surrogate pair dance)
898 res.push(codePoint >>> 10 & 0x3FF | 0xD800)
899 codePoint = 0xDC00 | codePoint & 0x3FF
903 i += bytesPerSequence
906 return decodeCodePointsArray(res)
909 // Based on http://stackoverflow.com/a/22747272/680742, the browser with
910 // the lowest limit is Chrome, with 0x10000 args.
911 // We go 1 magnitude less, for safety
912 var MAX_ARGUMENTS_LENGTH = 0x1000
914 function decodeCodePointsArray (codePoints) {
915 var len = codePoints.length
916 if (len <= MAX_ARGUMENTS_LENGTH) {
917 return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
920 // Decode in chunks to avoid "call stack size exceeded".
924 res += String.fromCharCode.apply(
926 codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
932 function asciiSlice (buf, start, end) {
934 end = Math.min(buf.length, end)
936 for (var i = start; i < end; i++) {
937 ret += String.fromCharCode(buf[i] & 0x7F)
942 function binarySlice (buf, start, end) {
944 end = Math.min(buf.length, end)
946 for (var i = start; i < end; i++) {
947 ret += String.fromCharCode(buf[i])
952 function hexSlice (buf, start, end) {
955 if (!start || start < 0) start = 0
956 if (!end || end < 0 || end > len) end = len
959 for (var i = start; i < end; i++) {
965 function utf16leSlice (buf, start, end) {
966 var bytes = buf.slice(start, end)
968 for (var i = 0; i < bytes.length; i += 2) {
969 res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)
974 Buffer.prototype.slice = function slice (start, end) {
975 var len = this.length
977 end = end === undefined ? len : ~~end
981 if (start < 0) start = 0
982 } else if (start > len) {
989 } else if (end > len) {
993 if (end < start) end = start
996 if (Buffer.TYPED_ARRAY_SUPPORT) {
997 newBuf = Buffer._augment(this.subarray(start, end))
999 var sliceLen = end - start
1000 newBuf = new Buffer(sliceLen, undefined)
1001 for (var i = 0; i < sliceLen; i++) {
1002 newBuf[i] = this[i + start]
1006 if (newBuf.length) newBuf.parent = this.parent || this
1012 * Need to make sure that buffer isn't trying to write out of bounds.
1014 function checkOffset (offset, ext, length) {
1015 if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
1016 if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
1019 Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
1021 byteLength = byteLength | 0
1022 if (!noAssert) checkOffset(offset, byteLength, this.length)
1024 var val = this[offset]
1027 while (++i < byteLength && (mul *= 0x100)) {
1028 val += this[offset + i] * mul
1034 Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
1036 byteLength = byteLength | 0
1038 checkOffset(offset, byteLength, this.length)
1041 var val = this[offset + --byteLength]
1043 while (byteLength > 0 && (mul *= 0x100)) {
1044 val += this[offset + --byteLength] * mul
1050 Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
1051 if (!noAssert) checkOffset(offset, 1, this.length)
1055 Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
1056 if (!noAssert) checkOffset(offset, 2, this.length)
1057 return this[offset] | (this[offset + 1] << 8)
1060 Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
1061 if (!noAssert) checkOffset(offset, 2, this.length)
1062 return (this[offset] << 8) | this[offset + 1]
1065 Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
1066 if (!noAssert) checkOffset(offset, 4, this.length)
1068 return ((this[offset]) |
1069 (this[offset + 1] << 8) |
1070 (this[offset + 2] << 16)) +
1071 (this[offset + 3] * 0x1000000)
1074 Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
1075 if (!noAssert) checkOffset(offset, 4, this.length)
1077 return (this[offset] * 0x1000000) +
1078 ((this[offset + 1] << 16) |
1079 (this[offset + 2] << 8) |
1083 Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
1085 byteLength = byteLength | 0
1086 if (!noAssert) checkOffset(offset, byteLength, this.length)
1088 var val = this[offset]
1091 while (++i < byteLength && (mul *= 0x100)) {
1092 val += this[offset + i] * mul
1096 if (val >= mul) val -= Math.pow(2, 8 * byteLength)
1101 Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
1103 byteLength = byteLength | 0
1104 if (!noAssert) checkOffset(offset, byteLength, this.length)
1108 var val = this[offset + --i]
1109 while (i > 0 && (mul *= 0x100)) {
1110 val += this[offset + --i] * mul
1114 if (val >= mul) val -= Math.pow(2, 8 * byteLength)
1119 Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
1120 if (!noAssert) checkOffset(offset, 1, this.length)
1121 if (!(this[offset] & 0x80)) return (this[offset])
1122 return ((0xff - this[offset] + 1) * -1)
1125 Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
1126 if (!noAssert) checkOffset(offset, 2, this.length)
1127 var val = this[offset] | (this[offset + 1] << 8)
1128 return (val & 0x8000) ? val | 0xFFFF0000 : val
1131 Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
1132 if (!noAssert) checkOffset(offset, 2, this.length)
1133 var val = this[offset + 1] | (this[offset] << 8)
1134 return (val & 0x8000) ? val | 0xFFFF0000 : val
1137 Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
1138 if (!noAssert) checkOffset(offset, 4, this.length)
1140 return (this[offset]) |
1141 (this[offset + 1] << 8) |
1142 (this[offset + 2] << 16) |
1143 (this[offset + 3] << 24)
1146 Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
1147 if (!noAssert) checkOffset(offset, 4, this.length)
1149 return (this[offset] << 24) |
1150 (this[offset + 1] << 16) |
1151 (this[offset + 2] << 8) |
1155 Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
1156 if (!noAssert) checkOffset(offset, 4, this.length)
1157 return ieee754.read(this, offset, true, 23, 4)
1160 Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
1161 if (!noAssert) checkOffset(offset, 4, this.length)
1162 return ieee754.read(this, offset, false, 23, 4)
1165 Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
1166 if (!noAssert) checkOffset(offset, 8, this.length)
1167 return ieee754.read(this, offset, true, 52, 8)
1170 Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
1171 if (!noAssert) checkOffset(offset, 8, this.length)
1172 return ieee754.read(this, offset, false, 52, 8)
1175 function checkInt (buf, value, offset, ext, max, min) {
1176 if (!Buffer.isBuffer(buf)) throw new TypeError('buffer must be a Buffer instance')
1177 if (value > max || value < min) throw new RangeError('value is out of bounds')
1178 if (offset + ext > buf.length) throw new RangeError('index out of range')
1181 Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
1184 byteLength = byteLength | 0
1185 if (!noAssert) checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0)
1189 this[offset] = value & 0xFF
1190 while (++i < byteLength && (mul *= 0x100)) {
1191 this[offset + i] = (value / mul) & 0xFF
1194 return offset + byteLength
1197 Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
1200 byteLength = byteLength | 0
1201 if (!noAssert) checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0)
1203 var i = byteLength - 1
1205 this[offset + i] = value & 0xFF
1206 while (--i >= 0 && (mul *= 0x100)) {
1207 this[offset + i] = (value / mul) & 0xFF
1210 return offset + byteLength
1213 Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
1216 if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
1217 if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
1218 this[offset] = (value & 0xff)
1222 function objectWriteUInt16 (buf, value, offset, littleEndian) {
1223 if (value < 0) value = 0xffff + value + 1
1224 for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; i++) {
1225 buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
1226 (littleEndian ? i : 1 - i) * 8
1230 Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
1233 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
1234 if (Buffer.TYPED_ARRAY_SUPPORT) {
1235 this[offset] = (value & 0xff)
1236 this[offset + 1] = (value >>> 8)
1238 objectWriteUInt16(this, value, offset, true)
1243 Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
1246 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
1247 if (Buffer.TYPED_ARRAY_SUPPORT) {
1248 this[offset] = (value >>> 8)
1249 this[offset + 1] = (value & 0xff)
1251 objectWriteUInt16(this, value, offset, false)
1256 function objectWriteUInt32 (buf, value, offset, littleEndian) {
1257 if (value < 0) value = 0xffffffff + value + 1
1258 for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; i++) {
1259 buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff
1263 Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
1266 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
1267 if (Buffer.TYPED_ARRAY_SUPPORT) {
1268 this[offset + 3] = (value >>> 24)
1269 this[offset + 2] = (value >>> 16)
1270 this[offset + 1] = (value >>> 8)
1271 this[offset] = (value & 0xff)
1273 objectWriteUInt32(this, value, offset, true)
1278 Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
1281 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
1282 if (Buffer.TYPED_ARRAY_SUPPORT) {
1283 this[offset] = (value >>> 24)
1284 this[offset + 1] = (value >>> 16)
1285 this[offset + 2] = (value >>> 8)
1286 this[offset + 3] = (value & 0xff)
1288 objectWriteUInt32(this, value, offset, false)
1293 Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
1297 var limit = Math.pow(2, 8 * byteLength - 1)
1299 checkInt(this, value, offset, byteLength, limit - 1, -limit)
1304 var sub = value < 0 ? 1 : 0
1305 this[offset] = value & 0xFF
1306 while (++i < byteLength && (mul *= 0x100)) {
1307 this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
1310 return offset + byteLength
1313 Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
1317 var limit = Math.pow(2, 8 * byteLength - 1)
1319 checkInt(this, value, offset, byteLength, limit - 1, -limit)
1322 var i = byteLength - 1
1324 var sub = value < 0 ? 1 : 0
1325 this[offset + i] = value & 0xFF
1326 while (--i >= 0 && (mul *= 0x100)) {
1327 this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
1330 return offset + byteLength
1333 Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
1336 if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
1337 if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
1338 if (value < 0) value = 0xff + value + 1
1339 this[offset] = (value & 0xff)
1343 Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
1346 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
1347 if (Buffer.TYPED_ARRAY_SUPPORT) {
1348 this[offset] = (value & 0xff)
1349 this[offset + 1] = (value >>> 8)
1351 objectWriteUInt16(this, value, offset, true)
1356 Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
1359 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
1360 if (Buffer.TYPED_ARRAY_SUPPORT) {
1361 this[offset] = (value >>> 8)
1362 this[offset + 1] = (value & 0xff)
1364 objectWriteUInt16(this, value, offset, false)
1369 Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
1372 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
1373 if (Buffer.TYPED_ARRAY_SUPPORT) {
1374 this[offset] = (value & 0xff)
1375 this[offset + 1] = (value >>> 8)
1376 this[offset + 2] = (value >>> 16)
1377 this[offset + 3] = (value >>> 24)
1379 objectWriteUInt32(this, value, offset, true)
1384 Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
1387 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
1388 if (value < 0) value = 0xffffffff + value + 1
1389 if (Buffer.TYPED_ARRAY_SUPPORT) {
1390 this[offset] = (value >>> 24)
1391 this[offset + 1] = (value >>> 16)
1392 this[offset + 2] = (value >>> 8)
1393 this[offset + 3] = (value & 0xff)
1395 objectWriteUInt32(this, value, offset, false)
1400 function checkIEEE754 (buf, value, offset, ext, max, min) {
1401 if (value > max || value < min) throw new RangeError('value is out of bounds')
1402 if (offset + ext > buf.length) throw new RangeError('index out of range')
1403 if (offset < 0) throw new RangeError('index out of range')
1406 function writeFloat (buf, value, offset, littleEndian, noAssert) {
1408 checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
1410 ieee754.write(buf, value, offset, littleEndian, 23, 4)
1414 Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
1415 return writeFloat(this, value, offset, true, noAssert)
1418 Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
1419 return writeFloat(this, value, offset, false, noAssert)
1422 function writeDouble (buf, value, offset, littleEndian, noAssert) {
1424 checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
1426 ieee754.write(buf, value, offset, littleEndian, 52, 8)
1430 Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
1431 return writeDouble(this, value, offset, true, noAssert)
1434 Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
1435 return writeDouble(this, value, offset, false, noAssert)
1438 // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
1439 Buffer.prototype.copy = function copy (target, targetStart, start, end) {
1440 if (!start) start = 0
1441 if (!end && end !== 0) end = this.length
1442 if (targetStart >= target.length) targetStart = target.length
1443 if (!targetStart) targetStart = 0
1444 if (end > 0 && end < start) end = start
1446 // Copy 0 bytes; we're done
1447 if (end === start) return 0
1448 if (target.length === 0 || this.length === 0) return 0
1450 // Fatal error conditions
1451 if (targetStart < 0) {
1452 throw new RangeError('targetStart out of bounds')
1454 if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
1455 if (end < 0) throw new RangeError('sourceEnd out of bounds')
1458 if (end > this.length) end = this.length
1459 if (target.length - targetStart < end - start) {
1460 end = target.length - targetStart + start
1463 var len = end - start
1466 if (this === target && start < targetStart && targetStart < end) {
1467 // descending copy from end
1468 for (i = len - 1; i >= 0; i--) {
1469 target[i + targetStart] = this[i + start]
1471 } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {
1472 // ascending copy from start
1473 for (i = 0; i < len; i++) {
1474 target[i + targetStart] = this[i + start]
1477 target._set(this.subarray(start, start + len), targetStart)
1483 // fill(value, start=0, end=buffer.length)
1484 Buffer.prototype.fill = function fill (value, start, end) {
1485 if (!value) value = 0
1486 if (!start) start = 0
1487 if (!end) end = this.length
1489 if (end < start) throw new RangeError('end < start')
1491 // Fill 0 bytes; we're done
1492 if (end === start) return
1493 if (this.length === 0) return
1495 if (start < 0 || start >= this.length) throw new RangeError('start out of bounds')
1496 if (end < 0 || end > this.length) throw new RangeError('end out of bounds')
1499 if (typeof value === 'number') {
1500 for (i = start; i < end; i++) {
1504 var bytes = utf8ToBytes(value.toString())
1505 var len = bytes.length
1506 for (i = start; i < end; i++) {
1507 this[i] = bytes[i % len]
1515 * Creates a new `ArrayBuffer` with the *copied* memory of the buffer instance.
1516 * Added in Node 0.12. Only available in browsers that support ArrayBuffer.
1518 Buffer.prototype.toArrayBuffer = function toArrayBuffer () {
1519 if (typeof Uint8Array !== 'undefined') {
1520 if (Buffer.TYPED_ARRAY_SUPPORT) {
1521 return (new Buffer(this)).buffer
1523 var buf = new Uint8Array(this.length)
1524 for (var i = 0, len = buf.length; i < len; i += 1) {
1530 throw new TypeError('Buffer.toArrayBuffer not supported in this browser')
1537 var BP = Buffer.prototype
1540 * Augment a Uint8Array *instance* (not the Uint8Array class!) with Buffer methods
1542 Buffer._augment = function _augment (arr) {
1543 arr.constructor = Buffer
1544 arr._isBuffer = true
1546 // save reference to original Uint8Array set method before overwriting
1553 arr.write = BP.write
1554 arr.toString = BP.toString
1555 arr.toLocaleString = BP.toString
1556 arr.toJSON = BP.toJSON
1557 arr.equals = BP.equals
1558 arr.compare = BP.compare
1559 arr.indexOf = BP.indexOf
1561 arr.slice = BP.slice
1562 arr.readUIntLE = BP.readUIntLE
1563 arr.readUIntBE = BP.readUIntBE
1564 arr.readUInt8 = BP.readUInt8
1565 arr.readUInt16LE = BP.readUInt16LE
1566 arr.readUInt16BE = BP.readUInt16BE
1567 arr.readUInt32LE = BP.readUInt32LE
1568 arr.readUInt32BE = BP.readUInt32BE
1569 arr.readIntLE = BP.readIntLE
1570 arr.readIntBE = BP.readIntBE
1571 arr.readInt8 = BP.readInt8
1572 arr.readInt16LE = BP.readInt16LE
1573 arr.readInt16BE = BP.readInt16BE
1574 arr.readInt32LE = BP.readInt32LE
1575 arr.readInt32BE = BP.readInt32BE
1576 arr.readFloatLE = BP.readFloatLE
1577 arr.readFloatBE = BP.readFloatBE
1578 arr.readDoubleLE = BP.readDoubleLE
1579 arr.readDoubleBE = BP.readDoubleBE
1580 arr.writeUInt8 = BP.writeUInt8
1581 arr.writeUIntLE = BP.writeUIntLE
1582 arr.writeUIntBE = BP.writeUIntBE
1583 arr.writeUInt16LE = BP.writeUInt16LE
1584 arr.writeUInt16BE = BP.writeUInt16BE
1585 arr.writeUInt32LE = BP.writeUInt32LE
1586 arr.writeUInt32BE = BP.writeUInt32BE
1587 arr.writeIntLE = BP.writeIntLE
1588 arr.writeIntBE = BP.writeIntBE
1589 arr.writeInt8 = BP.writeInt8
1590 arr.writeInt16LE = BP.writeInt16LE
1591 arr.writeInt16BE = BP.writeInt16BE
1592 arr.writeInt32LE = BP.writeInt32LE
1593 arr.writeInt32BE = BP.writeInt32BE
1594 arr.writeFloatLE = BP.writeFloatLE
1595 arr.writeFloatBE = BP.writeFloatBE
1596 arr.writeDoubleLE = BP.writeDoubleLE
1597 arr.writeDoubleBE = BP.writeDoubleBE
1599 arr.inspect = BP.inspect
1600 arr.toArrayBuffer = BP.toArrayBuffer
1605 var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g
1607 function base64clean (str) {
1608 // Node strips out invalid characters like \n and \t from the string, base64-js does not
1609 str = stringtrim(str).replace(INVALID_BASE64_RE, '')
1610 // Node converts strings with length < 2 to ''
1611 if (str.length < 2) return ''
1612 // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
1613 while (str.length % 4 !== 0) {
1619 function stringtrim (str) {
1620 if (str.trim) return str.trim()
1621 return str.replace(/^\s+|\s+$/g, '')
1624 function toHex (n) {
1625 if (n < 16) return '0' + n.toString(16)
1626 return n.toString(16)
1629 function utf8ToBytes (string, units) {
1630 units = units || Infinity
1632 var length = string.length
1633 var leadSurrogate = null
1636 for (var i = 0; i < length; i++) {
1637 codePoint = string.charCodeAt(i)
1639 // is surrogate component
1640 if (codePoint > 0xD7FF && codePoint < 0xE000) {
1641 // last char was a lead
1642 if (!leadSurrogate) {
1644 if (codePoint > 0xDBFF) {
1646 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
1648 } else if (i + 1 === length) {
1650 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
1655 leadSurrogate = codePoint
1661 if (codePoint < 0xDC00) {
1662 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
1663 leadSurrogate = codePoint
1667 // valid surrogate pair
1668 codePoint = leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00 | 0x10000
1669 } else if (leadSurrogate) {
1670 // valid bmp char, but last char was a lead
1671 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
1674 leadSurrogate = null
1677 if (codePoint < 0x80) {
1678 if ((units -= 1) < 0) break
1679 bytes.push(codePoint)
1680 } else if (codePoint < 0x800) {
1681 if ((units -= 2) < 0) break
1683 codePoint >> 0x6 | 0xC0,
1684 codePoint & 0x3F | 0x80
1686 } else if (codePoint < 0x10000) {
1687 if ((units -= 3) < 0) break
1689 codePoint >> 0xC | 0xE0,
1690 codePoint >> 0x6 & 0x3F | 0x80,
1691 codePoint & 0x3F | 0x80
1693 } else if (codePoint < 0x110000) {
1694 if ((units -= 4) < 0) break
1696 codePoint >> 0x12 | 0xF0,
1697 codePoint >> 0xC & 0x3F | 0x80,
1698 codePoint >> 0x6 & 0x3F | 0x80,
1699 codePoint & 0x3F | 0x80
1702 throw new Error('Invalid code point')
1709 function asciiToBytes (str) {
1711 for (var i = 0; i < str.length; i++) {
1712 // Node's code seems to be doing this and not & 0x7F..
1713 byteArray.push(str.charCodeAt(i) & 0xFF)
1718 function utf16leToBytes (str, units) {
1721 for (var i = 0; i < str.length; i++) {
1722 if ((units -= 2) < 0) break
1724 c = str.charCodeAt(i)
1734 function base64ToBytes (str) {
1735 return base64.toByteArray(base64clean(str))
1738 function blitBuffer (src, dst, offset, length) {
1739 for (var i = 0; i < length; i++) {
1740 if ((i + offset >= dst.length) || (i >= src.length)) break
1741 dst[i + offset] = src[i]
1746 /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2).Buffer, (function() { return this; }())))
1750 /***/ function(module, exports, __webpack_require__) {
1752 var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
1754 ;(function (exports) {
1757 var Arr = (typeof Uint8Array !== 'undefined')
1761 var PLUS = '+'.charCodeAt(0)
1762 var SLASH = '/'.charCodeAt(0)
1763 var NUMBER = '0'.charCodeAt(0)
1764 var LOWER = 'a'.charCodeAt(0)
1765 var UPPER = 'A'.charCodeAt(0)
1766 var PLUS_URL_SAFE = '-'.charCodeAt(0)
1767 var SLASH_URL_SAFE = '_'.charCodeAt(0)
1769 function decode (elt) {
1770 var code = elt.charCodeAt(0)
1771 if (code === PLUS ||
1772 code === PLUS_URL_SAFE)
1774 if (code === SLASH ||
1775 code === SLASH_URL_SAFE)
1778 return -1 //no match
1779 if (code < NUMBER + 10)
1780 return code - NUMBER + 26 + 26
1781 if (code < UPPER + 26)
1783 if (code < LOWER + 26)
1784 return code - LOWER + 26
1787 function b64ToByteArray (b64) {
1788 var i, j, l, tmp, placeHolders, arr
1790 if (b64.length % 4 > 0) {
1791 throw new Error('Invalid string. Length must be a multiple of 4')
1794 // the number of equal signs (place holders)
1795 // if there are two placeholders, than the two characters before it
1796 // represent one byte
1797 // if there is only one, then the three characters before it represent 2 bytes
1798 // this is just a cheap hack to not do indexOf twice
1799 var len = b64.length
1800 placeHolders = '=' === b64.charAt(len - 2) ? 2 : '=' === b64.charAt(len - 1) ? 1 : 0
1802 // base64 is 4/3 + up to two characters of the original data
1803 arr = new Arr(b64.length * 3 / 4 - placeHolders)
1805 // if there are placeholders, only get up to the last complete 4 chars
1806 l = placeHolders > 0 ? b64.length - 4 : b64.length
1814 for (i = 0, j = 0; i < l; i += 4, j += 3) {
1815 tmp = (decode(b64.charAt(i)) << 18) | (decode(b64.charAt(i + 1)) << 12) | (decode(b64.charAt(i + 2)) << 6) | decode(b64.charAt(i + 3))
1816 push((tmp & 0xFF0000) >> 16)
1817 push((tmp & 0xFF00) >> 8)
1821 if (placeHolders === 2) {
1822 tmp = (decode(b64.charAt(i)) << 2) | (decode(b64.charAt(i + 1)) >> 4)
1824 } else if (placeHolders === 1) {
1825 tmp = (decode(b64.charAt(i)) << 10) | (decode(b64.charAt(i + 1)) << 4) | (decode(b64.charAt(i + 2)) >> 2)
1826 push((tmp >> 8) & 0xFF)
1833 function uint8ToBase64 (uint8) {
1835 extraBytes = uint8.length % 3, // if we have 1 byte left, pad 2 bytes
1839 function encode (num) {
1840 return lookup.charAt(num)
1843 function tripletToBase64 (num) {
1844 return encode(num >> 18 & 0x3F) + encode(num >> 12 & 0x3F) + encode(num >> 6 & 0x3F) + encode(num & 0x3F)
1847 // go through the array every three bytes, we'll deal with trailing stuff later
1848 for (i = 0, length = uint8.length - extraBytes; i < length; i += 3) {
1849 temp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2])
1850 output += tripletToBase64(temp)
1853 // pad the end with zeros, but make sure to not forget the extra bytes
1854 switch (extraBytes) {
1856 temp = uint8[uint8.length - 1]
1857 output += encode(temp >> 2)
1858 output += encode((temp << 4) & 0x3F)
1862 temp = (uint8[uint8.length - 2] << 8) + (uint8[uint8.length - 1])
1863 output += encode(temp >> 10)
1864 output += encode((temp >> 4) & 0x3F)
1865 output += encode((temp << 2) & 0x3F)
1873 exports.toByteArray = b64ToByteArray
1874 exports.fromByteArray = uint8ToBase64
1875 }( false ? (this.base64js = {}) : exports))
1880 /***/ function(module, exports) {
1882 exports.read = function (buffer, offset, isLE, mLen, nBytes) {
1884 var eLen = nBytes * 8 - mLen - 1
1885 var eMax = (1 << eLen) - 1
1886 var eBias = eMax >> 1
1888 var i = isLE ? (nBytes - 1) : 0
1889 var d = isLE ? -1 : 1
1890 var s = buffer[offset + i]
1894 e = s & ((1 << (-nBits)) - 1)
1897 for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
1899 m = e & ((1 << (-nBits)) - 1)
1902 for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
1906 } else if (e === eMax) {
1907 return m ? NaN : ((s ? -1 : 1) * Infinity)
1909 m = m + Math.pow(2, mLen)
1912 return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
1915 exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
1917 var eLen = nBytes * 8 - mLen - 1
1918 var eMax = (1 << eLen) - 1
1919 var eBias = eMax >> 1
1920 var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
1921 var i = isLE ? 0 : (nBytes - 1)
1922 var d = isLE ? 1 : -1
1923 var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
1925 value = Math.abs(value)
1927 if (isNaN(value) || value === Infinity) {
1928 m = isNaN(value) ? 1 : 0
1931 e = Math.floor(Math.log(value) / Math.LN2)
1932 if (value * (c = Math.pow(2, -e)) < 1) {
1936 if (e + eBias >= 1) {
1939 value += rt * Math.pow(2, 1 - eBias)
1941 if (value * c >= 2) {
1946 if (e + eBias >= eMax) {
1949 } else if (e + eBias >= 1) {
1950 m = (value * c - 1) * Math.pow(2, mLen)
1953 m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
1958 for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
1962 for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
1964 buffer[offset + i - d] |= s * 128
1970 /***/ function(module, exports) {
1977 var isArray = Array.isArray;
1983 var str = Object.prototype.toString;
1986 * Whether or not the given `val`
1993 * isArray(arguments);
1998 * @param {mixed} val
2002 module.exports = isArray || function (val) {
2003 return !! val && '[object Array]' == str.call(val);
2009 /***/ function(module, exports, __webpack_require__) {
2011 /* jslint node: true */
2015 var _ = __webpack_require__(7);
2016 var FontProvider = __webpack_require__(9);
2017 var LayoutBuilder = __webpack_require__(11);
2018 var PdfKit = __webpack_require__(24);
2019 var PDFReference = __webpack_require__(46);
2020 var sizes = __webpack_require__(102);
2021 var ImageMeasure = __webpack_require__(103);
2022 var textDecorator = __webpack_require__(104);
2023 var FontProvider = __webpack_require__(9);
2025 ////////////////////////////////////////
2029 * @class Creates an instance of a PdfPrinter which turns document definition into a pdf
2031 * @param {Object} fontDescriptors font definition dictionary
2034 * var fontDescriptors = {
2036 * normal: 'fonts/Roboto-Regular.ttf',
2037 * bold: 'fonts/Roboto-Medium.ttf',
2038 * italics: 'fonts/Roboto-Italic.ttf',
2039 * bolditalics: 'fonts/Roboto-Italic.ttf'
2043 * var printer = new PdfPrinter(fontDescriptors);
2045 function PdfPrinter(fontDescriptors) {
2046 this.fontDescriptors = fontDescriptors;
2050 * Executes layout engine for the specified document and renders it into a pdfkit document
2051 * ready to be saved.
2053 * @param {Object} docDefinition document definition
2054 * @param {Object} docDefinition.content an array describing the pdf structure (for more information take a look at the examples in the /examples folder)
2055 * @param {Object} [docDefinition.defaultStyle] default (implicit) style definition
2056 * @param {Object} [docDefinition.styles] dictionary defining all styles which can be used in the document
2057 * @param {Object} [docDefinition.pageSize] page size (pdfkit units, A4 dimensions by default)
2058 * @param {Number} docDefinition.pageSize.width width
2059 * @param {Number} docDefinition.pageSize.height height
2060 * @param {Object} [docDefinition.pageMargins] page margins (pdfkit units)
2064 * var docDefinition = {
2066 * title: 'awesome Document',
2067 * author: 'john doe',
2068 * subject: 'subject of document',
2069 * keywords: 'keywords for document',
2072 * 'First paragraph',
2073 * 'Second paragraph, this time a little bit longer',
2074 * { text: 'Third paragraph, slightly bigger font size', fontSize: 20 },
2075 * { text: 'Another paragraph using a named style', style: 'header' },
2076 * { text: ['playing with ', 'inlines' ] },
2077 * { text: ['and ', { text: 'restyling ', bold: true }, 'them'] },
2080 * header: { fontSize: 30, bold: true }
2084 * var pdfDoc = printer.createPdfKitDocument(docDefinition);
2086 * pdfDoc.pipe(fs.createWriteStream('sample.pdf'));
2089 * @return {Object} a pdfKit document object which can be saved or encode to data-url
2091 PdfPrinter.prototype.createPdfKitDocument = function(docDefinition, options) {
2092 options = options || {};
2094 var pageSize = pageSize2widthAndHeight(docDefinition.pageSize || 'a4');
2096 if(docDefinition.pageOrientation === 'landscape') {
2097 pageSize = { width: pageSize.height, height: pageSize.width};
2099 pageSize.orientation = docDefinition.pageOrientation === 'landscape' ? docDefinition.pageOrientation : 'portrait';
2101 this.pdfKitDoc = new PdfKit({ size: [ pageSize.width, pageSize.height ], compress: false});
2102 this.pdfKitDoc.info.Producer = 'pdfmake';
2103 this.pdfKitDoc.info.Creator = 'pdfmake';
2105 // pdf kit maintains the uppercase fieldnames from pdf spec
2106 // to keep the pdfmake api consistent, the info field are defined lowercase
2107 if(docDefinition.info){
2108 var info = docDefinition.info;
2109 // check for falsey an set null, so that pdfkit always get either null or value
2110 this.pdfKitDoc.info.Title = docDefinition.info.title ? docDefinition.info.title : null;
2111 this.pdfKitDoc.info.Author = docDefinition.info.author ? docDefinition.info.author : null;
2112 this.pdfKitDoc.info.Subject = docDefinition.info.subject ? docDefinition.info.subject : null;
2113 this.pdfKitDoc.info.Keywords = docDefinition.info.keywords ? docDefinition.info.keywords : null;
2116 this.fontProvider = new FontProvider(this.fontDescriptors, this.pdfKitDoc);
2118 docDefinition.images = docDefinition.images || {};
2120 var builder = new LayoutBuilder(
2122 fixPageMargins(docDefinition.pageMargins || 40),
2123 new ImageMeasure(this.pdfKitDoc, docDefinition.images));
2125 registerDefaultTableLayouts(builder);
2126 if (options.tableLayouts) {
2127 builder.registerTableLayouts(options.tableLayouts);
2130 var pages = builder.layoutDocument(docDefinition.content, this.fontProvider, docDefinition.styles || {}, docDefinition.defaultStyle || { fontSize: 12, font: 'Roboto' }, docDefinition.background, docDefinition.header, docDefinition.footer, docDefinition.images, docDefinition.watermark, docDefinition.pageBreakBefore);
2132 renderPages(pages, this.fontProvider, this.pdfKitDoc);
2134 if(options.autoPrint){
2135 var printActionRef = this.pdfKitDoc.ref({
2140 this.pdfKitDoc._root.data.OpenAction = printActionRef;
2141 printActionRef.end();
2143 return this.pdfKitDoc;
2146 function fixPageMargins(margin) {
2147 if (!margin) return null;
2149 if (typeof margin === 'number' || margin instanceof Number) {
2150 margin = { left: margin, right: margin, top: margin, bottom: margin };
2151 } else if (margin instanceof Array) {
2152 if (margin.length === 2) {
2153 margin = { left: margin[0], top: margin[1], right: margin[0], bottom: margin[1] };
2154 } else if (margin.length === 4) {
2155 margin = { left: margin[0], top: margin[1], right: margin[2], bottom: margin[3] };
2156 } else throw 'Invalid pageMargins definition';
2162 function registerDefaultTableLayouts(layoutBuilder) {
2163 layoutBuilder.registerTableLayouts({
2165 hLineWidth: function(i) { return 0; },
2166 vLineWidth: function(i) { return 0; },
2167 paddingLeft: function(i) { return i && 4 || 0; },
2168 paddingRight: function(i, node) { return (i < node.table.widths.length - 1) ? 4 : 0; },
2171 hLineWidth: function(i, node) {
2172 if (i === 0 || i === node.table.body.length) return 0;
2173 return (i === node.table.headerRows) ? 2 : 0;
2175 vLineWidth: function(i) { return 0; },
2176 paddingLeft: function(i) {
2177 return i === 0 ? 0 : 8;
2179 paddingRight: function(i, node) {
2180 return (i === node.table.widths.length - 1) ? 0 : 8;
2183 lightHorizontalLines: {
2184 hLineWidth: function(i, node) {
2185 if (i === 0 || i === node.table.body.length) return 0;
2186 return (i === node.table.headerRows) ? 2 : 1;
2188 vLineWidth: function(i) { return 0; },
2189 hLineColor: function(i) { return i === 1 ? 'black' : '#aaa'; },
2190 paddingLeft: function(i) {
2191 return i === 0 ? 0 : 8;
2193 paddingRight: function(i, node) {
2194 return (i === node.table.widths.length - 1) ? 0 : 8;
2200 var defaultLayout = {
2201 hLineWidth: function(i, node) { return 1; }, //return node.table.headerRows && i === node.table.headerRows && 3 || 0; },
2202 vLineWidth: function(i, node) { return 1; },
2203 hLineColor: function(i, node) { return 'black'; },
2204 vLineColor: function(i, node) { return 'black'; },
2205 paddingLeft: function(i, node) { return 4; }, //i && 4 || 0; },
2206 paddingRight: function(i, node) { return 4; }, //(i < node.table.widths.length - 1) ? 4 : 0; },
2207 paddingTop: function(i, node) { return 2; },
2208 paddingBottom: function(i, node) { return 2; }
2211 function pageSize2widthAndHeight(pageSize) {
2212 if (typeof pageSize == 'string' || pageSize instanceof String) {
2213 var size = sizes[pageSize.toUpperCase()];
2214 if (!size) throw ('Page size ' + pageSize + ' not recognized');
2215 return { width: size[0], height: size[1] };
2221 function StringObject(str){
2222 this.isString = true;
2223 this.toString = function(){
2228 function updatePageOrientationInOptions(currentPage, pdfKitDoc) {
2229 var previousPageOrientation = pdfKitDoc.options.size[0] > pdfKitDoc.options.size[1] ? 'landscape' : 'portrait';
2231 if(currentPage.pageSize.orientation !== previousPageOrientation) {
2232 var width = pdfKitDoc.options.size[0];
2233 var height = pdfKitDoc.options.size[1];
2234 pdfKitDoc.options.size = [height, width];
2238 function renderPages(pages, fontProvider, pdfKitDoc) {
2239 pdfKitDoc._pdfMakePages = pages;
2240 for (var i = 0; i < pages.length; i++) {
2242 updatePageOrientationInOptions(pages[i], pdfKitDoc);
2243 pdfKitDoc.addPage(pdfKitDoc.options);
2246 var page = pages[i];
2247 for(var ii = 0, il = page.items.length; ii < il; ii++) {
2248 var item = page.items[ii];
2251 renderVector(item.item, pdfKitDoc);
2254 renderLine(item.item, item.item.x, item.item.y, pdfKitDoc);
2257 renderImage(item.item, item.item.x, item.item.y, pdfKitDoc);
2262 renderWatermark(page, pdfKitDoc);
2265 fontProvider.setFontRefsToPdfDoc();
2269 function renderLine(line, x, y, pdfKitDoc) {
2273 var lineHeight = line.getHeight();
2274 var ascenderHeight = line.getAscenderHeight();
2276 textDecorator.drawBackground(line, x, y, pdfKitDoc);
2278 //TODO: line.optimizeInlines();
2279 for(var i = 0, l = line.inlines.length; i < l; i++) {
2280 var inline = line.inlines[i];
2282 pdfKitDoc.fill(inline.color || 'black');
2285 pdfKitDoc.transform(1, 0, 0, -1, 0, pdfKitDoc.page.height);
2288 var encoded = inline.font.encode(inline.text);
2289 pdfKitDoc.addContent('BT');
2291 pdfKitDoc.addContent('' + (x + inline.x) + ' ' + (pdfKitDoc.page.height - y - ascenderHeight) + ' Td');
2292 pdfKitDoc.addContent('/' + encoded.fontId + ' ' + inline.fontSize + ' Tf');
2294 pdfKitDoc.addContent('<' + encoded.encodedText + '> Tj');
2296 pdfKitDoc.addContent('ET');
2299 pdfKitDoc.link(x + inline.x, pdfKitDoc.page.height - y - lineHeight, inline.width, lineHeight, inline.link);
2302 pdfKitDoc.restore();
2305 textDecorator.drawDecorations(line, x, y, pdfKitDoc);
2309 function renderWatermark(page, pdfKitDoc){
2310 var watermark = page.watermark;
2312 pdfKitDoc.fill('black');
2313 pdfKitDoc.opacity(0.6);
2316 pdfKitDoc.transform(1, 0, 0, -1, 0, pdfKitDoc.page.height);
2318 var angle = Math.atan2(pdfKitDoc.page.height, pdfKitDoc.page.width) * 180/Math.PI;
2319 pdfKitDoc.rotate(angle, {origin: [pdfKitDoc.page.width/2, pdfKitDoc.page.height/2]});
2321 var encoded = watermark.font.encode(watermark.text);
2322 pdfKitDoc.addContent('BT');
2323 pdfKitDoc.addContent('' + (pdfKitDoc.page.width/2 - watermark.size.size.width/2) + ' ' + (pdfKitDoc.page.height/2 - watermark.size.size.height/4) + ' Td');
2324 pdfKitDoc.addContent('/' + encoded.fontId + ' ' + watermark.size.fontSize + ' Tf');
2325 pdfKitDoc.addContent('<' + encoded.encodedText + '> Tj');
2326 pdfKitDoc.addContent('ET');
2327 pdfKitDoc.restore();
2330 function renderVector(vector, pdfDoc) {
2331 //TODO: pdf optimization (there's no need to write all properties everytime)
2332 pdfDoc.lineWidth(vector.lineWidth || 1);
2334 pdfDoc.dash(vector.dash.length, { space: vector.dash.space || vector.dash.length });
2338 pdfDoc.fillOpacity(vector.fillOpacity || 1);
2339 pdfDoc.strokeOpacity(vector.strokeOpacity || 1);
2340 pdfDoc.lineJoin(vector.lineJoin || 'miter');
2344 switch(vector.type) {
2346 pdfDoc.ellipse(vector.x, vector.y, vector.r1, vector.r2);
2350 pdfDoc.roundedRect(vector.x, vector.y, vector.w, vector.h, vector.r);
2352 pdfDoc.rect(vector.x, vector.y, vector.w, vector.h);
2356 pdfDoc.moveTo(vector.x1, vector.y1);
2357 pdfDoc.lineTo(vector.x2, vector.y2);
2360 if (vector.points.length === 0) break;
2362 pdfDoc.moveTo(vector.points[0].x, vector.points[0].y);
2363 for(var i = 1, l = vector.points.length; i < l; i++) {
2364 pdfDoc.lineTo(vector.points[i].x, vector.points[i].y);
2367 if (vector.points.length > 1) {
2368 var p1 = vector.points[0];
2369 var pn = vector.points[vector.points.length - 1];
2371 if (vector.closePath || p1.x === pn.x && p1.y === pn.y) {
2378 if (vector.color && vector.lineColor) {
2379 pdfDoc.fillAndStroke(vector.color, vector.lineColor);
2380 } else if (vector.color) {
2381 pdfDoc.fill(vector.color);
2383 pdfDoc.stroke(vector.lineColor || 'black');
2387 function renderImage(image, x, y, pdfKitDoc) {
2388 pdfKitDoc.image(image.image, image.x, image.y, { width: image._width, height: image._height });
2391 module.exports = PdfPrinter;
2394 /* temporary browser extension */
2395 PdfPrinter.prototype.fs = __webpack_require__(44);
2400 /***/ function(module, exports, __webpack_require__) {
2402 var __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(module, global) {/**
2404 * lodash 3.10.1 (Custom Build) <https://lodash.com/>
2405 * Build: `lodash modern -d -o ./index.js`
2406 * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
2407 * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
2408 * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
2409 * Available under MIT license <https://lodash.com/license>
2413 /** Used as a safe reference for `undefined` in pre-ES5 environments. */
2416 /** Used as the semantic version number. */
2417 var VERSION = '3.10.1';
2419 /** Used to compose bitmasks for wrapper metadata. */
2422 CURRY_BOUND_FLAG = 4,
2424 CURRY_RIGHT_FLAG = 16,
2426 PARTIAL_RIGHT_FLAG = 64,
2430 /** Used as default options for `_.trunc`. */
2431 var DEFAULT_TRUNC_LENGTH = 30,
2432 DEFAULT_TRUNC_OMISSION = '...';
2434 /** Used to detect when a function becomes hot. */
2435 var HOT_COUNT = 150,
2438 /** Used as the size to enable large array optimizations. */
2439 var LARGE_ARRAY_SIZE = 200;
2441 /** Used to indicate the type of lazy iteratees. */
2442 var LAZY_FILTER_FLAG = 1,
2445 /** Used as the `TypeError` message for "Functions" methods. */
2446 var FUNC_ERROR_TEXT = 'Expected a function';
2448 /** Used as the internal argument placeholder. */
2449 var PLACEHOLDER = '__lodash_placeholder__';
2451 /** `Object#toString` result references. */
2452 var argsTag = '[object Arguments]',
2453 arrayTag = '[object Array]',
2454 boolTag = '[object Boolean]',
2455 dateTag = '[object Date]',
2456 errorTag = '[object Error]',
2457 funcTag = '[object Function]',
2458 mapTag = '[object Map]',
2459 numberTag = '[object Number]',
2460 objectTag = '[object Object]',
2461 regexpTag = '[object RegExp]',
2462 setTag = '[object Set]',
2463 stringTag = '[object String]',
2464 weakMapTag = '[object WeakMap]';
2466 var arrayBufferTag = '[object ArrayBuffer]',
2467 float32Tag = '[object Float32Array]',
2468 float64Tag = '[object Float64Array]',
2469 int8Tag = '[object Int8Array]',
2470 int16Tag = '[object Int16Array]',
2471 int32Tag = '[object Int32Array]',
2472 uint8Tag = '[object Uint8Array]',
2473 uint8ClampedTag = '[object Uint8ClampedArray]',
2474 uint16Tag = '[object Uint16Array]',
2475 uint32Tag = '[object Uint32Array]';
2477 /** Used to match empty string literals in compiled template source. */
2478 var reEmptyStringLeading = /\b__p \+= '';/g,
2479 reEmptyStringMiddle = /\b(__p \+=) '' \+/g,
2480 reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g;
2482 /** Used to match HTML entities and HTML characters. */
2483 var reEscapedHtml = /&(?:amp|lt|gt|quot|#39|#96);/g,
2484 reUnescapedHtml = /[&<>"'`]/g,
2485 reHasEscapedHtml = RegExp(reEscapedHtml.source),
2486 reHasUnescapedHtml = RegExp(reUnescapedHtml.source);
2488 /** Used to match template delimiters. */
2489 var reEscape = /<%-([\s\S]+?)%>/g,
2490 reEvaluate = /<%([\s\S]+?)%>/g,
2491 reInterpolate = /<%=([\s\S]+?)%>/g;
2493 /** Used to match property names within property paths. */
2494 var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\n\\]|\\.)*?\1)\]/,
2495 reIsPlainProp = /^\w*$/,
2496 rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\n\\]|\\.)*?)\2)\]/g;
2499 * Used to match `RegExp` [syntax characters](http://ecma-international.org/ecma-262/6.0/#sec-patterns)
2500 * and those outlined by [`EscapeRegExpPattern`](http://ecma-international.org/ecma-262/6.0/#sec-escaperegexppattern).
2502 var reRegExpChars = /^[:!,]|[\\^$.*+?()[\]{}|\/]|(^[0-9a-fA-Fnrtuvx])|([\n\r\u2028\u2029])/g,
2503 reHasRegExpChars = RegExp(reRegExpChars.source);
2505 /** Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks). */
2506 var reComboMark = /[\u0300-\u036f\ufe20-\ufe23]/g;
2508 /** Used to match backslashes in property paths. */
2509 var reEscapeChar = /\\(\\)?/g;
2511 /** Used to match [ES template delimiters](http://ecma-international.org/ecma-262/6.0/#sec-template-literal-lexical-components). */
2512 var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g;
2514 /** Used to match `RegExp` flags from their coerced string values. */
2515 var reFlags = /\w*$/;
2517 /** Used to detect hexadecimal string values. */
2518 var reHasHexPrefix = /^0[xX]/;
2520 /** Used to detect host constructors (Safari > 5). */
2521 var reIsHostCtor = /^\[object .+?Constructor\]$/;
2523 /** Used to detect unsigned integer values. */
2524 var reIsUint = /^\d+$/;
2526 /** Used to match latin-1 supplementary letters (excluding mathematical operators). */
2527 var reLatin1 = /[\xc0-\xd6\xd8-\xde\xdf-\xf6\xf8-\xff]/g;
2529 /** Used to ensure capturing order of template delimiters. */
2530 var reNoMatch = /($^)/;
2532 /** Used to match unescaped characters in compiled string literals. */
2533 var reUnescapedString = /['\n\r\u2028\u2029\\]/g;
2535 /** Used to match words to create compound words. */
2536 var reWords = (function() {
2537 var upper = '[A-Z\\xc0-\\xd6\\xd8-\\xde]',
2538 lower = '[a-z\\xdf-\\xf6\\xf8-\\xff]+';
2540 return RegExp(upper + '+(?=' + upper + lower + ')|' + upper + '?' + lower + '|' + upper + '+|[0-9]+', 'g');
2543 /** Used to assign default `context` object properties. */
2544 var contextProps = [
2545 'Array', 'ArrayBuffer', 'Date', 'Error', 'Float32Array', 'Float64Array',
2546 'Function', 'Int8Array', 'Int16Array', 'Int32Array', 'Math', 'Number',
2547 'Object', 'RegExp', 'Set', 'String', '_', 'clearTimeout', 'isFinite',
2548 'parseFloat', 'parseInt', 'setTimeout', 'TypeError', 'Uint8Array',
2549 'Uint8ClampedArray', 'Uint16Array', 'Uint32Array', 'WeakMap'
2552 /** Used to make template sourceURLs easier to identify. */
2553 var templateCounter = -1;
2555 /** Used to identify `toStringTag` values of typed arrays. */
2556 var typedArrayTags = {};
2557 typedArrayTags[float32Tag] = typedArrayTags[float64Tag] =
2558 typedArrayTags[int8Tag] = typedArrayTags[int16Tag] =
2559 typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =
2560 typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =
2561 typedArrayTags[uint32Tag] = true;
2562 typedArrayTags[argsTag] = typedArrayTags[arrayTag] =
2563 typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =
2564 typedArrayTags[dateTag] = typedArrayTags[errorTag] =
2565 typedArrayTags[funcTag] = typedArrayTags[mapTag] =
2566 typedArrayTags[numberTag] = typedArrayTags[objectTag] =
2567 typedArrayTags[regexpTag] = typedArrayTags[setTag] =
2568 typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false;
2570 /** Used to identify `toStringTag` values supported by `_.clone`. */
2571 var cloneableTags = {};
2572 cloneableTags[argsTag] = cloneableTags[arrayTag] =
2573 cloneableTags[arrayBufferTag] = cloneableTags[boolTag] =
2574 cloneableTags[dateTag] = cloneableTags[float32Tag] =
2575 cloneableTags[float64Tag] = cloneableTags[int8Tag] =
2576 cloneableTags[int16Tag] = cloneableTags[int32Tag] =
2577 cloneableTags[numberTag] = cloneableTags[objectTag] =
2578 cloneableTags[regexpTag] = cloneableTags[stringTag] =
2579 cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] =
2580 cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true;
2581 cloneableTags[errorTag] = cloneableTags[funcTag] =
2582 cloneableTags[mapTag] = cloneableTags[setTag] =
2583 cloneableTags[weakMapTag] = false;
2585 /** Used to map latin-1 supplementary letters to basic latin letters. */
2586 var deburredLetters = {
2587 '\xc0': 'A', '\xc1': 'A', '\xc2': 'A', '\xc3': 'A', '\xc4': 'A', '\xc5': 'A',
2588 '\xe0': 'a', '\xe1': 'a', '\xe2': 'a', '\xe3': 'a', '\xe4': 'a', '\xe5': 'a',
2589 '\xc7': 'C', '\xe7': 'c',
2590 '\xd0': 'D', '\xf0': 'd',
2591 '\xc8': 'E', '\xc9': 'E', '\xca': 'E', '\xcb': 'E',
2592 '\xe8': 'e', '\xe9': 'e', '\xea': 'e', '\xeb': 'e',
2593 '\xcC': 'I', '\xcd': 'I', '\xce': 'I', '\xcf': 'I',
2594 '\xeC': 'i', '\xed': 'i', '\xee': 'i', '\xef': 'i',
2595 '\xd1': 'N', '\xf1': 'n',
2596 '\xd2': 'O', '\xd3': 'O', '\xd4': 'O', '\xd5': 'O', '\xd6': 'O', '\xd8': 'O',
2597 '\xf2': 'o', '\xf3': 'o', '\xf4': 'o', '\xf5': 'o', '\xf6': 'o', '\xf8': 'o',
2598 '\xd9': 'U', '\xda': 'U', '\xdb': 'U', '\xdc': 'U',
2599 '\xf9': 'u', '\xfa': 'u', '\xfb': 'u', '\xfc': 'u',
2600 '\xdd': 'Y', '\xfd': 'y', '\xff': 'y',
2601 '\xc6': 'Ae', '\xe6': 'ae',
2602 '\xde': 'Th', '\xfe': 'th',
2606 /** Used to map characters to HTML entities. */
2616 /** Used to map HTML entities to characters. */
2617 var htmlUnescapes = {
2626 /** Used to determine if values are of the language type `Object`. */
2632 /** Used to escape characters for inclusion in compiled regexes. */
2633 var regexpEscapes = {
2634 '0': 'x30', '1': 'x31', '2': 'x32', '3': 'x33', '4': 'x34',
2635 '5': 'x35', '6': 'x36', '7': 'x37', '8': 'x38', '9': 'x39',
2636 'A': 'x41', 'B': 'x42', 'C': 'x43', 'D': 'x44', 'E': 'x45', 'F': 'x46',
2637 'a': 'x61', 'b': 'x62', 'c': 'x63', 'd': 'x64', 'e': 'x65', 'f': 'x66',
2638 'n': 'x6e', 'r': 'x72', 't': 'x74', 'u': 'x75', 'v': 'x76', 'x': 'x78'
2641 /** Used to escape characters for inclusion in compiled string literals. */
2642 var stringEscapes = {
2651 /** Detect free variable `exports`. */
2652 var freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports;
2654 /** Detect free variable `module`. */
2655 var freeModule = objectTypes[typeof module] && module && !module.nodeType && module;
2657 /** Detect free variable `global` from Node.js. */
2658 var freeGlobal = freeExports && freeModule && typeof global == 'object' && global && global.Object && global;
2660 /** Detect free variable `self`. */
2661 var freeSelf = objectTypes[typeof self] && self && self.Object && self;
2663 /** Detect free variable `window`. */
2664 var freeWindow = objectTypes[typeof window] && window && window.Object && window;
2666 /** Detect the popular CommonJS extension `module.exports`. */
2667 var moduleExports = freeModule && freeModule.exports === freeExports && freeExports;
2670 * Used as a reference to the global object.
2672 * The `this` value is used if it's the global object to avoid Greasemonkey's
2673 * restricted `window` object, otherwise the `window` object is used.
2675 var root = freeGlobal || ((freeWindow !== (this && this.window)) && freeWindow) || freeSelf || this;
2677 /*--------------------------------------------------------------------------*/
2680 * The base implementation of `compareAscending` which compares values and
2681 * sorts them in ascending order without guaranteeing a stable sort.
2684 * @param {*} value The value to compare.
2685 * @param {*} other The other value to compare.
2686 * @returns {number} Returns the sort order indicator for `value`.
2688 function baseCompareAscending(value, other) {
2689 if (value !== other) {
2690 var valIsNull = value === null,
2691 valIsUndef = value === undefined,
2692 valIsReflexive = value === value;
2694 var othIsNull = other === null,
2695 othIsUndef = other === undefined,
2696 othIsReflexive = other === other;
2698 if ((value > other && !othIsNull) || !valIsReflexive ||
2699 (valIsNull && !othIsUndef && othIsReflexive) ||
2700 (valIsUndef && othIsReflexive)) {
2703 if ((value < other && !valIsNull) || !othIsReflexive ||
2704 (othIsNull && !valIsUndef && valIsReflexive) ||
2705 (othIsUndef && valIsReflexive)) {
2713 * The base implementation of `_.findIndex` and `_.findLastIndex` without
2714 * support for callback shorthands and `this` binding.
2717 * @param {Array} array The array to search.
2718 * @param {Function} predicate The function invoked per iteration.
2719 * @param {boolean} [fromRight] Specify iterating from right to left.
2720 * @returns {number} Returns the index of the matched value, else `-1`.
2722 function baseFindIndex(array, predicate, fromRight) {
2723 var length = array.length,
2724 index = fromRight ? length : -1;
2726 while ((fromRight ? index-- : ++index < length)) {
2727 if (predicate(array[index], index, array)) {
2735 * The base implementation of `_.indexOf` without support for binary searches.
2738 * @param {Array} array The array to search.
2739 * @param {*} value The value to search for.
2740 * @param {number} fromIndex The index to search from.
2741 * @returns {number} Returns the index of the matched value, else `-1`.
2743 function baseIndexOf(array, value, fromIndex) {
2744 if (value !== value) {
2745 return indexOfNaN(array, fromIndex);
2747 var index = fromIndex - 1,
2748 length = array.length;
2750 while (++index < length) {
2751 if (array[index] === value) {
2759 * The base implementation of `_.isFunction` without support for environments
2760 * with incorrect `typeof` results.
2763 * @param {*} value The value to check.
2764 * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
2766 function baseIsFunction(value) {
2767 // Avoid a Chakra JIT bug in compatibility modes of IE 11.
2768 // See https://github.com/jashkenas/underscore/issues/1621 for more details.
2769 return typeof value == 'function' || false;
2773 * Converts `value` to a string if it's not one. An empty string is returned
2774 * for `null` or `undefined` values.
2777 * @param {*} value The value to process.
2778 * @returns {string} Returns the string.
2780 function baseToString(value) {
2781 return value == null ? '' : (value + '');
2785 * Used by `_.trim` and `_.trimLeft` to get the index of the first character
2786 * of `string` that is not found in `chars`.
2789 * @param {string} string The string to inspect.
2790 * @param {string} chars The characters to find.
2791 * @returns {number} Returns the index of the first character not found in `chars`.
2793 function charsLeftIndex(string, chars) {
2795 length = string.length;
2797 while (++index < length && chars.indexOf(string.charAt(index)) > -1) {}
2802 * Used by `_.trim` and `_.trimRight` to get the index of the last character
2803 * of `string` that is not found in `chars`.
2806 * @param {string} string The string to inspect.
2807 * @param {string} chars The characters to find.
2808 * @returns {number} Returns the index of the last character not found in `chars`.
2810 function charsRightIndex(string, chars) {
2811 var index = string.length;
2813 while (index-- && chars.indexOf(string.charAt(index)) > -1) {}
2818 * Used by `_.sortBy` to compare transformed elements of a collection and stable
2819 * sort them in ascending order.
2822 * @param {Object} object The object to compare.
2823 * @param {Object} other The other object to compare.
2824 * @returns {number} Returns the sort order indicator for `object`.
2826 function compareAscending(object, other) {
2827 return baseCompareAscending(object.criteria, other.criteria) || (object.index - other.index);
2831 * Used by `_.sortByOrder` to compare multiple properties of a value to another
2832 * and stable sort them.
2834 * If `orders` is unspecified, all valuess are sorted in ascending order. Otherwise,
2835 * a value is sorted in ascending order if its corresponding order is "asc", and
2836 * descending if "desc".
2839 * @param {Object} object The object to compare.
2840 * @param {Object} other The other object to compare.
2841 * @param {boolean[]} orders The order to sort by for each property.
2842 * @returns {number} Returns the sort order indicator for `object`.
2844 function compareMultiple(object, other, orders) {
2846 objCriteria = object.criteria,
2847 othCriteria = other.criteria,
2848 length = objCriteria.length,
2849 ordersLength = orders.length;
2851 while (++index < length) {
2852 var result = baseCompareAscending(objCriteria[index], othCriteria[index]);
2854 if (index >= ordersLength) {
2857 var order = orders[index];
2858 return result * ((order === 'asc' || order === true) ? 1 : -1);
2861 // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications
2862 // that causes it, under certain circumstances, to provide the same value for
2863 // `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247
2864 // for more details.
2866 // This also ensures a stable sort in V8 and other engines.
2867 // See https://code.google.com/p/v8/issues/detail?id=90 for more details.
2868 return object.index - other.index;
2872 * Used by `_.deburr` to convert latin-1 supplementary letters to basic latin letters.
2875 * @param {string} letter The matched letter to deburr.
2876 * @returns {string} Returns the deburred letter.
2878 function deburrLetter(letter) {
2879 return deburredLetters[letter];
2883 * Used by `_.escape` to convert characters to HTML entities.
2886 * @param {string} chr The matched character to escape.
2887 * @returns {string} Returns the escaped character.
2889 function escapeHtmlChar(chr) {
2890 return htmlEscapes[chr];
2894 * Used by `_.escapeRegExp` to escape characters for inclusion in compiled regexes.
2897 * @param {string} chr The matched character to escape.
2898 * @param {string} leadingChar The capture group for a leading character.
2899 * @param {string} whitespaceChar The capture group for a whitespace character.
2900 * @returns {string} Returns the escaped character.
2902 function escapeRegExpChar(chr, leadingChar, whitespaceChar) {
2904 chr = regexpEscapes[chr];
2905 } else if (whitespaceChar) {
2906 chr = stringEscapes[chr];
2912 * Used by `_.template` to escape characters for inclusion in compiled string literals.
2915 * @param {string} chr The matched character to escape.
2916 * @returns {string} Returns the escaped character.
2918 function escapeStringChar(chr) {
2919 return '\\' + stringEscapes[chr];
2923 * Gets the index at which the first occurrence of `NaN` is found in `array`.
2926 * @param {Array} array The array to search.
2927 * @param {number} fromIndex The index to search from.
2928 * @param {boolean} [fromRight] Specify iterating from right to left.
2929 * @returns {number} Returns the index of the matched `NaN`, else `-1`.
2931 function indexOfNaN(array, fromIndex, fromRight) {
2932 var length = array.length,
2933 index = fromIndex + (fromRight ? 0 : -1);
2935 while ((fromRight ? index-- : ++index < length)) {
2936 var other = array[index];
2937 if (other !== other) {
2945 * Checks if `value` is object-like.
2948 * @param {*} value The value to check.
2949 * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
2951 function isObjectLike(value) {
2952 return !!value && typeof value == 'object';
2956 * Used by `trimmedLeftIndex` and `trimmedRightIndex` to determine if a
2957 * character code is whitespace.
2960 * @param {number} charCode The character code to inspect.
2961 * @returns {boolean} Returns `true` if `charCode` is whitespace, else `false`.
2963 function isSpace(charCode) {
2964 return ((charCode <= 160 && (charCode >= 9 && charCode <= 13) || charCode == 32 || charCode == 160) || charCode == 5760 || charCode == 6158 ||
2965 (charCode >= 8192 && (charCode <= 8202 || charCode == 8232 || charCode == 8233 || charCode == 8239 || charCode == 8287 || charCode == 12288 || charCode == 65279)));
2969 * Replaces all `placeholder` elements in `array` with an internal placeholder
2970 * and returns an array of their indexes.
2973 * @param {Array} array The array to modify.
2974 * @param {*} placeholder The placeholder to replace.
2975 * @returns {Array} Returns the new array of placeholder indexes.
2977 function replaceHolders(array, placeholder) {
2979 length = array.length,
2983 while (++index < length) {
2984 if (array[index] === placeholder) {
2985 array[index] = PLACEHOLDER;
2986 result[++resIndex] = index;
2993 * An implementation of `_.uniq` optimized for sorted arrays without support
2994 * for callback shorthands and `this` binding.
2997 * @param {Array} array The array to inspect.
2998 * @param {Function} [iteratee] The function invoked per iteration.
2999 * @returns {Array} Returns the new duplicate-value-free array.
3001 function sortedUniq(array, iteratee) {
3004 length = array.length,
3008 while (++index < length) {
3009 var value = array[index],
3010 computed = iteratee ? iteratee(value, index, array) : value;
3012 if (!index || seen !== computed) {
3014 result[++resIndex] = value;
3021 * Used by `_.trim` and `_.trimLeft` to get the index of the first non-whitespace
3022 * character of `string`.
3025 * @param {string} string The string to inspect.
3026 * @returns {number} Returns the index of the first non-whitespace character.
3028 function trimmedLeftIndex(string) {
3030 length = string.length;
3032 while (++index < length && isSpace(string.charCodeAt(index))) {}
3037 * Used by `_.trim` and `_.trimRight` to get the index of the last non-whitespace
3038 * character of `string`.
3041 * @param {string} string The string to inspect.
3042 * @returns {number} Returns the index of the last non-whitespace character.
3044 function trimmedRightIndex(string) {
3045 var index = string.length;
3047 while (index-- && isSpace(string.charCodeAt(index))) {}
3052 * Used by `_.unescape` to convert HTML entities to characters.
3055 * @param {string} chr The matched character to unescape.
3056 * @returns {string} Returns the unescaped character.
3058 function unescapeHtmlChar(chr) {
3059 return htmlUnescapes[chr];
3062 /*--------------------------------------------------------------------------*/
3065 * Create a new pristine `lodash` function using the given `context` object.
3070 * @param {Object} [context=root] The context object.
3071 * @returns {Function} Returns a new `lodash` function.
3074 * _.mixin({ 'foo': _.constant('foo') });
3076 * var lodash = _.runInContext();
3077 * lodash.mixin({ 'bar': lodash.constant('bar') });
3079 * _.isFunction(_.foo);
3081 * _.isFunction(_.bar);
3084 * lodash.isFunction(lodash.foo);
3086 * lodash.isFunction(lodash.bar);
3089 * // using `context` to mock `Date#getTime` use in `_.now`
3090 * var mock = _.runInContext({
3091 * 'Date': function() {
3092 * return { 'getTime': getTimeMock };
3096 * // or creating a suped-up `defer` in Node.js
3097 * var defer = _.runInContext({ 'setTimeout': setImmediate }).defer;
3099 function runInContext(context) {
3100 // Avoid issues with some ES3 environments that attempt to use values, named
3101 // after built-in constructors like `Object`, for the creation of literals.
3102 // ES5 clears this up by stating that literals must use built-in constructors.
3103 // See https://es5.github.io/#x11.1.5 for more details.
3104 context = context ? _.defaults(root.Object(), context, _.pick(root, contextProps)) : root;
3106 /** Native constructor references. */
3107 var Array = context.Array,
3108 Date = context.Date,
3109 Error = context.Error,
3110 Function = context.Function,
3111 Math = context.Math,
3112 Number = context.Number,
3113 Object = context.Object,
3114 RegExp = context.RegExp,
3115 String = context.String,
3116 TypeError = context.TypeError;
3118 /** Used for native method references. */
3119 var arrayProto = Array.prototype,
3120 objectProto = Object.prototype,
3121 stringProto = String.prototype;
3123 /** Used to resolve the decompiled source of functions. */
3124 var fnToString = Function.prototype.toString;
3126 /** Used to check objects for own properties. */
3127 var hasOwnProperty = objectProto.hasOwnProperty;
3129 /** Used to generate unique IDs. */
3133 * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
3136 var objToString = objectProto.toString;
3138 /** Used to restore the original `_` reference in `_.noConflict`. */
3139 var oldDash = root._;
3141 /** Used to detect if a method is native. */
3142 var reIsNative = RegExp('^' +
3143 fnToString.call(hasOwnProperty).replace(/[\\^$.*+?()[\]{}|]/g, '\\$&')
3144 .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
3147 /** Native method references. */
3148 var ArrayBuffer = context.ArrayBuffer,
3149 clearTimeout = context.clearTimeout,
3150 parseFloat = context.parseFloat,
3152 propertyIsEnumerable = objectProto.propertyIsEnumerable,
3153 Set = getNative(context, 'Set'),
3154 setTimeout = context.setTimeout,
3155 splice = arrayProto.splice,
3156 Uint8Array = context.Uint8Array,
3157 WeakMap = getNative(context, 'WeakMap');
3159 /* Native method references for those with the same name as other `lodash` methods. */
3160 var nativeCeil = Math.ceil,
3161 nativeCreate = getNative(Object, 'create'),
3162 nativeFloor = Math.floor,
3163 nativeIsArray = getNative(Array, 'isArray'),
3164 nativeIsFinite = context.isFinite,
3165 nativeKeys = getNative(Object, 'keys'),
3166 nativeMax = Math.max,
3167 nativeMin = Math.min,
3168 nativeNow = getNative(Date, 'now'),
3169 nativeParseInt = context.parseInt,
3170 nativeRandom = Math.random;
3172 /** Used as references for `-Infinity` and `Infinity`. */
3173 var NEGATIVE_INFINITY = Number.NEGATIVE_INFINITY,
3174 POSITIVE_INFINITY = Number.POSITIVE_INFINITY;
3176 /** Used as references for the maximum length and index of an array. */
3177 var MAX_ARRAY_LENGTH = 4294967295,
3178 MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1,
3179 HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH >>> 1;
3182 * Used as the [maximum length](http://ecma-international.org/ecma-262/6.0/#sec-number.max_safe_integer)
3183 * of an array-like value.
3185 var MAX_SAFE_INTEGER = 9007199254740991;
3187 /** Used to store function metadata. */
3188 var metaMap = WeakMap && new WeakMap;
3190 /** Used to lookup unminified function names. */
3193 /*------------------------------------------------------------------------*/
3196 * Creates a `lodash` object which wraps `value` to enable implicit chaining.
3197 * Methods that operate on and return arrays, collections, and functions can
3198 * be chained together. Methods that retrieve a single value or may return a
3199 * primitive value will automatically end the chain returning the unwrapped
3200 * value. Explicit chaining may be enabled using `_.chain`. The execution of
3201 * chained methods is lazy, that is, execution is deferred until `_#value`
3202 * is implicitly or explicitly called.
3204 * Lazy evaluation allows several methods to support shortcut fusion. Shortcut
3205 * fusion is an optimization strategy which merge iteratee calls; this can help
3206 * to avoid the creation of intermediate data structures and greatly reduce the
3207 * number of iteratee executions.
3209 * Chaining is supported in custom builds as long as the `_#value` method is
3210 * directly or indirectly included in the build.
3212 * In addition to lodash methods, wrappers have `Array` and `String` methods.
3214 * The wrapper `Array` methods are:
3215 * `concat`, `join`, `pop`, `push`, `reverse`, `shift`, `slice`, `sort`,
3216 * `splice`, and `unshift`
3218 * The wrapper `String` methods are:
3219 * `replace` and `split`
3221 * The wrapper methods that support shortcut fusion are:
3222 * `compact`, `drop`, `dropRight`, `dropRightWhile`, `dropWhile`, `filter`,
3223 * `first`, `initial`, `last`, `map`, `pluck`, `reject`, `rest`, `reverse`,
3224 * `slice`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, `toArray`,
3227 * The chainable wrapper methods are:
3228 * `after`, `ary`, `assign`, `at`, `before`, `bind`, `bindAll`, `bindKey`,
3229 * `callback`, `chain`, `chunk`, `commit`, `compact`, `concat`, `constant`,
3230 * `countBy`, `create`, `curry`, `debounce`, `defaults`, `defaultsDeep`,
3231 * `defer`, `delay`, `difference`, `drop`, `dropRight`, `dropRightWhile`,
3232 * `dropWhile`, `fill`, `filter`, `flatten`, `flattenDeep`, `flow`, `flowRight`,
3233 * `forEach`, `forEachRight`, `forIn`, `forInRight`, `forOwn`, `forOwnRight`,
3234 * `functions`, `groupBy`, `indexBy`, `initial`, `intersection`, `invert`,
3235 * `invoke`, `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`,
3236 * `matchesProperty`, `memoize`, `merge`, `method`, `methodOf`, `mixin`,
3237 * `modArgs`, `negate`, `omit`, `once`, `pairs`, `partial`, `partialRight`,
3238 * `partition`, `pick`, `plant`, `pluck`, `property`, `propertyOf`, `pull`,
3239 * `pullAt`, `push`, `range`, `rearg`, `reject`, `remove`, `rest`, `restParam`,
3240 * `reverse`, `set`, `shuffle`, `slice`, `sort`, `sortBy`, `sortByAll`,
3241 * `sortByOrder`, `splice`, `spread`, `take`, `takeRight`, `takeRightWhile`,
3242 * `takeWhile`, `tap`, `throttle`, `thru`, `times`, `toArray`, `toPlainObject`,
3243 * `transform`, `union`, `uniq`, `unshift`, `unzip`, `unzipWith`, `values`,
3244 * `valuesIn`, `where`, `without`, `wrap`, `xor`, `zip`, `zipObject`, `zipWith`
3246 * The wrapper methods that are **not** chainable by default are:
3247 * `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clone`, `cloneDeep`,
3248 * `deburr`, `endsWith`, `escape`, `escapeRegExp`, `every`, `find`, `findIndex`,
3249 * `findKey`, `findLast`, `findLastIndex`, `findLastKey`, `findWhere`, `first`,
3250 * `floor`, `get`, `gt`, `gte`, `has`, `identity`, `includes`, `indexOf`,
3251 * `inRange`, `isArguments`, `isArray`, `isBoolean`, `isDate`, `isElement`,
3252 * `isEmpty`, `isEqual`, `isError`, `isFinite` `isFunction`, `isMatch`,
3253 * `isNative`, `isNaN`, `isNull`, `isNumber`, `isObject`, `isPlainObject`,
3254 * `isRegExp`, `isString`, `isUndefined`, `isTypedArray`, `join`, `kebabCase`,
3255 * `last`, `lastIndexOf`, `lt`, `lte`, `max`, `min`, `noConflict`, `noop`,
3256 * `now`, `pad`, `padLeft`, `padRight`, `parseInt`, `pop`, `random`, `reduce`,
3257 * `reduceRight`, `repeat`, `result`, `round`, `runInContext`, `shift`, `size`,
3258 * `snakeCase`, `some`, `sortedIndex`, `sortedLastIndex`, `startCase`,
3259 * `startsWith`, `sum`, `template`, `trim`, `trimLeft`, `trimRight`, `trunc`,
3260 * `unescape`, `uniqueId`, `value`, and `words`
3262 * The wrapper method `sample` will return a wrapped value when `n` is provided,
3263 * otherwise an unwrapped value is returned.
3268 * @param {*} value The value to wrap in a `lodash` instance.
3269 * @returns {Object} Returns the new `lodash` wrapper instance.
3272 * var wrapped = _([1, 2, 3]);
3274 * // returns an unwrapped value
3275 * wrapped.reduce(function(total, n) {
3280 * // returns a wrapped value
3281 * var squares = wrapped.map(function(n) {
3285 * _.isArray(squares);
3288 * _.isArray(squares.value());
3291 function lodash(value) {
3292 if (isObjectLike(value) && !isArray(value) && !(value instanceof LazyWrapper)) {
3293 if (value instanceof LodashWrapper) {
3296 if (hasOwnProperty.call(value, '__chain__') && hasOwnProperty.call(value, '__wrapped__')) {
3297 return wrapperClone(value);
3300 return new LodashWrapper(value);
3304 * The function whose prototype all chaining wrappers inherit from.
3308 function baseLodash() {
3309 // No operation performed.
3313 * The base constructor for creating `lodash` wrapper objects.
3316 * @param {*} value The value to wrap.
3317 * @param {boolean} [chainAll] Enable chaining for all wrapper methods.
3318 * @param {Array} [actions=[]] Actions to peform to resolve the unwrapped value.
3320 function LodashWrapper(value, chainAll, actions) {
3321 this.__wrapped__ = value;
3322 this.__actions__ = actions || [];
3323 this.__chain__ = !!chainAll;
3327 * An object environment feature flags.
3333 var support = lodash.support = {};
3336 * By default, the template delimiters used by lodash are like those in
3337 * embedded Ruby (ERB). Change the following template settings to use
3338 * alternative delimiters.
3344 lodash.templateSettings = {
3347 * Used to detect `data` property values to be HTML-escaped.
3349 * @memberOf _.templateSettings
3355 * Used to detect code to be evaluated.
3357 * @memberOf _.templateSettings
3360 'evaluate': reEvaluate,
3363 * Used to detect `data` property values to inject.
3365 * @memberOf _.templateSettings
3368 'interpolate': reInterpolate,
3371 * Used to reference the data object in the template text.
3373 * @memberOf _.templateSettings
3379 * Used to import variables into the compiled template.
3381 * @memberOf _.templateSettings
3387 * A reference to the `lodash` function.
3389 * @memberOf _.templateSettings.imports
3396 /*------------------------------------------------------------------------*/
3399 * Creates a lazy wrapper object which wraps `value` to enable lazy evaluation.
3402 * @param {*} value The value to wrap.
3404 function LazyWrapper(value) {
3405 this.__wrapped__ = value;
3406 this.__actions__ = [];
3408 this.__filtered__ = false;
3409 this.__iteratees__ = [];
3410 this.__takeCount__ = POSITIVE_INFINITY;
3411 this.__views__ = [];
3415 * Creates a clone of the lazy wrapper object.
3419 * @memberOf LazyWrapper
3420 * @returns {Object} Returns the cloned `LazyWrapper` object.
3422 function lazyClone() {
3423 var result = new LazyWrapper(this.__wrapped__);
3424 result.__actions__ = arrayCopy(this.__actions__);
3425 result.__dir__ = this.__dir__;
3426 result.__filtered__ = this.__filtered__;
3427 result.__iteratees__ = arrayCopy(this.__iteratees__);
3428 result.__takeCount__ = this.__takeCount__;
3429 result.__views__ = arrayCopy(this.__views__);
3434 * Reverses the direction of lazy iteration.
3438 * @memberOf LazyWrapper
3439 * @returns {Object} Returns the new reversed `LazyWrapper` object.
3441 function lazyReverse() {
3442 if (this.__filtered__) {
3443 var result = new LazyWrapper(this);
3444 result.__dir__ = -1;
3445 result.__filtered__ = true;
3447 result = this.clone();
3448 result.__dir__ *= -1;
3454 * Extracts the unwrapped value from its lazy wrapper.
3458 * @memberOf LazyWrapper
3459 * @returns {*} Returns the unwrapped value.
3461 function lazyValue() {
3462 var array = this.__wrapped__.value(),
3464 isArr = isArray(array),
3466 arrLength = isArr ? array.length : 0,
3467 view = getView(0, arrLength, this.__views__),
3470 length = end - start,
3471 index = isRight ? end : (start - 1),
3472 iteratees = this.__iteratees__,
3473 iterLength = iteratees.length,
3475 takeCount = nativeMin(length, this.__takeCount__);
3477 if (!isArr || arrLength < LARGE_ARRAY_SIZE || (arrLength == length && takeCount == length)) {
3478 return baseWrapperValue((isRight && isArr) ? array.reverse() : array, this.__actions__);
3483 while (length-- && resIndex < takeCount) {
3487 value = array[index];
3489 while (++iterIndex < iterLength) {
3490 var data = iteratees[iterIndex],
3491 iteratee = data.iteratee,
3493 computed = iteratee(value);
3495 if (type == LAZY_MAP_FLAG) {
3497 } else if (!computed) {
3498 if (type == LAZY_FILTER_FLAG) {
3505 result[resIndex++] = value;
3510 /*------------------------------------------------------------------------*/
3513 * Creates a cache object to store key/value pairs.
3518 * @memberOf _.memoize
3520 function MapCache() {
3525 * Removes `key` and its value from the cache.
3529 * @memberOf _.memoize.Cache
3530 * @param {string} key The key of the value to remove.
3531 * @returns {boolean} Returns `true` if the entry was removed successfully, else `false`.
3533 function mapDelete(key) {
3534 return this.has(key) && delete this.__data__[key];
3538 * Gets the cached value for `key`.
3542 * @memberOf _.memoize.Cache
3543 * @param {string} key The key of the value to get.
3544 * @returns {*} Returns the cached value.
3546 function mapGet(key) {
3547 return key == '__proto__' ? undefined : this.__data__[key];
3551 * Checks if a cached value for `key` exists.
3555 * @memberOf _.memoize.Cache
3556 * @param {string} key The key of the entry to check.
3557 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
3559 function mapHas(key) {
3560 return key != '__proto__' && hasOwnProperty.call(this.__data__, key);
3564 * Sets `value` to `key` of the cache.
3568 * @memberOf _.memoize.Cache
3569 * @param {string} key The key of the value to cache.
3570 * @param {*} value The value to cache.
3571 * @returns {Object} Returns the cache object.
3573 function mapSet(key, value) {
3574 if (key != '__proto__') {
3575 this.__data__[key] = value;
3580 /*------------------------------------------------------------------------*/
3584 * Creates a cache object to store unique values.
3587 * @param {Array} [values] The values to cache.
3589 function SetCache(values) {
3590 var length = values ? values.length : 0;
3592 this.data = { 'hash': nativeCreate(null), 'set': new Set };
3594 this.push(values[length]);
3599 * Checks if `value` is in `cache` mimicking the return signature of
3600 * `_.indexOf` by returning `0` if the value is found, else `-1`.
3603 * @param {Object} cache The cache to search.
3604 * @param {*} value The value to search for.
3605 * @returns {number} Returns `0` if `value` is found, else `-1`.
3607 function cacheIndexOf(cache, value) {
3608 var data = cache.data,
3609 result = (typeof value == 'string' || isObject(value)) ? data.set.has(value) : data.hash[value];
3611 return result ? 0 : -1;
3615 * Adds `value` to the cache.
3619 * @memberOf SetCache
3620 * @param {*} value The value to cache.
3622 function cachePush(value) {
3623 var data = this.data;
3624 if (typeof value == 'string' || isObject(value)) {
3625 data.set.add(value);
3627 data.hash[value] = true;
3631 /*------------------------------------------------------------------------*/
3634 * Creates a new array joining `array` with `other`.
3637 * @param {Array} array The array to join.
3638 * @param {Array} other The other array to join.
3639 * @returns {Array} Returns the new concatenated array.
3641 function arrayConcat(array, other) {
3643 length = array.length,
3645 othLength = other.length,
3646 result = Array(length + othLength);
3648 while (++index < length) {
3649 result[index] = array[index];
3651 while (++othIndex < othLength) {
3652 result[index++] = other[othIndex];
3658 * Copies the values of `source` to `array`.
3661 * @param {Array} source The array to copy values from.
3662 * @param {Array} [array=[]] The array to copy values to.
3663 * @returns {Array} Returns `array`.
3665 function arrayCopy(source, array) {
3667 length = source.length;
3669 array || (array = Array(length));
3670 while (++index < length) {
3671 array[index] = source[index];
3677 * A specialized version of `_.forEach` for arrays without support for callback
3678 * shorthands and `this` binding.
3681 * @param {Array} array The array to iterate over.
3682 * @param {Function} iteratee The function invoked per iteration.
3683 * @returns {Array} Returns `array`.
3685 function arrayEach(array, iteratee) {
3687 length = array.length;
3689 while (++index < length) {
3690 if (iteratee(array[index], index, array) === false) {
3698 * A specialized version of `_.forEachRight` for arrays without support for
3699 * callback shorthands and `this` binding.
3702 * @param {Array} array The array to iterate over.
3703 * @param {Function} iteratee The function invoked per iteration.
3704 * @returns {Array} Returns `array`.
3706 function arrayEachRight(array, iteratee) {
3707 var length = array.length;
3710 if (iteratee(array[length], length, array) === false) {
3718 * A specialized version of `_.every` for arrays without support for callback
3719 * shorthands and `this` binding.
3722 * @param {Array} array The array to iterate over.
3723 * @param {Function} predicate The function invoked per iteration.
3724 * @returns {boolean} Returns `true` if all elements pass the predicate check,
3727 function arrayEvery(array, predicate) {
3729 length = array.length;
3731 while (++index < length) {
3732 if (!predicate(array[index], index, array)) {
3740 * A specialized version of `baseExtremum` for arrays which invokes `iteratee`
3741 * with one argument: (value).
3744 * @param {Array} array The array to iterate over.
3745 * @param {Function} iteratee The function invoked per iteration.
3746 * @param {Function} comparator The function used to compare values.
3747 * @param {*} exValue The initial extremum value.
3748 * @returns {*} Returns the extremum value.
3750 function arrayExtremum(array, iteratee, comparator, exValue) {
3752 length = array.length,
3756 while (++index < length) {
3757 var value = array[index],
3758 current = +iteratee(value);
3760 if (comparator(current, computed)) {
3769 * A specialized version of `_.filter` for arrays without support for callback
3770 * shorthands and `this` binding.
3773 * @param {Array} array The array to iterate over.
3774 * @param {Function} predicate The function invoked per iteration.
3775 * @returns {Array} Returns the new filtered array.
3777 function arrayFilter(array, predicate) {
3779 length = array.length,
3783 while (++index < length) {
3784 var value = array[index];
3785 if (predicate(value, index, array)) {
3786 result[++resIndex] = value;
3793 * A specialized version of `_.map` for arrays without support for callback
3794 * shorthands and `this` binding.
3797 * @param {Array} array The array to iterate over.
3798 * @param {Function} iteratee The function invoked per iteration.
3799 * @returns {Array} Returns the new mapped array.
3801 function arrayMap(array, iteratee) {
3803 length = array.length,
3804 result = Array(length);
3806 while (++index < length) {
3807 result[index] = iteratee(array[index], index, array);
3813 * Appends the elements of `values` to `array`.
3816 * @param {Array} array The array to modify.
3817 * @param {Array} values The values to append.
3818 * @returns {Array} Returns `array`.
3820 function arrayPush(array, values) {
3822 length = values.length,
3823 offset = array.length;
3825 while (++index < length) {
3826 array[offset + index] = values[index];
3832 * A specialized version of `_.reduce` for arrays without support for callback
3833 * shorthands and `this` binding.
3836 * @param {Array} array The array to iterate over.
3837 * @param {Function} iteratee The function invoked per iteration.
3838 * @param {*} [accumulator] The initial value.
3839 * @param {boolean} [initFromArray] Specify using the first element of `array`
3840 * as the initial value.
3841 * @returns {*} Returns the accumulated value.
3843 function arrayReduce(array, iteratee, accumulator, initFromArray) {
3845 length = array.length;
3847 if (initFromArray && length) {
3848 accumulator = array[++index];
3850 while (++index < length) {
3851 accumulator = iteratee(accumulator, array[index], index, array);
3857 * A specialized version of `_.reduceRight` for arrays without support for
3858 * callback shorthands and `this` binding.
3861 * @param {Array} array The array to iterate over.
3862 * @param {Function} iteratee The function invoked per iteration.
3863 * @param {*} [accumulator] The initial value.
3864 * @param {boolean} [initFromArray] Specify using the last element of `array`
3865 * as the initial value.
3866 * @returns {*} Returns the accumulated value.
3868 function arrayReduceRight(array, iteratee, accumulator, initFromArray) {
3869 var length = array.length;
3870 if (initFromArray && length) {
3871 accumulator = array[--length];
3874 accumulator = iteratee(accumulator, array[length], length, array);
3880 * A specialized version of `_.some` for arrays without support for callback
3881 * shorthands and `this` binding.
3884 * @param {Array} array The array to iterate over.
3885 * @param {Function} predicate The function invoked per iteration.
3886 * @returns {boolean} Returns `true` if any element passes the predicate check,
3889 function arraySome(array, predicate) {
3891 length = array.length;
3893 while (++index < length) {
3894 if (predicate(array[index], index, array)) {
3902 * A specialized version of `_.sum` for arrays without support for callback
3903 * shorthands and `this` binding..
3906 * @param {Array} array The array to iterate over.
3907 * @param {Function} iteratee The function invoked per iteration.
3908 * @returns {number} Returns the sum.
3910 function arraySum(array, iteratee) {
3911 var length = array.length,
3915 result += +iteratee(array[length]) || 0;
3921 * Used by `_.defaults` to customize its `_.assign` use.
3924 * @param {*} objectValue The destination object property value.
3925 * @param {*} sourceValue The source object property value.
3926 * @returns {*} Returns the value to assign to the destination object.
3928 function assignDefaults(objectValue, sourceValue) {
3929 return objectValue === undefined ? sourceValue : objectValue;
3933 * Used by `_.template` to customize its `_.assign` use.
3935 * **Note:** This function is like `assignDefaults` except that it ignores
3936 * inherited property values when checking if a property is `undefined`.
3939 * @param {*} objectValue The destination object property value.
3940 * @param {*} sourceValue The source object property value.
3941 * @param {string} key The key associated with the object and source values.
3942 * @param {Object} object The destination object.
3943 * @returns {*} Returns the value to assign to the destination object.
3945 function assignOwnDefaults(objectValue, sourceValue, key, object) {
3946 return (objectValue === undefined || !hasOwnProperty.call(object, key))
3952 * A specialized version of `_.assign` for customizing assigned values without
3953 * support for argument juggling, multiple sources, and `this` binding `customizer`
3957 * @param {Object} object The destination object.
3958 * @param {Object} source The source object.
3959 * @param {Function} customizer The function to customize assigned values.
3960 * @returns {Object} Returns `object`.
3962 function assignWith(object, source, customizer) {
3964 props = keys(source),
3965 length = props.length;
3967 while (++index < length) {
3968 var key = props[index],
3969 value = object[key],
3970 result = customizer(value, source[key], key, object, source);
3972 if ((result === result ? (result !== value) : (value === value)) ||
3973 (value === undefined && !(key in object))) {
3974 object[key] = result;
3981 * The base implementation of `_.assign` without support for argument juggling,
3982 * multiple sources, and `customizer` functions.
3985 * @param {Object} object The destination object.
3986 * @param {Object} source The source object.
3987 * @returns {Object} Returns `object`.
3989 function baseAssign(object, source) {
3990 return source == null
3992 : baseCopy(source, keys(source), object);
3996 * The base implementation of `_.at` without support for string collections
3997 * and individual key arguments.
4000 * @param {Array|Object} collection The collection to iterate over.
4001 * @param {number[]|string[]} props The property names or indexes of elements to pick.
4002 * @returns {Array} Returns the new array of picked elements.
4004 function baseAt(collection, props) {
4006 isNil = collection == null,
4007 isArr = !isNil && isArrayLike(collection),
4008 length = isArr ? collection.length : 0,
4009 propsLength = props.length,
4010 result = Array(propsLength);
4012 while(++index < propsLength) {
4013 var key = props[index];
4015 result[index] = isIndex(key, length) ? collection[key] : undefined;
4017 result[index] = isNil ? undefined : collection[key];
4024 * Copies properties of `source` to `object`.
4027 * @param {Object} source The object to copy properties from.
4028 * @param {Array} props The property names to copy.
4029 * @param {Object} [object={}] The object to copy properties to.
4030 * @returns {Object} Returns `object`.
4032 function baseCopy(source, props, object) {
4033 object || (object = {});
4036 length = props.length;
4038 while (++index < length) {
4039 var key = props[index];
4040 object[key] = source[key];
4046 * The base implementation of `_.callback` which supports specifying the
4047 * number of arguments to provide to `func`.
4050 * @param {*} [func=_.identity] The value to convert to a callback.
4051 * @param {*} [thisArg] The `this` binding of `func`.
4052 * @param {number} [argCount] The number of arguments to provide to `func`.
4053 * @returns {Function} Returns the callback.
4055 function baseCallback(func, thisArg, argCount) {
4056 var type = typeof func;
4057 if (type == 'function') {
4058 return thisArg === undefined
4060 : bindCallback(func, thisArg, argCount);
4065 if (type == 'object') {
4066 return baseMatches(func);
4068 return thisArg === undefined
4070 : baseMatchesProperty(func, thisArg);
4074 * The base implementation of `_.clone` without support for argument juggling
4075 * and `this` binding `customizer` functions.
4078 * @param {*} value The value to clone.
4079 * @param {boolean} [isDeep] Specify a deep clone.
4080 * @param {Function} [customizer] The function to customize cloning values.
4081 * @param {string} [key] The key of `value`.
4082 * @param {Object} [object] The object `value` belongs to.
4083 * @param {Array} [stackA=[]] Tracks traversed source objects.
4084 * @param {Array} [stackB=[]] Associates clones with source counterparts.
4085 * @returns {*} Returns the cloned value.
4087 function baseClone(value, isDeep, customizer, key, object, stackA, stackB) {
4090 result = object ? customizer(value, key, object) : customizer(value);
4092 if (result !== undefined) {
4095 if (!isObject(value)) {
4098 var isArr = isArray(value);
4100 result = initCloneArray(value);
4102 return arrayCopy(value, result);
4105 var tag = objToString.call(value),
4106 isFunc = tag == funcTag;
4108 if (tag == objectTag || tag == argsTag || (isFunc && !object)) {
4109 result = initCloneObject(isFunc ? {} : value);
4111 return baseAssign(result, value);
4114 return cloneableTags[tag]
4115 ? initCloneByTag(value, tag, isDeep)
4116 : (object ? value : {});
4119 // Check for circular references and return its corresponding clone.
4120 stackA || (stackA = []);
4121 stackB || (stackB = []);
4123 var length = stackA.length;
4125 if (stackA[length] == value) {
4126 return stackB[length];
4129 // Add the source value to the stack of traversed objects and associate it with its clone.
4131 stackB.push(result);
4133 // Recursively populate clone (susceptible to call stack limits).
4134 (isArr ? arrayEach : baseForOwn)(value, function(subValue, key) {
4135 result[key] = baseClone(subValue, isDeep, customizer, key, value, stackA, stackB);
4141 * The base implementation of `_.create` without support for assigning
4142 * properties to the created object.
4145 * @param {Object} prototype The object to inherit from.
4146 * @returns {Object} Returns the new object.
4148 var baseCreate = (function() {
4149 function object() {}
4150 return function(prototype) {
4151 if (isObject(prototype)) {
4152 object.prototype = prototype;
4153 var result = new object;
4154 object.prototype = undefined;
4156 return result || {};
4161 * The base implementation of `_.delay` and `_.defer` which accepts an index
4162 * of where to slice the arguments to provide to `func`.
4165 * @param {Function} func The function to delay.
4166 * @param {number} wait The number of milliseconds to delay invocation.
4167 * @param {Object} args The arguments provide to `func`.
4168 * @returns {number} Returns the timer id.
4170 function baseDelay(func, wait, args) {
4171 if (typeof func != 'function') {
4172 throw new TypeError(FUNC_ERROR_TEXT);
4174 return setTimeout(function() { func.apply(undefined, args); }, wait);
4178 * The base implementation of `_.difference` which accepts a single array
4179 * of values to exclude.
4182 * @param {Array} array The array to inspect.
4183 * @param {Array} values The values to exclude.
4184 * @returns {Array} Returns the new array of filtered values.
4186 function baseDifference(array, values) {
4187 var length = array ? array.length : 0,
4194 indexOf = getIndexOf(),
4195 isCommon = indexOf == baseIndexOf,
4196 cache = (isCommon && values.length >= LARGE_ARRAY_SIZE) ? createCache(values) : null,
4197 valuesLength = values.length;
4200 indexOf = cacheIndexOf;
4205 while (++index < length) {
4206 var value = array[index];
4208 if (isCommon && value === value) {
4209 var valuesIndex = valuesLength;
4210 while (valuesIndex--) {
4211 if (values[valuesIndex] === value) {
4217 else if (indexOf(values, value, 0) < 0) {
4225 * The base implementation of `_.forEach` without support for callback
4226 * shorthands and `this` binding.
4229 * @param {Array|Object|string} collection The collection to iterate over.
4230 * @param {Function} iteratee The function invoked per iteration.
4231 * @returns {Array|Object|string} Returns `collection`.
4233 var baseEach = createBaseEach(baseForOwn);
4236 * The base implementation of `_.forEachRight` without support for callback
4237 * shorthands and `this` binding.
4240 * @param {Array|Object|string} collection The collection to iterate over.
4241 * @param {Function} iteratee The function invoked per iteration.
4242 * @returns {Array|Object|string} Returns `collection`.
4244 var baseEachRight = createBaseEach(baseForOwnRight, true);
4247 * The base implementation of `_.every` without support for callback
4248 * shorthands and `this` binding.
4251 * @param {Array|Object|string} collection The collection to iterate over.
4252 * @param {Function} predicate The function invoked per iteration.
4253 * @returns {boolean} Returns `true` if all elements pass the predicate check,
4256 function baseEvery(collection, predicate) {
4258 baseEach(collection, function(value, index, collection) {
4259 result = !!predicate(value, index, collection);
4266 * Gets the extremum value of `collection` invoking `iteratee` for each value
4267 * in `collection` to generate the criterion by which the value is ranked.
4268 * The `iteratee` is invoked with three arguments: (value, index|key, collection).
4271 * @param {Array|Object|string} collection The collection to iterate over.
4272 * @param {Function} iteratee The function invoked per iteration.
4273 * @param {Function} comparator The function used to compare values.
4274 * @param {*} exValue The initial extremum value.
4275 * @returns {*} Returns the extremum value.
4277 function baseExtremum(collection, iteratee, comparator, exValue) {
4278 var computed = exValue,
4281 baseEach(collection, function(value, index, collection) {
4282 var current = +iteratee(value, index, collection);
4283 if (comparator(current, computed) || (current === exValue && current === result)) {
4292 * The base implementation of `_.fill` without an iteratee call guard.
4295 * @param {Array} array The array to fill.
4296 * @param {*} value The value to fill `array` with.
4297 * @param {number} [start=0] The start position.
4298 * @param {number} [end=array.length] The end position.
4299 * @returns {Array} Returns `array`.
4301 function baseFill(array, value, start, end) {
4302 var length = array.length;
4304 start = start == null ? 0 : (+start || 0);
4306 start = -start > length ? 0 : (length + start);
4308 end = (end === undefined || end > length) ? length : (+end || 0);
4312 length = start > end ? 0 : (end >>> 0);
4315 while (start < length) {
4316 array[start++] = value;
4322 * The base implementation of `_.filter` without support for callback
4323 * shorthands and `this` binding.
4326 * @param {Array|Object|string} collection The collection to iterate over.
4327 * @param {Function} predicate The function invoked per iteration.
4328 * @returns {Array} Returns the new filtered array.
4330 function baseFilter(collection, predicate) {
4332 baseEach(collection, function(value, index, collection) {
4333 if (predicate(value, index, collection)) {
4341 * The base implementation of `_.find`, `_.findLast`, `_.findKey`, and `_.findLastKey`,
4342 * without support for callback shorthands and `this` binding, which iterates
4343 * over `collection` using the provided `eachFunc`.
4346 * @param {Array|Object|string} collection The collection to search.
4347 * @param {Function} predicate The function invoked per iteration.
4348 * @param {Function} eachFunc The function to iterate over `collection`.
4349 * @param {boolean} [retKey] Specify returning the key of the found element
4350 * instead of the element itself.
4351 * @returns {*} Returns the found element or its key, else `undefined`.
4353 function baseFind(collection, predicate, eachFunc, retKey) {
4355 eachFunc(collection, function(value, key, collection) {
4356 if (predicate(value, key, collection)) {
4357 result = retKey ? key : value;
4365 * The base implementation of `_.flatten` with added support for restricting
4366 * flattening and specifying the start index.
4369 * @param {Array} array The array to flatten.
4370 * @param {boolean} [isDeep] Specify a deep flatten.
4371 * @param {boolean} [isStrict] Restrict flattening to arrays-like objects.
4372 * @param {Array} [result=[]] The initial result value.
4373 * @returns {Array} Returns the new flattened array.
4375 function baseFlatten(array, isDeep, isStrict, result) {
4376 result || (result = []);
4379 length = array.length;
4381 while (++index < length) {
4382 var value = array[index];
4383 if (isObjectLike(value) && isArrayLike(value) &&
4384 (isStrict || isArray(value) || isArguments(value))) {
4386 // Recursively flatten arrays (susceptible to call stack limits).
4387 baseFlatten(value, isDeep, isStrict, result);
4389 arrayPush(result, value);
4391 } else if (!isStrict) {
4392 result[result.length] = value;
4399 * The base implementation of `baseForIn` and `baseForOwn` which iterates
4400 * over `object` properties returned by `keysFunc` invoking `iteratee` for
4401 * each property. Iteratee functions may exit iteration early by explicitly
4402 * returning `false`.
4405 * @param {Object} object The object to iterate over.
4406 * @param {Function} iteratee The function invoked per iteration.
4407 * @param {Function} keysFunc The function to get the keys of `object`.
4408 * @returns {Object} Returns `object`.
4410 var baseFor = createBaseFor();
4413 * This function is like `baseFor` except that it iterates over properties
4414 * in the opposite order.
4417 * @param {Object} object The object to iterate over.
4418 * @param {Function} iteratee The function invoked per iteration.
4419 * @param {Function} keysFunc The function to get the keys of `object`.
4420 * @returns {Object} Returns `object`.
4422 var baseForRight = createBaseFor(true);
4425 * The base implementation of `_.forIn` without support for callback
4426 * shorthands and `this` binding.
4429 * @param {Object} object The object to iterate over.
4430 * @param {Function} iteratee The function invoked per iteration.
4431 * @returns {Object} Returns `object`.
4433 function baseForIn(object, iteratee) {
4434 return baseFor(object, iteratee, keysIn);
4438 * The base implementation of `_.forOwn` without support for callback
4439 * shorthands and `this` binding.
4442 * @param {Object} object The object to iterate over.
4443 * @param {Function} iteratee The function invoked per iteration.
4444 * @returns {Object} Returns `object`.
4446 function baseForOwn(object, iteratee) {
4447 return baseFor(object, iteratee, keys);
4451 * The base implementation of `_.forOwnRight` without support for callback
4452 * shorthands and `this` binding.
4455 * @param {Object} object The object to iterate over.
4456 * @param {Function} iteratee The function invoked per iteration.
4457 * @returns {Object} Returns `object`.
4459 function baseForOwnRight(object, iteratee) {
4460 return baseForRight(object, iteratee, keys);
4464 * The base implementation of `_.functions` which creates an array of
4465 * `object` function property names filtered from those provided.
4468 * @param {Object} object The object to inspect.
4469 * @param {Array} props The property names to filter.
4470 * @returns {Array} Returns the new array of filtered property names.
4472 function baseFunctions(object, props) {
4474 length = props.length,
4478 while (++index < length) {
4479 var key = props[index];
4480 if (isFunction(object[key])) {
4481 result[++resIndex] = key;
4488 * The base implementation of `get` without support for string paths
4489 * and default values.
4492 * @param {Object} object The object to query.
4493 * @param {Array} path The path of the property to get.
4494 * @param {string} [pathKey] The key representation of path.
4495 * @returns {*} Returns the resolved value.
4497 function baseGet(object, path, pathKey) {
4498 if (object == null) {
4501 if (pathKey !== undefined && pathKey in toObject(object)) {
4505 length = path.length;
4507 while (object != null && index < length) {
4508 object = object[path[index++]];
4510 return (index && index == length) ? object : undefined;
4514 * The base implementation of `_.isEqual` without support for `this` binding
4515 * `customizer` functions.
4518 * @param {*} value The value to compare.
4519 * @param {*} other The other value to compare.
4520 * @param {Function} [customizer] The function to customize comparing values.
4521 * @param {boolean} [isLoose] Specify performing partial comparisons.
4522 * @param {Array} [stackA] Tracks traversed `value` objects.
4523 * @param {Array} [stackB] Tracks traversed `other` objects.
4524 * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
4526 function baseIsEqual(value, other, customizer, isLoose, stackA, stackB) {
4527 if (value === other) {
4530 if (value == null || other == null || (!isObject(value) && !isObjectLike(other))) {
4531 return value !== value && other !== other;
4533 return baseIsEqualDeep(value, other, baseIsEqual, customizer, isLoose, stackA, stackB);
4537 * A specialized version of `baseIsEqual` for arrays and objects which performs
4538 * deep comparisons and tracks traversed objects enabling objects with circular
4539 * references to be compared.
4542 * @param {Object} object The object to compare.
4543 * @param {Object} other The other object to compare.
4544 * @param {Function} equalFunc The function to determine equivalents of values.
4545 * @param {Function} [customizer] The function to customize comparing objects.
4546 * @param {boolean} [isLoose] Specify performing partial comparisons.
4547 * @param {Array} [stackA=[]] Tracks traversed `value` objects.
4548 * @param {Array} [stackB=[]] Tracks traversed `other` objects.
4549 * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
4551 function baseIsEqualDeep(object, other, equalFunc, customizer, isLoose, stackA, stackB) {
4552 var objIsArr = isArray(object),
4553 othIsArr = isArray(other),
4558 objTag = objToString.call(object);
4559 if (objTag == argsTag) {
4561 } else if (objTag != objectTag) {
4562 objIsArr = isTypedArray(object);
4566 othTag = objToString.call(other);
4567 if (othTag == argsTag) {
4569 } else if (othTag != objectTag) {
4570 othIsArr = isTypedArray(other);
4573 var objIsObj = objTag == objectTag,
4574 othIsObj = othTag == objectTag,
4575 isSameTag = objTag == othTag;
4577 if (isSameTag && !(objIsArr || objIsObj)) {
4578 return equalByTag(object, other, objTag);
4581 var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'),
4582 othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__');
4584 if (objIsWrapped || othIsWrapped) {
4585 return equalFunc(objIsWrapped ? object.value() : object, othIsWrapped ? other.value() : other, customizer, isLoose, stackA, stackB);
4591 // Assume cyclic values are equal.
4592 // For more information on detecting circular references see https://es5.github.io/#JO.
4593 stackA || (stackA = []);
4594 stackB || (stackB = []);
4596 var length = stackA.length;
4598 if (stackA[length] == object) {
4599 return stackB[length] == other;
4602 // Add `object` and `other` to the stack of traversed objects.
4603 stackA.push(object);
4606 var result = (objIsArr ? equalArrays : equalObjects)(object, other, equalFunc, customizer, isLoose, stackA, stackB);
4615 * The base implementation of `_.isMatch` without support for callback
4616 * shorthands and `this` binding.
4619 * @param {Object} object The object to inspect.
4620 * @param {Array} matchData The propery names, values, and compare flags to match.
4621 * @param {Function} [customizer] The function to customize comparing objects.
4622 * @returns {boolean} Returns `true` if `object` is a match, else `false`.
4624 function baseIsMatch(object, matchData, customizer) {
4625 var index = matchData.length,
4627 noCustomizer = !customizer;
4629 if (object == null) {
4632 object = toObject(object);
4634 var data = matchData[index];
4635 if ((noCustomizer && data[2])
4636 ? data[1] !== object[data[0]]
4637 : !(data[0] in object)
4642 while (++index < length) {
4643 data = matchData[index];
4645 objValue = object[key],
4648 if (noCustomizer && data[2]) {
4649 if (objValue === undefined && !(key in object)) {
4653 var result = customizer ? customizer(objValue, srcValue, key) : undefined;
4654 if (!(result === undefined ? baseIsEqual(srcValue, objValue, customizer, true) : result)) {
4663 * The base implementation of `_.map` without support for callback shorthands
4664 * and `this` binding.
4667 * @param {Array|Object|string} collection The collection to iterate over.
4668 * @param {Function} iteratee The function invoked per iteration.
4669 * @returns {Array} Returns the new mapped array.
4671 function baseMap(collection, iteratee) {
4673 result = isArrayLike(collection) ? Array(collection.length) : [];
4675 baseEach(collection, function(value, key, collection) {
4676 result[++index] = iteratee(value, key, collection);
4682 * The base implementation of `_.matches` which does not clone `source`.
4685 * @param {Object} source The object of property values to match.
4686 * @returns {Function} Returns the new function.
4688 function baseMatches(source) {
4689 var matchData = getMatchData(source);
4690 if (matchData.length == 1 && matchData[0][2]) {
4691 var key = matchData[0][0],
4692 value = matchData[0][1];
4694 return function(object) {
4695 if (object == null) {
4698 return object[key] === value && (value !== undefined || (key in toObject(object)));
4701 return function(object) {
4702 return baseIsMatch(object, matchData);
4707 * The base implementation of `_.matchesProperty` which does not clone `srcValue`.
4710 * @param {string} path The path of the property to get.
4711 * @param {*} srcValue The value to compare.
4712 * @returns {Function} Returns the new function.
4714 function baseMatchesProperty(path, srcValue) {
4715 var isArr = isArray(path),
4716 isCommon = isKey(path) && isStrictComparable(srcValue),
4717 pathKey = (path + '');
4719 path = toPath(path);
4720 return function(object) {
4721 if (object == null) {
4725 object = toObject(object);
4726 if ((isArr || !isCommon) && !(key in object)) {
4727 object = path.length == 1 ? object : baseGet(object, baseSlice(path, 0, -1));
4728 if (object == null) {
4732 object = toObject(object);
4734 return object[key] === srcValue
4735 ? (srcValue !== undefined || (key in object))
4736 : baseIsEqual(srcValue, object[key], undefined, true);
4741 * The base implementation of `_.merge` without support for argument juggling,
4742 * multiple sources, and `this` binding `customizer` functions.
4745 * @param {Object} object The destination object.
4746 * @param {Object} source The source object.
4747 * @param {Function} [customizer] The function to customize merged values.
4748 * @param {Array} [stackA=[]] Tracks traversed source objects.
4749 * @param {Array} [stackB=[]] Associates values with source counterparts.
4750 * @returns {Object} Returns `object`.
4752 function baseMerge(object, source, customizer, stackA, stackB) {
4753 if (!isObject(object)) {
4756 var isSrcArr = isArrayLike(source) && (isArray(source) || isTypedArray(source)),
4757 props = isSrcArr ? undefined : keys(source);
4759 arrayEach(props || source, function(srcValue, key) {
4762 srcValue = source[key];
4764 if (isObjectLike(srcValue)) {
4765 stackA || (stackA = []);
4766 stackB || (stackB = []);
4767 baseMergeDeep(object, source, key, baseMerge, customizer, stackA, stackB);
4770 var value = object[key],
4771 result = customizer ? customizer(value, srcValue, key, object, source) : undefined,
4772 isCommon = result === undefined;
4777 if ((result !== undefined || (isSrcArr && !(key in object))) &&
4778 (isCommon || (result === result ? (result !== value) : (value === value)))) {
4779 object[key] = result;
4787 * A specialized version of `baseMerge` for arrays and objects which performs
4788 * deep merges and tracks traversed objects enabling objects with circular
4789 * references to be merged.
4792 * @param {Object} object The destination object.
4793 * @param {Object} source The source object.
4794 * @param {string} key The key of the value to merge.
4795 * @param {Function} mergeFunc The function to merge values.
4796 * @param {Function} [customizer] The function to customize merged values.
4797 * @param {Array} [stackA=[]] Tracks traversed source objects.
4798 * @param {Array} [stackB=[]] Associates values with source counterparts.
4799 * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
4801 function baseMergeDeep(object, source, key, mergeFunc, customizer, stackA, stackB) {
4802 var length = stackA.length,
4803 srcValue = source[key];
4806 if (stackA[length] == srcValue) {
4807 object[key] = stackB[length];
4811 var value = object[key],
4812 result = customizer ? customizer(value, srcValue, key, object, source) : undefined,
4813 isCommon = result === undefined;
4817 if (isArrayLike(srcValue) && (isArray(srcValue) || isTypedArray(srcValue))) {
4818 result = isArray(value)
4820 : (isArrayLike(value) ? arrayCopy(value) : []);
4822 else if (isPlainObject(srcValue) || isArguments(srcValue)) {
4823 result = isArguments(value)
4824 ? toPlainObject(value)
4825 : (isPlainObject(value) ? value : {});
4831 // Add the source value to the stack of traversed objects and associate
4832 // it with its merged value.
4833 stackA.push(srcValue);
4834 stackB.push(result);
4837 // Recursively merge objects and arrays (susceptible to call stack limits).
4838 object[key] = mergeFunc(result, srcValue, customizer, stackA, stackB);
4839 } else if (result === result ? (result !== value) : (value === value)) {
4840 object[key] = result;
4845 * The base implementation of `_.property` without support for deep paths.
4848 * @param {string} key The key of the property to get.
4849 * @returns {Function} Returns the new function.
4851 function baseProperty(key) {
4852 return function(object) {
4853 return object == null ? undefined : object[key];
4858 * A specialized version of `baseProperty` which supports deep paths.
4861 * @param {Array|string} path The path of the property to get.
4862 * @returns {Function} Returns the new function.
4864 function basePropertyDeep(path) {
4865 var pathKey = (path + '');
4866 path = toPath(path);
4867 return function(object) {
4868 return baseGet(object, path, pathKey);
4873 * The base implementation of `_.pullAt` without support for individual
4874 * index arguments and capturing the removed elements.
4877 * @param {Array} array The array to modify.
4878 * @param {number[]} indexes The indexes of elements to remove.
4879 * @returns {Array} Returns `array`.
4881 function basePullAt(array, indexes) {
4882 var length = array ? indexes.length : 0;
4884 var index = indexes[length];
4885 if (index != previous && isIndex(index)) {
4886 var previous = index;
4887 splice.call(array, index, 1);
4894 * The base implementation of `_.random` without support for argument juggling
4895 * and returning floating-point numbers.
4898 * @param {number} min The minimum possible value.
4899 * @param {number} max The maximum possible value.
4900 * @returns {number} Returns the random number.
4902 function baseRandom(min, max) {
4903 return min + nativeFloor(nativeRandom() * (max - min + 1));
4907 * The base implementation of `_.reduce` and `_.reduceRight` without support
4908 * for callback shorthands and `this` binding, which iterates over `collection`
4909 * using the provided `eachFunc`.
4912 * @param {Array|Object|string} collection The collection to iterate over.
4913 * @param {Function} iteratee The function invoked per iteration.
4914 * @param {*} accumulator The initial value.
4915 * @param {boolean} initFromCollection Specify using the first or last element
4916 * of `collection` as the initial value.
4917 * @param {Function} eachFunc The function to iterate over `collection`.
4918 * @returns {*} Returns the accumulated value.
4920 function baseReduce(collection, iteratee, accumulator, initFromCollection, eachFunc) {
4921 eachFunc(collection, function(value, index, collection) {
4922 accumulator = initFromCollection
4923 ? (initFromCollection = false, value)
4924 : iteratee(accumulator, value, index, collection);
4930 * The base implementation of `setData` without support for hot loop detection.
4933 * @param {Function} func The function to associate metadata with.
4934 * @param {*} data The metadata.
4935 * @returns {Function} Returns `func`.
4937 var baseSetData = !metaMap ? identity : function(func, data) {
4938 metaMap.set(func, data);
4943 * The base implementation of `_.slice` without an iteratee call guard.
4946 * @param {Array} array The array to slice.
4947 * @param {number} [start=0] The start position.
4948 * @param {number} [end=array.length] The end position.
4949 * @returns {Array} Returns the slice of `array`.
4951 function baseSlice(array, start, end) {
4953 length = array.length;
4955 start = start == null ? 0 : (+start || 0);
4957 start = -start > length ? 0 : (length + start);
4959 end = (end === undefined || end > length) ? length : (+end || 0);
4963 length = start > end ? 0 : ((end - start) >>> 0);
4966 var result = Array(length);
4967 while (++index < length) {
4968 result[index] = array[index + start];
4974 * The base implementation of `_.some` without support for callback shorthands
4975 * and `this` binding.
4978 * @param {Array|Object|string} collection The collection to iterate over.
4979 * @param {Function} predicate The function invoked per iteration.
4980 * @returns {boolean} Returns `true` if any element passes the predicate check,
4983 function baseSome(collection, predicate) {
4986 baseEach(collection, function(value, index, collection) {
4987 result = predicate(value, index, collection);
4994 * The base implementation of `_.sortBy` which uses `comparer` to define
4995 * the sort order of `array` and replaces criteria objects with their
4996 * corresponding values.
4999 * @param {Array} array The array to sort.
5000 * @param {Function} comparer The function to define sort order.
5001 * @returns {Array} Returns `array`.
5003 function baseSortBy(array, comparer) {
5004 var length = array.length;
5006 array.sort(comparer);
5008 array[length] = array[length].value;
5014 * The base implementation of `_.sortByOrder` without param guards.
5017 * @param {Array|Object|string} collection The collection to iterate over.
5018 * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by.
5019 * @param {boolean[]} orders The sort orders of `iteratees`.
5020 * @returns {Array} Returns the new sorted array.
5022 function baseSortByOrder(collection, iteratees, orders) {
5023 var callback = getCallback(),
5026 iteratees = arrayMap(iteratees, function(iteratee) { return callback(iteratee); });
5028 var result = baseMap(collection, function(value) {
5029 var criteria = arrayMap(iteratees, function(iteratee) { return iteratee(value); });
5030 return { 'criteria': criteria, 'index': ++index, 'value': value };
5033 return baseSortBy(result, function(object, other) {
5034 return compareMultiple(object, other, orders);
5039 * The base implementation of `_.sum` without support for callback shorthands
5040 * and `this` binding.
5043 * @param {Array|Object|string} collection The collection to iterate over.
5044 * @param {Function} iteratee The function invoked per iteration.
5045 * @returns {number} Returns the sum.
5047 function baseSum(collection, iteratee) {
5049 baseEach(collection, function(value, index, collection) {
5050 result += +iteratee(value, index, collection) || 0;
5056 * The base implementation of `_.uniq` without support for callback shorthands
5057 * and `this` binding.
5060 * @param {Array} array The array to inspect.
5061 * @param {Function} [iteratee] The function invoked per iteration.
5062 * @returns {Array} Returns the new duplicate-value-free array.
5064 function baseUniq(array, iteratee) {
5066 indexOf = getIndexOf(),
5067 length = array.length,
5068 isCommon = indexOf == baseIndexOf,
5069 isLarge = isCommon && length >= LARGE_ARRAY_SIZE,
5070 seen = isLarge ? createCache() : null,
5074 indexOf = cacheIndexOf;
5078 seen = iteratee ? [] : result;
5081 while (++index < length) {
5082 var value = array[index],
5083 computed = iteratee ? iteratee(value, index, array) : value;
5085 if (isCommon && value === value) {
5086 var seenIndex = seen.length;
5087 while (seenIndex--) {
5088 if (seen[seenIndex] === computed) {
5093 seen.push(computed);
5097 else if (indexOf(seen, computed, 0) < 0) {
5098 if (iteratee || isLarge) {
5099 seen.push(computed);
5108 * The base implementation of `_.values` and `_.valuesIn` which creates an
5109 * array of `object` property values corresponding to the property names
5113 * @param {Object} object The object to query.
5114 * @param {Array} props The property names to get values for.
5115 * @returns {Object} Returns the array of property values.
5117 function baseValues(object, props) {
5119 length = props.length,
5120 result = Array(length);
5122 while (++index < length) {
5123 result[index] = object[props[index]];
5129 * The base implementation of `_.dropRightWhile`, `_.dropWhile`, `_.takeRightWhile`,
5130 * and `_.takeWhile` without support for callback shorthands and `this` binding.
5133 * @param {Array} array The array to query.
5134 * @param {Function} predicate The function invoked per iteration.
5135 * @param {boolean} [isDrop] Specify dropping elements instead of taking them.
5136 * @param {boolean} [fromRight] Specify iterating from right to left.
5137 * @returns {Array} Returns the slice of `array`.
5139 function baseWhile(array, predicate, isDrop, fromRight) {
5140 var length = array.length,
5141 index = fromRight ? length : -1;
5143 while ((fromRight ? index-- : ++index < length) && predicate(array[index], index, array)) {}
5145 ? baseSlice(array, (fromRight ? 0 : index), (fromRight ? index + 1 : length))
5146 : baseSlice(array, (fromRight ? index + 1 : 0), (fromRight ? length : index));
5150 * The base implementation of `wrapperValue` which returns the result of
5151 * performing a sequence of actions on the unwrapped `value`, where each
5152 * successive action is supplied the return value of the previous.
5155 * @param {*} value The unwrapped value.
5156 * @param {Array} actions Actions to peform to resolve the unwrapped value.
5157 * @returns {*} Returns the resolved value.
5159 function baseWrapperValue(value, actions) {
5161 if (result instanceof LazyWrapper) {
5162 result = result.value();
5165 length = actions.length;
5167 while (++index < length) {
5168 var action = actions[index];
5169 result = action.func.apply(action.thisArg, arrayPush([result], action.args));
5175 * Performs a binary search of `array` to determine the index at which `value`
5176 * should be inserted into `array` in order to maintain its sort order.
5179 * @param {Array} array The sorted array to inspect.
5180 * @param {*} value The value to evaluate.
5181 * @param {boolean} [retHighest] Specify returning the highest qualified index.
5182 * @returns {number} Returns the index at which `value` should be inserted
5185 function binaryIndex(array, value, retHighest) {
5187 high = array ? array.length : low;
5189 if (typeof value == 'number' && value === value && high <= HALF_MAX_ARRAY_LENGTH) {
5190 while (low < high) {
5191 var mid = (low + high) >>> 1,
5192 computed = array[mid];
5194 if ((retHighest ? (computed <= value) : (computed < value)) && computed !== null) {
5202 return binaryIndexBy(array, value, identity, retHighest);
5206 * This function is like `binaryIndex` except that it invokes `iteratee` for
5207 * `value` and each element of `array` to compute their sort ranking. The
5208 * iteratee is invoked with one argument; (value).
5211 * @param {Array} array The sorted array to inspect.
5212 * @param {*} value The value to evaluate.
5213 * @param {Function} iteratee The function invoked per iteration.
5214 * @param {boolean} [retHighest] Specify returning the highest qualified index.
5215 * @returns {number} Returns the index at which `value` should be inserted
5218 function binaryIndexBy(array, value, iteratee, retHighest) {
5219 value = iteratee(value);
5222 high = array ? array.length : 0,
5223 valIsNaN = value !== value,
5224 valIsNull = value === null,
5225 valIsUndef = value === undefined;
5227 while (low < high) {
5228 var mid = nativeFloor((low + high) / 2),
5229 computed = iteratee(array[mid]),
5230 isDef = computed !== undefined,
5231 isReflexive = computed === computed;
5234 var setLow = isReflexive || retHighest;
5235 } else if (valIsNull) {
5236 setLow = isReflexive && isDef && (retHighest || computed != null);
5237 } else if (valIsUndef) {
5238 setLow = isReflexive && (retHighest || isDef);
5239 } else if (computed == null) {
5242 setLow = retHighest ? (computed <= value) : (computed < value);
5250 return nativeMin(high, MAX_ARRAY_INDEX);
5254 * A specialized version of `baseCallback` which only supports `this` binding
5255 * and specifying the number of arguments to provide to `func`.
5258 * @param {Function} func The function to bind.
5259 * @param {*} thisArg The `this` binding of `func`.
5260 * @param {number} [argCount] The number of arguments to provide to `func`.
5261 * @returns {Function} Returns the callback.
5263 function bindCallback(func, thisArg, argCount) {
5264 if (typeof func != 'function') {
5267 if (thisArg === undefined) {
5271 case 1: return function(value) {
5272 return func.call(thisArg, value);
5274 case 3: return function(value, index, collection) {
5275 return func.call(thisArg, value, index, collection);
5277 case 4: return function(accumulator, value, index, collection) {
5278 return func.call(thisArg, accumulator, value, index, collection);
5280 case 5: return function(value, other, key, object, source) {
5281 return func.call(thisArg, value, other, key, object, source);
5285 return func.apply(thisArg, arguments);
5290 * Creates a clone of the given array buffer.
5293 * @param {ArrayBuffer} buffer The array buffer to clone.
5294 * @returns {ArrayBuffer} Returns the cloned array buffer.
5296 function bufferClone(buffer) {
5297 var result = new ArrayBuffer(buffer.byteLength),
5298 view = new Uint8Array(result);
5300 view.set(new Uint8Array(buffer));
5305 * Creates an array that is the composition of partially applied arguments,
5306 * placeholders, and provided arguments into a single array of arguments.
5309 * @param {Array|Object} args The provided arguments.
5310 * @param {Array} partials The arguments to prepend to those provided.
5311 * @param {Array} holders The `partials` placeholder indexes.
5312 * @returns {Array} Returns the new array of composed arguments.
5314 function composeArgs(args, partials, holders) {
5315 var holdersLength = holders.length,
5317 argsLength = nativeMax(args.length - holdersLength, 0),
5319 leftLength = partials.length,
5320 result = Array(leftLength + argsLength);
5322 while (++leftIndex < leftLength) {
5323 result[leftIndex] = partials[leftIndex];
5325 while (++argsIndex < holdersLength) {
5326 result[holders[argsIndex]] = args[argsIndex];
5328 while (argsLength--) {
5329 result[leftIndex++] = args[argsIndex++];
5335 * This function is like `composeArgs` except that the arguments composition
5336 * is tailored for `_.partialRight`.
5339 * @param {Array|Object} args The provided arguments.
5340 * @param {Array} partials The arguments to append to those provided.
5341 * @param {Array} holders The `partials` placeholder indexes.
5342 * @returns {Array} Returns the new array of composed arguments.
5344 function composeArgsRight(args, partials, holders) {
5345 var holdersIndex = -1,
5346 holdersLength = holders.length,
5348 argsLength = nativeMax(args.length - holdersLength, 0),
5350 rightLength = partials.length,
5351 result = Array(argsLength + rightLength);
5353 while (++argsIndex < argsLength) {
5354 result[argsIndex] = args[argsIndex];
5356 var offset = argsIndex;
5357 while (++rightIndex < rightLength) {
5358 result[offset + rightIndex] = partials[rightIndex];
5360 while (++holdersIndex < holdersLength) {
5361 result[offset + holders[holdersIndex]] = args[argsIndex++];
5367 * Creates a `_.countBy`, `_.groupBy`, `_.indexBy`, or `_.partition` function.
5370 * @param {Function} setter The function to set keys and values of the accumulator object.
5371 * @param {Function} [initializer] The function to initialize the accumulator object.
5372 * @returns {Function} Returns the new aggregator function.
5374 function createAggregator(setter, initializer) {
5375 return function(collection, iteratee, thisArg) {
5376 var result = initializer ? initializer() : {};
5377 iteratee = getCallback(iteratee, thisArg, 3);
5379 if (isArray(collection)) {
5381 length = collection.length;
5383 while (++index < length) {
5384 var value = collection[index];
5385 setter(result, value, iteratee(value, index, collection), collection);
5388 baseEach(collection, function(value, key, collection) {
5389 setter(result, value, iteratee(value, key, collection), collection);
5397 * Creates a `_.assign`, `_.defaults`, or `_.merge` function.
5400 * @param {Function} assigner The function to assign values.
5401 * @returns {Function} Returns the new assigner function.
5403 function createAssigner(assigner) {
5404 return restParam(function(object, sources) {
5406 length = object == null ? 0 : sources.length,
5407 customizer = length > 2 ? sources[length - 2] : undefined,
5408 guard = length > 2 ? sources[2] : undefined,
5409 thisArg = length > 1 ? sources[length - 1] : undefined;
5411 if (typeof customizer == 'function') {
5412 customizer = bindCallback(customizer, thisArg, 5);
5415 customizer = typeof thisArg == 'function' ? thisArg : undefined;
5416 length -= (customizer ? 1 : 0);
5418 if (guard && isIterateeCall(sources[0], sources[1], guard)) {
5419 customizer = length < 3 ? undefined : customizer;
5422 while (++index < length) {
5423 var source = sources[index];
5425 assigner(object, source, customizer);
5433 * Creates a `baseEach` or `baseEachRight` function.
5436 * @param {Function} eachFunc The function to iterate over a collection.
5437 * @param {boolean} [fromRight] Specify iterating from right to left.
5438 * @returns {Function} Returns the new base function.
5440 function createBaseEach(eachFunc, fromRight) {
5441 return function(collection, iteratee) {
5442 var length = collection ? getLength(collection) : 0;
5443 if (!isLength(length)) {
5444 return eachFunc(collection, iteratee);
5446 var index = fromRight ? length : -1,
5447 iterable = toObject(collection);
5449 while ((fromRight ? index-- : ++index < length)) {
5450 if (iteratee(iterable[index], index, iterable) === false) {
5459 * Creates a base function for `_.forIn` or `_.forInRight`.
5462 * @param {boolean} [fromRight] Specify iterating from right to left.
5463 * @returns {Function} Returns the new base function.
5465 function createBaseFor(fromRight) {
5466 return function(object, iteratee, keysFunc) {
5467 var iterable = toObject(object),
5468 props = keysFunc(object),
5469 length = props.length,
5470 index = fromRight ? length : -1;
5472 while ((fromRight ? index-- : ++index < length)) {
5473 var key = props[index];
5474 if (iteratee(iterable[key], key, iterable) === false) {
5483 * Creates a function that wraps `func` and invokes it with the `this`
5484 * binding of `thisArg`.
5487 * @param {Function} func The function to bind.
5488 * @param {*} [thisArg] The `this` binding of `func`.
5489 * @returns {Function} Returns the new bound function.
5491 function createBindWrapper(func, thisArg) {
5492 var Ctor = createCtorWrapper(func);
5494 function wrapper() {
5495 var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;
5496 return fn.apply(thisArg, arguments);
5502 * Creates a `Set` cache object to optimize linear searches of large arrays.
5505 * @param {Array} [values] The values to cache.
5506 * @returns {null|Object} Returns the new cache object if `Set` is supported, else `null`.
5508 function createCache(values) {
5509 return (nativeCreate && Set) ? new SetCache(values) : null;
5513 * Creates a function that produces compound words out of the words in a
5517 * @param {Function} callback The function to combine each word.
5518 * @returns {Function} Returns the new compounder function.
5520 function createCompounder(callback) {
5521 return function(string) {
5523 array = words(deburr(string)),
5524 length = array.length,
5527 while (++index < length) {
5528 result = callback(result, array[index], index);
5535 * Creates a function that produces an instance of `Ctor` regardless of
5536 * whether it was invoked as part of a `new` expression or by `call` or `apply`.
5539 * @param {Function} Ctor The constructor to wrap.
5540 * @returns {Function} Returns the new wrapped function.
5542 function createCtorWrapper(Ctor) {
5544 // Use a `switch` statement to work with class constructors.
5545 // See http://ecma-international.org/ecma-262/6.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist
5546 // for more details.
5547 var args = arguments;
5548 switch (args.length) {
5549 case 0: return new Ctor;
5550 case 1: return new Ctor(args[0]);
5551 case 2: return new Ctor(args[0], args[1]);
5552 case 3: return new Ctor(args[0], args[1], args[2]);
5553 case 4: return new Ctor(args[0], args[1], args[2], args[3]);
5554 case 5: return new Ctor(args[0], args[1], args[2], args[3], args[4]);
5555 case 6: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]);
5556 case 7: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]);
5558 var thisBinding = baseCreate(Ctor.prototype),
5559 result = Ctor.apply(thisBinding, args);
5561 // Mimic the constructor's `return` behavior.
5562 // See https://es5.github.io/#x13.2.2 for more details.
5563 return isObject(result) ? result : thisBinding;
5568 * Creates a `_.curry` or `_.curryRight` function.
5571 * @param {boolean} flag The curry bit flag.
5572 * @returns {Function} Returns the new curry function.
5574 function createCurry(flag) {
5575 function curryFunc(func, arity, guard) {
5576 if (guard && isIterateeCall(func, arity, guard)) {
5579 var result = createWrapper(func, flag, undefined, undefined, undefined, undefined, undefined, arity);
5580 result.placeholder = curryFunc.placeholder;
5587 * Creates a `_.defaults` or `_.defaultsDeep` function.
5590 * @param {Function} assigner The function to assign values.
5591 * @param {Function} customizer The function to customize assigned values.
5592 * @returns {Function} Returns the new defaults function.
5594 function createDefaults(assigner, customizer) {
5595 return restParam(function(args) {
5596 var object = args[0];
5597 if (object == null) {
5600 args.push(customizer);
5601 return assigner.apply(undefined, args);
5606 * Creates a `_.max` or `_.min` function.
5609 * @param {Function} comparator The function used to compare values.
5610 * @param {*} exValue The initial extremum value.
5611 * @returns {Function} Returns the new extremum function.
5613 function createExtremum(comparator, exValue) {
5614 return function(collection, iteratee, thisArg) {
5615 if (thisArg && isIterateeCall(collection, iteratee, thisArg)) {
5616 iteratee = undefined;
5618 iteratee = getCallback(iteratee, thisArg, 3);
5619 if (iteratee.length == 1) {
5620 collection = isArray(collection) ? collection : toIterable(collection);
5621 var result = arrayExtremum(collection, iteratee, comparator, exValue);
5622 if (!(collection.length && result === exValue)) {
5626 return baseExtremum(collection, iteratee, comparator, exValue);
5631 * Creates a `_.find` or `_.findLast` function.
5634 * @param {Function} eachFunc The function to iterate over a collection.
5635 * @param {boolean} [fromRight] Specify iterating from right to left.
5636 * @returns {Function} Returns the new find function.
5638 function createFind(eachFunc, fromRight) {
5639 return function(collection, predicate, thisArg) {
5640 predicate = getCallback(predicate, thisArg, 3);
5641 if (isArray(collection)) {
5642 var index = baseFindIndex(collection, predicate, fromRight);
5643 return index > -1 ? collection[index] : undefined;
5645 return baseFind(collection, predicate, eachFunc);
5650 * Creates a `_.findIndex` or `_.findLastIndex` function.
5653 * @param {boolean} [fromRight] Specify iterating from right to left.
5654 * @returns {Function} Returns the new find function.
5656 function createFindIndex(fromRight) {
5657 return function(array, predicate, thisArg) {
5658 if (!(array && array.length)) {
5661 predicate = getCallback(predicate, thisArg, 3);
5662 return baseFindIndex(array, predicate, fromRight);
5667 * Creates a `_.findKey` or `_.findLastKey` function.
5670 * @param {Function} objectFunc The function to iterate over an object.
5671 * @returns {Function} Returns the new find function.
5673 function createFindKey(objectFunc) {
5674 return function(object, predicate, thisArg) {
5675 predicate = getCallback(predicate, thisArg, 3);
5676 return baseFind(object, predicate, objectFunc, true);
5681 * Creates a `_.flow` or `_.flowRight` function.
5684 * @param {boolean} [fromRight] Specify iterating from right to left.
5685 * @returns {Function} Returns the new flow function.
5687 function createFlow(fromRight) {
5690 length = arguments.length,
5691 index = fromRight ? length : -1,
5693 funcs = Array(length);
5695 while ((fromRight ? index-- : ++index < length)) {
5696 var func = funcs[leftIndex++] = arguments[index];
5697 if (typeof func != 'function') {
5698 throw new TypeError(FUNC_ERROR_TEXT);
5700 if (!wrapper && LodashWrapper.prototype.thru && getFuncName(func) == 'wrapper') {
5701 wrapper = new LodashWrapper([], true);
5704 index = wrapper ? -1 : length;
5705 while (++index < length) {
5706 func = funcs[index];
5708 var funcName = getFuncName(func),
5709 data = funcName == 'wrapper' ? getData(func) : undefined;
5711 if (data && isLaziable(data[0]) && data[1] == (ARY_FLAG | CURRY_FLAG | PARTIAL_FLAG | REARG_FLAG) && !data[4].length && data[9] == 1) {
5712 wrapper = wrapper[getFuncName(data[0])].apply(wrapper, data[3]);
5714 wrapper = (func.length == 1 && isLaziable(func)) ? wrapper[funcName]() : wrapper.thru(func);
5718 var args = arguments,
5721 if (wrapper && args.length == 1 && isArray(value) && value.length >= LARGE_ARRAY_SIZE) {
5722 return wrapper.plant(value).value();
5725 result = length ? funcs[index].apply(this, args) : value;
5727 while (++index < length) {
5728 result = funcs[index].call(this, result);
5736 * Creates a function for `_.forEach` or `_.forEachRight`.
5739 * @param {Function} arrayFunc The function to iterate over an array.
5740 * @param {Function} eachFunc The function to iterate over a collection.
5741 * @returns {Function} Returns the new each function.
5743 function createForEach(arrayFunc, eachFunc) {
5744 return function(collection, iteratee, thisArg) {
5745 return (typeof iteratee == 'function' && thisArg === undefined && isArray(collection))
5746 ? arrayFunc(collection, iteratee)
5747 : eachFunc(collection, bindCallback(iteratee, thisArg, 3));
5752 * Creates a function for `_.forIn` or `_.forInRight`.
5755 * @param {Function} objectFunc The function to iterate over an object.
5756 * @returns {Function} Returns the new each function.
5758 function createForIn(objectFunc) {
5759 return function(object, iteratee, thisArg) {
5760 if (typeof iteratee != 'function' || thisArg !== undefined) {
5761 iteratee = bindCallback(iteratee, thisArg, 3);
5763 return objectFunc(object, iteratee, keysIn);
5768 * Creates a function for `_.forOwn` or `_.forOwnRight`.
5771 * @param {Function} objectFunc The function to iterate over an object.
5772 * @returns {Function} Returns the new each function.
5774 function createForOwn(objectFunc) {
5775 return function(object, iteratee, thisArg) {
5776 if (typeof iteratee != 'function' || thisArg !== undefined) {
5777 iteratee = bindCallback(iteratee, thisArg, 3);
5779 return objectFunc(object, iteratee);
5784 * Creates a function for `_.mapKeys` or `_.mapValues`.
5787 * @param {boolean} [isMapKeys] Specify mapping keys instead of values.
5788 * @returns {Function} Returns the new map function.
5790 function createObjectMapper(isMapKeys) {
5791 return function(object, iteratee, thisArg) {
5793 iteratee = getCallback(iteratee, thisArg, 3);
5795 baseForOwn(object, function(value, key, object) {
5796 var mapped = iteratee(value, key, object);
5797 key = isMapKeys ? mapped : key;
5798 value = isMapKeys ? value : mapped;
5799 result[key] = value;
5806 * Creates a function for `_.padLeft` or `_.padRight`.
5809 * @param {boolean} [fromRight] Specify padding from the right.
5810 * @returns {Function} Returns the new pad function.
5812 function createPadDir(fromRight) {
5813 return function(string, length, chars) {
5814 string = baseToString(string);
5815 return (fromRight ? string : '') + createPadding(string, length, chars) + (fromRight ? '' : string);
5820 * Creates a `_.partial` or `_.partialRight` function.
5823 * @param {boolean} flag The partial bit flag.
5824 * @returns {Function} Returns the new partial function.
5826 function createPartial(flag) {
5827 var partialFunc = restParam(function(func, partials) {
5828 var holders = replaceHolders(partials, partialFunc.placeholder);
5829 return createWrapper(func, flag, undefined, partials, holders);
5835 * Creates a function for `_.reduce` or `_.reduceRight`.
5838 * @param {Function} arrayFunc The function to iterate over an array.
5839 * @param {Function} eachFunc The function to iterate over a collection.
5840 * @returns {Function} Returns the new each function.
5842 function createReduce(arrayFunc, eachFunc) {
5843 return function(collection, iteratee, accumulator, thisArg) {
5844 var initFromArray = arguments.length < 3;
5845 return (typeof iteratee == 'function' && thisArg === undefined && isArray(collection))
5846 ? arrayFunc(collection, iteratee, accumulator, initFromArray)
5847 : baseReduce(collection, getCallback(iteratee, thisArg, 4), accumulator, initFromArray, eachFunc);
5852 * Creates a function that wraps `func` and invokes it with optional `this`
5853 * binding of, partial application, and currying.
5856 * @param {Function|string} func The function or method name to reference.
5857 * @param {number} bitmask The bitmask of flags. See `createWrapper` for more details.
5858 * @param {*} [thisArg] The `this` binding of `func`.
5859 * @param {Array} [partials] The arguments to prepend to those provided to the new function.
5860 * @param {Array} [holders] The `partials` placeholder indexes.
5861 * @param {Array} [partialsRight] The arguments to append to those provided to the new function.
5862 * @param {Array} [holdersRight] The `partialsRight` placeholder indexes.
5863 * @param {Array} [argPos] The argument positions of the new function.
5864 * @param {number} [ary] The arity cap of `func`.
5865 * @param {number} [arity] The arity of `func`.
5866 * @returns {Function} Returns the new wrapped function.
5868 function createHybridWrapper(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) {
5869 var isAry = bitmask & ARY_FLAG,
5870 isBind = bitmask & BIND_FLAG,
5871 isBindKey = bitmask & BIND_KEY_FLAG,
5872 isCurry = bitmask & CURRY_FLAG,
5873 isCurryBound = bitmask & CURRY_BOUND_FLAG,
5874 isCurryRight = bitmask & CURRY_RIGHT_FLAG,
5875 Ctor = isBindKey ? undefined : createCtorWrapper(func);
5877 function wrapper() {
5878 // Avoid `arguments` object use disqualifying optimizations by
5879 // converting it to an array before providing it to other functions.
5880 var length = arguments.length,
5882 args = Array(length);
5885 args[index] = arguments[index];
5888 args = composeArgs(args, partials, holders);
5890 if (partialsRight) {
5891 args = composeArgsRight(args, partialsRight, holdersRight);
5893 if (isCurry || isCurryRight) {
5894 var placeholder = wrapper.placeholder,
5895 argsHolders = replaceHolders(args, placeholder);
5897 length -= argsHolders.length;
5898 if (length < arity) {
5899 var newArgPos = argPos ? arrayCopy(argPos) : undefined,
5900 newArity = nativeMax(arity - length, 0),
5901 newsHolders = isCurry ? argsHolders : undefined,
5902 newHoldersRight = isCurry ? undefined : argsHolders,
5903 newPartials = isCurry ? args : undefined,
5904 newPartialsRight = isCurry ? undefined : args;
5906 bitmask |= (isCurry ? PARTIAL_FLAG : PARTIAL_RIGHT_FLAG);
5907 bitmask &= ~(isCurry ? PARTIAL_RIGHT_FLAG : PARTIAL_FLAG);
5909 if (!isCurryBound) {
5910 bitmask &= ~(BIND_FLAG | BIND_KEY_FLAG);
5912 var newData = [func, bitmask, thisArg, newPartials, newsHolders, newPartialsRight, newHoldersRight, newArgPos, ary, newArity],
5913 result = createHybridWrapper.apply(undefined, newData);
5915 if (isLaziable(func)) {
5916 setData(result, newData);
5918 result.placeholder = placeholder;
5922 var thisBinding = isBind ? thisArg : this,
5923 fn = isBindKey ? thisBinding[func] : func;
5926 args = reorder(args, argPos);
5928 if (isAry && ary < args.length) {
5931 if (this && this !== root && this instanceof wrapper) {
5932 fn = Ctor || createCtorWrapper(func);
5934 return fn.apply(thisBinding, args);
5940 * Creates the padding required for `string` based on the given `length`.
5941 * The `chars` string is truncated if the number of characters exceeds `length`.
5944 * @param {string} string The string to create padding for.
5945 * @param {number} [length=0] The padding length.
5946 * @param {string} [chars=' '] The string used as padding.
5947 * @returns {string} Returns the pad for `string`.
5949 function createPadding(string, length, chars) {
5950 var strLength = string.length;
5953 if (strLength >= length || !nativeIsFinite(length)) {
5956 var padLength = length - strLength;
5957 chars = chars == null ? ' ' : (chars + '');
5958 return repeat(chars, nativeCeil(padLength / chars.length)).slice(0, padLength);
5962 * Creates a function that wraps `func` and invokes it with the optional `this`
5963 * binding of `thisArg` and the `partials` prepended to those provided to
5967 * @param {Function} func The function to partially apply arguments to.
5968 * @param {number} bitmask The bitmask of flags. See `createWrapper` for more details.
5969 * @param {*} thisArg The `this` binding of `func`.
5970 * @param {Array} partials The arguments to prepend to those provided to the new function.
5971 * @returns {Function} Returns the new bound function.
5973 function createPartialWrapper(func, bitmask, thisArg, partials) {
5974 var isBind = bitmask & BIND_FLAG,
5975 Ctor = createCtorWrapper(func);
5977 function wrapper() {
5978 // Avoid `arguments` object use disqualifying optimizations by
5979 // converting it to an array before providing it `func`.
5981 argsLength = arguments.length,
5983 leftLength = partials.length,
5984 args = Array(leftLength + argsLength);
5986 while (++leftIndex < leftLength) {
5987 args[leftIndex] = partials[leftIndex];
5989 while (argsLength--) {
5990 args[leftIndex++] = arguments[++argsIndex];
5992 var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;
5993 return fn.apply(isBind ? thisArg : this, args);
5999 * Creates a `_.ceil`, `_.floor`, or `_.round` function.
6002 * @param {string} methodName The name of the `Math` method to use when rounding.
6003 * @returns {Function} Returns the new round function.
6005 function createRound(methodName) {
6006 var func = Math[methodName];
6007 return function(number, precision) {
6008 precision = precision === undefined ? 0 : (+precision || 0);
6010 precision = pow(10, precision);
6011 return func(number * precision) / precision;
6013 return func(number);
6018 * Creates a `_.sortedIndex` or `_.sortedLastIndex` function.
6021 * @param {boolean} [retHighest] Specify returning the highest qualified index.
6022 * @returns {Function} Returns the new index function.
6024 function createSortedIndex(retHighest) {
6025 return function(array, value, iteratee, thisArg) {
6026 var callback = getCallback(iteratee);
6027 return (iteratee == null && callback === baseCallback)
6028 ? binaryIndex(array, value, retHighest)
6029 : binaryIndexBy(array, value, callback(iteratee, thisArg, 1), retHighest);
6034 * Creates a function that either curries or invokes `func` with optional
6035 * `this` binding and partially applied arguments.
6038 * @param {Function|string} func The function or method name to reference.
6039 * @param {number} bitmask The bitmask of flags.
6040 * The bitmask may be composed of the following flags:
6043 * 4 - `_.curry` or `_.curryRight` of a bound function
6045 * 16 - `_.curryRight`
6047 * 64 - `_.partialRight`
6050 * @param {*} [thisArg] The `this` binding of `func`.
6051 * @param {Array} [partials] The arguments to be partially applied.
6052 * @param {Array} [holders] The `partials` placeholder indexes.
6053 * @param {Array} [argPos] The argument positions of the new function.
6054 * @param {number} [ary] The arity cap of `func`.
6055 * @param {number} [arity] The arity of `func`.
6056 * @returns {Function} Returns the new wrapped function.
6058 function createWrapper(func, bitmask, thisArg, partials, holders, argPos, ary, arity) {
6059 var isBindKey = bitmask & BIND_KEY_FLAG;
6060 if (!isBindKey && typeof func != 'function') {
6061 throw new TypeError(FUNC_ERROR_TEXT);
6063 var length = partials ? partials.length : 0;
6065 bitmask &= ~(PARTIAL_FLAG | PARTIAL_RIGHT_FLAG);
6066 partials = holders = undefined;
6068 length -= (holders ? holders.length : 0);
6069 if (bitmask & PARTIAL_RIGHT_FLAG) {
6070 var partialsRight = partials,
6071 holdersRight = holders;
6073 partials = holders = undefined;
6075 var data = isBindKey ? undefined : getData(func),
6076 newData = [func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity];
6079 mergeData(newData, data);
6080 bitmask = newData[1];
6083 newData[9] = arity == null
6084 ? (isBindKey ? 0 : func.length)
6085 : (nativeMax(arity - length, 0) || 0);
6087 if (bitmask == BIND_FLAG) {
6088 var result = createBindWrapper(newData[0], newData[2]);
6089 } else if ((bitmask == PARTIAL_FLAG || bitmask == (BIND_FLAG | PARTIAL_FLAG)) && !newData[4].length) {
6090 result = createPartialWrapper.apply(undefined, newData);
6092 result = createHybridWrapper.apply(undefined, newData);
6094 var setter = data ? baseSetData : setData;
6095 return setter(result, newData);
6099 * A specialized version of `baseIsEqualDeep` for arrays with support for
6100 * partial deep comparisons.
6103 * @param {Array} array The array to compare.
6104 * @param {Array} other The other array to compare.
6105 * @param {Function} equalFunc The function to determine equivalents of values.
6106 * @param {Function} [customizer] The function to customize comparing arrays.
6107 * @param {boolean} [isLoose] Specify performing partial comparisons.
6108 * @param {Array} [stackA] Tracks traversed `value` objects.
6109 * @param {Array} [stackB] Tracks traversed `other` objects.
6110 * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.
6112 function equalArrays(array, other, equalFunc, customizer, isLoose, stackA, stackB) {
6114 arrLength = array.length,
6115 othLength = other.length;
6117 if (arrLength != othLength && !(isLoose && othLength > arrLength)) {
6120 // Ignore non-index properties.
6121 while (++index < arrLength) {
6122 var arrValue = array[index],
6123 othValue = other[index],
6124 result = customizer ? customizer(isLoose ? othValue : arrValue, isLoose ? arrValue : othValue, index) : undefined;
6126 if (result !== undefined) {
6132 // Recursively compare arrays (susceptible to call stack limits).
6134 if (!arraySome(other, function(othValue) {
6135 return arrValue === othValue || equalFunc(arrValue, othValue, customizer, isLoose, stackA, stackB);
6139 } else if (!(arrValue === othValue || equalFunc(arrValue, othValue, customizer, isLoose, stackA, stackB))) {
6147 * A specialized version of `baseIsEqualDeep` for comparing objects of
6148 * the same `toStringTag`.
6150 * **Note:** This function only supports comparing values with tags of
6151 * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
6154 * @param {Object} object The object to compare.
6155 * @param {Object} other The other object to compare.
6156 * @param {string} tag The `toStringTag` of the objects to compare.
6157 * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
6159 function equalByTag(object, other, tag) {
6163 // Coerce dates and booleans to numbers, dates to milliseconds and booleans
6164 // to `1` or `0` treating invalid dates coerced to `NaN` as not equal.
6165 return +object == +other;
6168 return object.name == other.name && object.message == other.message;
6171 // Treat `NaN` vs. `NaN` as equal.
6172 return (object != +object)
6178 // Coerce regexes to strings and treat strings primitives and string
6179 // objects as equal. See https://es5.github.io/#x15.10.6.4 for more details.
6180 return object == (other + '');
6186 * A specialized version of `baseIsEqualDeep` for objects with support for
6187 * partial deep comparisons.
6190 * @param {Object} object The object to compare.
6191 * @param {Object} other The other object to compare.
6192 * @param {Function} equalFunc The function to determine equivalents of values.
6193 * @param {Function} [customizer] The function to customize comparing values.
6194 * @param {boolean} [isLoose] Specify performing partial comparisons.
6195 * @param {Array} [stackA] Tracks traversed `value` objects.
6196 * @param {Array} [stackB] Tracks traversed `other` objects.
6197 * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
6199 function equalObjects(object, other, equalFunc, customizer, isLoose, stackA, stackB) {
6200 var objProps = keys(object),
6201 objLength = objProps.length,
6202 othProps = keys(other),
6203 othLength = othProps.length;
6205 if (objLength != othLength && !isLoose) {
6208 var index = objLength;
6210 var key = objProps[index];
6211 if (!(isLoose ? key in other : hasOwnProperty.call(other, key))) {
6215 var skipCtor = isLoose;
6216 while (++index < objLength) {
6217 key = objProps[index];
6218 var objValue = object[key],
6219 othValue = other[key],
6220 result = customizer ? customizer(isLoose ? othValue : objValue, isLoose? objValue : othValue, key) : undefined;
6222 // Recursively compare objects (susceptible to call stack limits).
6223 if (!(result === undefined ? equalFunc(objValue, othValue, customizer, isLoose, stackA, stackB) : result)) {
6226 skipCtor || (skipCtor = key == 'constructor');
6229 var objCtor = object.constructor,
6230 othCtor = other.constructor;
6232 // Non `Object` object instances with different constructors are not equal.
6233 if (objCtor != othCtor &&
6234 ('constructor' in object && 'constructor' in other) &&
6235 !(typeof objCtor == 'function' && objCtor instanceof objCtor &&
6236 typeof othCtor == 'function' && othCtor instanceof othCtor)) {
6244 * Gets the appropriate "callback" function. If the `_.callback` method is
6245 * customized this function returns the custom method, otherwise it returns
6246 * the `baseCallback` function. If arguments are provided the chosen function
6247 * is invoked with them and its result is returned.
6250 * @returns {Function} Returns the chosen function or its result.
6252 function getCallback(func, thisArg, argCount) {
6253 var result = lodash.callback || callback;
6254 result = result === callback ? baseCallback : result;
6255 return argCount ? result(func, thisArg, argCount) : result;
6259 * Gets metadata for `func`.
6262 * @param {Function} func The function to query.
6263 * @returns {*} Returns the metadata for `func`.
6265 var getData = !metaMap ? noop : function(func) {
6266 return metaMap.get(func);
6270 * Gets the name of `func`.
6273 * @param {Function} func The function to query.
6274 * @returns {string} Returns the function name.
6276 function getFuncName(func) {
6277 var result = func.name,
6278 array = realNames[result],
6279 length = array ? array.length : 0;
6282 var data = array[length],
6283 otherFunc = data.func;
6284 if (otherFunc == null || otherFunc == func) {
6292 * Gets the appropriate "indexOf" function. If the `_.indexOf` method is
6293 * customized this function returns the custom method, otherwise it returns
6294 * the `baseIndexOf` function. If arguments are provided the chosen function
6295 * is invoked with them and its result is returned.
6298 * @returns {Function|number} Returns the chosen function or its result.
6300 function getIndexOf(collection, target, fromIndex) {
6301 var result = lodash.indexOf || indexOf;
6302 result = result === indexOf ? baseIndexOf : result;
6303 return collection ? result(collection, target, fromIndex) : result;
6307 * Gets the "length" property value of `object`.
6309 * **Note:** This function is used to avoid a [JIT bug](https://bugs.webkit.org/show_bug.cgi?id=142792)
6310 * that affects Safari on at least iOS 8.1-8.3 ARM64.
6313 * @param {Object} object The object to query.
6314 * @returns {*} Returns the "length" value.
6316 var getLength = baseProperty('length');
6319 * Gets the propery names, values, and compare flags of `object`.
6322 * @param {Object} object The object to query.
6323 * @returns {Array} Returns the match data of `object`.
6325 function getMatchData(object) {
6326 var result = pairs(object),
6327 length = result.length;
6330 result[length][2] = isStrictComparable(result[length][1]);
6336 * Gets the native function at `key` of `object`.
6339 * @param {Object} object The object to query.
6340 * @param {string} key The key of the method to get.
6341 * @returns {*} Returns the function if it's native, else `undefined`.
6343 function getNative(object, key) {
6344 var value = object == null ? undefined : object[key];
6345 return isNative(value) ? value : undefined;
6349 * Gets the view, applying any `transforms` to the `start` and `end` positions.
6352 * @param {number} start The start of the view.
6353 * @param {number} end The end of the view.
6354 * @param {Array} transforms The transformations to apply to the view.
6355 * @returns {Object} Returns an object containing the `start` and `end`
6356 * positions of the view.
6358 function getView(start, end, transforms) {
6360 length = transforms.length;
6362 while (++index < length) {
6363 var data = transforms[index],
6366 switch (data.type) {
6367 case 'drop': start += size; break;
6368 case 'dropRight': end -= size; break;
6369 case 'take': end = nativeMin(end, start + size); break;
6370 case 'takeRight': start = nativeMax(start, end - size); break;
6373 return { 'start': start, 'end': end };
6377 * Initializes an array clone.
6380 * @param {Array} array The array to clone.
6381 * @returns {Array} Returns the initialized clone.
6383 function initCloneArray(array) {
6384 var length = array.length,
6385 result = new array.constructor(length);
6387 // Add array properties assigned by `RegExp#exec`.
6388 if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) {
6389 result.index = array.index;
6390 result.input = array.input;
6396 * Initializes an object clone.
6399 * @param {Object} object The object to clone.
6400 * @returns {Object} Returns the initialized clone.
6402 function initCloneObject(object) {
6403 var Ctor = object.constructor;
6404 if (!(typeof Ctor == 'function' && Ctor instanceof Ctor)) {
6411 * Initializes an object clone based on its `toStringTag`.
6413 * **Note:** This function only supports cloning values with tags of
6414 * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
6417 * @param {Object} object The object to clone.
6418 * @param {string} tag The `toStringTag` of the object to clone.
6419 * @param {boolean} [isDeep] Specify a deep clone.
6420 * @returns {Object} Returns the initialized clone.
6422 function initCloneByTag(object, tag, isDeep) {
6423 var Ctor = object.constructor;
6425 case arrayBufferTag:
6426 return bufferClone(object);
6430 return new Ctor(+object);
6432 case float32Tag: case float64Tag:
6433 case int8Tag: case int16Tag: case int32Tag:
6434 case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag:
6435 var buffer = object.buffer;
6436 return new Ctor(isDeep ? bufferClone(buffer) : buffer, object.byteOffset, object.length);
6440 return new Ctor(object);
6443 var result = new Ctor(object.source, reFlags.exec(object));
6444 result.lastIndex = object.lastIndex;
6450 * Invokes the method at `path` on `object`.
6453 * @param {Object} object The object to query.
6454 * @param {Array|string} path The path of the method to invoke.
6455 * @param {Array} args The arguments to invoke the method with.
6456 * @returns {*} Returns the result of the invoked method.
6458 function invokePath(object, path, args) {
6459 if (object != null && !isKey(path, object)) {
6460 path = toPath(path);
6461 object = path.length == 1 ? object : baseGet(object, baseSlice(path, 0, -1));
6464 var func = object == null ? object : object[path];
6465 return func == null ? undefined : func.apply(object, args);
6469 * Checks if `value` is array-like.
6472 * @param {*} value The value to check.
6473 * @returns {boolean} Returns `true` if `value` is array-like, else `false`.
6475 function isArrayLike(value) {
6476 return value != null && isLength(getLength(value));
6480 * Checks if `value` is a valid array-like index.
6483 * @param {*} value The value to check.
6484 * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
6485 * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
6487 function isIndex(value, length) {
6488 value = (typeof value == 'number' || reIsUint.test(value)) ? +value : -1;
6489 length = length == null ? MAX_SAFE_INTEGER : length;
6490 return value > -1 && value % 1 == 0 && value < length;
6494 * Checks if the provided arguments are from an iteratee call.
6497 * @param {*} value The potential iteratee value argument.
6498 * @param {*} index The potential iteratee index or key argument.
6499 * @param {*} object The potential iteratee object argument.
6500 * @returns {boolean} Returns `true` if the arguments are from an iteratee call, else `false`.
6502 function isIterateeCall(value, index, object) {
6503 if (!isObject(object)) {
6506 var type = typeof index;
6507 if (type == 'number'
6508 ? (isArrayLike(object) && isIndex(index, object.length))
6509 : (type == 'string' && index in object)) {
6510 var other = object[index];
6511 return value === value ? (value === other) : (other !== other);
6517 * Checks if `value` is a property name and not a property path.
6520 * @param {*} value The value to check.
6521 * @param {Object} [object] The object to query keys on.
6522 * @returns {boolean} Returns `true` if `value` is a property name, else `false`.
6524 function isKey(value, object) {
6525 var type = typeof value;
6526 if ((type == 'string' && reIsPlainProp.test(value)) || type == 'number') {
6529 if (isArray(value)) {
6532 var result = !reIsDeepProp.test(value);
6533 return result || (object != null && value in toObject(object));
6537 * Checks if `func` has a lazy counterpart.
6540 * @param {Function} func The function to check.
6541 * @returns {boolean} Returns `true` if `func` has a lazy counterpart, else `false`.
6543 function isLaziable(func) {
6544 var funcName = getFuncName(func);
6545 if (!(funcName in LazyWrapper.prototype)) {
6548 var other = lodash[funcName];
6549 if (func === other) {
6552 var data = getData(other);
6553 return !!data && func === data[0];
6557 * Checks if `value` is a valid array-like length.
6559 * **Note:** This function is based on [`ToLength`](http://ecma-international.org/ecma-262/6.0/#sec-tolength).
6562 * @param {*} value The value to check.
6563 * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
6565 function isLength(value) {
6566 return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
6570 * Checks if `value` is suitable for strict equality comparisons, i.e. `===`.
6573 * @param {*} value The value to check.
6574 * @returns {boolean} Returns `true` if `value` if suitable for strict
6575 * equality comparisons, else `false`.
6577 function isStrictComparable(value) {
6578 return value === value && !isObject(value);
6582 * Merges the function metadata of `source` into `data`.
6584 * Merging metadata reduces the number of wrappers required to invoke a function.
6585 * This is possible because methods like `_.bind`, `_.curry`, and `_.partial`
6586 * may be applied regardless of execution order. Methods like `_.ary` and `_.rearg`
6587 * augment function arguments, making the order in which they are executed important,
6588 * preventing the merging of metadata. However, we make an exception for a safe
6589 * common case where curried functions have `_.ary` and or `_.rearg` applied.
6592 * @param {Array} data The destination metadata.
6593 * @param {Array} source The source metadata.
6594 * @returns {Array} Returns `data`.
6596 function mergeData(data, source) {
6597 var bitmask = data[1],
6598 srcBitmask = source[1],
6599 newBitmask = bitmask | srcBitmask,
6600 isCommon = newBitmask < ARY_FLAG;
6603 (srcBitmask == ARY_FLAG && bitmask == CURRY_FLAG) ||
6604 (srcBitmask == ARY_FLAG && bitmask == REARG_FLAG && data[7].length <= source[8]) ||
6605 (srcBitmask == (ARY_FLAG | REARG_FLAG) && bitmask == CURRY_FLAG);
6607 // Exit early if metadata can't be merged.
6608 if (!(isCommon || isCombo)) {
6611 // Use source `thisArg` if available.
6612 if (srcBitmask & BIND_FLAG) {
6613 data[2] = source[2];
6614 // Set when currying a bound function.
6615 newBitmask |= (bitmask & BIND_FLAG) ? 0 : CURRY_BOUND_FLAG;
6617 // Compose partial arguments.
6618 var value = source[3];
6620 var partials = data[3];
6621 data[3] = partials ? composeArgs(partials, value, source[4]) : arrayCopy(value);
6622 data[4] = partials ? replaceHolders(data[3], PLACEHOLDER) : arrayCopy(source[4]);
6624 // Compose partial right arguments.
6628 data[5] = partials ? composeArgsRight(partials, value, source[6]) : arrayCopy(value);
6629 data[6] = partials ? replaceHolders(data[5], PLACEHOLDER) : arrayCopy(source[6]);
6631 // Use source `argPos` if available.
6634 data[7] = arrayCopy(value);
6636 // Use source `ary` if it's smaller.
6637 if (srcBitmask & ARY_FLAG) {
6638 data[8] = data[8] == null ? source[8] : nativeMin(data[8], source[8]);
6640 // Use source `arity` if one is not provided.
6641 if (data[9] == null) {
6642 data[9] = source[9];
6644 // Use source `func` and merge bitmasks.
6645 data[0] = source[0];
6646 data[1] = newBitmask;
6652 * Used by `_.defaultsDeep` to customize its `_.merge` use.
6655 * @param {*} objectValue The destination object property value.
6656 * @param {*} sourceValue The source object property value.
6657 * @returns {*} Returns the value to assign to the destination object.
6659 function mergeDefaults(objectValue, sourceValue) {
6660 return objectValue === undefined ? sourceValue : merge(objectValue, sourceValue, mergeDefaults);
6664 * A specialized version of `_.pick` which picks `object` properties specified
6668 * @param {Object} object The source object.
6669 * @param {string[]} props The property names to pick.
6670 * @returns {Object} Returns the new object.
6672 function pickByArray(object, props) {
6673 object = toObject(object);
6676 length = props.length,
6679 while (++index < length) {
6680 var key = props[index];
6681 if (key in object) {
6682 result[key] = object[key];
6689 * A specialized version of `_.pick` which picks `object` properties `predicate`
6690 * returns truthy for.
6693 * @param {Object} object The source object.
6694 * @param {Function} predicate The function invoked per iteration.
6695 * @returns {Object} Returns the new object.
6697 function pickByCallback(object, predicate) {
6699 baseForIn(object, function(value, key, object) {
6700 if (predicate(value, key, object)) {
6701 result[key] = value;
6708 * Reorder `array` according to the specified indexes where the element at
6709 * the first index is assigned as the first element, the element at
6710 * the second index is assigned as the second element, and so on.
6713 * @param {Array} array The array to reorder.
6714 * @param {Array} indexes The arranged array indexes.
6715 * @returns {Array} Returns `array`.
6717 function reorder(array, indexes) {
6718 var arrLength = array.length,
6719 length = nativeMin(indexes.length, arrLength),
6720 oldArray = arrayCopy(array);
6723 var index = indexes[length];
6724 array[length] = isIndex(index, arrLength) ? oldArray[index] : undefined;
6730 * Sets metadata for `func`.
6732 * **Note:** If this function becomes hot, i.e. is invoked a lot in a short
6733 * period of time, it will trip its breaker and transition to an identity function
6734 * to avoid garbage collection pauses in V8. See [V8 issue 2070](https://code.google.com/p/v8/issues/detail?id=2070)
6738 * @param {Function} func The function to associate metadata with.
6739 * @param {*} data The metadata.
6740 * @returns {Function} Returns `func`.
6742 var setData = (function() {
6746 return function(key, value) {
6748 remaining = HOT_SPAN - (stamp - lastCalled);
6751 if (remaining > 0) {
6752 if (++count >= HOT_COUNT) {
6758 return baseSetData(key, value);
6763 * A fallback implementation of `Object.keys` which creates an array of the
6764 * own enumerable property names of `object`.
6767 * @param {Object} object The object to query.
6768 * @returns {Array} Returns the array of property names.
6770 function shimKeys(object) {
6771 var props = keysIn(object),
6772 propsLength = props.length,
6773 length = propsLength && object.length;
6775 var allowIndexes = !!length && isLength(length) &&
6776 (isArray(object) || isArguments(object));
6781 while (++index < propsLength) {
6782 var key = props[index];
6783 if ((allowIndexes && isIndex(key, length)) || hasOwnProperty.call(object, key)) {
6791 * Converts `value` to an array-like object if it's not one.
6794 * @param {*} value The value to process.
6795 * @returns {Array|Object} Returns the array-like object.
6797 function toIterable(value) {
6798 if (value == null) {
6801 if (!isArrayLike(value)) {
6802 return values(value);
6804 return isObject(value) ? value : Object(value);
6808 * Converts `value` to an object if it's not one.
6811 * @param {*} value The value to process.
6812 * @returns {Object} Returns the object.
6814 function toObject(value) {
6815 return isObject(value) ? value : Object(value);
6819 * Converts `value` to property path array if it's not one.
6822 * @param {*} value The value to process.
6823 * @returns {Array} Returns the property path array.
6825 function toPath(value) {
6826 if (isArray(value)) {
6830 baseToString(value).replace(rePropName, function(match, number, quote, string) {
6831 result.push(quote ? string.replace(reEscapeChar, '$1') : (number || match));
6837 * Creates a clone of `wrapper`.
6840 * @param {Object} wrapper The wrapper to clone.
6841 * @returns {Object} Returns the cloned wrapper.
6843 function wrapperClone(wrapper) {
6844 return wrapper instanceof LazyWrapper
6846 : new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__, arrayCopy(wrapper.__actions__));
6849 /*------------------------------------------------------------------------*/
6852 * Creates an array of elements split into groups the length of `size`.
6853 * If `collection` can't be split evenly, the final chunk will be the remaining
6859 * @param {Array} array The array to process.
6860 * @param {number} [size=1] The length of each chunk.
6861 * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
6862 * @returns {Array} Returns the new array containing chunks.
6865 * _.chunk(['a', 'b', 'c', 'd'], 2);
6866 * // => [['a', 'b'], ['c', 'd']]
6868 * _.chunk(['a', 'b', 'c', 'd'], 3);
6869 * // => [['a', 'b', 'c'], ['d']]
6871 function chunk(array, size, guard) {
6872 if (guard ? isIterateeCall(array, size, guard) : size == null) {
6875 size = nativeMax(nativeFloor(size) || 1, 1);
6878 length = array ? array.length : 0,
6880 result = Array(nativeCeil(length / size));
6882 while (index < length) {
6883 result[++resIndex] = baseSlice(array, index, (index += size));
6889 * Creates an array with all falsey values removed. The values `false`, `null`,
6890 * `0`, `""`, `undefined`, and `NaN` are falsey.
6895 * @param {Array} array The array to compact.
6896 * @returns {Array} Returns the new array of filtered values.
6899 * _.compact([0, 1, false, 2, '', 3]);
6902 function compact(array) {
6904 length = array ? array.length : 0,
6908 while (++index < length) {
6909 var value = array[index];
6911 result[++resIndex] = value;
6918 * Creates an array of unique `array` values not included in the other
6919 * provided arrays using [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
6920 * for equality comparisons.
6925 * @param {Array} array The array to inspect.
6926 * @param {...Array} [values] The arrays of values to exclude.
6927 * @returns {Array} Returns the new array of filtered values.
6930 * _.difference([1, 2, 3], [4, 2]);
6933 var difference = restParam(function(array, values) {
6934 return (isObjectLike(array) && isArrayLike(array))
6935 ? baseDifference(array, baseFlatten(values, false, true))
6940 * Creates a slice of `array` with `n` elements dropped from the beginning.
6945 * @param {Array} array The array to query.
6946 * @param {number} [n=1] The number of elements to drop.
6947 * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
6948 * @returns {Array} Returns the slice of `array`.
6951 * _.drop([1, 2, 3]);
6954 * _.drop([1, 2, 3], 2);
6957 * _.drop([1, 2, 3], 5);
6960 * _.drop([1, 2, 3], 0);
6963 function drop(array, n, guard) {
6964 var length = array ? array.length : 0;
6968 if (guard ? isIterateeCall(array, n, guard) : n == null) {
6971 return baseSlice(array, n < 0 ? 0 : n);
6975 * Creates a slice of `array` with `n` elements dropped from the end.
6980 * @param {Array} array The array to query.
6981 * @param {number} [n=1] The number of elements to drop.
6982 * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
6983 * @returns {Array} Returns the slice of `array`.
6986 * _.dropRight([1, 2, 3]);
6989 * _.dropRight([1, 2, 3], 2);
6992 * _.dropRight([1, 2, 3], 5);
6995 * _.dropRight([1, 2, 3], 0);
6998 function dropRight(array, n, guard) {
6999 var length = array ? array.length : 0;
7003 if (guard ? isIterateeCall(array, n, guard) : n == null) {
7006 n = length - (+n || 0);
7007 return baseSlice(array, 0, n < 0 ? 0 : n);
7011 * Creates a slice of `array` excluding elements dropped from the end.
7012 * Elements are dropped until `predicate` returns falsey. The predicate is
7013 * bound to `thisArg` and invoked with three arguments: (value, index, array).
7015 * If a property name is provided for `predicate` the created `_.property`
7016 * style callback returns the property value of the given element.
7018 * If a value is also provided for `thisArg` the created `_.matchesProperty`
7019 * style callback returns `true` for elements that have a matching property
7020 * value, else `false`.
7022 * If an object is provided for `predicate` the created `_.matches` style
7023 * callback returns `true` for elements that match the properties of the given
7024 * object, else `false`.
7029 * @param {Array} array The array to query.
7030 * @param {Function|Object|string} [predicate=_.identity] The function invoked
7032 * @param {*} [thisArg] The `this` binding of `predicate`.
7033 * @returns {Array} Returns the slice of `array`.
7036 * _.dropRightWhile([1, 2, 3], function(n) {
7042 * { 'user': 'barney', 'active': true },
7043 * { 'user': 'fred', 'active': false },
7044 * { 'user': 'pebbles', 'active': false }
7047 * // using the `_.matches` callback shorthand
7048 * _.pluck(_.dropRightWhile(users, { 'user': 'pebbles', 'active': false }), 'user');
7049 * // => ['barney', 'fred']
7051 * // using the `_.matchesProperty` callback shorthand
7052 * _.pluck(_.dropRightWhile(users, 'active', false), 'user');
7055 * // using the `_.property` callback shorthand
7056 * _.pluck(_.dropRightWhile(users, 'active'), 'user');
7057 * // => ['barney', 'fred', 'pebbles']
7059 function dropRightWhile(array, predicate, thisArg) {
7060 return (array && array.length)
7061 ? baseWhile(array, getCallback(predicate, thisArg, 3), true, true)
7066 * Creates a slice of `array` excluding elements dropped from the beginning.
7067 * Elements are dropped until `predicate` returns falsey. The predicate is
7068 * bound to `thisArg` and invoked with three arguments: (value, index, array).
7070 * If a property name is provided for `predicate` the created `_.property`
7071 * style callback returns the property value of the given element.
7073 * If a value is also provided for `thisArg` the created `_.matchesProperty`
7074 * style callback returns `true` for elements that have a matching property
7075 * value, else `false`.
7077 * If an object is provided for `predicate` the created `_.matches` style
7078 * callback returns `true` for elements that have the properties of the given
7079 * object, else `false`.
7084 * @param {Array} array The array to query.
7085 * @param {Function|Object|string} [predicate=_.identity] The function invoked
7087 * @param {*} [thisArg] The `this` binding of `predicate`.
7088 * @returns {Array} Returns the slice of `array`.
7091 * _.dropWhile([1, 2, 3], function(n) {
7097 * { 'user': 'barney', 'active': false },
7098 * { 'user': 'fred', 'active': false },
7099 * { 'user': 'pebbles', 'active': true }
7102 * // using the `_.matches` callback shorthand
7103 * _.pluck(_.dropWhile(users, { 'user': 'barney', 'active': false }), 'user');
7104 * // => ['fred', 'pebbles']
7106 * // using the `_.matchesProperty` callback shorthand
7107 * _.pluck(_.dropWhile(users, 'active', false), 'user');
7110 * // using the `_.property` callback shorthand
7111 * _.pluck(_.dropWhile(users, 'active'), 'user');
7112 * // => ['barney', 'fred', 'pebbles']
7114 function dropWhile(array, predicate, thisArg) {
7115 return (array && array.length)
7116 ? baseWhile(array, getCallback(predicate, thisArg, 3), true)
7121 * Fills elements of `array` with `value` from `start` up to, but not
7124 * **Note:** This method mutates `array`.
7129 * @param {Array} array The array to fill.
7130 * @param {*} value The value to fill `array` with.
7131 * @param {number} [start=0] The start position.
7132 * @param {number} [end=array.length] The end position.
7133 * @returns {Array} Returns `array`.
7136 * var array = [1, 2, 3];
7138 * _.fill(array, 'a');
7139 * console.log(array);
7140 * // => ['a', 'a', 'a']
7142 * _.fill(Array(3), 2);
7145 * _.fill([4, 6, 8], '*', 1, 2);
7148 function fill(array, value, start, end) {
7149 var length = array ? array.length : 0;
7153 if (start && typeof start != 'number' && isIterateeCall(array, value, start)) {
7157 return baseFill(array, value, start, end);
7161 * This method is like `_.find` except that it returns the index of the first
7162 * element `predicate` returns truthy for instead of the element itself.
7164 * If a property name is provided for `predicate` the created `_.property`
7165 * style callback returns the property value of the given element.
7167 * If a value is also provided for `thisArg` the created `_.matchesProperty`
7168 * style callback returns `true` for elements that have a matching property
7169 * value, else `false`.
7171 * If an object is provided for `predicate` the created `_.matches` style
7172 * callback returns `true` for elements that have the properties of the given
7173 * object, else `false`.
7178 * @param {Array} array The array to search.
7179 * @param {Function|Object|string} [predicate=_.identity] The function invoked
7181 * @param {*} [thisArg] The `this` binding of `predicate`.
7182 * @returns {number} Returns the index of the found element, else `-1`.
7186 * { 'user': 'barney', 'active': false },
7187 * { 'user': 'fred', 'active': false },
7188 * { 'user': 'pebbles', 'active': true }
7191 * _.findIndex(users, function(chr) {
7192 * return chr.user == 'barney';
7196 * // using the `_.matches` callback shorthand
7197 * _.findIndex(users, { 'user': 'fred', 'active': false });
7200 * // using the `_.matchesProperty` callback shorthand
7201 * _.findIndex(users, 'active', false);
7204 * // using the `_.property` callback shorthand
7205 * _.findIndex(users, 'active');
7208 var findIndex = createFindIndex();
7211 * This method is like `_.findIndex` except that it iterates over elements
7212 * of `collection` from right to left.
7214 * If a property name is provided for `predicate` the created `_.property`
7215 * style callback returns the property value of the given element.
7217 * If a value is also provided for `thisArg` the created `_.matchesProperty`
7218 * style callback returns `true` for elements that have a matching property
7219 * value, else `false`.
7221 * If an object is provided for `predicate` the created `_.matches` style
7222 * callback returns `true` for elements that have the properties of the given
7223 * object, else `false`.
7228 * @param {Array} array The array to search.
7229 * @param {Function|Object|string} [predicate=_.identity] The function invoked
7231 * @param {*} [thisArg] The `this` binding of `predicate`.
7232 * @returns {number} Returns the index of the found element, else `-1`.
7236 * { 'user': 'barney', 'active': true },
7237 * { 'user': 'fred', 'active': false },
7238 * { 'user': 'pebbles', 'active': false }
7241 * _.findLastIndex(users, function(chr) {
7242 * return chr.user == 'pebbles';
7246 * // using the `_.matches` callback shorthand
7247 * _.findLastIndex(users, { 'user': 'barney', 'active': true });
7250 * // using the `_.matchesProperty` callback shorthand
7251 * _.findLastIndex(users, 'active', false);
7254 * // using the `_.property` callback shorthand
7255 * _.findLastIndex(users, 'active');
7258 var findLastIndex = createFindIndex(true);
7261 * Gets the first element of `array`.
7267 * @param {Array} array The array to query.
7268 * @returns {*} Returns the first element of `array`.
7271 * _.first([1, 2, 3]);
7277 function first(array) {
7278 return array ? array[0] : undefined;
7282 * Flattens a nested array. If `isDeep` is `true` the array is recursively
7283 * flattened, otherwise it is only flattened a single level.
7288 * @param {Array} array The array to flatten.
7289 * @param {boolean} [isDeep] Specify a deep flatten.
7290 * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
7291 * @returns {Array} Returns the new flattened array.
7294 * _.flatten([1, [2, 3, [4]]]);
7295 * // => [1, 2, 3, [4]]
7298 * _.flatten([1, [2, 3, [4]]], true);
7299 * // => [1, 2, 3, 4]
7301 function flatten(array, isDeep, guard) {
7302 var length = array ? array.length : 0;
7303 if (guard && isIterateeCall(array, isDeep, guard)) {
7306 return length ? baseFlatten(array, isDeep) : [];
7310 * Recursively flattens a nested array.
7315 * @param {Array} array The array to recursively flatten.
7316 * @returns {Array} Returns the new flattened array.
7319 * _.flattenDeep([1, [2, 3, [4]]]);
7320 * // => [1, 2, 3, 4]
7322 function flattenDeep(array) {
7323 var length = array ? array.length : 0;
7324 return length ? baseFlatten(array, true) : [];
7328 * Gets the index at which the first occurrence of `value` is found in `array`
7329 * using [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
7330 * for equality comparisons. If `fromIndex` is negative, it is used as the offset
7331 * from the end of `array`. If `array` is sorted providing `true` for `fromIndex`
7332 * performs a faster binary search.
7337 * @param {Array} array The array to search.
7338 * @param {*} value The value to search for.
7339 * @param {boolean|number} [fromIndex=0] The index to search from or `true`
7340 * to perform a binary search on a sorted array.
7341 * @returns {number} Returns the index of the matched value, else `-1`.
7344 * _.indexOf([1, 2, 1, 2], 2);
7347 * // using `fromIndex`
7348 * _.indexOf([1, 2, 1, 2], 2, 2);
7351 * // performing a binary search
7352 * _.indexOf([1, 1, 2, 2], 2, true);
7355 function indexOf(array, value, fromIndex) {
7356 var length = array ? array.length : 0;
7360 if (typeof fromIndex == 'number') {
7361 fromIndex = fromIndex < 0 ? nativeMax(length + fromIndex, 0) : fromIndex;
7362 } else if (fromIndex) {
7363 var index = binaryIndex(array, value);
7364 if (index < length &&
7365 (value === value ? (value === array[index]) : (array[index] !== array[index]))) {
7370 return baseIndexOf(array, value, fromIndex || 0);
7374 * Gets all but the last element of `array`.
7379 * @param {Array} array The array to query.
7380 * @returns {Array} Returns the slice of `array`.
7383 * _.initial([1, 2, 3]);
7386 function initial(array) {
7387 return dropRight(array, 1);
7391 * Creates an array of unique values that are included in all of the provided
7392 * arrays using [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
7393 * for equality comparisons.
7398 * @param {...Array} [arrays] The arrays to inspect.
7399 * @returns {Array} Returns the new array of shared values.
7401 * _.intersection([1, 2], [4, 2], [2, 1]);
7404 var intersection = restParam(function(arrays) {
7405 var othLength = arrays.length,
7406 othIndex = othLength,
7407 caches = Array(length),
7408 indexOf = getIndexOf(),
7409 isCommon = indexOf == baseIndexOf,
7412 while (othIndex--) {
7413 var value = arrays[othIndex] = isArrayLike(value = arrays[othIndex]) ? value : [];
7414 caches[othIndex] = (isCommon && value.length >= 120) ? createCache(othIndex && value) : null;
7416 var array = arrays[0],
7418 length = array ? array.length : 0,
7422 while (++index < length) {
7423 value = array[index];
7424 if ((seen ? cacheIndexOf(seen, value) : indexOf(result, value, 0)) < 0) {
7425 var othIndex = othLength;
7426 while (--othIndex) {
7427 var cache = caches[othIndex];
7428 if ((cache ? cacheIndexOf(cache, value) : indexOf(arrays[othIndex], value, 0)) < 0) {
7442 * Gets the last element of `array`.
7447 * @param {Array} array The array to query.
7448 * @returns {*} Returns the last element of `array`.
7451 * _.last([1, 2, 3]);
7454 function last(array) {
7455 var length = array ? array.length : 0;
7456 return length ? array[length - 1] : undefined;
7460 * This method is like `_.indexOf` except that it iterates over elements of
7461 * `array` from right to left.
7466 * @param {Array} array The array to search.
7467 * @param {*} value The value to search for.
7468 * @param {boolean|number} [fromIndex=array.length-1] The index to search from
7469 * or `true` to perform a binary search on a sorted array.
7470 * @returns {number} Returns the index of the matched value, else `-1`.
7473 * _.lastIndexOf([1, 2, 1, 2], 2);
7476 * // using `fromIndex`
7477 * _.lastIndexOf([1, 2, 1, 2], 2, 2);
7480 * // performing a binary search
7481 * _.lastIndexOf([1, 1, 2, 2], 2, true);
7484 function lastIndexOf(array, value, fromIndex) {
7485 var length = array ? array.length : 0;
7490 if (typeof fromIndex == 'number') {
7491 index = (fromIndex < 0 ? nativeMax(length + fromIndex, 0) : nativeMin(fromIndex || 0, length - 1)) + 1;
7492 } else if (fromIndex) {
7493 index = binaryIndex(array, value, true) - 1;
7494 var other = array[index];
7495 if (value === value ? (value === other) : (other !== other)) {
7500 if (value !== value) {
7501 return indexOfNaN(array, index, true);
7504 if (array[index] === value) {
7512 * Removes all provided values from `array` using
7513 * [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
7514 * for equality comparisons.
7516 * **Note:** Unlike `_.without`, this method mutates `array`.
7521 * @param {Array} array The array to modify.
7522 * @param {...*} [values] The values to remove.
7523 * @returns {Array} Returns `array`.
7526 * var array = [1, 2, 3, 1, 2, 3];
7528 * _.pull(array, 2, 3);
7529 * console.log(array);
7533 var args = arguments,
7536 if (!(array && array.length)) {
7540 indexOf = getIndexOf(),
7541 length = args.length;
7543 while (++index < length) {
7545 value = args[index];
7547 while ((fromIndex = indexOf(array, value, fromIndex)) > -1) {
7548 splice.call(array, fromIndex, 1);
7555 * Removes elements from `array` corresponding to the given indexes and returns
7556 * an array of the removed elements. Indexes may be specified as an array of
7557 * indexes or as individual arguments.
7559 * **Note:** Unlike `_.at`, this method mutates `array`.
7564 * @param {Array} array The array to modify.
7565 * @param {...(number|number[])} [indexes] The indexes of elements to remove,
7566 * specified as individual indexes or arrays of indexes.
7567 * @returns {Array} Returns the new array of removed elements.
7570 * var array = [5, 10, 15, 20];
7571 * var evens = _.pullAt(array, 1, 3);
7573 * console.log(array);
7576 * console.log(evens);
7579 var pullAt = restParam(function(array, indexes) {
7580 indexes = baseFlatten(indexes);
7582 var result = baseAt(array, indexes);
7583 basePullAt(array, indexes.sort(baseCompareAscending));
7588 * Removes all elements from `array` that `predicate` returns truthy for
7589 * and returns an array of the removed elements. The predicate is bound to
7590 * `thisArg` and invoked with three arguments: (value, index, array).
7592 * If a property name is provided for `predicate` the created `_.property`
7593 * style callback returns the property value of the given element.
7595 * If a value is also provided for `thisArg` the created `_.matchesProperty`
7596 * style callback returns `true` for elements that have a matching property
7597 * value, else `false`.
7599 * If an object is provided for `predicate` the created `_.matches` style
7600 * callback returns `true` for elements that have the properties of the given
7601 * object, else `false`.
7603 * **Note:** Unlike `_.filter`, this method mutates `array`.
7608 * @param {Array} array The array to modify.
7609 * @param {Function|Object|string} [predicate=_.identity] The function invoked
7611 * @param {*} [thisArg] The `this` binding of `predicate`.
7612 * @returns {Array} Returns the new array of removed elements.
7615 * var array = [1, 2, 3, 4];
7616 * var evens = _.remove(array, function(n) {
7617 * return n % 2 == 0;
7620 * console.log(array);
7623 * console.log(evens);
7626 function remove(array, predicate, thisArg) {
7628 if (!(array && array.length)) {
7633 length = array.length;
7635 predicate = getCallback(predicate, thisArg, 3);
7636 while (++index < length) {
7637 var value = array[index];
7638 if (predicate(value, index, array)) {
7640 indexes.push(index);
7643 basePullAt(array, indexes);
7648 * Gets all but the first element of `array`.
7654 * @param {Array} array The array to query.
7655 * @returns {Array} Returns the slice of `array`.
7658 * _.rest([1, 2, 3]);
7661 function rest(array) {
7662 return drop(array, 1);
7666 * Creates a slice of `array` from `start` up to, but not including, `end`.
7668 * **Note:** This method is used instead of `Array#slice` to support node
7669 * lists in IE < 9 and to ensure dense arrays are returned.
7674 * @param {Array} array The array to slice.
7675 * @param {number} [start=0] The start position.
7676 * @param {number} [end=array.length] The end position.
7677 * @returns {Array} Returns the slice of `array`.
7679 function slice(array, start, end) {
7680 var length = array ? array.length : 0;
7684 if (end && typeof end != 'number' && isIterateeCall(array, start, end)) {
7688 return baseSlice(array, start, end);
7692 * Uses a binary search to determine the lowest index at which `value` should
7693 * be inserted into `array` in order to maintain its sort order. If an iteratee
7694 * function is provided it is invoked for `value` and each element of `array`
7695 * to compute their sort ranking. The iteratee is bound to `thisArg` and
7696 * invoked with one argument; (value).
7698 * If a property name is provided for `iteratee` the created `_.property`
7699 * style callback returns the property value of the given element.
7701 * If a value is also provided for `thisArg` the created `_.matchesProperty`
7702 * style callback returns `true` for elements that have a matching property
7703 * value, else `false`.
7705 * If an object is provided for `iteratee` the created `_.matches` style
7706 * callback returns `true` for elements that have the properties of the given
7707 * object, else `false`.
7712 * @param {Array} array The sorted array to inspect.
7713 * @param {*} value The value to evaluate.
7714 * @param {Function|Object|string} [iteratee=_.identity] The function invoked
7716 * @param {*} [thisArg] The `this` binding of `iteratee`.
7717 * @returns {number} Returns the index at which `value` should be inserted
7721 * _.sortedIndex([30, 50], 40);
7724 * _.sortedIndex([4, 4, 5, 5], 5);
7727 * var dict = { 'data': { 'thirty': 30, 'forty': 40, 'fifty': 50 } };
7729 * // using an iteratee function
7730 * _.sortedIndex(['thirty', 'fifty'], 'forty', function(word) {
7731 * return this.data[word];
7735 * // using the `_.property` callback shorthand
7736 * _.sortedIndex([{ 'x': 30 }, { 'x': 50 }], { 'x': 40 }, 'x');
7739 var sortedIndex = createSortedIndex();
7742 * This method is like `_.sortedIndex` except that it returns the highest
7743 * index at which `value` should be inserted into `array` in order to
7744 * maintain its sort order.
7749 * @param {Array} array The sorted array to inspect.
7750 * @param {*} value The value to evaluate.
7751 * @param {Function|Object|string} [iteratee=_.identity] The function invoked
7753 * @param {*} [thisArg] The `this` binding of `iteratee`.
7754 * @returns {number} Returns the index at which `value` should be inserted
7758 * _.sortedLastIndex([4, 4, 5, 5], 5);
7761 var sortedLastIndex = createSortedIndex(true);
7764 * Creates a slice of `array` with `n` elements taken from the beginning.
7769 * @param {Array} array The array to query.
7770 * @param {number} [n=1] The number of elements to take.
7771 * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
7772 * @returns {Array} Returns the slice of `array`.
7775 * _.take([1, 2, 3]);
7778 * _.take([1, 2, 3], 2);
7781 * _.take([1, 2, 3], 5);
7784 * _.take([1, 2, 3], 0);
7787 function take(array, n, guard) {
7788 var length = array ? array.length : 0;
7792 if (guard ? isIterateeCall(array, n, guard) : n == null) {
7795 return baseSlice(array, 0, n < 0 ? 0 : n);
7799 * Creates a slice of `array` with `n` elements taken from the end.
7804 * @param {Array} array The array to query.
7805 * @param {number} [n=1] The number of elements to take.
7806 * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
7807 * @returns {Array} Returns the slice of `array`.
7810 * _.takeRight([1, 2, 3]);
7813 * _.takeRight([1, 2, 3], 2);
7816 * _.takeRight([1, 2, 3], 5);
7819 * _.takeRight([1, 2, 3], 0);
7822 function takeRight(array, n, guard) {
7823 var length = array ? array.length : 0;
7827 if (guard ? isIterateeCall(array, n, guard) : n == null) {
7830 n = length - (+n || 0);
7831 return baseSlice(array, n < 0 ? 0 : n);
7835 * Creates a slice of `array` with elements taken from the end. Elements are
7836 * taken until `predicate` returns falsey. The predicate is bound to `thisArg`
7837 * and invoked with three arguments: (value, index, array).
7839 * If a property name is provided for `predicate` the created `_.property`
7840 * style callback returns the property value of the given element.
7842 * If a value is also provided for `thisArg` the created `_.matchesProperty`
7843 * style callback returns `true` for elements that have a matching property
7844 * value, else `false`.
7846 * If an object is provided for `predicate` the created `_.matches` style
7847 * callback returns `true` for elements that have the properties of the given
7848 * object, else `false`.
7853 * @param {Array} array The array to query.
7854 * @param {Function|Object|string} [predicate=_.identity] The function invoked
7856 * @param {*} [thisArg] The `this` binding of `predicate`.
7857 * @returns {Array} Returns the slice of `array`.
7860 * _.takeRightWhile([1, 2, 3], function(n) {
7866 * { 'user': 'barney', 'active': true },
7867 * { 'user': 'fred', 'active': false },
7868 * { 'user': 'pebbles', 'active': false }
7871 * // using the `_.matches` callback shorthand
7872 * _.pluck(_.takeRightWhile(users, { 'user': 'pebbles', 'active': false }), 'user');
7875 * // using the `_.matchesProperty` callback shorthand
7876 * _.pluck(_.takeRightWhile(users, 'active', false), 'user');
7877 * // => ['fred', 'pebbles']
7879 * // using the `_.property` callback shorthand
7880 * _.pluck(_.takeRightWhile(users, 'active'), 'user');
7883 function takeRightWhile(array, predicate, thisArg) {
7884 return (array && array.length)
7885 ? baseWhile(array, getCallback(predicate, thisArg, 3), false, true)
7890 * Creates a slice of `array` with elements taken from the beginning. Elements
7891 * are taken until `predicate` returns falsey. The predicate is bound to
7892 * `thisArg` and invoked with three arguments: (value, index, array).
7894 * If a property name is provided for `predicate` the created `_.property`
7895 * style callback returns the property value of the given element.
7897 * If a value is also provided for `thisArg` the created `_.matchesProperty`
7898 * style callback returns `true` for elements that have a matching property
7899 * value, else `false`.
7901 * If an object is provided for `predicate` the created `_.matches` style
7902 * callback returns `true` for elements that have the properties of the given
7903 * object, else `false`.
7908 * @param {Array} array The array to query.
7909 * @param {Function|Object|string} [predicate=_.identity] The function invoked
7911 * @param {*} [thisArg] The `this` binding of `predicate`.
7912 * @returns {Array} Returns the slice of `array`.
7915 * _.takeWhile([1, 2, 3], function(n) {
7921 * { 'user': 'barney', 'active': false },
7922 * { 'user': 'fred', 'active': false},
7923 * { 'user': 'pebbles', 'active': true }
7926 * // using the `_.matches` callback shorthand
7927 * _.pluck(_.takeWhile(users, { 'user': 'barney', 'active': false }), 'user');
7930 * // using the `_.matchesProperty` callback shorthand
7931 * _.pluck(_.takeWhile(users, 'active', false), 'user');
7932 * // => ['barney', 'fred']
7934 * // using the `_.property` callback shorthand
7935 * _.pluck(_.takeWhile(users, 'active'), 'user');
7938 function takeWhile(array, predicate, thisArg) {
7939 return (array && array.length)
7940 ? baseWhile(array, getCallback(predicate, thisArg, 3))
7945 * Creates an array of unique values, in order, from all of the provided arrays
7946 * using [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
7947 * for equality comparisons.
7952 * @param {...Array} [arrays] The arrays to inspect.
7953 * @returns {Array} Returns the new array of combined values.
7956 * _.union([1, 2], [4, 2], [2, 1]);
7959 var union = restParam(function(arrays) {
7960 return baseUniq(baseFlatten(arrays, false, true));
7964 * Creates a duplicate-free version of an array, using
7965 * [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
7966 * for equality comparisons, in which only the first occurence of each element
7967 * is kept. Providing `true` for `isSorted` performs a faster search algorithm
7968 * for sorted arrays. If an iteratee function is provided it is invoked for
7969 * each element in the array to generate the criterion by which uniqueness
7970 * is computed. The `iteratee` is bound to `thisArg` and invoked with three
7971 * arguments: (value, index, array).
7973 * If a property name is provided for `iteratee` the created `_.property`
7974 * style callback returns the property value of the given element.
7976 * If a value is also provided for `thisArg` the created `_.matchesProperty`
7977 * style callback returns `true` for elements that have a matching property
7978 * value, else `false`.
7980 * If an object is provided for `iteratee` the created `_.matches` style
7981 * callback returns `true` for elements that have the properties of the given
7982 * object, else `false`.
7988 * @param {Array} array The array to inspect.
7989 * @param {boolean} [isSorted] Specify the array is sorted.
7990 * @param {Function|Object|string} [iteratee] The function invoked per iteration.
7991 * @param {*} [thisArg] The `this` binding of `iteratee`.
7992 * @returns {Array} Returns the new duplicate-value-free array.
7995 * _.uniq([2, 1, 2]);
7998 * // using `isSorted`
7999 * _.uniq([1, 1, 2], true);
8002 * // using an iteratee function
8003 * _.uniq([1, 2.5, 1.5, 2], function(n) {
8004 * return this.floor(n);
8008 * // using the `_.property` callback shorthand
8009 * _.uniq([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x');
8010 * // => [{ 'x': 1 }, { 'x': 2 }]
8012 function uniq(array, isSorted, iteratee, thisArg) {
8013 var length = array ? array.length : 0;
8017 if (isSorted != null && typeof isSorted != 'boolean') {
8019 iteratee = isIterateeCall(array, isSorted, thisArg) ? undefined : isSorted;
8022 var callback = getCallback();
8023 if (!(iteratee == null && callback === baseCallback)) {
8024 iteratee = callback(iteratee, thisArg, 3);
8026 return (isSorted && getIndexOf() == baseIndexOf)
8027 ? sortedUniq(array, iteratee)
8028 : baseUniq(array, iteratee);
8032 * This method is like `_.zip` except that it accepts an array of grouped
8033 * elements and creates an array regrouping the elements to their pre-zip
8039 * @param {Array} array The array of grouped elements to process.
8040 * @returns {Array} Returns the new array of regrouped elements.
8043 * var zipped = _.zip(['fred', 'barney'], [30, 40], [true, false]);
8044 * // => [['fred', 30, true], ['barney', 40, false]]
8047 * // => [['fred', 'barney'], [30, 40], [true, false]]
8049 function unzip(array) {
8050 if (!(array && array.length)) {
8056 array = arrayFilter(array, function(group) {
8057 if (isArrayLike(group)) {
8058 length = nativeMax(group.length, length);
8062 var result = Array(length);
8063 while (++index < length) {
8064 result[index] = arrayMap(array, baseProperty(index));
8070 * This method is like `_.unzip` except that it accepts an iteratee to specify
8071 * how regrouped values should be combined. The `iteratee` is bound to `thisArg`
8072 * and invoked with four arguments: (accumulator, value, index, group).
8077 * @param {Array} array The array of grouped elements to process.
8078 * @param {Function} [iteratee] The function to combine regrouped values.
8079 * @param {*} [thisArg] The `this` binding of `iteratee`.
8080 * @returns {Array} Returns the new array of regrouped elements.
8083 * var zipped = _.zip([1, 2], [10, 20], [100, 200]);
8084 * // => [[1, 10, 100], [2, 20, 200]]
8086 * _.unzipWith(zipped, _.add);
8087 * // => [3, 30, 300]
8089 function unzipWith(array, iteratee, thisArg) {
8090 var length = array ? array.length : 0;
8094 var result = unzip(array);
8095 if (iteratee == null) {
8098 iteratee = bindCallback(iteratee, thisArg, 4);
8099 return arrayMap(result, function(group) {
8100 return arrayReduce(group, iteratee, undefined, true);
8105 * Creates an array excluding all provided values using
8106 * [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
8107 * for equality comparisons.
8112 * @param {Array} array The array to filter.
8113 * @param {...*} [values] The values to exclude.
8114 * @returns {Array} Returns the new array of filtered values.
8117 * _.without([1, 2, 1, 3], 1, 2);
8120 var without = restParam(function(array, values) {
8121 return isArrayLike(array)
8122 ? baseDifference(array, values)
8127 * Creates an array of unique values that is the [symmetric difference](https://en.wikipedia.org/wiki/Symmetric_difference)
8128 * of the provided arrays.
8133 * @param {...Array} [arrays] The arrays to inspect.
8134 * @returns {Array} Returns the new array of values.
8137 * _.xor([1, 2], [4, 2]);
8142 length = arguments.length;
8144 while (++index < length) {
8145 var array = arguments[index];
8146 if (isArrayLike(array)) {
8148 ? arrayPush(baseDifference(result, array), baseDifference(array, result))
8152 return result ? baseUniq(result) : [];
8156 * Creates an array of grouped elements, the first of which contains the first
8157 * elements of the given arrays, the second of which contains the second elements
8158 * of the given arrays, and so on.
8163 * @param {...Array} [arrays] The arrays to process.
8164 * @returns {Array} Returns the new array of grouped elements.
8167 * _.zip(['fred', 'barney'], [30, 40], [true, false]);
8168 * // => [['fred', 30, true], ['barney', 40, false]]
8170 var zip = restParam(unzip);
8173 * The inverse of `_.pairs`; this method returns an object composed from arrays
8174 * of property names and values. Provide either a single two dimensional array,
8175 * e.g. `[[key1, value1], [key2, value2]]` or two arrays, one of property names
8176 * and one of corresponding values.
8182 * @param {Array} props The property names.
8183 * @param {Array} [values=[]] The property values.
8184 * @returns {Object} Returns the new object.
8187 * _.zipObject([['fred', 30], ['barney', 40]]);
8188 * // => { 'fred': 30, 'barney': 40 }
8190 * _.zipObject(['fred', 'barney'], [30, 40]);
8191 * // => { 'fred': 30, 'barney': 40 }
8193 function zipObject(props, values) {
8195 length = props ? props.length : 0,
8198 if (length && !values && !isArray(props[0])) {
8201 while (++index < length) {
8202 var key = props[index];
8204 result[key] = values[index];
8206 result[key[0]] = key[1];
8213 * This method is like `_.zip` except that it accepts an iteratee to specify
8214 * how grouped values should be combined. The `iteratee` is bound to `thisArg`
8215 * and invoked with four arguments: (accumulator, value, index, group).
8220 * @param {...Array} [arrays] The arrays to process.
8221 * @param {Function} [iteratee] The function to combine grouped values.
8222 * @param {*} [thisArg] The `this` binding of `iteratee`.
8223 * @returns {Array} Returns the new array of grouped elements.
8226 * _.zipWith([1, 2], [10, 20], [100, 200], _.add);
8229 var zipWith = restParam(function(arrays) {
8230 var length = arrays.length,
8231 iteratee = length > 2 ? arrays[length - 2] : undefined,
8232 thisArg = length > 1 ? arrays[length - 1] : undefined;
8234 if (length > 2 && typeof iteratee == 'function') {
8237 iteratee = (length > 1 && typeof thisArg == 'function') ? (--length, thisArg) : undefined;
8238 thisArg = undefined;
8240 arrays.length = length;
8241 return unzipWith(arrays, iteratee, thisArg);
8244 /*------------------------------------------------------------------------*/
8247 * Creates a `lodash` object that wraps `value` with explicit method
8253 * @param {*} value The value to wrap.
8254 * @returns {Object} Returns the new `lodash` wrapper instance.
8258 * { 'user': 'barney', 'age': 36 },
8259 * { 'user': 'fred', 'age': 40 },
8260 * { 'user': 'pebbles', 'age': 1 }
8263 * var youngest = _.chain(users)
8265 * .map(function(chr) {
8266 * return chr.user + ' is ' + chr.age;
8270 * // => 'pebbles is 1'
8272 function chain(value) {
8273 var result = lodash(value);
8274 result.__chain__ = true;
8279 * This method invokes `interceptor` and returns `value`. The interceptor is
8280 * bound to `thisArg` and invoked with one argument; (value). The purpose of
8281 * this method is to "tap into" a method chain in order to perform operations
8282 * on intermediate results within the chain.
8287 * @param {*} value The value to provide to `interceptor`.
8288 * @param {Function} interceptor The function to invoke.
8289 * @param {*} [thisArg] The `this` binding of `interceptor`.
8290 * @returns {*} Returns `value`.
8294 * .tap(function(array) {
8301 function tap(value, interceptor, thisArg) {
8302 interceptor.call(thisArg, value);
8307 * This method is like `_.tap` except that it returns the result of `interceptor`.
8312 * @param {*} value The value to provide to `interceptor`.
8313 * @param {Function} interceptor The function to invoke.
8314 * @param {*} [thisArg] The `this` binding of `interceptor`.
8315 * @returns {*} Returns the result of `interceptor`.
8321 * .thru(function(value) {
8327 function thru(value, interceptor, thisArg) {
8328 return interceptor.call(thisArg, value);
8332 * Enables explicit method chaining on the wrapper object.
8337 * @returns {Object} Returns the new `lodash` wrapper instance.
8341 * { 'user': 'barney', 'age': 36 },
8342 * { 'user': 'fred', 'age': 40 }
8345 * // without explicit chaining
8347 * // => { 'user': 'barney', 'age': 36 }
8349 * // with explicit chaining
8354 * // => { 'user': 'barney' }
8356 function wrapperChain() {
8361 * Executes the chained sequence and returns the wrapped result.
8366 * @returns {Object} Returns the new `lodash` wrapper instance.
8369 * var array = [1, 2];
8370 * var wrapped = _(array).push(3);
8372 * console.log(array);
8375 * wrapped = wrapped.commit();
8376 * console.log(array);
8382 * console.log(array);
8385 function wrapperCommit() {
8386 return new LodashWrapper(this.value(), this.__chain__);
8390 * Creates a new array joining a wrapped array with any additional arrays
8396 * @param {...*} [values] The values to concatenate.
8397 * @returns {Array} Returns the new concatenated array.
8401 * var wrapped = _(array).concat(2, [3], [[4]]);
8403 * console.log(wrapped.value());
8404 * // => [1, 2, 3, [4]]
8406 * console.log(array);
8409 var wrapperConcat = restParam(function(values) {
8410 values = baseFlatten(values);
8411 return this.thru(function(array) {
8412 return arrayConcat(isArray(array) ? array : [toObject(array)], values);
8417 * Creates a clone of the chained sequence planting `value` as the wrapped value.
8422 * @returns {Object} Returns the new `lodash` wrapper instance.
8425 * var array = [1, 2];
8426 * var wrapped = _(array).map(function(value) {
8427 * return Math.pow(value, 2);
8430 * var other = [3, 4];
8431 * var otherWrapped = wrapped.plant(other);
8433 * otherWrapped.value();
8439 function wrapperPlant(value) {
8443 while (parent instanceof baseLodash) {
8444 var clone = wrapperClone(parent);
8446 previous.__wrapped__ = clone;
8450 var previous = clone;
8451 parent = parent.__wrapped__;
8453 previous.__wrapped__ = value;
8458 * Reverses the wrapped array so the first element becomes the last, the
8459 * second element becomes the second to last, and so on.
8461 * **Note:** This method mutates the wrapped array.
8466 * @returns {Object} Returns the new reversed `lodash` wrapper instance.
8469 * var array = [1, 2, 3];
8471 * _(array).reverse().value()
8474 * console.log(array);
8477 function wrapperReverse() {
8478 var value = this.__wrapped__;
8480 var interceptor = function(value) {
8481 return (wrapped && wrapped.__dir__ < 0) ? value : value.reverse();
8483 if (value instanceof LazyWrapper) {
8484 var wrapped = value;
8485 if (this.__actions__.length) {
8486 wrapped = new LazyWrapper(this);
8488 wrapped = wrapped.reverse();
8489 wrapped.__actions__.push({ 'func': thru, 'args': [interceptor], 'thisArg': undefined });
8490 return new LodashWrapper(wrapped, this.__chain__);
8492 return this.thru(interceptor);
8496 * Produces the result of coercing the unwrapped value to a string.
8501 * @returns {string} Returns the coerced string value.
8504 * _([1, 2, 3]).toString();
8507 function wrapperToString() {
8508 return (this.value() + '');
8512 * Executes the chained sequence to extract the unwrapped value.
8516 * @alias run, toJSON, valueOf
8518 * @returns {*} Returns the resolved unwrapped value.
8521 * _([1, 2, 3]).value();
8524 function wrapperValue() {
8525 return baseWrapperValue(this.__wrapped__, this.__actions__);
8528 /*------------------------------------------------------------------------*/
8531 * Creates an array of elements corresponding to the given keys, or indexes,
8532 * of `collection`. Keys may be specified as individual arguments or as arrays
8537 * @category Collection
8538 * @param {Array|Object|string} collection The collection to iterate over.
8539 * @param {...(number|number[]|string|string[])} [props] The property names
8540 * or indexes of elements to pick, specified individually or in arrays.
8541 * @returns {Array} Returns the new array of picked elements.
8544 * _.at(['a', 'b', 'c'], [0, 2]);
8547 * _.at(['barney', 'fred', 'pebbles'], 0, 2);
8548 * // => ['barney', 'pebbles']
8550 var at = restParam(function(collection, props) {
8551 return baseAt(collection, baseFlatten(props));
8555 * Creates an object composed of keys generated from the results of running
8556 * each element of `collection` through `iteratee`. The corresponding value
8557 * of each key is the number of times the key was returned by `iteratee`.
8558 * The `iteratee` is bound to `thisArg` and invoked with three arguments:
8559 * (value, index|key, collection).
8561 * If a property name is provided for `iteratee` the created `_.property`
8562 * style callback returns the property value of the given element.
8564 * If a value is also provided for `thisArg` the created `_.matchesProperty`
8565 * style callback returns `true` for elements that have a matching property
8566 * value, else `false`.
8568 * If an object is provided for `iteratee` the created `_.matches` style
8569 * callback returns `true` for elements that have the properties of the given
8570 * object, else `false`.
8574 * @category Collection
8575 * @param {Array|Object|string} collection The collection to iterate over.
8576 * @param {Function|Object|string} [iteratee=_.identity] The function invoked
8578 * @param {*} [thisArg] The `this` binding of `iteratee`.
8579 * @returns {Object} Returns the composed aggregate object.
8582 * _.countBy([4.3, 6.1, 6.4], function(n) {
8583 * return Math.floor(n);
8585 * // => { '4': 1, '6': 2 }
8587 * _.countBy([4.3, 6.1, 6.4], function(n) {
8588 * return this.floor(n);
8590 * // => { '4': 1, '6': 2 }
8592 * _.countBy(['one', 'two', 'three'], 'length');
8593 * // => { '3': 2, '5': 1 }
8595 var countBy = createAggregator(function(result, value, key) {
8596 hasOwnProperty.call(result, key) ? ++result[key] : (result[key] = 1);
8600 * Checks if `predicate` returns truthy for **all** elements of `collection`.
8601 * The predicate is bound to `thisArg` and invoked with three arguments:
8602 * (value, index|key, collection).
8604 * If a property name is provided for `predicate` the created `_.property`
8605 * style callback returns the property value of the given element.
8607 * If a value is also provided for `thisArg` the created `_.matchesProperty`
8608 * style callback returns `true` for elements that have a matching property
8609 * value, else `false`.
8611 * If an object is provided for `predicate` the created `_.matches` style
8612 * callback returns `true` for elements that have the properties of the given
8613 * object, else `false`.
8618 * @category Collection
8619 * @param {Array|Object|string} collection The collection to iterate over.
8620 * @param {Function|Object|string} [predicate=_.identity] The function invoked
8622 * @param {*} [thisArg] The `this` binding of `predicate`.
8623 * @returns {boolean} Returns `true` if all elements pass the predicate check,
8627 * _.every([true, 1, null, 'yes'], Boolean);
8631 * { 'user': 'barney', 'active': false },
8632 * { 'user': 'fred', 'active': false }
8635 * // using the `_.matches` callback shorthand
8636 * _.every(users, { 'user': 'barney', 'active': false });
8639 * // using the `_.matchesProperty` callback shorthand
8640 * _.every(users, 'active', false);
8643 * // using the `_.property` callback shorthand
8644 * _.every(users, 'active');
8647 function every(collection, predicate, thisArg) {
8648 var func = isArray(collection) ? arrayEvery : baseEvery;
8649 if (thisArg && isIterateeCall(collection, predicate, thisArg)) {
8650 predicate = undefined;
8652 if (typeof predicate != 'function' || thisArg !== undefined) {
8653 predicate = getCallback(predicate, thisArg, 3);
8655 return func(collection, predicate);
8659 * Iterates over elements of `collection`, returning an array of all elements
8660 * `predicate` returns truthy for. The predicate is bound to `thisArg` and
8661 * invoked with three arguments: (value, index|key, collection).
8663 * If a property name is provided for `predicate` the created `_.property`
8664 * style callback returns the property value of the given element.
8666 * If a value is also provided for `thisArg` the created `_.matchesProperty`
8667 * style callback returns `true` for elements that have a matching property
8668 * value, else `false`.
8670 * If an object is provided for `predicate` the created `_.matches` style
8671 * callback returns `true` for elements that have the properties of the given
8672 * object, else `false`.
8677 * @category Collection
8678 * @param {Array|Object|string} collection The collection to iterate over.
8679 * @param {Function|Object|string} [predicate=_.identity] The function invoked
8681 * @param {*} [thisArg] The `this` binding of `predicate`.
8682 * @returns {Array} Returns the new filtered array.
8685 * _.filter([4, 5, 6], function(n) {
8686 * return n % 2 == 0;
8691 * { 'user': 'barney', 'age': 36, 'active': true },
8692 * { 'user': 'fred', 'age': 40, 'active': false }
8695 * // using the `_.matches` callback shorthand
8696 * _.pluck(_.filter(users, { 'age': 36, 'active': true }), 'user');
8699 * // using the `_.matchesProperty` callback shorthand
8700 * _.pluck(_.filter(users, 'active', false), 'user');
8703 * // using the `_.property` callback shorthand
8704 * _.pluck(_.filter(users, 'active'), 'user');
8707 function filter(collection, predicate, thisArg) {
8708 var func = isArray(collection) ? arrayFilter : baseFilter;
8709 predicate = getCallback(predicate, thisArg, 3);
8710 return func(collection, predicate);
8714 * Iterates over elements of `collection`, returning the first element
8715 * `predicate` returns truthy for. The predicate is bound to `thisArg` and
8716 * invoked with three arguments: (value, index|key, collection).
8718 * If a property name is provided for `predicate` the created `_.property`
8719 * style callback returns the property value of the given element.
8721 * If a value is also provided for `thisArg` the created `_.matchesProperty`
8722 * style callback returns `true` for elements that have a matching property
8723 * value, else `false`.
8725 * If an object is provided for `predicate` the created `_.matches` style
8726 * callback returns `true` for elements that have the properties of the given
8727 * object, else `false`.
8732 * @category Collection
8733 * @param {Array|Object|string} collection The collection to search.
8734 * @param {Function|Object|string} [predicate=_.identity] The function invoked
8736 * @param {*} [thisArg] The `this` binding of `predicate`.
8737 * @returns {*} Returns the matched element, else `undefined`.
8741 * { 'user': 'barney', 'age': 36, 'active': true },
8742 * { 'user': 'fred', 'age': 40, 'active': false },
8743 * { 'user': 'pebbles', 'age': 1, 'active': true }
8746 * _.result(_.find(users, function(chr) {
8747 * return chr.age < 40;
8751 * // using the `_.matches` callback shorthand
8752 * _.result(_.find(users, { 'age': 1, 'active': true }), 'user');
8755 * // using the `_.matchesProperty` callback shorthand
8756 * _.result(_.find(users, 'active', false), 'user');
8759 * // using the `_.property` callback shorthand
8760 * _.result(_.find(users, 'active'), 'user');
8763 var find = createFind(baseEach);
8766 * This method is like `_.find` except that it iterates over elements of
8767 * `collection` from right to left.
8771 * @category Collection
8772 * @param {Array|Object|string} collection The collection to search.
8773 * @param {Function|Object|string} [predicate=_.identity] The function invoked
8775 * @param {*} [thisArg] The `this` binding of `predicate`.
8776 * @returns {*} Returns the matched element, else `undefined`.
8779 * _.findLast([1, 2, 3, 4], function(n) {
8780 * return n % 2 == 1;
8784 var findLast = createFind(baseEachRight, true);
8787 * Performs a deep comparison between each element in `collection` and the
8788 * source object, returning the first element that has equivalent property
8791 * **Note:** This method supports comparing arrays, booleans, `Date` objects,
8792 * numbers, `Object` objects, regexes, and strings. Objects are compared by
8793 * their own, not inherited, enumerable properties. For comparing a single
8794 * own or inherited property value see `_.matchesProperty`.
8798 * @category Collection
8799 * @param {Array|Object|string} collection The collection to search.
8800 * @param {Object} source The object of property values to match.
8801 * @returns {*} Returns the matched element, else `undefined`.
8805 * { 'user': 'barney', 'age': 36, 'active': true },
8806 * { 'user': 'fred', 'age': 40, 'active': false }
8809 * _.result(_.findWhere(users, { 'age': 36, 'active': true }), 'user');
8812 * _.result(_.findWhere(users, { 'age': 40, 'active': false }), 'user');
8815 function findWhere(collection, source) {
8816 return find(collection, baseMatches(source));
8820 * Iterates over elements of `collection` invoking `iteratee` for each element.
8821 * The `iteratee` is bound to `thisArg` and invoked with three arguments:
8822 * (value, index|key, collection). Iteratee functions may exit iteration early
8823 * by explicitly returning `false`.
8825 * **Note:** As with other "Collections" methods, objects with a "length" property
8826 * are iterated like arrays. To avoid this behavior `_.forIn` or `_.forOwn`
8827 * may be used for object iteration.
8832 * @category Collection
8833 * @param {Array|Object|string} collection The collection to iterate over.
8834 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
8835 * @param {*} [thisArg] The `this` binding of `iteratee`.
8836 * @returns {Array|Object|string} Returns `collection`.
8839 * _([1, 2]).forEach(function(n) {
8842 * // => logs each value from left to right and returns the array
8844 * _.forEach({ 'a': 1, 'b': 2 }, function(n, key) {
8845 * console.log(n, key);
8847 * // => logs each value-key pair and returns the object (iteration order is not guaranteed)
8849 var forEach = createForEach(arrayEach, baseEach);
8852 * This method is like `_.forEach` except that it iterates over elements of
8853 * `collection` from right to left.
8858 * @category Collection
8859 * @param {Array|Object|string} collection The collection to iterate over.
8860 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
8861 * @param {*} [thisArg] The `this` binding of `iteratee`.
8862 * @returns {Array|Object|string} Returns `collection`.
8865 * _([1, 2]).forEachRight(function(n) {
8868 * // => logs each value from right to left and returns the array
8870 var forEachRight = createForEach(arrayEachRight, baseEachRight);
8873 * Creates an object composed of keys generated from the results of running
8874 * each element of `collection` through `iteratee`. The corresponding value
8875 * of each key is an array of the elements responsible for generating the key.
8876 * The `iteratee` is bound to `thisArg` and invoked with three arguments:
8877 * (value, index|key, collection).
8879 * If a property name is provided for `iteratee` the created `_.property`
8880 * style callback returns the property value of the given element.
8882 * If a value is also provided for `thisArg` the created `_.matchesProperty`
8883 * style callback returns `true` for elements that have a matching property
8884 * value, else `false`.
8886 * If an object is provided for `iteratee` the created `_.matches` style
8887 * callback returns `true` for elements that have the properties of the given
8888 * object, else `false`.
8892 * @category Collection
8893 * @param {Array|Object|string} collection The collection to iterate over.
8894 * @param {Function|Object|string} [iteratee=_.identity] The function invoked
8896 * @param {*} [thisArg] The `this` binding of `iteratee`.
8897 * @returns {Object} Returns the composed aggregate object.
8900 * _.groupBy([4.2, 6.1, 6.4], function(n) {
8901 * return Math.floor(n);
8903 * // => { '4': [4.2], '6': [6.1, 6.4] }
8905 * _.groupBy([4.2, 6.1, 6.4], function(n) {
8906 * return this.floor(n);
8908 * // => { '4': [4.2], '6': [6.1, 6.4] }
8910 * // using the `_.property` callback shorthand
8911 * _.groupBy(['one', 'two', 'three'], 'length');
8912 * // => { '3': ['one', 'two'], '5': ['three'] }
8914 var groupBy = createAggregator(function(result, value, key) {
8915 if (hasOwnProperty.call(result, key)) {
8916 result[key].push(value);
8918 result[key] = [value];
8923 * Checks if `value` is in `collection` using
8924 * [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
8925 * for equality comparisons. If `fromIndex` is negative, it is used as the offset
8926 * from the end of `collection`.
8930 * @alias contains, include
8931 * @category Collection
8932 * @param {Array|Object|string} collection The collection to search.
8933 * @param {*} target The value to search for.
8934 * @param {number} [fromIndex=0] The index to search from.
8935 * @param- {Object} [guard] Enables use as a callback for functions like `_.reduce`.
8936 * @returns {boolean} Returns `true` if a matching element is found, else `false`.
8939 * _.includes([1, 2, 3], 1);
8942 * _.includes([1, 2, 3], 1, 2);
8945 * _.includes({ 'user': 'fred', 'age': 40 }, 'fred');
8948 * _.includes('pebbles', 'eb');
8951 function includes(collection, target, fromIndex, guard) {
8952 var length = collection ? getLength(collection) : 0;
8953 if (!isLength(length)) {
8954 collection = values(collection);
8955 length = collection.length;
8957 if (typeof fromIndex != 'number' || (guard && isIterateeCall(target, fromIndex, guard))) {
8960 fromIndex = fromIndex < 0 ? nativeMax(length + fromIndex, 0) : (fromIndex || 0);
8962 return (typeof collection == 'string' || !isArray(collection) && isString(collection))
8963 ? (fromIndex <= length && collection.indexOf(target, fromIndex) > -1)
8964 : (!!length && getIndexOf(collection, target, fromIndex) > -1);
8968 * Creates an object composed of keys generated from the results of running
8969 * each element of `collection` through `iteratee`. The corresponding value
8970 * of each key is the last element responsible for generating the key. The
8971 * iteratee function is bound to `thisArg` and invoked with three arguments:
8972 * (value, index|key, collection).
8974 * If a property name is provided for `iteratee` the created `_.property`
8975 * style callback returns the property value of the given element.
8977 * If a value is also provided for `thisArg` the created `_.matchesProperty`
8978 * style callback returns `true` for elements that have a matching property
8979 * value, else `false`.
8981 * If an object is provided for `iteratee` the created `_.matches` style
8982 * callback returns `true` for elements that have the properties of the given
8983 * object, else `false`.
8987 * @category Collection
8988 * @param {Array|Object|string} collection The collection to iterate over.
8989 * @param {Function|Object|string} [iteratee=_.identity] The function invoked
8991 * @param {*} [thisArg] The `this` binding of `iteratee`.
8992 * @returns {Object} Returns the composed aggregate object.
8996 * { 'dir': 'left', 'code': 97 },
8997 * { 'dir': 'right', 'code': 100 }
9000 * _.indexBy(keyData, 'dir');
9001 * // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } }
9003 * _.indexBy(keyData, function(object) {
9004 * return String.fromCharCode(object.code);
9006 * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } }
9008 * _.indexBy(keyData, function(object) {
9009 * return this.fromCharCode(object.code);
9011 * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } }
9013 var indexBy = createAggregator(function(result, value, key) {
9014 result[key] = value;
9018 * Invokes the method at `path` of each element in `collection`, returning
9019 * an array of the results of each invoked method. Any additional arguments
9020 * are provided to each invoked method. If `methodName` is a function it is
9021 * invoked for, and `this` bound to, each element in `collection`.
9025 * @category Collection
9026 * @param {Array|Object|string} collection The collection to iterate over.
9027 * @param {Array|Function|string} path The path of the method to invoke or
9028 * the function invoked per iteration.
9029 * @param {...*} [args] The arguments to invoke the method with.
9030 * @returns {Array} Returns the array of results.
9033 * _.invoke([[5, 1, 7], [3, 2, 1]], 'sort');
9034 * // => [[1, 5, 7], [1, 2, 3]]
9036 * _.invoke([123, 456], String.prototype.split, '');
9037 * // => [['1', '2', '3'], ['4', '5', '6']]
9039 var invoke = restParam(function(collection, path, args) {
9041 isFunc = typeof path == 'function',
9042 isProp = isKey(path),
9043 result = isArrayLike(collection) ? Array(collection.length) : [];
9045 baseEach(collection, function(value) {
9046 var func = isFunc ? path : ((isProp && value != null) ? value[path] : undefined);
9047 result[++index] = func ? func.apply(value, args) : invokePath(value, path, args);
9053 * Creates an array of values by running each element in `collection` through
9054 * `iteratee`. The `iteratee` is bound to `thisArg` and invoked with three
9055 * arguments: (value, index|key, collection).
9057 * If a property name is provided for `iteratee` the created `_.property`
9058 * style callback returns the property value of the given element.
9060 * If a value is also provided for `thisArg` the created `_.matchesProperty`
9061 * style callback returns `true` for elements that have a matching property
9062 * value, else `false`.
9064 * If an object is provided for `iteratee` the created `_.matches` style
9065 * callback returns `true` for elements that have the properties of the given
9066 * object, else `false`.
9068 * Many lodash methods are guarded to work as iteratees for methods like
9069 * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`.
9071 * The guarded methods are:
9072 * `ary`, `callback`, `chunk`, `clone`, `create`, `curry`, `curryRight`,
9073 * `drop`, `dropRight`, `every`, `fill`, `flatten`, `invert`, `max`, `min`,
9074 * `parseInt`, `slice`, `sortBy`, `take`, `takeRight`, `template`, `trim`,
9075 * `trimLeft`, `trimRight`, `trunc`, `random`, `range`, `sample`, `some`,
9076 * `sum`, `uniq`, and `words`
9081 * @category Collection
9082 * @param {Array|Object|string} collection The collection to iterate over.
9083 * @param {Function|Object|string} [iteratee=_.identity] The function invoked
9085 * @param {*} [thisArg] The `this` binding of `iteratee`.
9086 * @returns {Array} Returns the new mapped array.
9089 * function timesThree(n) {
9093 * _.map([1, 2], timesThree);
9096 * _.map({ 'a': 1, 'b': 2 }, timesThree);
9097 * // => [3, 6] (iteration order is not guaranteed)
9100 * { 'user': 'barney' },
9101 * { 'user': 'fred' }
9104 * // using the `_.property` callback shorthand
9105 * _.map(users, 'user');
9106 * // => ['barney', 'fred']
9108 function map(collection, iteratee, thisArg) {
9109 var func = isArray(collection) ? arrayMap : baseMap;
9110 iteratee = getCallback(iteratee, thisArg, 3);
9111 return func(collection, iteratee);
9115 * Creates an array of elements split into two groups, the first of which
9116 * contains elements `predicate` returns truthy for, while the second of which
9117 * contains elements `predicate` returns falsey for. The predicate is bound
9118 * to `thisArg` and invoked with three arguments: (value, index|key, collection).
9120 * If a property name is provided for `predicate` the created `_.property`
9121 * style callback returns the property value of the given element.
9123 * If a value is also provided for `thisArg` the created `_.matchesProperty`
9124 * style callback returns `true` for elements that have a matching property
9125 * value, else `false`.
9127 * If an object is provided for `predicate` the created `_.matches` style
9128 * callback returns `true` for elements that have the properties of the given
9129 * object, else `false`.
9133 * @category Collection
9134 * @param {Array|Object|string} collection The collection to iterate over.
9135 * @param {Function|Object|string} [predicate=_.identity] The function invoked
9137 * @param {*} [thisArg] The `this` binding of `predicate`.
9138 * @returns {Array} Returns the array of grouped elements.
9141 * _.partition([1, 2, 3], function(n) {
9144 * // => [[1, 3], [2]]
9146 * _.partition([1.2, 2.3, 3.4], function(n) {
9147 * return this.floor(n) % 2;
9149 * // => [[1.2, 3.4], [2.3]]
9152 * { 'user': 'barney', 'age': 36, 'active': false },
9153 * { 'user': 'fred', 'age': 40, 'active': true },
9154 * { 'user': 'pebbles', 'age': 1, 'active': false }
9157 * var mapper = function(array) {
9158 * return _.pluck(array, 'user');
9161 * // using the `_.matches` callback shorthand
9162 * _.map(_.partition(users, { 'age': 1, 'active': false }), mapper);
9163 * // => [['pebbles'], ['barney', 'fred']]
9165 * // using the `_.matchesProperty` callback shorthand
9166 * _.map(_.partition(users, 'active', false), mapper);
9167 * // => [['barney', 'pebbles'], ['fred']]
9169 * // using the `_.property` callback shorthand
9170 * _.map(_.partition(users, 'active'), mapper);
9171 * // => [['fred'], ['barney', 'pebbles']]
9173 var partition = createAggregator(function(result, value, key) {
9174 result[key ? 0 : 1].push(value);
9175 }, function() { return [[], []]; });
9178 * Gets the property value of `path` from all elements in `collection`.
9182 * @category Collection
9183 * @param {Array|Object|string} collection The collection to iterate over.
9184 * @param {Array|string} path The path of the property to pluck.
9185 * @returns {Array} Returns the property values.
9189 * { 'user': 'barney', 'age': 36 },
9190 * { 'user': 'fred', 'age': 40 }
9193 * _.pluck(users, 'user');
9194 * // => ['barney', 'fred']
9196 * var userIndex = _.indexBy(users, 'user');
9197 * _.pluck(userIndex, 'age');
9198 * // => [36, 40] (iteration order is not guaranteed)
9200 function pluck(collection, path) {
9201 return map(collection, property(path));
9205 * Reduces `collection` to a value which is the accumulated result of running
9206 * each element in `collection` through `iteratee`, where each successive
9207 * invocation is supplied the return value of the previous. If `accumulator`
9208 * is not provided the first element of `collection` is used as the initial
9209 * value. The `iteratee` is bound to `thisArg` and invoked with four arguments:
9210 * (accumulator, value, index|key, collection).
9212 * Many lodash methods are guarded to work as iteratees for methods like
9213 * `_.reduce`, `_.reduceRight`, and `_.transform`.
9215 * The guarded methods are:
9216 * `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `sortByAll`,
9221 * @alias foldl, inject
9222 * @category Collection
9223 * @param {Array|Object|string} collection The collection to iterate over.
9224 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
9225 * @param {*} [accumulator] The initial value.
9226 * @param {*} [thisArg] The `this` binding of `iteratee`.
9227 * @returns {*} Returns the accumulated value.
9230 * _.reduce([1, 2], function(total, n) {
9235 * _.reduce({ 'a': 1, 'b': 2 }, function(result, n, key) {
9236 * result[key] = n * 3;
9239 * // => { 'a': 3, 'b': 6 } (iteration order is not guaranteed)
9241 var reduce = createReduce(arrayReduce, baseEach);
9244 * This method is like `_.reduce` except that it iterates over elements of
9245 * `collection` from right to left.
9250 * @category Collection
9251 * @param {Array|Object|string} collection The collection to iterate over.
9252 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
9253 * @param {*} [accumulator] The initial value.
9254 * @param {*} [thisArg] The `this` binding of `iteratee`.
9255 * @returns {*} Returns the accumulated value.
9258 * var array = [[0, 1], [2, 3], [4, 5]];
9260 * _.reduceRight(array, function(flattened, other) {
9261 * return flattened.concat(other);
9263 * // => [4, 5, 2, 3, 0, 1]
9265 var reduceRight = createReduce(arrayReduceRight, baseEachRight);
9268 * The opposite of `_.filter`; this method returns the elements of `collection`
9269 * that `predicate` does **not** return truthy for.
9273 * @category Collection
9274 * @param {Array|Object|string} collection The collection to iterate over.
9275 * @param {Function|Object|string} [predicate=_.identity] The function invoked
9277 * @param {*} [thisArg] The `this` binding of `predicate`.
9278 * @returns {Array} Returns the new filtered array.
9281 * _.reject([1, 2, 3, 4], function(n) {
9282 * return n % 2 == 0;
9287 * { 'user': 'barney', 'age': 36, 'active': false },
9288 * { 'user': 'fred', 'age': 40, 'active': true }
9291 * // using the `_.matches` callback shorthand
9292 * _.pluck(_.reject(users, { 'age': 40, 'active': true }), 'user');
9295 * // using the `_.matchesProperty` callback shorthand
9296 * _.pluck(_.reject(users, 'active', false), 'user');
9299 * // using the `_.property` callback shorthand
9300 * _.pluck(_.reject(users, 'active'), 'user');
9303 function reject(collection, predicate, thisArg) {
9304 var func = isArray(collection) ? arrayFilter : baseFilter;
9305 predicate = getCallback(predicate, thisArg, 3);
9306 return func(collection, function(value, index, collection) {
9307 return !predicate(value, index, collection);
9312 * Gets a random element or `n` random elements from a collection.
9316 * @category Collection
9317 * @param {Array|Object|string} collection The collection to sample.
9318 * @param {number} [n] The number of elements to sample.
9319 * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
9320 * @returns {*} Returns the random sample(s).
9323 * _.sample([1, 2, 3, 4]);
9326 * _.sample([1, 2, 3, 4], 2);
9329 function sample(collection, n, guard) {
9330 if (guard ? isIterateeCall(collection, n, guard) : n == null) {
9331 collection = toIterable(collection);
9332 var length = collection.length;
9333 return length > 0 ? collection[baseRandom(0, length - 1)] : undefined;
9336 result = toArray(collection),
9337 length = result.length,
9338 lastIndex = length - 1;
9340 n = nativeMin(n < 0 ? 0 : (+n || 0), length);
9341 while (++index < n) {
9342 var rand = baseRandom(index, lastIndex),
9343 value = result[rand];
9345 result[rand] = result[index];
9346 result[index] = value;
9353 * Creates an array of shuffled values, using a version of the
9354 * [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher-Yates_shuffle).
9358 * @category Collection
9359 * @param {Array|Object|string} collection The collection to shuffle.
9360 * @returns {Array} Returns the new shuffled array.
9363 * _.shuffle([1, 2, 3, 4]);
9364 * // => [4, 1, 3, 2]
9366 function shuffle(collection) {
9367 return sample(collection, POSITIVE_INFINITY);
9371 * Gets the size of `collection` by returning its length for array-like
9372 * values or the number of own enumerable properties for objects.
9376 * @category Collection
9377 * @param {Array|Object|string} collection The collection to inspect.
9378 * @returns {number} Returns the size of `collection`.
9381 * _.size([1, 2, 3]);
9384 * _.size({ 'a': 1, 'b': 2 });
9387 * _.size('pebbles');
9390 function size(collection) {
9391 var length = collection ? getLength(collection) : 0;
9392 return isLength(length) ? length : keys(collection).length;
9396 * Checks if `predicate` returns truthy for **any** element of `collection`.
9397 * The function returns as soon as it finds a passing value and does not iterate
9398 * over the entire collection. The predicate is bound to `thisArg` and invoked
9399 * with three arguments: (value, index|key, collection).
9401 * If a property name is provided for `predicate` the created `_.property`
9402 * style callback returns the property value of the given element.
9404 * If a value is also provided for `thisArg` the created `_.matchesProperty`
9405 * style callback returns `true` for elements that have a matching property
9406 * value, else `false`.
9408 * If an object is provided for `predicate` the created `_.matches` style
9409 * callback returns `true` for elements that have the properties of the given
9410 * object, else `false`.
9415 * @category Collection
9416 * @param {Array|Object|string} collection The collection to iterate over.
9417 * @param {Function|Object|string} [predicate=_.identity] The function invoked
9419 * @param {*} [thisArg] The `this` binding of `predicate`.
9420 * @returns {boolean} Returns `true` if any element passes the predicate check,
9424 * _.some([null, 0, 'yes', false], Boolean);
9428 * { 'user': 'barney', 'active': true },
9429 * { 'user': 'fred', 'active': false }
9432 * // using the `_.matches` callback shorthand
9433 * _.some(users, { 'user': 'barney', 'active': false });
9436 * // using the `_.matchesProperty` callback shorthand
9437 * _.some(users, 'active', false);
9440 * // using the `_.property` callback shorthand
9441 * _.some(users, 'active');
9444 function some(collection, predicate, thisArg) {
9445 var func = isArray(collection) ? arraySome : baseSome;
9446 if (thisArg && isIterateeCall(collection, predicate, thisArg)) {
9447 predicate = undefined;
9449 if (typeof predicate != 'function' || thisArg !== undefined) {
9450 predicate = getCallback(predicate, thisArg, 3);
9452 return func(collection, predicate);
9456 * Creates an array of elements, sorted in ascending order by the results of
9457 * running each element in a collection through `iteratee`. This method performs
9458 * a stable sort, that is, it preserves the original sort order of equal elements.
9459 * The `iteratee` is bound to `thisArg` and invoked with three arguments:
9460 * (value, index|key, collection).
9462 * If a property name is provided for `iteratee` the created `_.property`
9463 * style callback returns the property value of the given element.
9465 * If a value is also provided for `thisArg` the created `_.matchesProperty`
9466 * style callback returns `true` for elements that have a matching property
9467 * value, else `false`.
9469 * If an object is provided for `iteratee` the created `_.matches` style
9470 * callback returns `true` for elements that have the properties of the given
9471 * object, else `false`.
9475 * @category Collection
9476 * @param {Array|Object|string} collection The collection to iterate over.
9477 * @param {Function|Object|string} [iteratee=_.identity] The function invoked
9479 * @param {*} [thisArg] The `this` binding of `iteratee`.
9480 * @returns {Array} Returns the new sorted array.
9483 * _.sortBy([1, 2, 3], function(n) {
9484 * return Math.sin(n);
9488 * _.sortBy([1, 2, 3], function(n) {
9489 * return this.sin(n);
9494 * { 'user': 'fred' },
9495 * { 'user': 'pebbles' },
9496 * { 'user': 'barney' }
9499 * // using the `_.property` callback shorthand
9500 * _.pluck(_.sortBy(users, 'user'), 'user');
9501 * // => ['barney', 'fred', 'pebbles']
9503 function sortBy(collection, iteratee, thisArg) {
9504 if (collection == null) {
9507 if (thisArg && isIterateeCall(collection, iteratee, thisArg)) {
9508 iteratee = undefined;
9511 iteratee = getCallback(iteratee, thisArg, 3);
9513 var result = baseMap(collection, function(value, key, collection) {
9514 return { 'criteria': iteratee(value, key, collection), 'index': ++index, 'value': value };
9516 return baseSortBy(result, compareAscending);
9520 * This method is like `_.sortBy` except that it can sort by multiple iteratees
9521 * or property names.
9523 * If a property name is provided for an iteratee the created `_.property`
9524 * style callback returns the property value of the given element.
9526 * If an object is provided for an iteratee the created `_.matches` style
9527 * callback returns `true` for elements that have the properties of the given
9528 * object, else `false`.
9532 * @category Collection
9533 * @param {Array|Object|string} collection The collection to iterate over.
9534 * @param {...(Function|Function[]|Object|Object[]|string|string[])} iteratees
9535 * The iteratees to sort by, specified as individual values or arrays of values.
9536 * @returns {Array} Returns the new sorted array.
9540 * { 'user': 'fred', 'age': 48 },
9541 * { 'user': 'barney', 'age': 36 },
9542 * { 'user': 'fred', 'age': 42 },
9543 * { 'user': 'barney', 'age': 34 }
9546 * _.map(_.sortByAll(users, ['user', 'age']), _.values);
9547 * // => [['barney', 34], ['barney', 36], ['fred', 42], ['fred', 48]]
9549 * _.map(_.sortByAll(users, 'user', function(chr) {
9550 * return Math.floor(chr.age / 10);
9552 * // => [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 42]]
9554 var sortByAll = restParam(function(collection, iteratees) {
9555 if (collection == null) {
9558 var guard = iteratees[2];
9559 if (guard && isIterateeCall(iteratees[0], iteratees[1], guard)) {
9560 iteratees.length = 1;
9562 return baseSortByOrder(collection, baseFlatten(iteratees), []);
9566 * This method is like `_.sortByAll` except that it allows specifying the
9567 * sort orders of the iteratees to sort by. If `orders` is unspecified, all
9568 * values are sorted in ascending order. Otherwise, a value is sorted in
9569 * ascending order if its corresponding order is "asc", and descending if "desc".
9571 * If a property name is provided for an iteratee the created `_.property`
9572 * style callback returns the property value of the given element.
9574 * If an object is provided for an iteratee the created `_.matches` style
9575 * callback returns `true` for elements that have the properties of the given
9576 * object, else `false`.
9580 * @category Collection
9581 * @param {Array|Object|string} collection The collection to iterate over.
9582 * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by.
9583 * @param {boolean[]} [orders] The sort orders of `iteratees`.
9584 * @param- {Object} [guard] Enables use as a callback for functions like `_.reduce`.
9585 * @returns {Array} Returns the new sorted array.
9589 * { 'user': 'fred', 'age': 48 },
9590 * { 'user': 'barney', 'age': 34 },
9591 * { 'user': 'fred', 'age': 42 },
9592 * { 'user': 'barney', 'age': 36 }
9595 * // sort by `user` in ascending order and by `age` in descending order
9596 * _.map(_.sortByOrder(users, ['user', 'age'], ['asc', 'desc']), _.values);
9597 * // => [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 42]]
9599 function sortByOrder(collection, iteratees, orders, guard) {
9600 if (collection == null) {
9603 if (guard && isIterateeCall(iteratees, orders, guard)) {
9606 if (!isArray(iteratees)) {
9607 iteratees = iteratees == null ? [] : [iteratees];
9609 if (!isArray(orders)) {
9610 orders = orders == null ? [] : [orders];
9612 return baseSortByOrder(collection, iteratees, orders);
9616 * Performs a deep comparison between each element in `collection` and the
9617 * source object, returning an array of all elements that have equivalent
9620 * **Note:** This method supports comparing arrays, booleans, `Date` objects,
9621 * numbers, `Object` objects, regexes, and strings. Objects are compared by
9622 * their own, not inherited, enumerable properties. For comparing a single
9623 * own or inherited property value see `_.matchesProperty`.
9627 * @category Collection
9628 * @param {Array|Object|string} collection The collection to search.
9629 * @param {Object} source The object of property values to match.
9630 * @returns {Array} Returns the new filtered array.
9634 * { 'user': 'barney', 'age': 36, 'active': false, 'pets': ['hoppy'] },
9635 * { 'user': 'fred', 'age': 40, 'active': true, 'pets': ['baby puss', 'dino'] }
9638 * _.pluck(_.where(users, { 'age': 36, 'active': false }), 'user');
9641 * _.pluck(_.where(users, { 'pets': ['dino'] }), 'user');
9644 function where(collection, source) {
9645 return filter(collection, baseMatches(source));
9648 /*------------------------------------------------------------------------*/
9651 * Gets the number of milliseconds that have elapsed since the Unix epoch
9652 * (1 January 1970 00:00:00 UTC).
9659 * _.defer(function(stamp) {
9660 * console.log(_.now() - stamp);
9662 * // => logs the number of milliseconds it took for the deferred function to be invoked
9664 var now = nativeNow || function() {
9665 return new Date().getTime();
9668 /*------------------------------------------------------------------------*/
9671 * The opposite of `_.before`; this method creates a function that invokes
9672 * `func` once it is called `n` or more times.
9676 * @category Function
9677 * @param {number} n The number of calls before `func` is invoked.
9678 * @param {Function} func The function to restrict.
9679 * @returns {Function} Returns the new restricted function.
9682 * var saves = ['profile', 'settings'];
9684 * var done = _.after(saves.length, function() {
9685 * console.log('done saving!');
9688 * _.forEach(saves, function(type) {
9689 * asyncSave({ 'type': type, 'complete': done });
9691 * // => logs 'done saving!' after the two async saves have completed
9693 function after(n, func) {
9694 if (typeof func != 'function') {
9695 if (typeof n == 'function') {
9700 throw new TypeError(FUNC_ERROR_TEXT);
9703 n = nativeIsFinite(n = +n) ? n : 0;
9706 return func.apply(this, arguments);
9712 * Creates a function that accepts up to `n` arguments ignoring any
9713 * additional arguments.
9717 * @category Function
9718 * @param {Function} func The function to cap arguments for.
9719 * @param {number} [n=func.length] The arity cap.
9720 * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
9721 * @returns {Function} Returns the new function.
9724 * _.map(['6', '8', '10'], _.ary(parseInt, 1));
9727 function ary(func, n, guard) {
9728 if (guard && isIterateeCall(func, n, guard)) {
9731 n = (func && n == null) ? func.length : nativeMax(+n || 0, 0);
9732 return createWrapper(func, ARY_FLAG, undefined, undefined, undefined, undefined, n);
9736 * Creates a function that invokes `func`, with the `this` binding and arguments
9737 * of the created function, while it is called less than `n` times. Subsequent
9738 * calls to the created function return the result of the last `func` invocation.
9742 * @category Function
9743 * @param {number} n The number of calls at which `func` is no longer invoked.
9744 * @param {Function} func The function to restrict.
9745 * @returns {Function} Returns the new restricted function.
9748 * jQuery('#add').on('click', _.before(5, addContactToList));
9749 * // => allows adding up to 4 contacts to the list
9751 function before(n, func) {
9753 if (typeof func != 'function') {
9754 if (typeof n == 'function') {
9759 throw new TypeError(FUNC_ERROR_TEXT);
9764 result = func.apply(this, arguments);
9774 * Creates a function that invokes `func` with the `this` binding of `thisArg`
9775 * and prepends any additional `_.bind` arguments to those provided to the
9778 * The `_.bind.placeholder` value, which defaults to `_` in monolithic builds,
9779 * may be used as a placeholder for partially applied arguments.
9781 * **Note:** Unlike native `Function#bind` this method does not set the "length"
9782 * property of bound functions.
9786 * @category Function
9787 * @param {Function} func The function to bind.
9788 * @param {*} thisArg The `this` binding of `func`.
9789 * @param {...*} [partials] The arguments to be partially applied.
9790 * @returns {Function} Returns the new bound function.
9793 * var greet = function(greeting, punctuation) {
9794 * return greeting + ' ' + this.user + punctuation;
9797 * var object = { 'user': 'fred' };
9799 * var bound = _.bind(greet, object, 'hi');
9803 * // using placeholders
9804 * var bound = _.bind(greet, object, _, '!');
9808 var bind = restParam(function(func, thisArg, partials) {
9809 var bitmask = BIND_FLAG;
9810 if (partials.length) {
9811 var holders = replaceHolders(partials, bind.placeholder);
9812 bitmask |= PARTIAL_FLAG;
9814 return createWrapper(func, bitmask, thisArg, partials, holders);
9818 * Binds methods of an object to the object itself, overwriting the existing
9819 * method. Method names may be specified as individual arguments or as arrays
9820 * of method names. If no method names are provided all enumerable function
9821 * properties, own and inherited, of `object` are bound.
9823 * **Note:** This method does not set the "length" property of bound functions.
9827 * @category Function
9828 * @param {Object} object The object to bind and assign the bound methods to.
9829 * @param {...(string|string[])} [methodNames] The object method names to bind,
9830 * specified as individual method names or arrays of method names.
9831 * @returns {Object} Returns `object`.
9836 * 'onClick': function() {
9837 * console.log('clicked ' + this.label);
9842 * jQuery('#docs').on('click', view.onClick);
9843 * // => logs 'clicked docs' when the element is clicked
9845 var bindAll = restParam(function(object, methodNames) {
9846 methodNames = methodNames.length ? baseFlatten(methodNames) : functions(object);
9849 length = methodNames.length;
9851 while (++index < length) {
9852 var key = methodNames[index];
9853 object[key] = createWrapper(object[key], BIND_FLAG, object);
9859 * Creates a function that invokes the method at `object[key]` and prepends
9860 * any additional `_.bindKey` arguments to those provided to the bound function.
9862 * This method differs from `_.bind` by allowing bound functions to reference
9863 * methods that may be redefined or don't yet exist.
9864 * See [Peter Michaux's article](http://peter.michaux.ca/articles/lazy-function-definition-pattern)
9867 * The `_.bindKey.placeholder` value, which defaults to `_` in monolithic
9868 * builds, may be used as a placeholder for partially applied arguments.
9872 * @category Function
9873 * @param {Object} object The object the method belongs to.
9874 * @param {string} key The key of the method.
9875 * @param {...*} [partials] The arguments to be partially applied.
9876 * @returns {Function} Returns the new bound function.
9881 * 'greet': function(greeting, punctuation) {
9882 * return greeting + ' ' + this.user + punctuation;
9886 * var bound = _.bindKey(object, 'greet', 'hi');
9890 * object.greet = function(greeting, punctuation) {
9891 * return greeting + 'ya ' + this.user + punctuation;
9895 * // => 'hiya fred!'
9897 * // using placeholders
9898 * var bound = _.bindKey(object, 'greet', _, '!');
9900 * // => 'hiya fred!'
9902 var bindKey = restParam(function(object, key, partials) {
9903 var bitmask = BIND_FLAG | BIND_KEY_FLAG;
9904 if (partials.length) {
9905 var holders = replaceHolders(partials, bindKey.placeholder);
9906 bitmask |= PARTIAL_FLAG;
9908 return createWrapper(key, bitmask, object, partials, holders);
9912 * Creates a function that accepts one or more arguments of `func` that when
9913 * called either invokes `func` returning its result, if all `func` arguments
9914 * have been provided, or returns a function that accepts one or more of the
9915 * remaining `func` arguments, and so on. The arity of `func` may be specified
9916 * if `func.length` is not sufficient.
9918 * The `_.curry.placeholder` value, which defaults to `_` in monolithic builds,
9919 * may be used as a placeholder for provided arguments.
9921 * **Note:** This method does not set the "length" property of curried functions.
9925 * @category Function
9926 * @param {Function} func The function to curry.
9927 * @param {number} [arity=func.length] The arity of `func`.
9928 * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
9929 * @returns {Function} Returns the new curried function.
9932 * var abc = function(a, b, c) {
9936 * var curried = _.curry(abc);
9947 * // using placeholders
9948 * curried(1)(_, 3)(2);
9951 var curry = createCurry(CURRY_FLAG);
9954 * This method is like `_.curry` except that arguments are applied to `func`
9955 * in the manner of `_.partialRight` instead of `_.partial`.
9957 * The `_.curryRight.placeholder` value, which defaults to `_` in monolithic
9958 * builds, may be used as a placeholder for provided arguments.
9960 * **Note:** This method does not set the "length" property of curried functions.
9964 * @category Function
9965 * @param {Function} func The function to curry.
9966 * @param {number} [arity=func.length] The arity of `func`.
9967 * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
9968 * @returns {Function} Returns the new curried function.
9971 * var abc = function(a, b, c) {
9975 * var curried = _.curryRight(abc);
9986 * // using placeholders
9987 * curried(3)(1, _)(2);
9990 var curryRight = createCurry(CURRY_RIGHT_FLAG);
9993 * Creates a debounced function that delays invoking `func` until after `wait`
9994 * milliseconds have elapsed since the last time the debounced function was
9995 * invoked. The debounced function comes with a `cancel` method to cancel
9996 * delayed invocations. Provide an options object to indicate that `func`
9997 * should be invoked on the leading and/or trailing edge of the `wait` timeout.
9998 * Subsequent calls to the debounced function return the result of the last
9999 * `func` invocation.
10001 * **Note:** If `leading` and `trailing` options are `true`, `func` is invoked
10002 * on the trailing edge of the timeout only if the the debounced function is
10003 * invoked more than once during the `wait` timeout.
10005 * See [David Corbacho's article](http://drupalmotion.com/article/debounce-and-throttle-visual-explanation)
10006 * for details over the differences between `_.debounce` and `_.throttle`.
10010 * @category Function
10011 * @param {Function} func The function to debounce.
10012 * @param {number} [wait=0] The number of milliseconds to delay.
10013 * @param {Object} [options] The options object.
10014 * @param {boolean} [options.leading=false] Specify invoking on the leading
10015 * edge of the timeout.
10016 * @param {number} [options.maxWait] The maximum time `func` is allowed to be
10017 * delayed before it is invoked.
10018 * @param {boolean} [options.trailing=true] Specify invoking on the trailing
10019 * edge of the timeout.
10020 * @returns {Function} Returns the new debounced function.
10023 * // avoid costly calculations while the window size is in flux
10024 * jQuery(window).on('resize', _.debounce(calculateLayout, 150));
10026 * // invoke `sendMail` when the click event is fired, debouncing subsequent calls
10027 * jQuery('#postbox').on('click', _.debounce(sendMail, 300, {
10029 * 'trailing': false
10032 * // ensure `batchLog` is invoked once after 1 second of debounced calls
10033 * var source = new EventSource('/stream');
10034 * jQuery(source).on('message', _.debounce(batchLog, 250, {
10038 * // cancel a debounced call
10039 * var todoChanges = _.debounce(batchLog, 1000);
10040 * Object.observe(models.todo, todoChanges);
10042 * Object.observe(models, function(changes) {
10043 * if (_.find(changes, { 'user': 'todo', 'type': 'delete'})) {
10044 * todoChanges.cancel();
10048 * // ...at some point `models.todo` is changed
10049 * models.todo.completed = true;
10051 * // ...before 1 second has passed `models.todo` is deleted
10052 * // which cancels the debounced `todoChanges` call
10053 * delete models.todo;
10055 function debounce(func, wait, options) {
10067 if (typeof func != 'function') {
10068 throw new TypeError(FUNC_ERROR_TEXT);
10070 wait = wait < 0 ? 0 : (+wait || 0);
10071 if (options === true) {
10072 var leading = true;
10074 } else if (isObject(options)) {
10075 leading = !!options.leading;
10076 maxWait = 'maxWait' in options && nativeMax(+options.maxWait || 0, wait);
10077 trailing = 'trailing' in options ? !!options.trailing : trailing;
10080 function cancel() {
10082 clearTimeout(timeoutId);
10084 if (maxTimeoutId) {
10085 clearTimeout(maxTimeoutId);
10088 maxTimeoutId = timeoutId = trailingCall = undefined;
10091 function complete(isCalled, id) {
10095 maxTimeoutId = timeoutId = trailingCall = undefined;
10097 lastCalled = now();
10098 result = func.apply(thisArg, args);
10099 if (!timeoutId && !maxTimeoutId) {
10100 args = thisArg = undefined;
10105 function delayed() {
10106 var remaining = wait - (now() - stamp);
10107 if (remaining <= 0 || remaining > wait) {
10108 complete(trailingCall, maxTimeoutId);
10110 timeoutId = setTimeout(delayed, remaining);
10114 function maxDelayed() {
10115 complete(trailing, timeoutId);
10118 function debounced() {
10122 trailingCall = trailing && (timeoutId || !leading);
10124 if (maxWait === false) {
10125 var leadingCall = leading && !timeoutId;
10127 if (!maxTimeoutId && !leading) {
10128 lastCalled = stamp;
10130 var remaining = maxWait - (stamp - lastCalled),
10131 isCalled = remaining <= 0 || remaining > maxWait;
10134 if (maxTimeoutId) {
10135 maxTimeoutId = clearTimeout(maxTimeoutId);
10137 lastCalled = stamp;
10138 result = func.apply(thisArg, args);
10140 else if (!maxTimeoutId) {
10141 maxTimeoutId = setTimeout(maxDelayed, remaining);
10144 if (isCalled && timeoutId) {
10145 timeoutId = clearTimeout(timeoutId);
10147 else if (!timeoutId && wait !== maxWait) {
10148 timeoutId = setTimeout(delayed, wait);
10152 result = func.apply(thisArg, args);
10154 if (isCalled && !timeoutId && !maxTimeoutId) {
10155 args = thisArg = undefined;
10159 debounced.cancel = cancel;
10164 * Defers invoking the `func` until the current call stack has cleared. Any
10165 * additional arguments are provided to `func` when it is invoked.
10169 * @category Function
10170 * @param {Function} func The function to defer.
10171 * @param {...*} [args] The arguments to invoke the function with.
10172 * @returns {number} Returns the timer id.
10175 * _.defer(function(text) {
10176 * console.log(text);
10178 * // logs 'deferred' after one or more milliseconds
10180 var defer = restParam(function(func, args) {
10181 return baseDelay(func, 1, args);
10185 * Invokes `func` after `wait` milliseconds. Any additional arguments are
10186 * provided to `func` when it is invoked.
10190 * @category Function
10191 * @param {Function} func The function to delay.
10192 * @param {number} wait The number of milliseconds to delay invocation.
10193 * @param {...*} [args] The arguments to invoke the function with.
10194 * @returns {number} Returns the timer id.
10197 * _.delay(function(text) {
10198 * console.log(text);
10199 * }, 1000, 'later');
10200 * // => logs 'later' after one second
10202 var delay = restParam(function(func, wait, args) {
10203 return baseDelay(func, wait, args);
10207 * Creates a function that returns the result of invoking the provided
10208 * functions with the `this` binding of the created function, where each
10209 * successive invocation is supplied the return value of the previous.
10213 * @category Function
10214 * @param {...Function} [funcs] Functions to invoke.
10215 * @returns {Function} Returns the new function.
10218 * function square(n) {
10222 * var addSquare = _.flow(_.add, square);
10226 var flow = createFlow();
10229 * This method is like `_.flow` except that it creates a function that
10230 * invokes the provided functions from right to left.
10234 * @alias backflow, compose
10235 * @category Function
10236 * @param {...Function} [funcs] Functions to invoke.
10237 * @returns {Function} Returns the new function.
10240 * function square(n) {
10244 * var addSquare = _.flowRight(square, _.add);
10248 var flowRight = createFlow(true);
10251 * Creates a function that memoizes the result of `func`. If `resolver` is
10252 * provided it determines the cache key for storing the result based on the
10253 * arguments provided to the memoized function. By default, the first argument
10254 * provided to the memoized function is coerced to a string and used as the
10255 * cache key. The `func` is invoked with the `this` binding of the memoized
10258 * **Note:** The cache is exposed as the `cache` property on the memoized
10259 * function. Its creation may be customized by replacing the `_.memoize.Cache`
10260 * constructor with one whose instances implement the [`Map`](http://ecma-international.org/ecma-262/6.0/#sec-properties-of-the-map-prototype-object)
10261 * method interface of `get`, `has`, and `set`.
10265 * @category Function
10266 * @param {Function} func The function to have its output memoized.
10267 * @param {Function} [resolver] The function to resolve the cache key.
10268 * @returns {Function} Returns the new memoizing function.
10271 * var upperCase = _.memoize(function(string) {
10272 * return string.toUpperCase();
10275 * upperCase('fred');
10278 * // modifying the result cache
10279 * upperCase.cache.set('fred', 'BARNEY');
10280 * upperCase('fred');
10283 * // replacing `_.memoize.Cache`
10284 * var object = { 'user': 'fred' };
10285 * var other = { 'user': 'barney' };
10286 * var identity = _.memoize(_.identity);
10288 * identity(object);
10289 * // => { 'user': 'fred' }
10291 * // => { 'user': 'fred' }
10293 * _.memoize.Cache = WeakMap;
10294 * var identity = _.memoize(_.identity);
10296 * identity(object);
10297 * // => { 'user': 'fred' }
10299 * // => { 'user': 'barney' }
10301 function memoize(func, resolver) {
10302 if (typeof func != 'function' || (resolver && typeof resolver != 'function')) {
10303 throw new TypeError(FUNC_ERROR_TEXT);
10305 var memoized = function() {
10306 var args = arguments,
10307 key = resolver ? resolver.apply(this, args) : args[0],
10308 cache = memoized.cache;
10310 if (cache.has(key)) {
10311 return cache.get(key);
10313 var result = func.apply(this, args);
10314 memoized.cache = cache.set(key, result);
10317 memoized.cache = new memoize.Cache;
10322 * Creates a function that runs each argument through a corresponding
10323 * transform function.
10327 * @category Function
10328 * @param {Function} func The function to wrap.
10329 * @param {...(Function|Function[])} [transforms] The functions to transform
10330 * arguments, specified as individual functions or arrays of functions.
10331 * @returns {Function} Returns the new function.
10334 * function doubled(n) {
10338 * function square(n) {
10342 * var modded = _.modArgs(function(x, y) {
10344 * }, square, doubled);
10352 var modArgs = restParam(function(func, transforms) {
10353 transforms = baseFlatten(transforms);
10354 if (typeof func != 'function' || !arrayEvery(transforms, baseIsFunction)) {
10355 throw new TypeError(FUNC_ERROR_TEXT);
10357 var length = transforms.length;
10358 return restParam(function(args) {
10359 var index = nativeMin(args.length, length);
10361 args[index] = transforms[index](args[index]);
10363 return func.apply(this, args);
10368 * Creates a function that negates the result of the predicate `func`. The
10369 * `func` predicate is invoked with the `this` binding and arguments of the
10370 * created function.
10374 * @category Function
10375 * @param {Function} predicate The predicate to negate.
10376 * @returns {Function} Returns the new function.
10379 * function isEven(n) {
10380 * return n % 2 == 0;
10383 * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven));
10386 function negate(predicate) {
10387 if (typeof predicate != 'function') {
10388 throw new TypeError(FUNC_ERROR_TEXT);
10390 return function() {
10391 return !predicate.apply(this, arguments);
10396 * Creates a function that is restricted to invoking `func` once. Repeat calls
10397 * to the function return the value of the first call. The `func` is invoked
10398 * with the `this` binding and arguments of the created function.
10402 * @category Function
10403 * @param {Function} func The function to restrict.
10404 * @returns {Function} Returns the new restricted function.
10407 * var initialize = _.once(createApplication);
10410 * // `initialize` invokes `createApplication` once
10412 function once(func) {
10413 return before(2, func);
10417 * Creates a function that invokes `func` with `partial` arguments prepended
10418 * to those provided to the new function. This method is like `_.bind` except
10419 * it does **not** alter the `this` binding.
10421 * The `_.partial.placeholder` value, which defaults to `_` in monolithic
10422 * builds, may be used as a placeholder for partially applied arguments.
10424 * **Note:** This method does not set the "length" property of partially
10425 * applied functions.
10429 * @category Function
10430 * @param {Function} func The function to partially apply arguments to.
10431 * @param {...*} [partials] The arguments to be partially applied.
10432 * @returns {Function} Returns the new partially applied function.
10435 * var greet = function(greeting, name) {
10436 * return greeting + ' ' + name;
10439 * var sayHelloTo = _.partial(greet, 'hello');
10440 * sayHelloTo('fred');
10441 * // => 'hello fred'
10443 * // using placeholders
10444 * var greetFred = _.partial(greet, _, 'fred');
10448 var partial = createPartial(PARTIAL_FLAG);
10451 * This method is like `_.partial` except that partially applied arguments
10452 * are appended to those provided to the new function.
10454 * The `_.partialRight.placeholder` value, which defaults to `_` in monolithic
10455 * builds, may be used as a placeholder for partially applied arguments.
10457 * **Note:** This method does not set the "length" property of partially
10458 * applied functions.
10462 * @category Function
10463 * @param {Function} func The function to partially apply arguments to.
10464 * @param {...*} [partials] The arguments to be partially applied.
10465 * @returns {Function} Returns the new partially applied function.
10468 * var greet = function(greeting, name) {
10469 * return greeting + ' ' + name;
10472 * var greetFred = _.partialRight(greet, 'fred');
10476 * // using placeholders
10477 * var sayHelloTo = _.partialRight(greet, 'hello', _);
10478 * sayHelloTo('fred');
10479 * // => 'hello fred'
10481 var partialRight = createPartial(PARTIAL_RIGHT_FLAG);
10484 * Creates a function that invokes `func` with arguments arranged according
10485 * to the specified indexes where the argument value at the first index is
10486 * provided as the first argument, the argument value at the second index is
10487 * provided as the second argument, and so on.
10491 * @category Function
10492 * @param {Function} func The function to rearrange arguments for.
10493 * @param {...(number|number[])} indexes The arranged argument indexes,
10494 * specified as individual indexes or arrays of indexes.
10495 * @returns {Function} Returns the new function.
10498 * var rearged = _.rearg(function(a, b, c) {
10499 * return [a, b, c];
10502 * rearged('b', 'c', 'a')
10503 * // => ['a', 'b', 'c']
10505 * var map = _.rearg(_.map, [1, 0]);
10506 * map(function(n) {
10511 var rearg = restParam(function(func, indexes) {
10512 return createWrapper(func, REARG_FLAG, undefined, undefined, undefined, baseFlatten(indexes));
10516 * Creates a function that invokes `func` with the `this` binding of the
10517 * created function and arguments from `start` and beyond provided as an array.
10519 * **Note:** This method is based on the [rest parameter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters).
10523 * @category Function
10524 * @param {Function} func The function to apply a rest parameter to.
10525 * @param {number} [start=func.length-1] The start position of the rest parameter.
10526 * @returns {Function} Returns the new function.
10529 * var say = _.restParam(function(what, names) {
10530 * return what + ' ' + _.initial(names).join(', ') +
10531 * (_.size(names) > 1 ? ', & ' : '') + _.last(names);
10534 * say('hello', 'fred', 'barney', 'pebbles');
10535 * // => 'hello fred, barney, & pebbles'
10537 function restParam(func, start) {
10538 if (typeof func != 'function') {
10539 throw new TypeError(FUNC_ERROR_TEXT);
10541 start = nativeMax(start === undefined ? (func.length - 1) : (+start || 0), 0);
10542 return function() {
10543 var args = arguments,
10545 length = nativeMax(args.length - start, 0),
10546 rest = Array(length);
10548 while (++index < length) {
10549 rest[index] = args[start + index];
10552 case 0: return func.call(this, rest);
10553 case 1: return func.call(this, args[0], rest);
10554 case 2: return func.call(this, args[0], args[1], rest);
10556 var otherArgs = Array(start + 1);
10558 while (++index < start) {
10559 otherArgs[index] = args[index];
10561 otherArgs[start] = rest;
10562 return func.apply(this, otherArgs);
10567 * Creates a function that invokes `func` with the `this` binding of the created
10568 * function and an array of arguments much like [`Function#apply`](https://es5.github.io/#x15.3.4.3).
10570 * **Note:** This method is based on the [spread operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator).
10574 * @category Function
10575 * @param {Function} func The function to spread arguments over.
10576 * @returns {Function} Returns the new function.
10579 * var say = _.spread(function(who, what) {
10580 * return who + ' says ' + what;
10583 * say(['fred', 'hello']);
10584 * // => 'fred says hello'
10586 * // with a Promise
10587 * var numbers = Promise.all([
10588 * Promise.resolve(40),
10589 * Promise.resolve(36)
10592 * numbers.then(_.spread(function(x, y) {
10595 * // => a Promise of 76
10597 function spread(func) {
10598 if (typeof func != 'function') {
10599 throw new TypeError(FUNC_ERROR_TEXT);
10601 return function(array) {
10602 return func.apply(this, array);
10607 * Creates a throttled function that only invokes `func` at most once per
10608 * every `wait` milliseconds. The throttled function comes with a `cancel`
10609 * method to cancel delayed invocations. Provide an options object to indicate
10610 * that `func` should be invoked on the leading and/or trailing edge of the
10611 * `wait` timeout. Subsequent calls to the throttled function return the
10612 * result of the last `func` call.
10614 * **Note:** If `leading` and `trailing` options are `true`, `func` is invoked
10615 * on the trailing edge of the timeout only if the the throttled function is
10616 * invoked more than once during the `wait` timeout.
10618 * See [David Corbacho's article](http://drupalmotion.com/article/debounce-and-throttle-visual-explanation)
10619 * for details over the differences between `_.throttle` and `_.debounce`.
10623 * @category Function
10624 * @param {Function} func The function to throttle.
10625 * @param {number} [wait=0] The number of milliseconds to throttle invocations to.
10626 * @param {Object} [options] The options object.
10627 * @param {boolean} [options.leading=true] Specify invoking on the leading
10628 * edge of the timeout.
10629 * @param {boolean} [options.trailing=true] Specify invoking on the trailing
10630 * edge of the timeout.
10631 * @returns {Function} Returns the new throttled function.
10634 * // avoid excessively updating the position while scrolling
10635 * jQuery(window).on('scroll', _.throttle(updatePosition, 100));
10637 * // invoke `renewToken` when the click event is fired, but not more than once every 5 minutes
10638 * jQuery('.interactive').on('click', _.throttle(renewToken, 300000, {
10639 * 'trailing': false
10642 * // cancel a trailing throttled call
10643 * jQuery(window).on('popstate', throttled.cancel);
10645 function throttle(func, wait, options) {
10646 var leading = true,
10649 if (typeof func != 'function') {
10650 throw new TypeError(FUNC_ERROR_TEXT);
10652 if (options === false) {
10654 } else if (isObject(options)) {
10655 leading = 'leading' in options ? !!options.leading : leading;
10656 trailing = 'trailing' in options ? !!options.trailing : trailing;
10658 return debounce(func, wait, { 'leading': leading, 'maxWait': +wait, 'trailing': trailing });
10662 * Creates a function that provides `value` to the wrapper function as its
10663 * first argument. Any additional arguments provided to the function are
10664 * appended to those provided to the wrapper function. The wrapper is invoked
10665 * with the `this` binding of the created function.
10669 * @category Function
10670 * @param {*} value The value to wrap.
10671 * @param {Function} wrapper The wrapper function.
10672 * @returns {Function} Returns the new function.
10675 * var p = _.wrap(_.escape, function(func, text) {
10676 * return '<p>' + func(text) + '</p>';
10679 * p('fred, barney, & pebbles');
10680 * // => '<p>fred, barney, & pebbles</p>'
10682 function wrap(value, wrapper) {
10683 wrapper = wrapper == null ? identity : wrapper;
10684 return createWrapper(wrapper, PARTIAL_FLAG, undefined, [value], []);
10687 /*------------------------------------------------------------------------*/
10690 * Creates a clone of `value`. If `isDeep` is `true` nested objects are cloned,
10691 * otherwise they are assigned by reference. If `customizer` is provided it is
10692 * invoked to produce the cloned values. If `customizer` returns `undefined`
10693 * cloning is handled by the method instead. The `customizer` is bound to
10694 * `thisArg` and invoked with two argument; (value [, index|key, object]).
10696 * **Note:** This method is loosely based on the
10697 * [structured clone algorithm](http://www.w3.org/TR/html5/infrastructure.html#internal-structured-cloning-algorithm).
10698 * The enumerable properties of `arguments` objects and objects created by
10699 * constructors other than `Object` are cloned to plain `Object` objects. An
10700 * empty object is returned for uncloneable values such as functions, DOM nodes,
10701 * Maps, Sets, and WeakMaps.
10706 * @param {*} value The value to clone.
10707 * @param {boolean} [isDeep] Specify a deep clone.
10708 * @param {Function} [customizer] The function to customize cloning values.
10709 * @param {*} [thisArg] The `this` binding of `customizer`.
10710 * @returns {*} Returns the cloned value.
10714 * { 'user': 'barney' },
10715 * { 'user': 'fred' }
10718 * var shallow = _.clone(users);
10719 * shallow[0] === users[0];
10722 * var deep = _.clone(users, true);
10723 * deep[0] === users[0];
10726 * // using a customizer callback
10727 * var el = _.clone(document.body, function(value) {
10728 * if (_.isElement(value)) {
10729 * return value.cloneNode(false);
10733 * el === document.body
10737 * el.childNodes.length;
10740 function clone(value, isDeep, customizer, thisArg) {
10741 if (isDeep && typeof isDeep != 'boolean' && isIterateeCall(value, isDeep, customizer)) {
10744 else if (typeof isDeep == 'function') {
10745 thisArg = customizer;
10746 customizer = isDeep;
10749 return typeof customizer == 'function'
10750 ? baseClone(value, isDeep, bindCallback(customizer, thisArg, 1))
10751 : baseClone(value, isDeep);
10755 * Creates a deep clone of `value`. If `customizer` is provided it is invoked
10756 * to produce the cloned values. If `customizer` returns `undefined` cloning
10757 * is handled by the method instead. The `customizer` is bound to `thisArg`
10758 * and invoked with two argument; (value [, index|key, object]).
10760 * **Note:** This method is loosely based on the
10761 * [structured clone algorithm](http://www.w3.org/TR/html5/infrastructure.html#internal-structured-cloning-algorithm).
10762 * The enumerable properties of `arguments` objects and objects created by
10763 * constructors other than `Object` are cloned to plain `Object` objects. An
10764 * empty object is returned for uncloneable values such as functions, DOM nodes,
10765 * Maps, Sets, and WeakMaps.
10770 * @param {*} value The value to deep clone.
10771 * @param {Function} [customizer] The function to customize cloning values.
10772 * @param {*} [thisArg] The `this` binding of `customizer`.
10773 * @returns {*} Returns the deep cloned value.
10777 * { 'user': 'barney' },
10778 * { 'user': 'fred' }
10781 * var deep = _.cloneDeep(users);
10782 * deep[0] === users[0];
10785 * // using a customizer callback
10786 * var el = _.cloneDeep(document.body, function(value) {
10787 * if (_.isElement(value)) {
10788 * return value.cloneNode(true);
10792 * el === document.body
10796 * el.childNodes.length;
10799 function cloneDeep(value, customizer, thisArg) {
10800 return typeof customizer == 'function'
10801 ? baseClone(value, true, bindCallback(customizer, thisArg, 1))
10802 : baseClone(value, true);
10806 * Checks if `value` is greater than `other`.
10811 * @param {*} value The value to compare.
10812 * @param {*} other The other value to compare.
10813 * @returns {boolean} Returns `true` if `value` is greater than `other`, else `false`.
10825 function gt(value, other) {
10826 return value > other;
10830 * Checks if `value` is greater than or equal to `other`.
10835 * @param {*} value The value to compare.
10836 * @param {*} other The other value to compare.
10837 * @returns {boolean} Returns `true` if `value` is greater than or equal to `other`, else `false`.
10849 function gte(value, other) {
10850 return value >= other;
10854 * Checks if `value` is classified as an `arguments` object.
10859 * @param {*} value The value to check.
10860 * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
10863 * _.isArguments(function() { return arguments; }());
10866 * _.isArguments([1, 2, 3]);
10869 function isArguments(value) {
10870 return isObjectLike(value) && isArrayLike(value) &&
10871 hasOwnProperty.call(value, 'callee') && !propertyIsEnumerable.call(value, 'callee');
10875 * Checks if `value` is classified as an `Array` object.
10880 * @param {*} value The value to check.
10881 * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
10884 * _.isArray([1, 2, 3]);
10887 * _.isArray(function() { return arguments; }());
10890 var isArray = nativeIsArray || function(value) {
10891 return isObjectLike(value) && isLength(value.length) && objToString.call(value) == arrayTag;
10895 * Checks if `value` is classified as a boolean primitive or object.
10900 * @param {*} value The value to check.
10901 * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
10904 * _.isBoolean(false);
10907 * _.isBoolean(null);
10910 function isBoolean(value) {
10911 return value === true || value === false || (isObjectLike(value) && objToString.call(value) == boolTag);
10915 * Checks if `value` is classified as a `Date` object.
10920 * @param {*} value The value to check.
10921 * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
10924 * _.isDate(new Date);
10927 * _.isDate('Mon April 23 2012');
10930 function isDate(value) {
10931 return isObjectLike(value) && objToString.call(value) == dateTag;
10935 * Checks if `value` is a DOM element.
10940 * @param {*} value The value to check.
10941 * @returns {boolean} Returns `true` if `value` is a DOM element, else `false`.
10944 * _.isElement(document.body);
10947 * _.isElement('<body>');
10950 function isElement(value) {
10951 return !!value && value.nodeType === 1 && isObjectLike(value) && !isPlainObject(value);
10955 * Checks if `value` is empty. A value is considered empty unless it is an
10956 * `arguments` object, array, string, or jQuery-like collection with a length
10957 * greater than `0` or an object with own enumerable properties.
10962 * @param {Array|Object|string} value The value to inspect.
10963 * @returns {boolean} Returns `true` if `value` is empty, else `false`.
10975 * _.isEmpty([1, 2, 3]);
10978 * _.isEmpty({ 'a': 1 });
10981 function isEmpty(value) {
10982 if (value == null) {
10985 if (isArrayLike(value) && (isArray(value) || isString(value) || isArguments(value) ||
10986 (isObjectLike(value) && isFunction(value.splice)))) {
10987 return !value.length;
10989 return !keys(value).length;
10993 * Performs a deep comparison between two values to determine if they are
10994 * equivalent. If `customizer` is provided it is invoked to compare values.
10995 * If `customizer` returns `undefined` comparisons are handled by the method
10996 * instead. The `customizer` is bound to `thisArg` and invoked with three
10997 * arguments: (value, other [, index|key]).
10999 * **Note:** This method supports comparing arrays, booleans, `Date` objects,
11000 * numbers, `Object` objects, regexes, and strings. Objects are compared by
11001 * their own, not inherited, enumerable properties. Functions and DOM nodes
11002 * are **not** supported. Provide a customizer function to extend support
11003 * for comparing other values.
11009 * @param {*} value The value to compare.
11010 * @param {*} other The other value to compare.
11011 * @param {Function} [customizer] The function to customize value comparisons.
11012 * @param {*} [thisArg] The `this` binding of `customizer`.
11013 * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
11016 * var object = { 'user': 'fred' };
11017 * var other = { 'user': 'fred' };
11022 * _.isEqual(object, other);
11025 * // using a customizer callback
11026 * var array = ['hello', 'goodbye'];
11027 * var other = ['hi', 'goodbye'];
11029 * _.isEqual(array, other, function(value, other) {
11030 * if (_.every([value, other], RegExp.prototype.test, /^h(?:i|ello)$/)) {
11036 function isEqual(value, other, customizer, thisArg) {
11037 customizer = typeof customizer == 'function' ? bindCallback(customizer, thisArg, 3) : undefined;
11038 var result = customizer ? customizer(value, other) : undefined;
11039 return result === undefined ? baseIsEqual(value, other, customizer) : !!result;
11043 * Checks if `value` is an `Error`, `EvalError`, `RangeError`, `ReferenceError`,
11044 * `SyntaxError`, `TypeError`, or `URIError` object.
11049 * @param {*} value The value to check.
11050 * @returns {boolean} Returns `true` if `value` is an error object, else `false`.
11053 * _.isError(new Error);
11056 * _.isError(Error);
11059 function isError(value) {
11060 return isObjectLike(value) && typeof value.message == 'string' && objToString.call(value) == errorTag;
11064 * Checks if `value` is a finite primitive number.
11066 * **Note:** This method is based on [`Number.isFinite`](http://ecma-international.org/ecma-262/6.0/#sec-number.isfinite).
11071 * @param {*} value The value to check.
11072 * @returns {boolean} Returns `true` if `value` is a finite number, else `false`.
11078 * _.isFinite('10');
11081 * _.isFinite(true);
11084 * _.isFinite(Object(10));
11087 * _.isFinite(Infinity);
11090 function isFinite(value) {
11091 return typeof value == 'number' && nativeIsFinite(value);
11095 * Checks if `value` is classified as a `Function` object.
11100 * @param {*} value The value to check.
11101 * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
11107 * _.isFunction(/abc/);
11110 function isFunction(value) {
11111 // The use of `Object#toString` avoids issues with the `typeof` operator
11112 // in older versions of Chrome and Safari which return 'function' for regexes
11113 // and Safari 8 equivalents which return 'object' for typed array constructors.
11114 return isObject(value) && objToString.call(value) == funcTag;
11118 * Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`.
11119 * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
11124 * @param {*} value The value to check.
11125 * @returns {boolean} Returns `true` if `value` is an object, else `false`.
11131 * _.isObject([1, 2, 3]);
11137 function isObject(value) {
11138 // Avoid a V8 JIT bug in Chrome 19-20.
11139 // See https://code.google.com/p/v8/issues/detail?id=2291 for more details.
11140 var type = typeof value;
11141 return !!value && (type == 'object' || type == 'function');
11145 * Performs a deep comparison between `object` and `source` to determine if
11146 * `object` contains equivalent property values. If `customizer` is provided
11147 * it is invoked to compare values. If `customizer` returns `undefined`
11148 * comparisons are handled by the method instead. The `customizer` is bound
11149 * to `thisArg` and invoked with three arguments: (value, other, index|key).
11151 * **Note:** This method supports comparing properties of arrays, booleans,
11152 * `Date` objects, numbers, `Object` objects, regexes, and strings. Functions
11153 * and DOM nodes are **not** supported. Provide a customizer function to extend
11154 * support for comparing other values.
11159 * @param {Object} object The object to inspect.
11160 * @param {Object} source The object of property values to match.
11161 * @param {Function} [customizer] The function to customize value comparisons.
11162 * @param {*} [thisArg] The `this` binding of `customizer`.
11163 * @returns {boolean} Returns `true` if `object` is a match, else `false`.
11166 * var object = { 'user': 'fred', 'age': 40 };
11168 * _.isMatch(object, { 'age': 40 });
11171 * _.isMatch(object, { 'age': 36 });
11174 * // using a customizer callback
11175 * var object = { 'greeting': 'hello' };
11176 * var source = { 'greeting': 'hi' };
11178 * _.isMatch(object, source, function(value, other) {
11179 * return _.every([value, other], RegExp.prototype.test, /^h(?:i|ello)$/) || undefined;
11183 function isMatch(object, source, customizer, thisArg) {
11184 customizer = typeof customizer == 'function' ? bindCallback(customizer, thisArg, 3) : undefined;
11185 return baseIsMatch(object, getMatchData(source), customizer);
11189 * Checks if `value` is `NaN`.
11191 * **Note:** This method is not the same as [`isNaN`](https://es5.github.io/#x15.1.2.4)
11192 * which returns `true` for `undefined` and other non-numeric values.
11197 * @param {*} value The value to check.
11198 * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.
11204 * _.isNaN(new Number(NaN));
11207 * isNaN(undefined);
11210 * _.isNaN(undefined);
11213 function isNaN(value) {
11214 // An `NaN` primitive is the only value that is not equal to itself.
11215 // Perform the `toStringTag` check first to avoid errors with some host objects in IE.
11216 return isNumber(value) && value != +value;
11220 * Checks if `value` is a native function.
11225 * @param {*} value The value to check.
11226 * @returns {boolean} Returns `true` if `value` is a native function, else `false`.
11229 * _.isNative(Array.prototype.push);
11235 function isNative(value) {
11236 if (value == null) {
11239 if (isFunction(value)) {
11240 return reIsNative.test(fnToString.call(value));
11242 return isObjectLike(value) && reIsHostCtor.test(value);
11246 * Checks if `value` is `null`.
11251 * @param {*} value The value to check.
11252 * @returns {boolean} Returns `true` if `value` is `null`, else `false`.
11258 * _.isNull(void 0);
11261 function isNull(value) {
11262 return value === null;
11266 * Checks if `value` is classified as a `Number` primitive or object.
11268 * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are classified
11269 * as numbers, use the `_.isFinite` method.
11274 * @param {*} value The value to check.
11275 * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
11284 * _.isNumber('8.4');
11287 function isNumber(value) {
11288 return typeof value == 'number' || (isObjectLike(value) && objToString.call(value) == numberTag);
11292 * Checks if `value` is a plain object, that is, an object created by the
11293 * `Object` constructor or one with a `[[Prototype]]` of `null`.
11295 * **Note:** This method assumes objects created by the `Object` constructor
11296 * have no inherited enumerable properties.
11301 * @param {*} value The value to check.
11302 * @returns {boolean} Returns `true` if `value` is a plain object, else `false`.
11309 * _.isPlainObject(new Foo);
11312 * _.isPlainObject([1, 2, 3]);
11315 * _.isPlainObject({ 'x': 0, 'y': 0 });
11318 * _.isPlainObject(Object.create(null));
11321 function isPlainObject(value) {
11324 // Exit early for non `Object` objects.
11325 if (!(isObjectLike(value) && objToString.call(value) == objectTag && !isArguments(value)) ||
11326 (!hasOwnProperty.call(value, 'constructor') && (Ctor = value.constructor, typeof Ctor == 'function' && !(Ctor instanceof Ctor)))) {
11329 // IE < 9 iterates inherited properties before own properties. If the first
11330 // iterated property is an object's own property then there are no inherited
11331 // enumerable properties.
11333 // In most environments an object's own properties are iterated before
11334 // its inherited properties. If the last iterated property is an object's
11335 // own property then there are no inherited enumerable properties.
11336 baseForIn(value, function(subValue, key) {
11339 return result === undefined || hasOwnProperty.call(value, result);
11343 * Checks if `value` is classified as a `RegExp` object.
11348 * @param {*} value The value to check.
11349 * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
11352 * _.isRegExp(/abc/);
11355 * _.isRegExp('/abc/');
11358 function isRegExp(value) {
11359 return isObject(value) && objToString.call(value) == regexpTag;
11363 * Checks if `value` is classified as a `String` primitive or object.
11368 * @param {*} value The value to check.
11369 * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
11372 * _.isString('abc');
11378 function isString(value) {
11379 return typeof value == 'string' || (isObjectLike(value) && objToString.call(value) == stringTag);
11383 * Checks if `value` is classified as a typed array.
11388 * @param {*} value The value to check.
11389 * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
11392 * _.isTypedArray(new Uint8Array);
11395 * _.isTypedArray([]);
11398 function isTypedArray(value) {
11399 return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[objToString.call(value)];
11403 * Checks if `value` is `undefined`.
11408 * @param {*} value The value to check.
11409 * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`.
11412 * _.isUndefined(void 0);
11415 * _.isUndefined(null);
11418 function isUndefined(value) {
11419 return value === undefined;
11423 * Checks if `value` is less than `other`.
11428 * @param {*} value The value to compare.
11429 * @param {*} other The other value to compare.
11430 * @returns {boolean} Returns `true` if `value` is less than `other`, else `false`.
11442 function lt(value, other) {
11443 return value < other;
11447 * Checks if `value` is less than or equal to `other`.
11452 * @param {*} value The value to compare.
11453 * @param {*} other The other value to compare.
11454 * @returns {boolean} Returns `true` if `value` is less than or equal to `other`, else `false`.
11466 function lte(value, other) {
11467 return value <= other;
11471 * Converts `value` to an array.
11476 * @param {*} value The value to convert.
11477 * @returns {Array} Returns the converted array.
11481 * return _.toArray(arguments).slice(1);
11485 function toArray(value) {
11486 var length = value ? getLength(value) : 0;
11487 if (!isLength(length)) {
11488 return values(value);
11493 return arrayCopy(value);
11497 * Converts `value` to a plain object flattening inherited enumerable
11498 * properties of `value` to own properties of the plain object.
11503 * @param {*} value The value to convert.
11504 * @returns {Object} Returns the converted plain object.
11511 * Foo.prototype.c = 3;
11513 * _.assign({ 'a': 1 }, new Foo);
11514 * // => { 'a': 1, 'b': 2 }
11516 * _.assign({ 'a': 1 }, _.toPlainObject(new Foo));
11517 * // => { 'a': 1, 'b': 2, 'c': 3 }
11519 function toPlainObject(value) {
11520 return baseCopy(value, keysIn(value));
11523 /*------------------------------------------------------------------------*/
11526 * Recursively merges own enumerable properties of the source object(s), that
11527 * don't resolve to `undefined` into the destination object. Subsequent sources
11528 * overwrite property assignments of previous sources. If `customizer` is
11529 * provided it is invoked to produce the merged values of the destination and
11530 * source properties. If `customizer` returns `undefined` merging is handled
11531 * by the method instead. The `customizer` is bound to `thisArg` and invoked
11532 * with five arguments: (objectValue, sourceValue, key, object, source).
11537 * @param {Object} object The destination object.
11538 * @param {...Object} [sources] The source objects.
11539 * @param {Function} [customizer] The function to customize assigned values.
11540 * @param {*} [thisArg] The `this` binding of `customizer`.
11541 * @returns {Object} Returns `object`.
11545 * 'data': [{ 'user': 'barney' }, { 'user': 'fred' }]
11549 * 'data': [{ 'age': 36 }, { 'age': 40 }]
11552 * _.merge(users, ages);
11553 * // => { 'data': [{ 'user': 'barney', 'age': 36 }, { 'user': 'fred', 'age': 40 }] }
11555 * // using a customizer callback
11557 * 'fruits': ['apple'],
11558 * 'vegetables': ['beet']
11562 * 'fruits': ['banana'],
11563 * 'vegetables': ['carrot']
11566 * _.merge(object, other, function(a, b) {
11567 * if (_.isArray(a)) {
11568 * return a.concat(b);
11571 * // => { 'fruits': ['apple', 'banana'], 'vegetables': ['beet', 'carrot'] }
11573 var merge = createAssigner(baseMerge);
11576 * Assigns own enumerable properties of source object(s) to the destination
11577 * object. Subsequent sources overwrite property assignments of previous sources.
11578 * If `customizer` is provided it is invoked to produce the assigned values.
11579 * The `customizer` is bound to `thisArg` and invoked with five arguments:
11580 * (objectValue, sourceValue, key, object, source).
11582 * **Note:** This method mutates `object` and is based on
11583 * [`Object.assign`](http://ecma-international.org/ecma-262/6.0/#sec-object.assign).
11589 * @param {Object} object The destination object.
11590 * @param {...Object} [sources] The source objects.
11591 * @param {Function} [customizer] The function to customize assigned values.
11592 * @param {*} [thisArg] The `this` binding of `customizer`.
11593 * @returns {Object} Returns `object`.
11596 * _.assign({ 'user': 'barney' }, { 'age': 40 }, { 'user': 'fred' });
11597 * // => { 'user': 'fred', 'age': 40 }
11599 * // using a customizer callback
11600 * var defaults = _.partialRight(_.assign, function(value, other) {
11601 * return _.isUndefined(value) ? other : value;
11604 * defaults({ 'user': 'barney' }, { 'age': 36 }, { 'user': 'fred' });
11605 * // => { 'user': 'barney', 'age': 36 }
11607 var assign = createAssigner(function(object, source, customizer) {
11609 ? assignWith(object, source, customizer)
11610 : baseAssign(object, source);
11614 * Creates an object that inherits from the given `prototype` object. If a
11615 * `properties` object is provided its own enumerable properties are assigned
11616 * to the created object.
11621 * @param {Object} prototype The object to inherit from.
11622 * @param {Object} [properties] The properties to assign to the object.
11623 * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
11624 * @returns {Object} Returns the new object.
11627 * function Shape() {
11632 * function Circle() {
11633 * Shape.call(this);
11636 * Circle.prototype = _.create(Shape.prototype, {
11637 * 'constructor': Circle
11640 * var circle = new Circle;
11641 * circle instanceof Circle;
11644 * circle instanceof Shape;
11647 function create(prototype, properties, guard) {
11648 var result = baseCreate(prototype);
11649 if (guard && isIterateeCall(prototype, properties, guard)) {
11650 properties = undefined;
11652 return properties ? baseAssign(result, properties) : result;
11656 * Assigns own enumerable properties of source object(s) to the destination
11657 * object for all destination properties that resolve to `undefined`. Once a
11658 * property is set, additional values of the same property are ignored.
11660 * **Note:** This method mutates `object`.
11665 * @param {Object} object The destination object.
11666 * @param {...Object} [sources] The source objects.
11667 * @returns {Object} Returns `object`.
11670 * _.defaults({ 'user': 'barney' }, { 'age': 36 }, { 'user': 'fred' });
11671 * // => { 'user': 'barney', 'age': 36 }
11673 var defaults = createDefaults(assign, assignDefaults);
11676 * This method is like `_.defaults` except that it recursively assigns
11677 * default properties.
11679 * **Note:** This method mutates `object`.
11684 * @param {Object} object The destination object.
11685 * @param {...Object} [sources] The source objects.
11686 * @returns {Object} Returns `object`.
11689 * _.defaultsDeep({ 'user': { 'name': 'barney' } }, { 'user': { 'name': 'fred', 'age': 36 } });
11690 * // => { 'user': { 'name': 'barney', 'age': 36 } }
11693 var defaultsDeep = createDefaults(merge, mergeDefaults);
11696 * This method is like `_.find` except that it returns the key of the first
11697 * element `predicate` returns truthy for instead of the element itself.
11699 * If a property name is provided for `predicate` the created `_.property`
11700 * style callback returns the property value of the given element.
11702 * If a value is also provided for `thisArg` the created `_.matchesProperty`
11703 * style callback returns `true` for elements that have a matching property
11704 * value, else `false`.
11706 * If an object is provided for `predicate` the created `_.matches` style
11707 * callback returns `true` for elements that have the properties of the given
11708 * object, else `false`.
11713 * @param {Object} object The object to search.
11714 * @param {Function|Object|string} [predicate=_.identity] The function invoked
11716 * @param {*} [thisArg] The `this` binding of `predicate`.
11717 * @returns {string|undefined} Returns the key of the matched element, else `undefined`.
11721 * 'barney': { 'age': 36, 'active': true },
11722 * 'fred': { 'age': 40, 'active': false },
11723 * 'pebbles': { 'age': 1, 'active': true }
11726 * _.findKey(users, function(chr) {
11727 * return chr.age < 40;
11729 * // => 'barney' (iteration order is not guaranteed)
11731 * // using the `_.matches` callback shorthand
11732 * _.findKey(users, { 'age': 1, 'active': true });
11735 * // using the `_.matchesProperty` callback shorthand
11736 * _.findKey(users, 'active', false);
11739 * // using the `_.property` callback shorthand
11740 * _.findKey(users, 'active');
11743 var findKey = createFindKey(baseForOwn);
11746 * This method is like `_.findKey` except that it iterates over elements of
11747 * a collection in the opposite order.
11749 * If a property name is provided for `predicate` the created `_.property`
11750 * style callback returns the property value of the given element.
11752 * If a value is also provided for `thisArg` the created `_.matchesProperty`
11753 * style callback returns `true` for elements that have a matching property
11754 * value, else `false`.
11756 * If an object is provided for `predicate` the created `_.matches` style
11757 * callback returns `true` for elements that have the properties of the given
11758 * object, else `false`.
11763 * @param {Object} object The object to search.
11764 * @param {Function|Object|string} [predicate=_.identity] The function invoked
11766 * @param {*} [thisArg] The `this` binding of `predicate`.
11767 * @returns {string|undefined} Returns the key of the matched element, else `undefined`.
11771 * 'barney': { 'age': 36, 'active': true },
11772 * 'fred': { 'age': 40, 'active': false },
11773 * 'pebbles': { 'age': 1, 'active': true }
11776 * _.findLastKey(users, function(chr) {
11777 * return chr.age < 40;
11779 * // => returns `pebbles` assuming `_.findKey` returns `barney`
11781 * // using the `_.matches` callback shorthand
11782 * _.findLastKey(users, { 'age': 36, 'active': true });
11785 * // using the `_.matchesProperty` callback shorthand
11786 * _.findLastKey(users, 'active', false);
11789 * // using the `_.property` callback shorthand
11790 * _.findLastKey(users, 'active');
11793 var findLastKey = createFindKey(baseForOwnRight);
11796 * Iterates over own and inherited enumerable properties of an object invoking
11797 * `iteratee` for each property. The `iteratee` is bound to `thisArg` and invoked
11798 * with three arguments: (value, key, object). Iteratee functions may exit
11799 * iteration early by explicitly returning `false`.
11804 * @param {Object} object The object to iterate over.
11805 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
11806 * @param {*} [thisArg] The `this` binding of `iteratee`.
11807 * @returns {Object} Returns `object`.
11815 * Foo.prototype.c = 3;
11817 * _.forIn(new Foo, function(value, key) {
11818 * console.log(key);
11820 * // => logs 'a', 'b', and 'c' (iteration order is not guaranteed)
11822 var forIn = createForIn(baseFor);
11825 * This method is like `_.forIn` except that it iterates over properties of
11826 * `object` in the opposite order.
11831 * @param {Object} object The object to iterate over.
11832 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
11833 * @param {*} [thisArg] The `this` binding of `iteratee`.
11834 * @returns {Object} Returns `object`.
11842 * Foo.prototype.c = 3;
11844 * _.forInRight(new Foo, function(value, key) {
11845 * console.log(key);
11847 * // => logs 'c', 'b', and 'a' assuming `_.forIn ` logs 'a', 'b', and 'c'
11849 var forInRight = createForIn(baseForRight);
11852 * Iterates over own enumerable properties of an object invoking `iteratee`
11853 * for each property. The `iteratee` is bound to `thisArg` and invoked with
11854 * three arguments: (value, key, object). Iteratee functions may exit iteration
11855 * early by explicitly returning `false`.
11860 * @param {Object} object The object to iterate over.
11861 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
11862 * @param {*} [thisArg] The `this` binding of `iteratee`.
11863 * @returns {Object} Returns `object`.
11871 * Foo.prototype.c = 3;
11873 * _.forOwn(new Foo, function(value, key) {
11874 * console.log(key);
11876 * // => logs 'a' and 'b' (iteration order is not guaranteed)
11878 var forOwn = createForOwn(baseForOwn);
11881 * This method is like `_.forOwn` except that it iterates over properties of
11882 * `object` in the opposite order.
11887 * @param {Object} object The object to iterate over.
11888 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
11889 * @param {*} [thisArg] The `this` binding of `iteratee`.
11890 * @returns {Object} Returns `object`.
11898 * Foo.prototype.c = 3;
11900 * _.forOwnRight(new Foo, function(value, key) {
11901 * console.log(key);
11903 * // => logs 'b' and 'a' assuming `_.forOwn` logs 'a' and 'b'
11905 var forOwnRight = createForOwn(baseForOwnRight);
11908 * Creates an array of function property names from all enumerable properties,
11909 * own and inherited, of `object`.
11915 * @param {Object} object The object to inspect.
11916 * @returns {Array} Returns the new array of property names.
11920 * // => ['after', 'ary', 'assign', ...]
11922 function functions(object) {
11923 return baseFunctions(object, keysIn(object));
11927 * Gets the property value at `path` of `object`. If the resolved value is
11928 * `undefined` the `defaultValue` is used in its place.
11933 * @param {Object} object The object to query.
11934 * @param {Array|string} path The path of the property to get.
11935 * @param {*} [defaultValue] The value returned if the resolved value is `undefined`.
11936 * @returns {*} Returns the resolved value.
11939 * var object = { 'a': [{ 'b': { 'c': 3 } }] };
11941 * _.get(object, 'a[0].b.c');
11944 * _.get(object, ['a', '0', 'b', 'c']);
11947 * _.get(object, 'a.b.c', 'default');
11950 function get(object, path, defaultValue) {
11951 var result = object == null ? undefined : baseGet(object, toPath(path), path + '');
11952 return result === undefined ? defaultValue : result;
11956 * Checks if `path` is a direct property.
11961 * @param {Object} object The object to query.
11962 * @param {Array|string} path The path to check.
11963 * @returns {boolean} Returns `true` if `path` is a direct property, else `false`.
11966 * var object = { 'a': { 'b': { 'c': 3 } } };
11968 * _.has(object, 'a');
11971 * _.has(object, 'a.b.c');
11974 * _.has(object, ['a', 'b', 'c']);
11977 function has(object, path) {
11978 if (object == null) {
11981 var result = hasOwnProperty.call(object, path);
11982 if (!result && !isKey(path)) {
11983 path = toPath(path);
11984 object = path.length == 1 ? object : baseGet(object, baseSlice(path, 0, -1));
11985 if (object == null) {
11989 result = hasOwnProperty.call(object, path);
11991 return result || (isLength(object.length) && isIndex(path, object.length) &&
11992 (isArray(object) || isArguments(object)));
11996 * Creates an object composed of the inverted keys and values of `object`.
11997 * If `object` contains duplicate values, subsequent values overwrite property
11998 * assignments of previous values unless `multiValue` is `true`.
12003 * @param {Object} object The object to invert.
12004 * @param {boolean} [multiValue] Allow multiple values per key.
12005 * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
12006 * @returns {Object} Returns the new inverted object.
12009 * var object = { 'a': 1, 'b': 2, 'c': 1 };
12011 * _.invert(object);
12012 * // => { '1': 'c', '2': 'b' }
12014 * // with `multiValue`
12015 * _.invert(object, true);
12016 * // => { '1': ['a', 'c'], '2': ['b'] }
12018 function invert(object, multiValue, guard) {
12019 if (guard && isIterateeCall(object, multiValue, guard)) {
12020 multiValue = undefined;
12023 props = keys(object),
12024 length = props.length,
12027 while (++index < length) {
12028 var key = props[index],
12029 value = object[key];
12032 if (hasOwnProperty.call(result, value)) {
12033 result[value].push(key);
12035 result[value] = [key];
12039 result[value] = key;
12046 * Creates an array of the own enumerable property names of `object`.
12048 * **Note:** Non-object values are coerced to objects. See the
12049 * [ES spec](http://ecma-international.org/ecma-262/6.0/#sec-object.keys)
12050 * for more details.
12055 * @param {Object} object The object to query.
12056 * @returns {Array} Returns the array of property names.
12064 * Foo.prototype.c = 3;
12067 * // => ['a', 'b'] (iteration order is not guaranteed)
12072 var keys = !nativeKeys ? shimKeys : function(object) {
12073 var Ctor = object == null ? undefined : object.constructor;
12074 if ((typeof Ctor == 'function' && Ctor.prototype === object) ||
12075 (typeof object != 'function' && isArrayLike(object))) {
12076 return shimKeys(object);
12078 return isObject(object) ? nativeKeys(object) : [];
12082 * Creates an array of the own and inherited enumerable property names of `object`.
12084 * **Note:** Non-object values are coerced to objects.
12089 * @param {Object} object The object to query.
12090 * @returns {Array} Returns the array of property names.
12098 * Foo.prototype.c = 3;
12100 * _.keysIn(new Foo);
12101 * // => ['a', 'b', 'c'] (iteration order is not guaranteed)
12103 function keysIn(object) {
12104 if (object == null) {
12107 if (!isObject(object)) {
12108 object = Object(object);
12110 var length = object.length;
12111 length = (length && isLength(length) &&
12112 (isArray(object) || isArguments(object)) && length) || 0;
12114 var Ctor = object.constructor,
12116 isProto = typeof Ctor == 'function' && Ctor.prototype === object,
12117 result = Array(length),
12118 skipIndexes = length > 0;
12120 while (++index < length) {
12121 result[index] = (index + '');
12123 for (var key in object) {
12124 if (!(skipIndexes && isIndex(key, length)) &&
12125 !(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) {
12133 * The opposite of `_.mapValues`; this method creates an object with the
12134 * same values as `object` and keys generated by running each own enumerable
12135 * property of `object` through `iteratee`.
12140 * @param {Object} object The object to iterate over.
12141 * @param {Function|Object|string} [iteratee=_.identity] The function invoked
12143 * @param {*} [thisArg] The `this` binding of `iteratee`.
12144 * @returns {Object} Returns the new mapped object.
12147 * _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) {
12148 * return key + value;
12150 * // => { 'a1': 1, 'b2': 2 }
12152 var mapKeys = createObjectMapper(true);
12155 * Creates an object with the same keys as `object` and values generated by
12156 * running each own enumerable property of `object` through `iteratee`. The
12157 * iteratee function is bound to `thisArg` and invoked with three arguments:
12158 * (value, key, object).
12160 * If a property name is provided for `iteratee` the created `_.property`
12161 * style callback returns the property value of the given element.
12163 * If a value is also provided for `thisArg` the created `_.matchesProperty`
12164 * style callback returns `true` for elements that have a matching property
12165 * value, else `false`.
12167 * If an object is provided for `iteratee` the created `_.matches` style
12168 * callback returns `true` for elements that have the properties of the given
12169 * object, else `false`.
12174 * @param {Object} object The object to iterate over.
12175 * @param {Function|Object|string} [iteratee=_.identity] The function invoked
12177 * @param {*} [thisArg] The `this` binding of `iteratee`.
12178 * @returns {Object} Returns the new mapped object.
12181 * _.mapValues({ 'a': 1, 'b': 2 }, function(n) {
12184 * // => { 'a': 3, 'b': 6 }
12187 * 'fred': { 'user': 'fred', 'age': 40 },
12188 * 'pebbles': { 'user': 'pebbles', 'age': 1 }
12191 * // using the `_.property` callback shorthand
12192 * _.mapValues(users, 'age');
12193 * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)
12195 var mapValues = createObjectMapper();
12198 * The opposite of `_.pick`; this method creates an object composed of the
12199 * own and inherited enumerable properties of `object` that are not omitted.
12204 * @param {Object} object The source object.
12205 * @param {Function|...(string|string[])} [predicate] The function invoked per
12206 * iteration or property names to omit, specified as individual property
12207 * names or arrays of property names.
12208 * @param {*} [thisArg] The `this` binding of `predicate`.
12209 * @returns {Object} Returns the new object.
12212 * var object = { 'user': 'fred', 'age': 40 };
12214 * _.omit(object, 'age');
12215 * // => { 'user': 'fred' }
12217 * _.omit(object, _.isNumber);
12218 * // => { 'user': 'fred' }
12220 var omit = restParam(function(object, props) {
12221 if (object == null) {
12224 if (typeof props[0] != 'function') {
12225 var props = arrayMap(baseFlatten(props), String);
12226 return pickByArray(object, baseDifference(keysIn(object), props));
12228 var predicate = bindCallback(props[0], props[1], 3);
12229 return pickByCallback(object, function(value, key, object) {
12230 return !predicate(value, key, object);
12235 * Creates a two dimensional array of the key-value pairs for `object`,
12236 * e.g. `[[key1, value1], [key2, value2]]`.
12241 * @param {Object} object The object to query.
12242 * @returns {Array} Returns the new array of key-value pairs.
12245 * _.pairs({ 'barney': 36, 'fred': 40 });
12246 * // => [['barney', 36], ['fred', 40]] (iteration order is not guaranteed)
12248 function pairs(object) {
12249 object = toObject(object);
12252 props = keys(object),
12253 length = props.length,
12254 result = Array(length);
12256 while (++index < length) {
12257 var key = props[index];
12258 result[index] = [key, object[key]];
12264 * Creates an object composed of the picked `object` properties. Property
12265 * names may be specified as individual arguments or as arrays of property
12266 * names. If `predicate` is provided it is invoked for each property of `object`
12267 * picking the properties `predicate` returns truthy for. The predicate is
12268 * bound to `thisArg` and invoked with three arguments: (value, key, object).
12273 * @param {Object} object The source object.
12274 * @param {Function|...(string|string[])} [predicate] The function invoked per
12275 * iteration or property names to pick, specified as individual property
12276 * names or arrays of property names.
12277 * @param {*} [thisArg] The `this` binding of `predicate`.
12278 * @returns {Object} Returns the new object.
12281 * var object = { 'user': 'fred', 'age': 40 };
12283 * _.pick(object, 'user');
12284 * // => { 'user': 'fred' }
12286 * _.pick(object, _.isString);
12287 * // => { 'user': 'fred' }
12289 var pick = restParam(function(object, props) {
12290 if (object == null) {
12293 return typeof props[0] == 'function'
12294 ? pickByCallback(object, bindCallback(props[0], props[1], 3))
12295 : pickByArray(object, baseFlatten(props));
12299 * This method is like `_.get` except that if the resolved value is a function
12300 * it is invoked with the `this` binding of its parent object and its result
12306 * @param {Object} object The object to query.
12307 * @param {Array|string} path The path of the property to resolve.
12308 * @param {*} [defaultValue] The value returned if the resolved value is `undefined`.
12309 * @returns {*} Returns the resolved value.
12312 * var object = { 'a': [{ 'b': { 'c1': 3, 'c2': _.constant(4) } }] };
12314 * _.result(object, 'a[0].b.c1');
12317 * _.result(object, 'a[0].b.c2');
12320 * _.result(object, 'a.b.c', 'default');
12323 * _.result(object, 'a.b.c', _.constant('default'));
12326 function result(object, path, defaultValue) {
12327 var result = object == null ? undefined : object[path];
12328 if (result === undefined) {
12329 if (object != null && !isKey(path, object)) {
12330 path = toPath(path);
12331 object = path.length == 1 ? object : baseGet(object, baseSlice(path, 0, -1));
12332 result = object == null ? undefined : object[last(path)];
12334 result = result === undefined ? defaultValue : result;
12336 return isFunction(result) ? result.call(object) : result;
12340 * Sets the property value of `path` on `object`. If a portion of `path`
12341 * does not exist it is created.
12346 * @param {Object} object The object to augment.
12347 * @param {Array|string} path The path of the property to set.
12348 * @param {*} value The value to set.
12349 * @returns {Object} Returns `object`.
12352 * var object = { 'a': [{ 'b': { 'c': 3 } }] };
12354 * _.set(object, 'a[0].b.c', 4);
12355 * console.log(object.a[0].b.c);
12358 * _.set(object, 'x[0].y.z', 5);
12359 * console.log(object.x[0].y.z);
12362 function set(object, path, value) {
12363 if (object == null) {
12366 var pathKey = (path + '');
12367 path = (object[pathKey] != null || isKey(path, object)) ? [pathKey] : toPath(path);
12370 length = path.length,
12371 lastIndex = length - 1,
12374 while (nested != null && ++index < length) {
12375 var key = path[index];
12376 if (isObject(nested)) {
12377 if (index == lastIndex) {
12378 nested[key] = value;
12379 } else if (nested[key] == null) {
12380 nested[key] = isIndex(path[index + 1]) ? [] : {};
12383 nested = nested[key];
12389 * An alternative to `_.reduce`; this method transforms `object` to a new
12390 * `accumulator` object which is the result of running each of its own enumerable
12391 * properties through `iteratee`, with each invocation potentially mutating
12392 * the `accumulator` object. The `iteratee` is bound to `thisArg` and invoked
12393 * with four arguments: (accumulator, value, key, object). Iteratee functions
12394 * may exit iteration early by explicitly returning `false`.
12399 * @param {Array|Object} object The object to iterate over.
12400 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
12401 * @param {*} [accumulator] The custom accumulator value.
12402 * @param {*} [thisArg] The `this` binding of `iteratee`.
12403 * @returns {*} Returns the accumulated value.
12406 * _.transform([2, 3, 4], function(result, n) {
12407 * result.push(n *= n);
12408 * return n % 2 == 0;
12412 * _.transform({ 'a': 1, 'b': 2 }, function(result, n, key) {
12413 * result[key] = n * 3;
12415 * // => { 'a': 3, 'b': 6 }
12417 function transform(object, iteratee, accumulator, thisArg) {
12418 var isArr = isArray(object) || isTypedArray(object);
12419 iteratee = getCallback(iteratee, thisArg, 4);
12421 if (accumulator == null) {
12422 if (isArr || isObject(object)) {
12423 var Ctor = object.constructor;
12425 accumulator = isArray(object) ? new Ctor : [];
12427 accumulator = baseCreate(isFunction(Ctor) ? Ctor.prototype : undefined);
12433 (isArr ? arrayEach : baseForOwn)(object, function(value, index, object) {
12434 return iteratee(accumulator, value, index, object);
12436 return accumulator;
12440 * Creates an array of the own enumerable property values of `object`.
12442 * **Note:** Non-object values are coerced to objects.
12447 * @param {Object} object The object to query.
12448 * @returns {Array} Returns the array of property values.
12456 * Foo.prototype.c = 3;
12458 * _.values(new Foo);
12459 * // => [1, 2] (iteration order is not guaranteed)
12464 function values(object) {
12465 return baseValues(object, keys(object));
12469 * Creates an array of the own and inherited enumerable property values
12472 * **Note:** Non-object values are coerced to objects.
12477 * @param {Object} object The object to query.
12478 * @returns {Array} Returns the array of property values.
12486 * Foo.prototype.c = 3;
12488 * _.valuesIn(new Foo);
12489 * // => [1, 2, 3] (iteration order is not guaranteed)
12491 function valuesIn(object) {
12492 return baseValues(object, keysIn(object));
12495 /*------------------------------------------------------------------------*/
12498 * Checks if `n` is between `start` and up to but not including, `end`. If
12499 * `end` is not specified it is set to `start` with `start` then set to `0`.
12504 * @param {number} n The number to check.
12505 * @param {number} [start=0] The start of the range.
12506 * @param {number} end The end of the range.
12507 * @returns {boolean} Returns `true` if `n` is in the range, else `false`.
12510 * _.inRange(3, 2, 4);
12522 * _.inRange(1.2, 2);
12525 * _.inRange(5.2, 4);
12528 function inRange(value, start, end) {
12529 start = +start || 0;
12530 if (end === undefined) {
12536 return value >= nativeMin(start, end) && value < nativeMax(start, end);
12540 * Produces a random number between `min` and `max` (inclusive). If only one
12541 * argument is provided a number between `0` and the given number is returned.
12542 * If `floating` is `true`, or either `min` or `max` are floats, a floating-point
12543 * number is returned instead of an integer.
12548 * @param {number} [min=0] The minimum possible value.
12549 * @param {number} [max=1] The maximum possible value.
12550 * @param {boolean} [floating] Specify returning a floating-point number.
12551 * @returns {number} Returns the random number.
12555 * // => an integer between 0 and 5
12558 * // => also an integer between 0 and 5
12560 * _.random(5, true);
12561 * // => a floating-point number between 0 and 5
12563 * _.random(1.2, 5.2);
12564 * // => a floating-point number between 1.2 and 5.2
12566 function random(min, max, floating) {
12567 if (floating && isIterateeCall(min, max, floating)) {
12568 max = floating = undefined;
12570 var noMin = min == null,
12571 noMax = max == null;
12573 if (floating == null) {
12574 if (noMax && typeof min == 'boolean') {
12578 else if (typeof max == 'boolean') {
12583 if (noMin && noMax) {
12594 if (floating || min % 1 || max % 1) {
12595 var rand = nativeRandom();
12596 return nativeMin(min + (rand * (max - min + parseFloat('1e-' + ((rand + '').length - 1)))), max);
12598 return baseRandom(min, max);
12601 /*------------------------------------------------------------------------*/
12604 * Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase).
12609 * @param {string} [string=''] The string to convert.
12610 * @returns {string} Returns the camel cased string.
12613 * _.camelCase('Foo Bar');
12616 * _.camelCase('--foo-bar');
12619 * _.camelCase('__foo_bar__');
12622 var camelCase = createCompounder(function(result, word, index) {
12623 word = word.toLowerCase();
12624 return result + (index ? (word.charAt(0).toUpperCase() + word.slice(1)) : word);
12628 * Capitalizes the first character of `string`.
12633 * @param {string} [string=''] The string to capitalize.
12634 * @returns {string} Returns the capitalized string.
12637 * _.capitalize('fred');
12640 function capitalize(string) {
12641 string = baseToString(string);
12642 return string && (string.charAt(0).toUpperCase() + string.slice(1));
12646 * Deburrs `string` by converting [latin-1 supplementary letters](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table)
12647 * to basic latin letters and removing [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks).
12652 * @param {string} [string=''] The string to deburr.
12653 * @returns {string} Returns the deburred string.
12656 * _.deburr('déjà vu');
12659 function deburr(string) {
12660 string = baseToString(string);
12661 return string && string.replace(reLatin1, deburrLetter).replace(reComboMark, '');
12665 * Checks if `string` ends with the given target string.
12670 * @param {string} [string=''] The string to search.
12671 * @param {string} [target] The string to search for.
12672 * @param {number} [position=string.length] The position to search from.
12673 * @returns {boolean} Returns `true` if `string` ends with `target`, else `false`.
12676 * _.endsWith('abc', 'c');
12679 * _.endsWith('abc', 'b');
12682 * _.endsWith('abc', 'b', 2);
12685 function endsWith(string, target, position) {
12686 string = baseToString(string);
12687 target = (target + '');
12689 var length = string.length;
12690 position = position === undefined
12692 : nativeMin(position < 0 ? 0 : (+position || 0), length);
12694 position -= target.length;
12695 return position >= 0 && string.indexOf(target, position) == position;
12699 * Converts the characters "&", "<", ">", '"', "'", and "\`", in `string` to
12700 * their corresponding HTML entities.
12702 * **Note:** No other characters are escaped. To escape additional characters
12703 * use a third-party library like [_he_](https://mths.be/he).
12705 * Though the ">" character is escaped for symmetry, characters like
12706 * ">" and "/" don't need escaping in HTML and have no special meaning
12707 * unless they're part of a tag or unquoted attribute value.
12708 * See [Mathias Bynens's article](https://mathiasbynens.be/notes/ambiguous-ampersands)
12709 * (under "semi-related fun fact") for more details.
12711 * Backticks are escaped because in Internet Explorer < 9, they can break out
12712 * of attribute values or HTML comments. See [#59](https://html5sec.org/#59),
12713 * [#102](https://html5sec.org/#102), [#108](https://html5sec.org/#108), and
12714 * [#133](https://html5sec.org/#133) of the [HTML5 Security Cheatsheet](https://html5sec.org/)
12715 * for more details.
12717 * When working with HTML you should always [quote attribute values](http://wonko.com/post/html-escaping)
12718 * to reduce XSS vectors.
12723 * @param {string} [string=''] The string to escape.
12724 * @returns {string} Returns the escaped string.
12727 * _.escape('fred, barney, & pebbles');
12728 * // => 'fred, barney, & pebbles'
12730 function escape(string) {
12731 // Reset `lastIndex` because in IE < 9 `String#replace` does not.
12732 string = baseToString(string);
12733 return (string && reHasUnescapedHtml.test(string))
12734 ? string.replace(reUnescapedHtml, escapeHtmlChar)
12739 * Escapes the `RegExp` special characters "\", "/", "^", "$", ".", "|", "?",
12740 * "*", "+", "(", ")", "[", "]", "{" and "}" in `string`.
12745 * @param {string} [string=''] The string to escape.
12746 * @returns {string} Returns the escaped string.
12749 * _.escapeRegExp('[lodash](https://lodash.com/)');
12750 * // => '\[lodash\]\(https:\/\/lodash\.com\/\)'
12752 function escapeRegExp(string) {
12753 string = baseToString(string);
12754 return (string && reHasRegExpChars.test(string))
12755 ? string.replace(reRegExpChars, escapeRegExpChar)
12756 : (string || '(?:)');
12760 * Converts `string` to [kebab case](https://en.wikipedia.org/wiki/Letter_case#Special_case_styles).
12765 * @param {string} [string=''] The string to convert.
12766 * @returns {string} Returns the kebab cased string.
12769 * _.kebabCase('Foo Bar');
12772 * _.kebabCase('fooBar');
12775 * _.kebabCase('__foo_bar__');
12778 var kebabCase = createCompounder(function(result, word, index) {
12779 return result + (index ? '-' : '') + word.toLowerCase();
12783 * Pads `string` on the left and right sides if it's shorter than `length`.
12784 * Padding characters are truncated if they can't be evenly divided by `length`.
12789 * @param {string} [string=''] The string to pad.
12790 * @param {number} [length=0] The padding length.
12791 * @param {string} [chars=' '] The string used as padding.
12792 * @returns {string} Returns the padded string.
12798 * _.pad('abc', 8, '_-');
12804 function pad(string, length, chars) {
12805 string = baseToString(string);
12808 var strLength = string.length;
12809 if (strLength >= length || !nativeIsFinite(length)) {
12812 var mid = (length - strLength) / 2,
12813 leftLength = nativeFloor(mid),
12814 rightLength = nativeCeil(mid);
12816 chars = createPadding('', rightLength, chars);
12817 return chars.slice(0, leftLength) + string + chars;
12821 * Pads `string` on the left side if it's shorter than `length`. Padding
12822 * characters are truncated if they exceed `length`.
12827 * @param {string} [string=''] The string to pad.
12828 * @param {number} [length=0] The padding length.
12829 * @param {string} [chars=' '] The string used as padding.
12830 * @returns {string} Returns the padded string.
12833 * _.padLeft('abc', 6);
12836 * _.padLeft('abc', 6, '_-');
12839 * _.padLeft('abc', 3);
12842 var padLeft = createPadDir();
12845 * Pads `string` on the right side if it's shorter than `length`. Padding
12846 * characters are truncated if they exceed `length`.
12851 * @param {string} [string=''] The string to pad.
12852 * @param {number} [length=0] The padding length.
12853 * @param {string} [chars=' '] The string used as padding.
12854 * @returns {string} Returns the padded string.
12857 * _.padRight('abc', 6);
12860 * _.padRight('abc', 6, '_-');
12863 * _.padRight('abc', 3);
12866 var padRight = createPadDir(true);
12869 * Converts `string` to an integer of the specified radix. If `radix` is
12870 * `undefined` or `0`, a `radix` of `10` is used unless `value` is a hexadecimal,
12871 * in which case a `radix` of `16` is used.
12873 * **Note:** This method aligns with the [ES5 implementation](https://es5.github.io/#E)
12879 * @param {string} string The string to convert.
12880 * @param {number} [radix] The radix to interpret `value` by.
12881 * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
12882 * @returns {number} Returns the converted integer.
12885 * _.parseInt('08');
12888 * _.map(['6', '08', '10'], _.parseInt);
12891 function parseInt(string, radix, guard) {
12892 // Firefox < 21 and Opera < 15 follow ES3 for `parseInt`.
12893 // Chrome fails to trim leading <BOM> whitespace characters.
12894 // See https://code.google.com/p/v8/issues/detail?id=3109 for more details.
12895 if (guard ? isIterateeCall(string, radix, guard) : radix == null) {
12897 } else if (radix) {
12900 string = trim(string);
12901 return nativeParseInt(string, radix || (reHasHexPrefix.test(string) ? 16 : 10));
12905 * Repeats the given string `n` times.
12910 * @param {string} [string=''] The string to repeat.
12911 * @param {number} [n=0] The number of times to repeat the string.
12912 * @returns {string} Returns the repeated string.
12915 * _.repeat('*', 3);
12918 * _.repeat('abc', 2);
12921 * _.repeat('abc', 0);
12924 function repeat(string, n) {
12926 string = baseToString(string);
12928 if (n < 1 || !string || !nativeIsFinite(n)) {
12931 // Leverage the exponentiation by squaring algorithm for a faster repeat.
12932 // See https://en.wikipedia.org/wiki/Exponentiation_by_squaring for more details.
12937 n = nativeFloor(n / 2);
12945 * Converts `string` to [snake case](https://en.wikipedia.org/wiki/Snake_case).
12950 * @param {string} [string=''] The string to convert.
12951 * @returns {string} Returns the snake cased string.
12954 * _.snakeCase('Foo Bar');
12957 * _.snakeCase('fooBar');
12960 * _.snakeCase('--foo-bar');
12963 var snakeCase = createCompounder(function(result, word, index) {
12964 return result + (index ? '_' : '') + word.toLowerCase();
12968 * Converts `string` to [start case](https://en.wikipedia.org/wiki/Letter_case#Stylistic_or_specialised_usage).
12973 * @param {string} [string=''] The string to convert.
12974 * @returns {string} Returns the start cased string.
12977 * _.startCase('--foo-bar');
12980 * _.startCase('fooBar');
12983 * _.startCase('__foo_bar__');
12986 var startCase = createCompounder(function(result, word, index) {
12987 return result + (index ? ' ' : '') + (word.charAt(0).toUpperCase() + word.slice(1));
12991 * Checks if `string` starts with the given target string.
12996 * @param {string} [string=''] The string to search.
12997 * @param {string} [target] The string to search for.
12998 * @param {number} [position=0] The position to search from.
12999 * @returns {boolean} Returns `true` if `string` starts with `target`, else `false`.
13002 * _.startsWith('abc', 'a');
13005 * _.startsWith('abc', 'b');
13008 * _.startsWith('abc', 'b', 1);
13011 function startsWith(string, target, position) {
13012 string = baseToString(string);
13013 position = position == null
13015 : nativeMin(position < 0 ? 0 : (+position || 0), string.length);
13017 return string.lastIndexOf(target, position) == position;
13021 * Creates a compiled template function that can interpolate data properties
13022 * in "interpolate" delimiters, HTML-escape interpolated data properties in
13023 * "escape" delimiters, and execute JavaScript in "evaluate" delimiters. Data
13024 * properties may be accessed as free variables in the template. If a setting
13025 * object is provided it takes precedence over `_.templateSettings` values.
13027 * **Note:** In the development build `_.template` utilizes
13028 * [sourceURLs](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl)
13029 * for easier debugging.
13031 * For more information on precompiling templates see
13032 * [lodash's custom builds documentation](https://lodash.com/custom-builds).
13034 * For more information on Chrome extension sandboxes see
13035 * [Chrome's extensions documentation](https://developer.chrome.com/extensions/sandboxingEval).
13040 * @param {string} [string=''] The template string.
13041 * @param {Object} [options] The options object.
13042 * @param {RegExp} [options.escape] The HTML "escape" delimiter.
13043 * @param {RegExp} [options.evaluate] The "evaluate" delimiter.
13044 * @param {Object} [options.imports] An object to import into the template as free variables.
13045 * @param {RegExp} [options.interpolate] The "interpolate" delimiter.
13046 * @param {string} [options.sourceURL] The sourceURL of the template's compiled source.
13047 * @param {string} [options.variable] The data object variable name.
13048 * @param- {Object} [otherOptions] Enables the legacy `options` param signature.
13049 * @returns {Function} Returns the compiled template function.
13052 * // using the "interpolate" delimiter to create a compiled template
13053 * var compiled = _.template('hello <%= user %>!');
13054 * compiled({ 'user': 'fred' });
13055 * // => 'hello fred!'
13057 * // using the HTML "escape" delimiter to escape data property values
13058 * var compiled = _.template('<b><%- value %></b>');
13059 * compiled({ 'value': '<script>' });
13060 * // => '<b><script></b>'
13062 * // using the "evaluate" delimiter to execute JavaScript and generate HTML
13063 * var compiled = _.template('<% _.forEach(users, function(user) { %><li><%- user %></li><% }); %>');
13064 * compiled({ 'users': ['fred', 'barney'] });
13065 * // => '<li>fred</li><li>barney</li>'
13067 * // using the internal `print` function in "evaluate" delimiters
13068 * var compiled = _.template('<% print("hello " + user); %>!');
13069 * compiled({ 'user': 'barney' });
13070 * // => 'hello barney!'
13072 * // using the ES delimiter as an alternative to the default "interpolate" delimiter
13073 * var compiled = _.template('hello ${ user }!');
13074 * compiled({ 'user': 'pebbles' });
13075 * // => 'hello pebbles!'
13077 * // using custom template delimiters
13078 * _.templateSettings.interpolate = /{{([\s\S]+?)}}/g;
13079 * var compiled = _.template('hello {{ user }}!');
13080 * compiled({ 'user': 'mustache' });
13081 * // => 'hello mustache!'
13083 * // using backslashes to treat delimiters as plain text
13084 * var compiled = _.template('<%= "\\<%- value %\\>" %>');
13085 * compiled({ 'value': 'ignored' });
13086 * // => '<%- value %>'
13088 * // using the `imports` option to import `jQuery` as `jq`
13089 * var text = '<% jq.each(users, function(user) { %><li><%- user %></li><% }); %>';
13090 * var compiled = _.template(text, { 'imports': { 'jq': jQuery } });
13091 * compiled({ 'users': ['fred', 'barney'] });
13092 * // => '<li>fred</li><li>barney</li>'
13094 * // using the `sourceURL` option to specify a custom sourceURL for the template
13095 * var compiled = _.template('hello <%= user %>!', { 'sourceURL': '/basic/greeting.jst' });
13097 * // => find the source of "greeting.jst" under the Sources tab or Resources panel of the web inspector
13099 * // using the `variable` option to ensure a with-statement isn't used in the compiled template
13100 * var compiled = _.template('hi <%= data.user %>!', { 'variable': 'data' });
13102 * // => function(data) {
13103 * // var __t, __p = '';
13104 * // __p += 'hi ' + ((__t = ( data.user )) == null ? '' : __t) + '!';
13108 * // using the `source` property to inline compiled templates for meaningful
13109 * // line numbers in error messages and a stack trace
13110 * fs.writeFileSync(path.join(cwd, 'jst.js'), '\
13112 * "main": ' + _.template(mainText).source + '\
13116 function template(string, options, otherOptions) {
13117 // Based on John Resig's `tmpl` implementation (http://ejohn.org/blog/javascript-micro-templating/)
13118 // and Laura Doktorova's doT.js (https://github.com/olado/doT).
13119 var settings = lodash.templateSettings;
13121 if (otherOptions && isIterateeCall(string, options, otherOptions)) {
13122 options = otherOptions = undefined;
13124 string = baseToString(string);
13125 options = assignWith(baseAssign({}, otherOptions || options), settings, assignOwnDefaults);
13127 var imports = assignWith(baseAssign({}, options.imports), settings.imports, assignOwnDefaults),
13128 importsKeys = keys(imports),
13129 importsValues = baseValues(imports, importsKeys);
13134 interpolate = options.interpolate || reNoMatch,
13135 source = "__p += '";
13137 // Compile the regexp to match each delimiter.
13138 var reDelimiters = RegExp(
13139 (options.escape || reNoMatch).source + '|' +
13140 interpolate.source + '|' +
13141 (interpolate === reInterpolate ? reEsTemplate : reNoMatch).source + '|' +
13142 (options.evaluate || reNoMatch).source + '|$'
13145 // Use a sourceURL for easier debugging.
13146 var sourceURL = '//# sourceURL=' +
13147 ('sourceURL' in options
13148 ? options.sourceURL
13149 : ('lodash.templateSources[' + (++templateCounter) + ']')
13152 string.replace(reDelimiters, function(match, escapeValue, interpolateValue, esTemplateValue, evaluateValue, offset) {
13153 interpolateValue || (interpolateValue = esTemplateValue);
13155 // Escape characters that can't be included in string literals.
13156 source += string.slice(index, offset).replace(reUnescapedString, escapeStringChar);
13158 // Replace delimiters with snippets.
13161 source += "' +\n__e(" + escapeValue + ") +\n'";
13163 if (evaluateValue) {
13164 isEvaluating = true;
13165 source += "';\n" + evaluateValue + ";\n__p += '";
13167 if (interpolateValue) {
13168 source += "' +\n((__t = (" + interpolateValue + ")) == null ? '' : __t) +\n'";
13170 index = offset + match.length;
13172 // The JS engine embedded in Adobe products requires returning the `match`
13173 // string in order to produce the correct `offset` value.
13179 // If `variable` is not specified wrap a with-statement around the generated
13180 // code to add the data object to the top of the scope chain.
13181 var variable = options.variable;
13183 source = 'with (obj) {\n' + source + '\n}\n';
13185 // Cleanup code by stripping empty strings.
13186 source = (isEvaluating ? source.replace(reEmptyStringLeading, '') : source)
13187 .replace(reEmptyStringMiddle, '$1')
13188 .replace(reEmptyStringTrailing, '$1;');
13190 // Frame code as the function body.
13191 source = 'function(' + (variable || 'obj') + ') {\n' +
13194 : 'obj || (obj = {});\n'
13196 "var __t, __p = ''" +
13198 ? ', __e = _.escape'
13202 ? ', __j = Array.prototype.join;\n' +
13203 "function print() { __p += __j.call(arguments, '') }\n"
13209 var result = attempt(function() {
13210 return Function(importsKeys, sourceURL + 'return ' + source).apply(undefined, importsValues);
13213 // Provide the compiled function's source by its `toString` method or
13214 // the `source` property as a convenience for inlining compiled templates.
13215 result.source = source;
13216 if (isError(result)) {
13223 * Removes leading and trailing whitespace or specified characters from `string`.
13228 * @param {string} [string=''] The string to trim.
13229 * @param {string} [chars=whitespace] The characters to trim.
13230 * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
13231 * @returns {string} Returns the trimmed string.
13237 * _.trim('-_-abc-_-', '_-');
13240 * _.map([' foo ', ' bar '], _.trim);
13241 * // => ['foo', 'bar']
13243 function trim(string, chars, guard) {
13244 var value = string;
13245 string = baseToString(string);
13249 if (guard ? isIterateeCall(value, chars, guard) : chars == null) {
13250 return string.slice(trimmedLeftIndex(string), trimmedRightIndex(string) + 1);
13252 chars = (chars + '');
13253 return string.slice(charsLeftIndex(string, chars), charsRightIndex(string, chars) + 1);
13257 * Removes leading whitespace or specified characters from `string`.
13262 * @param {string} [string=''] The string to trim.
13263 * @param {string} [chars=whitespace] The characters to trim.
13264 * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
13265 * @returns {string} Returns the trimmed string.
13268 * _.trimLeft(' abc ');
13271 * _.trimLeft('-_-abc-_-', '_-');
13274 function trimLeft(string, chars, guard) {
13275 var value = string;
13276 string = baseToString(string);
13280 if (guard ? isIterateeCall(value, chars, guard) : chars == null) {
13281 return string.slice(trimmedLeftIndex(string));
13283 return string.slice(charsLeftIndex(string, (chars + '')));
13287 * Removes trailing whitespace or specified characters from `string`.
13292 * @param {string} [string=''] The string to trim.
13293 * @param {string} [chars=whitespace] The characters to trim.
13294 * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
13295 * @returns {string} Returns the trimmed string.
13298 * _.trimRight(' abc ');
13301 * _.trimRight('-_-abc-_-', '_-');
13304 function trimRight(string, chars, guard) {
13305 var value = string;
13306 string = baseToString(string);
13310 if (guard ? isIterateeCall(value, chars, guard) : chars == null) {
13311 return string.slice(0, trimmedRightIndex(string) + 1);
13313 return string.slice(0, charsRightIndex(string, (chars + '')) + 1);
13317 * Truncates `string` if it's longer than the given maximum string length.
13318 * The last characters of the truncated string are replaced with the omission
13319 * string which defaults to "...".
13324 * @param {string} [string=''] The string to truncate.
13325 * @param {Object|number} [options] The options object or maximum string length.
13326 * @param {number} [options.length=30] The maximum string length.
13327 * @param {string} [options.omission='...'] The string to indicate text is omitted.
13328 * @param {RegExp|string} [options.separator] The separator pattern to truncate to.
13329 * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
13330 * @returns {string} Returns the truncated string.
13333 * _.trunc('hi-diddly-ho there, neighborino');
13334 * // => 'hi-diddly-ho there, neighbo...'
13336 * _.trunc('hi-diddly-ho there, neighborino', 24);
13337 * // => 'hi-diddly-ho there, n...'
13339 * _.trunc('hi-diddly-ho there, neighborino', {
13343 * // => 'hi-diddly-ho there,...'
13345 * _.trunc('hi-diddly-ho there, neighborino', {
13347 * 'separator': /,? +/
13349 * // => 'hi-diddly-ho there...'
13351 * _.trunc('hi-diddly-ho there, neighborino', {
13352 * 'omission': ' [...]'
13354 * // => 'hi-diddly-ho there, neig [...]'
13356 function trunc(string, options, guard) {
13357 if (guard && isIterateeCall(string, options, guard)) {
13358 options = undefined;
13360 var length = DEFAULT_TRUNC_LENGTH,
13361 omission = DEFAULT_TRUNC_OMISSION;
13363 if (options != null) {
13364 if (isObject(options)) {
13365 var separator = 'separator' in options ? options.separator : separator;
13366 length = 'length' in options ? (+options.length || 0) : length;
13367 omission = 'omission' in options ? baseToString(options.omission) : omission;
13369 length = +options || 0;
13372 string = baseToString(string);
13373 if (length >= string.length) {
13376 var end = length - omission.length;
13380 var result = string.slice(0, end);
13381 if (separator == null) {
13382 return result + omission;
13384 if (isRegExp(separator)) {
13385 if (string.slice(end).search(separator)) {
13388 substring = string.slice(0, end);
13390 if (!separator.global) {
13391 separator = RegExp(separator.source, (reFlags.exec(separator) || '') + 'g');
13393 separator.lastIndex = 0;
13394 while ((match = separator.exec(substring))) {
13395 newEnd = match.index;
13397 result = result.slice(0, newEnd == null ? end : newEnd);
13399 } else if (string.indexOf(separator, end) != end) {
13400 var index = result.lastIndexOf(separator);
13402 result = result.slice(0, index);
13405 return result + omission;
13409 * The inverse of `_.escape`; this method converts the HTML entities
13410 * `&`, `<`, `>`, `"`, `'`, and ``` in `string` to their
13411 * corresponding characters.
13413 * **Note:** No other HTML entities are unescaped. To unescape additional HTML
13414 * entities use a third-party library like [_he_](https://mths.be/he).
13419 * @param {string} [string=''] The string to unescape.
13420 * @returns {string} Returns the unescaped string.
13423 * _.unescape('fred, barney, & pebbles');
13424 * // => 'fred, barney, & pebbles'
13426 function unescape(string) {
13427 string = baseToString(string);
13428 return (string && reHasEscapedHtml.test(string))
13429 ? string.replace(reEscapedHtml, unescapeHtmlChar)
13434 * Splits `string` into an array of its words.
13439 * @param {string} [string=''] The string to inspect.
13440 * @param {RegExp|string} [pattern] The pattern to match words.
13441 * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
13442 * @returns {Array} Returns the words of `string`.
13445 * _.words('fred, barney, & pebbles');
13446 * // => ['fred', 'barney', 'pebbles']
13448 * _.words('fred, barney, & pebbles', /[^, ]+/g);
13449 * // => ['fred', 'barney', '&', 'pebbles']
13451 function words(string, pattern, guard) {
13452 if (guard && isIterateeCall(string, pattern, guard)) {
13453 pattern = undefined;
13455 string = baseToString(string);
13456 return string.match(pattern || reWords) || [];
13459 /*------------------------------------------------------------------------*/
13462 * Attempts to invoke `func`, returning either the result or the caught error
13463 * object. Any additional arguments are provided to `func` when it is invoked.
13467 * @category Utility
13468 * @param {Function} func The function to attempt.
13469 * @returns {*} Returns the `func` result or error object.
13472 * // avoid throwing errors for invalid selectors
13473 * var elements = _.attempt(function(selector) {
13474 * return document.querySelectorAll(selector);
13477 * if (_.isError(elements)) {
13481 var attempt = restParam(function(func, args) {
13483 return func.apply(undefined, args);
13485 return isError(e) ? e : new Error(e);
13490 * Creates a function that invokes `func` with the `this` binding of `thisArg`
13491 * and arguments of the created function. If `func` is a property name the
13492 * created callback returns the property value for a given element. If `func`
13493 * is an object the created callback returns `true` for elements that contain
13494 * the equivalent object properties, otherwise it returns `false`.
13499 * @category Utility
13500 * @param {*} [func=_.identity] The value to convert to a callback.
13501 * @param {*} [thisArg] The `this` binding of `func`.
13502 * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
13503 * @returns {Function} Returns the callback.
13507 * { 'user': 'barney', 'age': 36 },
13508 * { 'user': 'fred', 'age': 40 }
13511 * // wrap to create custom callback shorthands
13512 * _.callback = _.wrap(_.callback, function(callback, func, thisArg) {
13513 * var match = /^(.+?)__([gl]t)(.+)$/.exec(func);
13515 * return callback(func, thisArg);
13517 * return function(object) {
13518 * return match[2] == 'gt'
13519 * ? object[match[1]] > match[3]
13520 * : object[match[1]] < match[3];
13524 * _.filter(users, 'age__gt36');
13525 * // => [{ 'user': 'fred', 'age': 40 }]
13527 function callback(func, thisArg, guard) {
13528 if (guard && isIterateeCall(func, thisArg, guard)) {
13529 thisArg = undefined;
13531 return isObjectLike(func)
13533 : baseCallback(func, thisArg);
13537 * Creates a function that returns `value`.
13541 * @category Utility
13542 * @param {*} value The value to return from the new function.
13543 * @returns {Function} Returns the new function.
13546 * var object = { 'user': 'fred' };
13547 * var getter = _.constant(object);
13549 * getter() === object;
13552 function constant(value) {
13553 return function() {
13559 * This method returns the first argument provided to it.
13563 * @category Utility
13564 * @param {*} value Any value.
13565 * @returns {*} Returns `value`.
13568 * var object = { 'user': 'fred' };
13570 * _.identity(object) === object;
13573 function identity(value) {
13578 * Creates a function that performs a deep comparison between a given object
13579 * and `source`, returning `true` if the given object has equivalent property
13580 * values, else `false`.
13582 * **Note:** This method supports comparing arrays, booleans, `Date` objects,
13583 * numbers, `Object` objects, regexes, and strings. Objects are compared by
13584 * their own, not inherited, enumerable properties. For comparing a single
13585 * own or inherited property value see `_.matchesProperty`.
13589 * @category Utility
13590 * @param {Object} source The object of property values to match.
13591 * @returns {Function} Returns the new function.
13595 * { 'user': 'barney', 'age': 36, 'active': true },
13596 * { 'user': 'fred', 'age': 40, 'active': false }
13599 * _.filter(users, _.matches({ 'age': 40, 'active': false }));
13600 * // => [{ 'user': 'fred', 'age': 40, 'active': false }]
13602 function matches(source) {
13603 return baseMatches(baseClone(source, true));
13607 * Creates a function that compares the property value of `path` on a given
13608 * object to `value`.
13610 * **Note:** This method supports comparing arrays, booleans, `Date` objects,
13611 * numbers, `Object` objects, regexes, and strings. Objects are compared by
13612 * their own, not inherited, enumerable properties.
13616 * @category Utility
13617 * @param {Array|string} path The path of the property to get.
13618 * @param {*} srcValue The value to match.
13619 * @returns {Function} Returns the new function.
13623 * { 'user': 'barney' },
13624 * { 'user': 'fred' }
13627 * _.find(users, _.matchesProperty('user', 'fred'));
13628 * // => { 'user': 'fred' }
13630 function matchesProperty(path, srcValue) {
13631 return baseMatchesProperty(path, baseClone(srcValue, true));
13635 * Creates a function that invokes the method at `path` on a given object.
13636 * Any additional arguments are provided to the invoked method.
13640 * @category Utility
13641 * @param {Array|string} path The path of the method to invoke.
13642 * @param {...*} [args] The arguments to invoke the method with.
13643 * @returns {Function} Returns the new function.
13647 * { 'a': { 'b': { 'c': _.constant(2) } } },
13648 * { 'a': { 'b': { 'c': _.constant(1) } } }
13651 * _.map(objects, _.method('a.b.c'));
13654 * _.invoke(_.sortBy(objects, _.method(['a', 'b', 'c'])), 'a.b.c');
13657 var method = restParam(function(path, args) {
13658 return function(object) {
13659 return invokePath(object, path, args);
13664 * The opposite of `_.method`; this method creates a function that invokes
13665 * the method at a given path on `object`. Any additional arguments are
13666 * provided to the invoked method.
13670 * @category Utility
13671 * @param {Object} object The object to query.
13672 * @param {...*} [args] The arguments to invoke the method with.
13673 * @returns {Function} Returns the new function.
13676 * var array = _.times(3, _.constant),
13677 * object = { 'a': array, 'b': array, 'c': array };
13679 * _.map(['a[2]', 'c[0]'], _.methodOf(object));
13682 * _.map([['a', '2'], ['c', '0']], _.methodOf(object));
13685 var methodOf = restParam(function(object, args) {
13686 return function(path) {
13687 return invokePath(object, path, args);
13692 * Adds all own enumerable function properties of a source object to the
13693 * destination object. If `object` is a function then methods are added to
13694 * its prototype as well.
13696 * **Note:** Use `_.runInContext` to create a pristine `lodash` function to
13697 * avoid conflicts caused by modifying the original.
13701 * @category Utility
13702 * @param {Function|Object} [object=lodash] The destination object.
13703 * @param {Object} source The object of functions to add.
13704 * @param {Object} [options] The options object.
13705 * @param {boolean} [options.chain=true] Specify whether the functions added
13707 * @returns {Function|Object} Returns `object`.
13710 * function vowels(string) {
13711 * return _.filter(string, function(v) {
13712 * return /[aeiou]/i.test(v);
13716 * _.mixin({ 'vowels': vowels });
13717 * _.vowels('fred');
13720 * _('fred').vowels().value();
13723 * _.mixin({ 'vowels': vowels }, { 'chain': false });
13724 * _('fred').vowels();
13727 function mixin(object, source, options) {
13728 if (options == null) {
13729 var isObj = isObject(source),
13730 props = isObj ? keys(source) : undefined,
13731 methodNames = (props && props.length) ? baseFunctions(source, props) : undefined;
13733 if (!(methodNames ? methodNames.length : isObj)) {
13734 methodNames = false;
13740 if (!methodNames) {
13741 methodNames = baseFunctions(source, keys(source));
13745 isFunc = isFunction(object),
13746 length = methodNames.length;
13748 if (options === false) {
13750 } else if (isObject(options) && 'chain' in options) {
13751 chain = options.chain;
13753 while (++index < length) {
13754 var methodName = methodNames[index],
13755 func = source[methodName];
13757 object[methodName] = func;
13759 object.prototype[methodName] = (function(func) {
13760 return function() {
13761 var chainAll = this.__chain__;
13762 if (chain || chainAll) {
13763 var result = object(this.__wrapped__),
13764 actions = result.__actions__ = arrayCopy(this.__actions__);
13766 actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
13767 result.__chain__ = chainAll;
13770 return func.apply(object, arrayPush([this.value()], arguments));
13779 * Reverts the `_` variable to its previous value and returns a reference to
13780 * the `lodash` function.
13784 * @category Utility
13785 * @returns {Function} Returns the `lodash` function.
13788 * var lodash = _.noConflict();
13790 function noConflict() {
13796 * A no-operation function that returns `undefined` regardless of the
13797 * arguments it receives.
13801 * @category Utility
13804 * var object = { 'user': 'fred' };
13806 * _.noop(object) === undefined;
13810 // No operation performed.
13814 * Creates a function that returns the property value at `path` on a
13819 * @category Utility
13820 * @param {Array|string} path The path of the property to get.
13821 * @returns {Function} Returns the new function.
13825 * { 'a': { 'b': { 'c': 2 } } },
13826 * { 'a': { 'b': { 'c': 1 } } }
13829 * _.map(objects, _.property('a.b.c'));
13832 * _.pluck(_.sortBy(objects, _.property(['a', 'b', 'c'])), 'a.b.c');
13835 function property(path) {
13836 return isKey(path) ? baseProperty(path) : basePropertyDeep(path);
13840 * The opposite of `_.property`; this method creates a function that returns
13841 * the property value at a given path on `object`.
13845 * @category Utility
13846 * @param {Object} object The object to query.
13847 * @returns {Function} Returns the new function.
13850 * var array = [0, 1, 2],
13851 * object = { 'a': array, 'b': array, 'c': array };
13853 * _.map(['a[2]', 'c[0]'], _.propertyOf(object));
13856 * _.map([['a', '2'], ['c', '0']], _.propertyOf(object));
13859 function propertyOf(object) {
13860 return function(path) {
13861 return baseGet(object, toPath(path), path + '');
13866 * Creates an array of numbers (positive and/or negative) progressing from
13867 * `start` up to, but not including, `end`. If `end` is not specified it is
13868 * set to `start` with `start` then set to `0`. If `end` is less than `start`
13869 * a zero-length range is created unless a negative `step` is specified.
13873 * @category Utility
13874 * @param {number} [start=0] The start of the range.
13875 * @param {number} end The end of the range.
13876 * @param {number} [step=1] The value to increment or decrement by.
13877 * @returns {Array} Returns the new array of numbers.
13881 * // => [0, 1, 2, 3]
13884 * // => [1, 2, 3, 4]
13886 * _.range(0, 20, 5);
13887 * // => [0, 5, 10, 15]
13889 * _.range(0, -4, -1);
13890 * // => [0, -1, -2, -3]
13892 * _.range(1, 4, 0);
13898 function range(start, end, step) {
13899 if (step && isIterateeCall(start, end, step)) {
13900 end = step = undefined;
13902 start = +start || 0;
13903 step = step == null ? 1 : (+step || 0);
13911 // Use `Array(length)` so engines like Chakra and V8 avoid slower modes.
13912 // See https://youtu.be/XAqIpGU8ZZk#t=17m25s for more details.
13914 length = nativeMax(nativeCeil((end - start) / (step || 1)), 0),
13915 result = Array(length);
13917 while (++index < length) {
13918 result[index] = start;
13925 * Invokes the iteratee function `n` times, returning an array of the results
13926 * of each invocation. The `iteratee` is bound to `thisArg` and invoked with
13927 * one argument; (index).
13931 * @category Utility
13932 * @param {number} n The number of times to invoke `iteratee`.
13933 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
13934 * @param {*} [thisArg] The `this` binding of `iteratee`.
13935 * @returns {Array} Returns the array of results.
13938 * var diceRolls = _.times(3, _.partial(_.random, 1, 6, false));
13941 * _.times(3, function(n) {
13942 * mage.castSpell(n);
13944 * // => invokes `mage.castSpell(n)` three times with `n` of `0`, `1`, and `2`
13946 * _.times(3, function(n) {
13949 * // => also invokes `mage.castSpell(n)` three times
13951 function times(n, iteratee, thisArg) {
13952 n = nativeFloor(n);
13954 // Exit early to avoid a JSC JIT bug in Safari 8
13955 // where `Array(0)` is treated as `Array(1)`.
13956 if (n < 1 || !nativeIsFinite(n)) {
13960 result = Array(nativeMin(n, MAX_ARRAY_LENGTH));
13962 iteratee = bindCallback(iteratee, thisArg, 1);
13963 while (++index < n) {
13964 if (index < MAX_ARRAY_LENGTH) {
13965 result[index] = iteratee(index);
13974 * Generates a unique ID. If `prefix` is provided the ID is appended to it.
13978 * @category Utility
13979 * @param {string} [prefix] The value to prefix the ID with.
13980 * @returns {string} Returns the unique ID.
13983 * _.uniqueId('contact_');
13984 * // => 'contact_104'
13989 function uniqueId(prefix) {
13990 var id = ++idCounter;
13991 return baseToString(prefix) + id;
13994 /*------------------------------------------------------------------------*/
13997 * Adds two numbers.
14002 * @param {number} augend The first number to add.
14003 * @param {number} addend The second number to add.
14004 * @returns {number} Returns the sum.
14010 function add(augend, addend) {
14011 return (+augend || 0) + (+addend || 0);
14015 * Calculates `n` rounded up to `precision`.
14020 * @param {number} n The number to round up.
14021 * @param {number} [precision=0] The precision to round up to.
14022 * @returns {number} Returns the rounded up number.
14028 * _.ceil(6.004, 2);
14031 * _.ceil(6040, -2);
14034 var ceil = createRound('ceil');
14037 * Calculates `n` rounded down to `precision`.
14042 * @param {number} n The number to round down.
14043 * @param {number} [precision=0] The precision to round down to.
14044 * @returns {number} Returns the rounded down number.
14050 * _.floor(0.046, 2);
14053 * _.floor(4060, -2);
14056 var floor = createRound('floor');
14059 * Gets the maximum value of `collection`. If `collection` is empty or falsey
14060 * `-Infinity` is returned. If an iteratee function is provided it is invoked
14061 * for each value in `collection` to generate the criterion by which the value
14062 * is ranked. The `iteratee` is bound to `thisArg` and invoked with three
14063 * arguments: (value, index, collection).
14065 * If a property name is provided for `iteratee` the created `_.property`
14066 * style callback returns the property value of the given element.
14068 * If a value is also provided for `thisArg` the created `_.matchesProperty`
14069 * style callback returns `true` for elements that have a matching property
14070 * value, else `false`.
14072 * If an object is provided for `iteratee` the created `_.matches` style
14073 * callback returns `true` for elements that have the properties of the given
14074 * object, else `false`.
14079 * @param {Array|Object|string} collection The collection to iterate over.
14080 * @param {Function|Object|string} [iteratee] The function invoked per iteration.
14081 * @param {*} [thisArg] The `this` binding of `iteratee`.
14082 * @returns {*} Returns the maximum value.
14085 * _.max([4, 2, 8, 6]);
14092 * { 'user': 'barney', 'age': 36 },
14093 * { 'user': 'fred', 'age': 40 }
14096 * _.max(users, function(chr) {
14099 * // => { 'user': 'fred', 'age': 40 }
14101 * // using the `_.property` callback shorthand
14102 * _.max(users, 'age');
14103 * // => { 'user': 'fred', 'age': 40 }
14105 var max = createExtremum(gt, NEGATIVE_INFINITY);
14108 * Gets the minimum value of `collection`. If `collection` is empty or falsey
14109 * `Infinity` is returned. If an iteratee function is provided it is invoked
14110 * for each value in `collection` to generate the criterion by which the value
14111 * is ranked. The `iteratee` is bound to `thisArg` and invoked with three
14112 * arguments: (value, index, collection).
14114 * If a property name is provided for `iteratee` the created `_.property`
14115 * style callback returns the property value of the given element.
14117 * If a value is also provided for `thisArg` the created `_.matchesProperty`
14118 * style callback returns `true` for elements that have a matching property
14119 * value, else `false`.
14121 * If an object is provided for `iteratee` the created `_.matches` style
14122 * callback returns `true` for elements that have the properties of the given
14123 * object, else `false`.
14128 * @param {Array|Object|string} collection The collection to iterate over.
14129 * @param {Function|Object|string} [iteratee] The function invoked per iteration.
14130 * @param {*} [thisArg] The `this` binding of `iteratee`.
14131 * @returns {*} Returns the minimum value.
14134 * _.min([4, 2, 8, 6]);
14141 * { 'user': 'barney', 'age': 36 },
14142 * { 'user': 'fred', 'age': 40 }
14145 * _.min(users, function(chr) {
14148 * // => { 'user': 'barney', 'age': 36 }
14150 * // using the `_.property` callback shorthand
14151 * _.min(users, 'age');
14152 * // => { 'user': 'barney', 'age': 36 }
14154 var min = createExtremum(lt, POSITIVE_INFINITY);
14157 * Calculates `n` rounded to `precision`.
14162 * @param {number} n The number to round.
14163 * @param {number} [precision=0] The precision to round to.
14164 * @returns {number} Returns the rounded number.
14170 * _.round(4.006, 2);
14173 * _.round(4060, -2);
14176 var round = createRound('round');
14179 * Gets the sum of the values in `collection`.
14184 * @param {Array|Object|string} collection The collection to iterate over.
14185 * @param {Function|Object|string} [iteratee] The function invoked per iteration.
14186 * @param {*} [thisArg] The `this` binding of `iteratee`.
14187 * @returns {number} Returns the sum.
14193 * _.sum({ 'a': 4, 'b': 6 });
14201 * _.sum(objects, function(object) {
14206 * // using the `_.property` callback shorthand
14207 * _.sum(objects, 'n');
14210 function sum(collection, iteratee, thisArg) {
14211 if (thisArg && isIterateeCall(collection, iteratee, thisArg)) {
14212 iteratee = undefined;
14214 iteratee = getCallback(iteratee, thisArg, 3);
14215 return iteratee.length == 1
14216 ? arraySum(isArray(collection) ? collection : toIterable(collection), iteratee)
14217 : baseSum(collection, iteratee);
14220 /*------------------------------------------------------------------------*/
14222 // Ensure wrappers are instances of `baseLodash`.
14223 lodash.prototype = baseLodash.prototype;
14225 LodashWrapper.prototype = baseCreate(baseLodash.prototype);
14226 LodashWrapper.prototype.constructor = LodashWrapper;
14228 LazyWrapper.prototype = baseCreate(baseLodash.prototype);
14229 LazyWrapper.prototype.constructor = LazyWrapper;
14231 // Add functions to the `Map` cache.
14232 MapCache.prototype['delete'] = mapDelete;
14233 MapCache.prototype.get = mapGet;
14234 MapCache.prototype.has = mapHas;
14235 MapCache.prototype.set = mapSet;
14237 // Add functions to the `Set` cache.
14238 SetCache.prototype.push = cachePush;
14240 // Assign cache to `_.memoize`.
14241 memoize.Cache = MapCache;
14243 // Add functions that return wrapped values when chaining.
14244 lodash.after = after;
14246 lodash.assign = assign;
14248 lodash.before = before;
14249 lodash.bind = bind;
14250 lodash.bindAll = bindAll;
14251 lodash.bindKey = bindKey;
14252 lodash.callback = callback;
14253 lodash.chain = chain;
14254 lodash.chunk = chunk;
14255 lodash.compact = compact;
14256 lodash.constant = constant;
14257 lodash.countBy = countBy;
14258 lodash.create = create;
14259 lodash.curry = curry;
14260 lodash.curryRight = curryRight;
14261 lodash.debounce = debounce;
14262 lodash.defaults = defaults;
14263 lodash.defaultsDeep = defaultsDeep;
14264 lodash.defer = defer;
14265 lodash.delay = delay;
14266 lodash.difference = difference;
14267 lodash.drop = drop;
14268 lodash.dropRight = dropRight;
14269 lodash.dropRightWhile = dropRightWhile;
14270 lodash.dropWhile = dropWhile;
14271 lodash.fill = fill;
14272 lodash.filter = filter;
14273 lodash.flatten = flatten;
14274 lodash.flattenDeep = flattenDeep;
14275 lodash.flow = flow;
14276 lodash.flowRight = flowRight;
14277 lodash.forEach = forEach;
14278 lodash.forEachRight = forEachRight;
14279 lodash.forIn = forIn;
14280 lodash.forInRight = forInRight;
14281 lodash.forOwn = forOwn;
14282 lodash.forOwnRight = forOwnRight;
14283 lodash.functions = functions;
14284 lodash.groupBy = groupBy;
14285 lodash.indexBy = indexBy;
14286 lodash.initial = initial;
14287 lodash.intersection = intersection;
14288 lodash.invert = invert;
14289 lodash.invoke = invoke;
14290 lodash.keys = keys;
14291 lodash.keysIn = keysIn;
14293 lodash.mapKeys = mapKeys;
14294 lodash.mapValues = mapValues;
14295 lodash.matches = matches;
14296 lodash.matchesProperty = matchesProperty;
14297 lodash.memoize = memoize;
14298 lodash.merge = merge;
14299 lodash.method = method;
14300 lodash.methodOf = methodOf;
14301 lodash.mixin = mixin;
14302 lodash.modArgs = modArgs;
14303 lodash.negate = negate;
14304 lodash.omit = omit;
14305 lodash.once = once;
14306 lodash.pairs = pairs;
14307 lodash.partial = partial;
14308 lodash.partialRight = partialRight;
14309 lodash.partition = partition;
14310 lodash.pick = pick;
14311 lodash.pluck = pluck;
14312 lodash.property = property;
14313 lodash.propertyOf = propertyOf;
14314 lodash.pull = pull;
14315 lodash.pullAt = pullAt;
14316 lodash.range = range;
14317 lodash.rearg = rearg;
14318 lodash.reject = reject;
14319 lodash.remove = remove;
14320 lodash.rest = rest;
14321 lodash.restParam = restParam;
14323 lodash.shuffle = shuffle;
14324 lodash.slice = slice;
14325 lodash.sortBy = sortBy;
14326 lodash.sortByAll = sortByAll;
14327 lodash.sortByOrder = sortByOrder;
14328 lodash.spread = spread;
14329 lodash.take = take;
14330 lodash.takeRight = takeRight;
14331 lodash.takeRightWhile = takeRightWhile;
14332 lodash.takeWhile = takeWhile;
14334 lodash.throttle = throttle;
14335 lodash.thru = thru;
14336 lodash.times = times;
14337 lodash.toArray = toArray;
14338 lodash.toPlainObject = toPlainObject;
14339 lodash.transform = transform;
14340 lodash.union = union;
14341 lodash.uniq = uniq;
14342 lodash.unzip = unzip;
14343 lodash.unzipWith = unzipWith;
14344 lodash.values = values;
14345 lodash.valuesIn = valuesIn;
14346 lodash.where = where;
14347 lodash.without = without;
14348 lodash.wrap = wrap;
14351 lodash.zipObject = zipObject;
14352 lodash.zipWith = zipWith;
14355 lodash.backflow = flowRight;
14356 lodash.collect = map;
14357 lodash.compose = flowRight;
14358 lodash.each = forEach;
14359 lodash.eachRight = forEachRight;
14360 lodash.extend = assign;
14361 lodash.iteratee = callback;
14362 lodash.methods = functions;
14363 lodash.object = zipObject;
14364 lodash.select = filter;
14365 lodash.tail = rest;
14366 lodash.unique = uniq;
14368 // Add functions to `lodash.prototype`.
14369 mixin(lodash, lodash);
14371 /*------------------------------------------------------------------------*/
14373 // Add functions that return unwrapped values when chaining.
14375 lodash.attempt = attempt;
14376 lodash.camelCase = camelCase;
14377 lodash.capitalize = capitalize;
14378 lodash.ceil = ceil;
14379 lodash.clone = clone;
14380 lodash.cloneDeep = cloneDeep;
14381 lodash.deburr = deburr;
14382 lodash.endsWith = endsWith;
14383 lodash.escape = escape;
14384 lodash.escapeRegExp = escapeRegExp;
14385 lodash.every = every;
14386 lodash.find = find;
14387 lodash.findIndex = findIndex;
14388 lodash.findKey = findKey;
14389 lodash.findLast = findLast;
14390 lodash.findLastIndex = findLastIndex;
14391 lodash.findLastKey = findLastKey;
14392 lodash.findWhere = findWhere;
14393 lodash.first = first;
14394 lodash.floor = floor;
14399 lodash.identity = identity;
14400 lodash.includes = includes;
14401 lodash.indexOf = indexOf;
14402 lodash.inRange = inRange;
14403 lodash.isArguments = isArguments;
14404 lodash.isArray = isArray;
14405 lodash.isBoolean = isBoolean;
14406 lodash.isDate = isDate;
14407 lodash.isElement = isElement;
14408 lodash.isEmpty = isEmpty;
14409 lodash.isEqual = isEqual;
14410 lodash.isError = isError;
14411 lodash.isFinite = isFinite;
14412 lodash.isFunction = isFunction;
14413 lodash.isMatch = isMatch;
14414 lodash.isNaN = isNaN;
14415 lodash.isNative = isNative;
14416 lodash.isNull = isNull;
14417 lodash.isNumber = isNumber;
14418 lodash.isObject = isObject;
14419 lodash.isPlainObject = isPlainObject;
14420 lodash.isRegExp = isRegExp;
14421 lodash.isString = isString;
14422 lodash.isTypedArray = isTypedArray;
14423 lodash.isUndefined = isUndefined;
14424 lodash.kebabCase = kebabCase;
14425 lodash.last = last;
14426 lodash.lastIndexOf = lastIndexOf;
14431 lodash.noConflict = noConflict;
14432 lodash.noop = noop;
14435 lodash.padLeft = padLeft;
14436 lodash.padRight = padRight;
14437 lodash.parseInt = parseInt;
14438 lodash.random = random;
14439 lodash.reduce = reduce;
14440 lodash.reduceRight = reduceRight;
14441 lodash.repeat = repeat;
14442 lodash.result = result;
14443 lodash.round = round;
14444 lodash.runInContext = runInContext;
14445 lodash.size = size;
14446 lodash.snakeCase = snakeCase;
14447 lodash.some = some;
14448 lodash.sortedIndex = sortedIndex;
14449 lodash.sortedLastIndex = sortedLastIndex;
14450 lodash.startCase = startCase;
14451 lodash.startsWith = startsWith;
14453 lodash.template = template;
14454 lodash.trim = trim;
14455 lodash.trimLeft = trimLeft;
14456 lodash.trimRight = trimRight;
14457 lodash.trunc = trunc;
14458 lodash.unescape = unescape;
14459 lodash.uniqueId = uniqueId;
14460 lodash.words = words;
14463 lodash.all = every;
14465 lodash.contains = includes;
14466 lodash.eq = isEqual;
14467 lodash.detect = find;
14468 lodash.foldl = reduce;
14469 lodash.foldr = reduceRight;
14470 lodash.head = first;
14471 lodash.include = includes;
14472 lodash.inject = reduce;
14474 mixin(lodash, (function() {
14476 baseForOwn(lodash, function(func, methodName) {
14477 if (!lodash.prototype[methodName]) {
14478 source[methodName] = func;
14484 /*------------------------------------------------------------------------*/
14486 // Add functions capable of returning wrapped and unwrapped values when chaining.
14487 lodash.sample = sample;
14489 lodash.prototype.sample = function(n) {
14490 if (!this.__chain__ && n == null) {
14491 return sample(this.value());
14493 return this.thru(function(value) {
14494 return sample(value, n);
14498 /*------------------------------------------------------------------------*/
14501 * The semantic version number.
14507 lodash.VERSION = VERSION;
14509 // Assign default placeholders.
14510 arrayEach(['bind', 'bindKey', 'curry', 'curryRight', 'partial', 'partialRight'], function(methodName) {
14511 lodash[methodName].placeholder = lodash;
14514 // Add `LazyWrapper` methods for `_.drop` and `_.take` variants.
14515 arrayEach(['drop', 'take'], function(methodName, index) {
14516 LazyWrapper.prototype[methodName] = function(n) {
14517 var filtered = this.__filtered__;
14518 if (filtered && !index) {
14519 return new LazyWrapper(this);
14521 n = n == null ? 1 : nativeMax(nativeFloor(n) || 0, 0);
14523 var result = this.clone();
14525 result.__takeCount__ = nativeMin(result.__takeCount__, n);
14527 result.__views__.push({ 'size': n, 'type': methodName + (result.__dir__ < 0 ? 'Right' : '') });
14532 LazyWrapper.prototype[methodName + 'Right'] = function(n) {
14533 return this.reverse()[methodName](n).reverse();
14537 // Add `LazyWrapper` methods that accept an `iteratee` value.
14538 arrayEach(['filter', 'map', 'takeWhile'], function(methodName, index) {
14539 var type = index + 1,
14540 isFilter = type != LAZY_MAP_FLAG;
14542 LazyWrapper.prototype[methodName] = function(iteratee, thisArg) {
14543 var result = this.clone();
14544 result.__iteratees__.push({ 'iteratee': getCallback(iteratee, thisArg, 1), 'type': type });
14545 result.__filtered__ = result.__filtered__ || isFilter;
14550 // Add `LazyWrapper` methods for `_.first` and `_.last`.
14551 arrayEach(['first', 'last'], function(methodName, index) {
14552 var takeName = 'take' + (index ? 'Right' : '');
14554 LazyWrapper.prototype[methodName] = function() {
14555 return this[takeName](1).value()[0];
14559 // Add `LazyWrapper` methods for `_.initial` and `_.rest`.
14560 arrayEach(['initial', 'rest'], function(methodName, index) {
14561 var dropName = 'drop' + (index ? '' : 'Right');
14563 LazyWrapper.prototype[methodName] = function() {
14564 return this.__filtered__ ? new LazyWrapper(this) : this[dropName](1);
14568 // Add `LazyWrapper` methods for `_.pluck` and `_.where`.
14569 arrayEach(['pluck', 'where'], function(methodName, index) {
14570 var operationName = index ? 'filter' : 'map',
14571 createCallback = index ? baseMatches : property;
14573 LazyWrapper.prototype[methodName] = function(value) {
14574 return this[operationName](createCallback(value));
14578 LazyWrapper.prototype.compact = function() {
14579 return this.filter(identity);
14582 LazyWrapper.prototype.reject = function(predicate, thisArg) {
14583 predicate = getCallback(predicate, thisArg, 1);
14584 return this.filter(function(value) {
14585 return !predicate(value);
14589 LazyWrapper.prototype.slice = function(start, end) {
14590 start = start == null ? 0 : (+start || 0);
14593 if (result.__filtered__ && (start > 0 || end < 0)) {
14594 return new LazyWrapper(result);
14597 result = result.takeRight(-start);
14598 } else if (start) {
14599 result = result.drop(start);
14601 if (end !== undefined) {
14603 result = end < 0 ? result.dropRight(-end) : result.take(end - start);
14608 LazyWrapper.prototype.takeRightWhile = function(predicate, thisArg) {
14609 return this.reverse().takeWhile(predicate, thisArg).reverse();
14612 LazyWrapper.prototype.toArray = function() {
14613 return this.take(POSITIVE_INFINITY);
14616 // Add `LazyWrapper` methods to `lodash.prototype`.
14617 baseForOwn(LazyWrapper.prototype, function(func, methodName) {
14618 var checkIteratee = /^(?:filter|map|reject)|While$/.test(methodName),
14619 retUnwrapped = /^(?:first|last)$/.test(methodName),
14620 lodashFunc = lodash[retUnwrapped ? ('take' + (methodName == 'last' ? 'Right' : '')) : methodName];
14625 lodash.prototype[methodName] = function() {
14626 var args = retUnwrapped ? [1] : arguments,
14627 chainAll = this.__chain__,
14628 value = this.__wrapped__,
14629 isHybrid = !!this.__actions__.length,
14630 isLazy = value instanceof LazyWrapper,
14631 iteratee = args[0],
14632 useLazy = isLazy || isArray(value);
14634 if (useLazy && checkIteratee && typeof iteratee == 'function' && iteratee.length != 1) {
14635 // Avoid lazy use if the iteratee has a "length" value other than `1`.
14636 isLazy = useLazy = false;
14638 var interceptor = function(value) {
14639 return (retUnwrapped && chainAll)
14640 ? lodashFunc(value, 1)[0]
14641 : lodashFunc.apply(undefined, arrayPush([value], args));
14644 var action = { 'func': thru, 'args': [interceptor], 'thisArg': undefined },
14645 onlyLazy = isLazy && !isHybrid;
14647 if (retUnwrapped && !chainAll) {
14649 value = value.clone();
14650 value.__actions__.push(action);
14651 return func.call(value);
14653 return lodashFunc.call(undefined, this.value())[0];
14655 if (!retUnwrapped && useLazy) {
14656 value = onlyLazy ? value : new LazyWrapper(this);
14657 var result = func.apply(value, args);
14658 result.__actions__.push(action);
14659 return new LodashWrapper(result, chainAll);
14661 return this.thru(interceptor);
14665 // Add `Array` and `String` methods to `lodash.prototype`.
14666 arrayEach(['join', 'pop', 'push', 'replace', 'shift', 'sort', 'splice', 'split', 'unshift'], function(methodName) {
14667 var func = (/^(?:replace|split)$/.test(methodName) ? stringProto : arrayProto)[methodName],
14668 chainName = /^(?:push|sort|unshift)$/.test(methodName) ? 'tap' : 'thru',
14669 retUnwrapped = /^(?:join|pop|replace|shift)$/.test(methodName);
14671 lodash.prototype[methodName] = function() {
14672 var args = arguments;
14673 if (retUnwrapped && !this.__chain__) {
14674 return func.apply(this.value(), args);
14676 return this[chainName](function(value) {
14677 return func.apply(value, args);
14682 // Map minified function names to their real names.
14683 baseForOwn(LazyWrapper.prototype, function(func, methodName) {
14684 var lodashFunc = lodash[methodName];
14686 var key = lodashFunc.name,
14687 names = realNames[key] || (realNames[key] = []);
14689 names.push({ 'name': methodName, 'func': lodashFunc });
14693 realNames[createHybridWrapper(undefined, BIND_KEY_FLAG).name] = [{ 'name': 'wrapper', 'func': undefined }];
14695 // Add functions to the lazy wrapper.
14696 LazyWrapper.prototype.clone = lazyClone;
14697 LazyWrapper.prototype.reverse = lazyReverse;
14698 LazyWrapper.prototype.value = lazyValue;
14700 // Add chaining functions to the `lodash` wrapper.
14701 lodash.prototype.chain = wrapperChain;
14702 lodash.prototype.commit = wrapperCommit;
14703 lodash.prototype.concat = wrapperConcat;
14704 lodash.prototype.plant = wrapperPlant;
14705 lodash.prototype.reverse = wrapperReverse;
14706 lodash.prototype.toString = wrapperToString;
14707 lodash.prototype.run = lodash.prototype.toJSON = lodash.prototype.valueOf = lodash.prototype.value = wrapperValue;
14709 // Add function aliases to the `lodash` wrapper.
14710 lodash.prototype.collect = lodash.prototype.map;
14711 lodash.prototype.head = lodash.prototype.first;
14712 lodash.prototype.select = lodash.prototype.filter;
14713 lodash.prototype.tail = lodash.prototype.rest;
14718 /*--------------------------------------------------------------------------*/
14721 var _ = runInContext();
14723 // Some AMD build optimizers like r.js check for condition patterns like the following:
14725 // Expose lodash to the global object when an AMD loader is present to avoid
14726 // errors in cases where lodash is loaded by a script tag and not intended
14727 // as an AMD module. See http://requirejs.org/docs/errors.html#mismatch for
14731 // Define as an anonymous module so, through path mapping, it can be
14732 // referenced as the "underscore" module.
14733 !(__WEBPACK_AMD_DEFINE_RESULT__ = function() {
14735 }.call(exports, __webpack_require__, exports, module), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
14737 // Check for `exports` after `define` in case a build optimizer adds an `exports` object.
14738 else if (freeExports && freeModule) {
14739 // Export for Node.js or RingoJS.
14740 if (moduleExports) {
14741 (freeModule.exports = _)._ = _;
14743 // Export for Rhino with CommonJS support.
14749 // Export for a browser or Rhino.
14754 /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(8)(module), (function() { return this; }())))
14758 /***/ function(module, exports) {
14760 module.exports = function(module) {
14761 if(!module.webpackPolyfill) {
14762 module.deprecate = function() {};
14764 // module.parent = undefined by default
14765 module.children = [];
14766 module.webpackPolyfill = 1;
14774 /***/ function(module, exports, __webpack_require__) {
14776 /* jslint node: true */
14779 var _ = __webpack_require__(7);
14780 var FontWrapper = __webpack_require__(10);
14782 function typeName(bold, italics){
14783 var type = 'normal';
14784 if (bold && italics) type = 'bolditalics';
14785 else if (bold) type = 'bold';
14786 else if (italics) type = 'italics';
14790 function FontProvider(fontDescriptors, pdfDoc) {
14792 this.pdfDoc = pdfDoc;
14793 this.fontWrappers = {};
14795 for(var font in fontDescriptors) {
14796 if (fontDescriptors.hasOwnProperty(font)) {
14797 var fontDef = fontDescriptors[font];
14799 this.fonts[font] = {
14800 normal: fontDef.normal,
14801 bold: fontDef.bold,
14802 italics: fontDef.italics,
14803 bolditalics: fontDef.bolditalics
14809 FontProvider.prototype.provideFont = function(familyName, bold, italics) {
14810 var type = typeName(bold, italics);
14811 if (!this.fonts[familyName] || !this.fonts[familyName][type]) {
14812 throw new Error('Font \''+ familyName + '\' in style \''+type+ '\' is not defined in the font section of the document definition.');
14815 this.fontWrappers[familyName] = this.fontWrappers[familyName] || {};
14817 if (!this.fontWrappers[familyName][type]) {
14818 this.fontWrappers[familyName][type] = new FontWrapper(this.pdfDoc, this.fonts[familyName][type], familyName + '(' + type + ')');
14821 return this.fontWrappers[familyName][type];
14824 FontProvider.prototype.setFontRefsToPdfDoc = function(){
14827 _.each(self.fontWrappers, function(fontFamily) {
14828 _.each(fontFamily, function(fontWrapper){
14829 _.each(fontWrapper.pdfFonts, function(font){
14830 if (!self.pdfDoc.page.fonts[font.id]) {
14831 self.pdfDoc.page.fonts[font.id] = font.ref();
14838 module.exports = FontProvider;
14843 /***/ function(module, exports, __webpack_require__) {
14845 /* jslint node: true */
14848 var _ = __webpack_require__(7);
14850 function FontWrapper(pdfkitDoc, path, fontName){
14851 this.MAX_CHAR_TYPES = 92;
14853 this.pdfkitDoc = pdfkitDoc;
14855 this.pdfFonts = [];
14856 this.charCatalogue = [];
14857 this.name = fontName;
14859 Object.defineProperty(this, 'ascender', {
14861 var font = this.getFont(0);
14862 return font.ascender;
14865 Object.defineProperty(this, 'decender', {
14867 var font = this.getFont(0);
14868 return font.decender;
14875 FontWrapper.prototype.getFont = function(index){
14876 if(!this.pdfFonts[index]){
14878 var pseudoName = this.name + index;
14880 if(this.postscriptName){
14881 delete this.pdfkitDoc._fontFamilies[this.postscriptName];
14884 this.pdfFonts[index] = this.pdfkitDoc.font(this.path, pseudoName)._font;
14885 if(!this.postscriptName){
14886 this.postscriptName = this.pdfFonts[index].name;
14890 return this.pdfFonts[index];
14894 FontWrapper.prototype.widthOfString = function(){
14895 var font = this.getFont(0);
14896 return font.widthOfString.apply(font, arguments);
14899 FontWrapper.prototype.lineHeight = function(){
14900 var font = this.getFont(0);
14901 return font.lineHeight.apply(font, arguments);
14904 FontWrapper.prototype.ref = function(){
14905 var font = this.getFont(0);
14906 return font.ref.apply(font, arguments);
14909 var toCharCode = function(char){
14910 return char.charCodeAt(0);
14913 FontWrapper.prototype.encode = function(text){
14916 var charTypesInInline = _.chain(text.split('')).map(toCharCode).uniq().value();
14917 if (charTypesInInline.length > self.MAX_CHAR_TYPES) {
14918 throw new Error('Inline has more than '+ self.MAX_CHAR_TYPES + ': ' + text + ' different character types and therefore cannot be properly embedded into pdf.');
14922 var characterFitInFontWithIndex = function (charCatalogue) {
14923 return _.uniq(charCatalogue.concat(charTypesInInline)).length <= self.MAX_CHAR_TYPES;
14926 var index = _.findIndex(self.charCatalogue, characterFitInFontWithIndex);
14929 index = self.charCatalogue.length;
14930 self.charCatalogue[index] = [];
14933 var font = self.getFont(index);
14936 _.each(charTypesInInline, function(charCode){
14937 if(!_.includes(self.charCatalogue[index], charCode)){
14938 self.charCatalogue[index].push(charCode);
14942 var encodedText = _.map(font.encode(text), function (char) {
14943 return char.charCodeAt(0).toString(16);
14947 encodedText: encodedText,
14953 module.exports = FontWrapper;
14958 /***/ function(module, exports, __webpack_require__) {
14960 /* jslint node: true */
14963 var _ = __webpack_require__(7);
14964 var TraversalTracker = __webpack_require__(12);
14965 var DocMeasure = __webpack_require__(13);
14966 var DocumentContext = __webpack_require__(19);
14967 var PageElementWriter = __webpack_require__(20);
14968 var ColumnCalculator = __webpack_require__(16);
14969 var TableProcessor = __webpack_require__(23);
14970 var Line = __webpack_require__(22);
14971 var pack = __webpack_require__(17).pack;
14972 var offsetVector = __webpack_require__(17).offsetVector;
14973 var fontStringify = __webpack_require__(17).fontStringify;
14974 var isFunction = __webpack_require__(17).isFunction;
14975 var TextTools = __webpack_require__(14);
14976 var StyleContextStack = __webpack_require__(15);
14978 function addAll(target, otherArray){
14979 _.each(otherArray, function(item){
14985 * Creates an instance of LayoutBuilder - layout engine which turns document-definition-object
14986 * into a set of pages, lines, inlines and vectors ready to be rendered into a PDF
14988 * @param {Object} pageSize - an object defining page width and height
14989 * @param {Object} pageMargins - an object defining top, left, right and bottom margins
14991 function LayoutBuilder(pageSize, pageMargins, imageMeasure) {
14992 this.pageSize = pageSize;
14993 this.pageMargins = pageMargins;
14994 this.tracker = new TraversalTracker();
14995 this.imageMeasure = imageMeasure;
14996 this.tableLayouts = {};
14999 LayoutBuilder.prototype.registerTableLayouts = function (tableLayouts) {
15000 this.tableLayouts = pack(this.tableLayouts, tableLayouts);
15004 * Executes layout engine on document-definition-object and creates an array of pages
15005 * containing positioned Blocks, Lines and inlines
15007 * @param {Object} docStructure document-definition-object
15008 * @param {Object} fontProvider font provider
15009 * @param {Object} styleDictionary dictionary with style definitions
15010 * @param {Object} defaultStyle default style definition
15011 * @return {Array} an array of pages
15013 LayoutBuilder.prototype.layoutDocument = function (docStructure, fontProvider, styleDictionary, defaultStyle, background, header, footer, images, watermark, pageBreakBeforeFct) {
15015 function addPageBreaksIfNecessary(linearNodeList, pages) {
15017 if(!isFunction(pageBreakBeforeFct)){
15021 linearNodeList = _.reject(linearNodeList, function(node){
15022 return _.isEmpty(node.positions);
15025 _.each(linearNodeList, function(node) {
15026 var nodeInfo = _.pick(node, [
15027 'id', 'text', 'ul', 'ol', 'table', 'image', 'qr', 'canvas', 'columns',
15028 'headlineLevel', 'style', 'pageBreak', 'pageOrientation',
15031 nodeInfo.startPosition = _.first(node.positions);
15032 nodeInfo.pageNumbers = _.chain(node.positions).map('pageNumber').uniq().value();
15033 nodeInfo.pages = pages.length;
15034 nodeInfo.stack = _.isArray(node.stack);
15036 node.nodeInfo = nodeInfo;
15039 return _.any(linearNodeList, function (node, index, followingNodeList) {
15040 if (node.pageBreak !== 'before' && !node.pageBreakCalculated) {
15041 node.pageBreakCalculated = true;
15042 var pageNumber = _.first(node.nodeInfo.pageNumbers);
15044 var followingNodesOnPage = _.chain(followingNodeList).drop(index + 1).filter(function (node0) {
15045 return _.contains(node0.nodeInfo.pageNumbers, pageNumber);
15048 var nodesOnNextPage = _.chain(followingNodeList).drop(index + 1).filter(function (node0) {
15049 return _.contains(node0.nodeInfo.pageNumbers, pageNumber + 1);
15052 var previousNodesOnPage = _.chain(followingNodeList).take(index).filter(function (node0) {
15053 return _.contains(node0.nodeInfo.pageNumbers, pageNumber);
15056 if (pageBreakBeforeFct(node.nodeInfo,
15057 _.map(followingNodesOnPage, 'nodeInfo'),
15058 _.map(nodesOnNextPage, 'nodeInfo'),
15059 _.map(previousNodesOnPage, 'nodeInfo'))) {
15060 node.pageBreak = 'before';
15067 this.docMeasure = new DocMeasure(fontProvider, styleDictionary, defaultStyle, this.imageMeasure, this.tableLayouts, images);
15070 function resetXYs(result) {
15071 _.each(result.linearNodeList, function (node) {
15076 var result = this.tryLayoutDocument(docStructure, fontProvider, styleDictionary, defaultStyle, background, header, footer, images, watermark);
15077 while(addPageBreaksIfNecessary(result.linearNodeList, result.pages)){
15079 result = this.tryLayoutDocument(docStructure, fontProvider, styleDictionary, defaultStyle, background, header, footer, images, watermark);
15082 return result.pages;
15085 LayoutBuilder.prototype.tryLayoutDocument = function (docStructure, fontProvider, styleDictionary, defaultStyle, background, header, footer, images, watermark, pageBreakBeforeFct) {
15087 this.linearNodeList = [];
15088 docStructure = this.docMeasure.measureDocument(docStructure);
15090 this.writer = new PageElementWriter(
15091 new DocumentContext(this.pageSize, this.pageMargins), this.tracker);
15094 this.writer.context().tracker.startTracking('pageAdded', function() {
15095 _this.addBackground(background);
15098 this.addBackground(background);
15099 this.processNode(docStructure);
15100 this.addHeadersAndFooters(header, footer);
15101 /* jshint eqnull:true */
15102 if(watermark != null)
15103 this.addWatermark(watermark, fontProvider);
15105 return {pages: this.writer.context().pages, linearNodeList: this.linearNodeList};
15109 LayoutBuilder.prototype.addBackground = function(background) {
15110 var backgroundGetter = isFunction(background) ? background : function() { return background; };
15112 var pageBackground = backgroundGetter(this.writer.context().page + 1);
15114 if (pageBackground) {
15115 var pageSize = this.writer.context().getCurrentPage().pageSize;
15116 this.writer.beginUnbreakableBlock(pageSize.width, pageSize.height);
15117 this.processNode(this.docMeasure.measureDocument(pageBackground));
15118 this.writer.commitUnbreakableBlock(0, 0);
15122 LayoutBuilder.prototype.addStaticRepeatable = function(headerOrFooter, sizeFunction) {
15123 this.addDynamicRepeatable(function() { return headerOrFooter; }, sizeFunction);
15126 LayoutBuilder.prototype.addDynamicRepeatable = function(nodeGetter, sizeFunction) {
15127 var pages = this.writer.context().pages;
15129 for(var pageIndex = 0, l = pages.length; pageIndex < l; pageIndex++) {
15130 this.writer.context().page = pageIndex;
15132 var node = nodeGetter(pageIndex + 1, l);
15135 var sizes = sizeFunction(this.writer.context().getCurrentPage().pageSize, this.pageMargins);
15136 this.writer.beginUnbreakableBlock(sizes.width, sizes.height);
15137 this.processNode(this.docMeasure.measureDocument(node));
15138 this.writer.commitUnbreakableBlock(sizes.x, sizes.y);
15143 LayoutBuilder.prototype.addHeadersAndFooters = function(header, footer) {
15144 var headerSizeFct = function(pageSize, pageMargins){
15148 width: pageSize.width,
15149 height: pageMargins.top
15153 var footerSizeFct = function (pageSize, pageMargins) {
15156 y: pageSize.height - pageMargins.bottom,
15157 width: pageSize.width,
15158 height: pageMargins.bottom
15162 if(isFunction(header)) {
15163 this.addDynamicRepeatable(header, headerSizeFct);
15164 } else if(header) {
15165 this.addStaticRepeatable(header, headerSizeFct);
15168 if(isFunction(footer)) {
15169 this.addDynamicRepeatable(footer, footerSizeFct);
15170 } else if(footer) {
15171 this.addStaticRepeatable(footer, footerSizeFct);
15175 LayoutBuilder.prototype.addWatermark = function(watermark, fontProvider){
15176 var defaultFont = Object.getOwnPropertyNames(fontProvider.fonts)[0]; // TODO allow selection of other font
15177 var watermarkObject = {
15179 font: fontProvider.provideFont(fontProvider[defaultFont], false, false),
15180 size: getSize(this.pageSize, watermark, fontProvider)
15183 var pages = this.writer.context().pages;
15184 for(var i = 0, l = pages.length; i < l; i++) {
15185 pages[i].watermark = watermarkObject;
15188 function getSize(pageSize, watermark, fontProvider){
15189 var width = pageSize.width;
15190 var height = pageSize.height;
15191 var targetWidth = Math.sqrt(width*width + height*height)*0.8; /* page diagnoal * sample factor */
15192 var textTools = new TextTools(fontProvider);
15193 var styleContextStack = new StyleContextStack();
15197 * Binary search the best font size.
15198 * Initial bounds [0, 1000]
15199 * Break when range < 1
15204 while(Math.abs(a - b) > 1){
15205 styleContextStack.push({
15208 size = textTools.sizeOfString(watermark, styleContextStack);
15209 if(size.width > targetWidth){
15213 else if(size.width < targetWidth){
15217 styleContextStack.pop();
15222 return {size: size, fontSize: c};
15226 function decorateNode(node){
15227 var x = node.x, y = node.y;
15228 node.positions = [];
15230 _.each(node.canvas, function(vector){
15231 var x = vector.x, y = vector.y, x1 = vector.x1, y1 = vector.y1, x2 = vector.x2, y2 = vector.y2;
15232 vector.resetXY = function(){
15242 node.resetXY = function(){
15245 _.each(node.canvas, function(vector){
15251 LayoutBuilder.prototype.processNode = function(node) {
15254 this.linearNodeList.push(node);
15255 decorateNode(node);
15257 applyMargins(function() {
15258 var absPosition = node.absolutePosition;
15260 self.writer.context().beginDetachedBlock();
15261 self.writer.context().moveTo(absPosition.x || 0, absPosition.y || 0);
15265 self.processVerticalContainer(node);
15266 } else if (node.columns) {
15267 self.processColumns(node);
15268 } else if (node.ul) {
15269 self.processList(false, node);
15270 } else if (node.ol) {
15271 self.processList(true, node);
15272 } else if (node.table) {
15273 self.processTable(node);
15274 } else if (node.text !== undefined) {
15275 self.processLeaf(node);
15276 } else if (node.image) {
15277 self.processImage(node);
15278 } else if (node.canvas) {
15279 self.processCanvas(node);
15280 } else if (node.qr) {
15281 self.processQr(node);
15282 }else if (!node._span) {
15283 throw 'Unrecognized document structure: ' + JSON.stringify(node, fontStringify);
15287 self.writer.context().endDetachedBlock();
15291 function applyMargins(callback) {
15292 var margin = node._margin;
15294 if (node.pageBreak === 'before') {
15295 self.writer.moveToNextPage(node.pageOrientation);
15299 self.writer.context().moveDown(margin[1]);
15300 self.writer.context().addMargin(margin[0], margin[2]);
15306 self.writer.context().addMargin(-margin[0], -margin[2]);
15307 self.writer.context().moveDown(margin[3]);
15310 if (node.pageBreak === 'after') {
15311 self.writer.moveToNextPage(node.pageOrientation);
15316 // vertical container
15317 LayoutBuilder.prototype.processVerticalContainer = function(node) {
15319 node.stack.forEach(function(item) {
15320 self.processNode(item);
15321 addAll(node.positions, item.positions);
15323 //TODO: paragraph gap
15328 LayoutBuilder.prototype.processColumns = function(columnNode) {
15329 var columns = columnNode.columns;
15330 var availableWidth = this.writer.context().availableWidth;
15331 var gaps = gapArray(columnNode._gap);
15333 if (gaps) availableWidth -= (gaps.length - 1) * columnNode._gap;
15335 ColumnCalculator.buildColumnWidths(columns, availableWidth);
15336 var result = this.processRow(columns, columns, gaps);
15337 addAll(columnNode.positions, result.positions);
15340 function gapArray(gap) {
15341 if (!gap) return null;
15346 for(var i = columns.length - 1; i > 0; i--) {
15354 LayoutBuilder.prototype.processRow = function(columns, widths, gaps, tableBody, tableRow) {
15356 var pageBreaks = [], positions = [];
15358 this.tracker.auto('pageChanged', storePageBreakData, function() {
15359 widths = widths || columns;
15361 self.writer.context().beginColumnGroup();
15363 for(var i = 0, l = columns.length; i < l; i++) {
15364 var column = columns[i];
15365 var width = widths[i]._calcWidth;
15366 var leftOffset = colLeftOffset(i);
15368 if (column.colSpan && column.colSpan > 1) {
15369 for(var j = 1; j < column.colSpan; j++) {
15370 width += widths[++i]._calcWidth + gaps[i];
15374 self.writer.context().beginColumn(width, leftOffset, getEndingCell(column, i));
15375 if (!column._span) {
15376 self.processNode(column);
15377 addAll(positions, column.positions);
15378 } else if (column._columnEndingContext) {
15380 self.writer.context().markEnding(column);
15384 self.writer.context().completeColumnGroup();
15387 return {pageBreaks: pageBreaks, positions: positions};
15389 function storePageBreakData(data) {
15392 for(var i = 0, l = pageBreaks.length; i < l; i++) {
15393 var desc = pageBreaks[i];
15394 if (desc.prevPage === data.prevPage) {
15402 pageBreaks.push(pageDesc);
15404 pageDesc.prevY = Math.max(pageDesc.prevY, data.prevY);
15405 pageDesc.y = Math.min(pageDesc.y, data.y);
15408 function colLeftOffset(i) {
15409 if (gaps && gaps.length > i) return gaps[i];
15413 function getEndingCell(column, columnIndex) {
15414 if (column.rowSpan && column.rowSpan > 1) {
15415 var endingRow = tableRow + column.rowSpan - 1;
15416 if (endingRow >= tableBody.length) throw 'Row span for column ' + columnIndex + ' (with indexes starting from 0) exceeded row count';
15417 return tableBody[endingRow][columnIndex];
15425 LayoutBuilder.prototype.processList = function(orderedList, node) {
15427 items = orderedList ? node.ol : node.ul,
15428 gapSize = node._gapSize;
15430 this.writer.context().addMargin(gapSize.width);
15433 this.tracker.auto('lineAdded', addMarkerToFirstLeaf, function() {
15434 items.forEach(function(item) {
15435 nextMarker = item.listMarker;
15436 self.processNode(item);
15437 addAll(node.positions, item.positions);
15441 this.writer.context().addMargin(-gapSize.width);
15443 function addMarkerToFirstLeaf(line) {
15444 // I'm not very happy with the way list processing is implemented
15445 // (both code and algorithm should be rethinked)
15447 var marker = nextMarker;
15450 if (marker.canvas) {
15451 var vector = marker.canvas[0];
15453 offsetVector(vector, -marker._minWidth, 0);
15454 self.writer.addVector(vector);
15456 var markerLine = new Line(self.pageSize.width);
15457 markerLine.addInline(marker._inlines[0]);
15458 markerLine.x = -marker._minWidth;
15459 markerLine.y = line.getAscenderHeight() - markerLine.getAscenderHeight();
15460 self.writer.addLine(markerLine, true);
15467 LayoutBuilder.prototype.processTable = function(tableNode) {
15468 var processor = new TableProcessor(tableNode);
15470 processor.beginTable(this.writer);
15472 for(var i = 0, l = tableNode.table.body.length; i < l; i++) {
15473 processor.beginRow(i, this.writer);
15475 var result = this.processRow(tableNode.table.body[i], tableNode.table.widths, tableNode._offsets.offsets, tableNode.table.body, i);
15476 addAll(tableNode.positions, result.positions);
15478 processor.endRow(i, this.writer, result.pageBreaks);
15481 processor.endTable(this.writer);
15485 LayoutBuilder.prototype.processLeaf = function(node) {
15486 var line = this.buildNextLine(node);
15487 var currentHeight = (line) ? line.getHeight() : 0;
15488 var maxHeight = node.maxHeight || -1;
15490 while (line && (maxHeight === -1 || currentHeight < maxHeight)) {
15491 var positions = this.writer.addLine(line);
15492 node.positions.push(positions);
15493 line = this.buildNextLine(node);
15495 currentHeight += line.getHeight();
15500 LayoutBuilder.prototype.buildNextLine = function(textNode) {
15501 if (!textNode._inlines || textNode._inlines.length === 0) return null;
15503 var line = new Line(this.writer.context().availableWidth);
15505 while(textNode._inlines && textNode._inlines.length > 0 && line.hasEnoughSpaceForInline(textNode._inlines[0])) {
15506 line.addInline(textNode._inlines.shift());
15509 line.lastLineInParagraph = textNode._inlines.length === 0;
15515 LayoutBuilder.prototype.processImage = function(node) {
15516 var position = this.writer.addImage(node);
15517 node.positions.push(position);
15520 LayoutBuilder.prototype.processCanvas = function(node) {
15521 var height = node._minHeight;
15523 if (this.writer.context().availableHeight < height) {
15524 // TODO: support for canvas larger than a page
15525 // TODO: support for other overflow methods
15527 this.writer.moveToNextPage();
15530 node.canvas.forEach(function(vector) {
15531 var position = this.writer.addVector(vector);
15532 node.positions.push(position);
15535 this.writer.context().moveDown(height);
15538 LayoutBuilder.prototype.processQr = function(node) {
15539 var position = this.writer.addQr(node);
15540 node.positions.push(position);
15543 module.exports = LayoutBuilder;
15548 /***/ function(module, exports) {
15550 /* jslint node: true */
15554 * Creates an instance of TraversalTracker
15558 function TraversalTracker() {
15562 TraversalTracker.prototype.startTracking = function(event, cb) {
15563 var callbacks = (this.events[event] || (this.events[event] = []));
15565 if (callbacks.indexOf(cb) < 0) {
15566 callbacks.push(cb);
15570 TraversalTracker.prototype.stopTracking = function(event, cb) {
15571 var callbacks = this.events[event];
15574 var index = callbacks.indexOf(cb);
15576 callbacks.splice(index, 1);
15581 TraversalTracker.prototype.emit = function(event) {
15582 var args = Array.prototype.slice.call(arguments, 1);
15584 var callbacks = this.events[event];
15587 callbacks.forEach(function(cb) {
15588 cb.apply(this, args);
15593 TraversalTracker.prototype.auto = function(event, cb, innerBlock) {
15594 this.startTracking(event, cb);
15596 this.stopTracking(event, cb);
15599 module.exports = TraversalTracker;
15604 /***/ function(module, exports, __webpack_require__) {
15606 /* jslint node: true */
15609 var TextTools = __webpack_require__(14);
15610 var StyleContextStack = __webpack_require__(15);
15611 var ColumnCalculator = __webpack_require__(16);
15612 var fontStringify = __webpack_require__(17).fontStringify;
15613 var pack = __webpack_require__(17).pack;
15614 var qrEncoder = __webpack_require__(18);
15619 function DocMeasure(fontProvider, styleDictionary, defaultStyle, imageMeasure, tableLayouts, images) {
15620 this.textTools = new TextTools(fontProvider);
15621 this.styleStack = new StyleContextStack(styleDictionary, defaultStyle);
15622 this.imageMeasure = imageMeasure;
15623 this.tableLayouts = tableLayouts;
15624 this.images = images;
15625 this.autoImageIndex = 1;
15629 * Measures all nodes and sets min/max-width properties required for the second
15631 * @param {Object} docStructure document-definition-object
15632 * @return {Object} document-measurement-object
15634 DocMeasure.prototype.measureDocument = function(docStructure) {
15635 return this.measureNode(docStructure);
15638 DocMeasure.prototype.measureNode = function(node) {
15639 // expand shortcuts
15640 if (node instanceof Array) {
15641 node = { stack: node };
15642 } else if (typeof node == 'string' || node instanceof String) {
15643 node = { text: node };
15646 // Deal with empty nodes to prevent crash in getNodeMargin
15647 if (Object.keys(node).length === 0) {
15648 // A warning could be logged: console.warn('pdfmake: Empty node, ignoring it');
15649 node = { text: '' };
15654 return this.styleStack.auto(node, function() {
15655 // TODO: refactor + rethink whether this is the proper way to handle margins
15656 node._margin = getNodeMargin(node);
15658 if (node.columns) {
15659 return extendMargins(self.measureColumns(node));
15660 } else if (node.stack) {
15661 return extendMargins(self.measureVerticalContainer(node));
15662 } else if (node.ul) {
15663 return extendMargins(self.measureList(false, node));
15664 } else if (node.ol) {
15665 return extendMargins(self.measureList(true, node));
15666 } else if (node.table) {
15667 return extendMargins(self.measureTable(node));
15668 } else if (node.text !== undefined) {
15669 return extendMargins(self.measureLeaf(node));
15670 } else if (node.image) {
15671 return extendMargins(self.measureImage(node));
15672 } else if (node.canvas) {
15673 return extendMargins(self.measureCanvas(node));
15674 } else if (node.qr) {
15675 return extendMargins(self.measureQr(node));
15677 throw 'Unrecognized document structure: ' + JSON.stringify(node, fontStringify);
15681 function extendMargins(node) {
15682 var margin = node._margin;
15685 node._minWidth += margin[0] + margin[2];
15686 node._maxWidth += margin[0] + margin[2];
15692 function getNodeMargin() {
15694 function processSingleMargins(node, currentMargin){
15695 if (node.marginLeft || node.marginTop || node.marginRight || node.marginBottom) {
15697 node.marginLeft || currentMargin[0] || 0,
15698 node.marginTop || currentMargin[1] || 0,
15699 node.marginRight || currentMargin[2] || 0,
15700 node.marginBottom || currentMargin[3] || 0
15703 return currentMargin;
15706 function flattenStyleArray(styleArray){
15707 var flattenedStyles = {};
15708 for (var i = styleArray.length - 1; i >= 0; i--) {
15709 var styleName = styleArray[i];
15710 var style = self.styleStack.styleDictionary[styleName];
15711 for(var key in style){
15712 if(style.hasOwnProperty(key)){
15713 flattenedStyles[key] = style[key];
15717 return flattenedStyles;
15720 function convertMargin(margin) {
15721 if (typeof margin === 'number' || margin instanceof Number) {
15722 margin = [ margin, margin, margin, margin ];
15723 } else if (margin instanceof Array) {
15724 if (margin.length === 2) {
15725 margin = [ margin[0], margin[1], margin[0], margin[1] ];
15731 var margin = [undefined, undefined, undefined, undefined];
15734 var styleArray = (node.style instanceof Array) ? node.style : [node.style];
15735 var flattenedStyleArray = flattenStyleArray(styleArray);
15737 if(flattenedStyleArray) {
15738 margin = processSingleMargins(flattenedStyleArray, margin);
15741 if(flattenedStyleArray.margin){
15742 margin = convertMargin(flattenedStyleArray.margin);
15746 margin = processSingleMargins(node, margin);
15749 margin = convertMargin(node.margin);
15752 if(margin[0] === undefined && margin[1] === undefined && margin[2] === undefined && margin[3] === undefined) {
15760 DocMeasure.prototype.convertIfBase64Image = function(node) {
15761 if (/^data:image\/(jpeg|jpg|png);base64,/.test(node.image)) {
15762 var label = '$$pdfmake$$' + this.autoImageIndex++;
15763 this.images[label] = node.image;
15764 node.image = label;
15768 DocMeasure.prototype.measureImage = function(node) {
15770 this.convertIfBase64Image(node);
15773 var imageSize = this.imageMeasure.measureImage(node.image);
15776 var factor = (imageSize.width / imageSize.height > node.fit[0] / node.fit[1]) ? node.fit[0] / imageSize.width : node.fit[1] / imageSize.height;
15777 node._width = node._minWidth = node._maxWidth = imageSize.width * factor;
15778 node._height = imageSize.height * factor;
15780 node._width = node._minWidth = node._maxWidth = node.width || imageSize.width;
15781 node._height = node.height || (imageSize.height * node._width / imageSize.width);
15784 node._alignment = this.styleStack.getProperty('alignment');
15788 DocMeasure.prototype.measureLeaf = function(node) {
15790 // Make sure style properties of the node itself are considered when building inlines.
15791 // We could also just pass [node] to buildInlines, but that fails for bullet points.
15792 var styleStack = this.styleStack.clone();
15793 styleStack.push(node);
15795 var data = this.textTools.buildInlines(node.text, styleStack);
15797 node._inlines = data.items;
15798 node._minWidth = data.minWidth;
15799 node._maxWidth = data.maxWidth;
15804 DocMeasure.prototype.measureVerticalContainer = function(node) {
15805 var items = node.stack;
15807 node._minWidth = 0;
15808 node._maxWidth = 0;
15810 for(var i = 0, l = items.length; i < l; i++) {
15811 items[i] = this.measureNode(items[i]);
15813 node._minWidth = Math.max(node._minWidth, items[i]._minWidth);
15814 node._maxWidth = Math.max(node._maxWidth, items[i]._maxWidth);
15820 DocMeasure.prototype.gapSizeForList = function(isOrderedList, listItems) {
15821 if (isOrderedList) {
15822 var longestNo = (listItems.length).toString().replace(/./g, '9');
15823 return this.textTools.sizeOfString(longestNo + '. ', this.styleStack);
15825 return this.textTools.sizeOfString('9. ', this.styleStack);
15829 DocMeasure.prototype.buildMarker = function(isOrderedList, counter, styleStack, gapSize) {
15832 if (isOrderedList) {
15833 marker = { _inlines: this.textTools.buildInlines(counter, styleStack).items };
15836 // TODO: ascender-based calculations
15837 var radius = gapSize.fontSize / 6;
15841 y: (gapSize.height / gapSize.lineHeight) + gapSize.decender - gapSize.fontSize / 3,//0,// gapSize.fontSize * 2 / 3,
15850 marker._minWidth = marker._maxWidth = gapSize.width;
15851 marker._minHeight = marker._maxHeight = gapSize.height;
15856 DocMeasure.prototype.measureList = function(isOrdered, node) {
15857 var style = this.styleStack.clone();
15859 var items = isOrdered ? node.ol : node.ul;
15860 node._gapSize = this.gapSizeForList(isOrdered, items);
15861 node._minWidth = 0;
15862 node._maxWidth = 0;
15866 for(var i = 0, l = items.length; i < l; i++) {
15867 var nextItem = items[i] = this.measureNode(items[i]);
15869 var marker = counter++ + '. ';
15871 if (!nextItem.ol && !nextItem.ul) {
15872 nextItem.listMarker = this.buildMarker(isOrdered, nextItem.counter || marker, style, node._gapSize);
15873 } // TODO: else - nested lists numbering
15875 node._minWidth = Math.max(node._minWidth, items[i]._minWidth + node._gapSize.width);
15876 node._maxWidth = Math.max(node._maxWidth, items[i]._maxWidth + node._gapSize.width);
15882 DocMeasure.prototype.measureColumns = function(node) {
15883 var columns = node.columns;
15884 node._gap = this.styleStack.getProperty('columnGap') || 0;
15886 for(var i = 0, l = columns.length; i < l; i++) {
15887 columns[i] = this.measureNode(columns[i]);
15890 var measures = ColumnCalculator.measureMinMax(columns);
15892 node._minWidth = measures.min + node._gap * (columns.length - 1);
15893 node._maxWidth = measures.max + node._gap * (columns.length - 1);
15898 DocMeasure.prototype.measureTable = function(node) {
15899 extendTableWidths(node);
15900 node._layout = getLayout(this.tableLayouts);
15901 node._offsets = getOffsets(node._layout);
15904 var col, row, cols, rows;
15906 for(col = 0, cols = node.table.body[0].length; col < cols; col++) {
15907 var c = node.table.widths[col];
15911 for(row = 0, rows = node.table.body.length; row < rows; row++) {
15912 var rowData = node.table.body[row];
15913 var data = rowData[col];
15916 data = rowData[col] = this.styleStack.auto(data, measureCb(this, data));
15918 if (data.colSpan && data.colSpan > 1) {
15919 markSpans(rowData, col, data.colSpan);
15920 colSpans.push({ col: col, span: data.colSpan, minWidth: data._minWidth, maxWidth: data._maxWidth });
15922 c._minWidth = Math.max(c._minWidth, data._minWidth);
15923 c._maxWidth = Math.max(c._maxWidth, data._maxWidth);
15927 if (data.rowSpan && data.rowSpan > 1) {
15928 markVSpans(node.table, row, col, data.rowSpan);
15933 extendWidthsForColSpans();
15935 var measures = ColumnCalculator.measureMinMax(node.table.widths);
15937 node._minWidth = measures.min + node._offsets.total;
15938 node._maxWidth = measures.max + node._offsets.total;
15942 function measureCb(_this, data) {
15943 return function() {
15944 if (data !== null && typeof data === 'object') {
15945 data.fillColor = _this.styleStack.getProperty('fillColor');
15947 return _this.measureNode(data);
15951 function getLayout(tableLayouts) {
15952 var layout = node.layout;
15954 if (typeof node.layout === 'string' || node instanceof String) {
15955 layout = tableLayouts[layout];
15958 var defaultLayout = {
15959 hLineWidth: function(i, node) { return 1; }, //return node.table.headerRows && i === node.table.headerRows && 3 || 0; },
15960 vLineWidth: function(i, node) { return 1; },
15961 hLineColor: function(i, node) { return 'black'; },
15962 vLineColor: function(i, node) { return 'black'; },
15963 paddingLeft: function(i, node) { return 4; }, //i && 4 || 0; },
15964 paddingRight: function(i, node) { return 4; }, //(i < node.table.widths.length - 1) ? 4 : 0; },
15965 paddingTop: function(i, node) { return 2; },
15966 paddingBottom: function(i, node) { return 2; }
15969 return pack(defaultLayout, layout);
15972 function getOffsets(layout) {
15974 var totalOffset = 0;
15975 var prevRightPadding = 0;
15977 for(var i = 0, l = node.table.widths.length; i < l; i++) {
15978 var lOffset = prevRightPadding + layout.vLineWidth(i, node) + layout.paddingLeft(i, node);
15979 offsets.push(lOffset);
15980 totalOffset += lOffset;
15981 prevRightPadding = layout.paddingRight(i, node);
15984 totalOffset += prevRightPadding + layout.vLineWidth(node.table.widths.length, node);
15987 total: totalOffset,
15992 function extendWidthsForColSpans() {
15995 for (var i = 0, l = colSpans.length; i < l; i++) {
15996 var span = colSpans[i];
15998 var currentMinMax = getMinMax(span.col, span.span, node._offsets);
15999 var minDifference = span.minWidth - currentMinMax.minWidth;
16000 var maxDifference = span.maxWidth - currentMinMax.maxWidth;
16002 if (minDifference > 0) {
16003 q = minDifference / span.span;
16005 for(j = 0; j < span.span; j++) {
16006 node.table.widths[span.col + j]._minWidth += q;
16010 if (maxDifference > 0) {
16011 q = maxDifference / span.span;
16013 for(j = 0; j < span.span; j++) {
16014 node.table.widths[span.col + j]._maxWidth += q;
16020 function getMinMax(col, span, offsets) {
16021 var result = { minWidth: 0, maxWidth: 0 };
16023 for(var i = 0; i < span; i++) {
16024 result.minWidth += node.table.widths[col + i]._minWidth + (i? offsets.offsets[col + i] : 0);
16025 result.maxWidth += node.table.widths[col + i]._maxWidth + (i? offsets.offsets[col + i] : 0);
16031 function markSpans(rowData, col, span) {
16032 for (var i = 1; i < span; i++) {
16033 rowData[col + i] = {
16037 rowSpan: rowData[col].rowSpan
16042 function markVSpans(table, row, col, span) {
16043 for (var i = 1; i < span; i++) {
16044 table.body[row + i][col] = {
16048 fillColor: table.body[row][col].fillColor
16053 function extendTableWidths(node) {
16054 if (!node.table.widths) {
16055 node.table.widths = 'auto';
16058 if (typeof node.table.widths === 'string' || node.table.widths instanceof String) {
16059 node.table.widths = [ node.table.widths ];
16061 while(node.table.widths.length < node.table.body[0].length) {
16062 node.table.widths.push(node.table.widths[node.table.widths.length - 1]);
16066 for(var i = 0, l = node.table.widths.length; i < l; i++) {
16067 var w = node.table.widths[i];
16068 if (typeof w === 'number' || w instanceof Number || typeof w === 'string' || w instanceof String) {
16069 node.table.widths[i] = { width: w };
16075 DocMeasure.prototype.measureCanvas = function(node) {
16078 for(var i = 0, l = node.canvas.length; i < l; i++) {
16079 var vector = node.canvas[i];
16081 switch(vector.type) {
16083 w = Math.max(w, vector.x + vector.r1);
16084 h = Math.max(h, vector.y + vector.r2);
16087 w = Math.max(w, vector.x + vector.w);
16088 h = Math.max(h, vector.y + vector.h);
16091 w = Math.max(w, vector.x1, vector.x2);
16092 h = Math.max(h, vector.y1, vector.y2);
16095 for(var i2 = 0, l2 = vector.points.length; i2 < l2; i2++) {
16096 w = Math.max(w, vector.points[i2].x);
16097 h = Math.max(h, vector.points[i2].y);
16103 node._minWidth = node._maxWidth = w;
16104 node._minHeight = node._maxHeight = h;
16109 DocMeasure.prototype.measureQr = function(node) {
16110 node = qrEncoder.measure(node);
16111 node._alignment = this.styleStack.getProperty('alignment');
16115 module.exports = DocMeasure;
16120 /***/ function(module, exports) {
16122 /* jslint node: true */
16125 var WORD_RE = /([^ ,\/!.?:;\-\n]*[ ,\/!.?:;\-]*)|\n/g;
16126 // /\S*\s*/g to be considered (I'm not sure however - we shouldn't split 'aaa !!!!')
16128 var LEADING = /^(\s)+/g;
16129 var TRAILING = /(\s)+$/g;
16132 * Creates an instance of TextTools - text measurement utility
16135 * @param {FontProvider} fontProvider
16137 function TextTools(fontProvider) {
16138 this.fontProvider = fontProvider;
16142 * Converts an array of strings (or inline-definition-objects) into a collection
16143 * of inlines and calculated minWidth/maxWidth.
16144 * and their min/max widths
16145 * @param {Object} textArray - an array of inline-definition-objects (or strings)
16146 * @param {Object} styleContextStack current style stack
16147 * @return {Object} collection of inlines, minWidth, maxWidth
16149 TextTools.prototype.buildInlines = function(textArray, styleContextStack) {
16150 var measured = measure(this.fontProvider, textArray, styleContextStack);
16156 measured.forEach(function (inline) {
16157 minWidth = Math.max(minWidth, inline.width - inline.leadingCut - inline.trailingCut);
16159 if (!currentLineWidth) {
16160 currentLineWidth = { width: 0, leadingCut: inline.leadingCut, trailingCut: 0 };
16163 currentLineWidth.width += inline.width;
16164 currentLineWidth.trailingCut = inline.trailingCut;
16166 maxWidth = Math.max(maxWidth, getTrimmedWidth(currentLineWidth));
16168 if (inline.lineEnd) {
16169 currentLineWidth = null;
16173 if (getStyleProperty({}, styleContextStack, 'noWrap', false)) {
16174 minWidth = maxWidth;
16179 minWidth: minWidth,
16183 function getTrimmedWidth(item) {
16184 return Math.max(0, item.width - item.leadingCut - item.trailingCut);
16189 * Returns size of the specified string (without breaking it) using the current style
16190 * @param {String} text text to be measured
16191 * @param {Object} styleContextStack current style stack
16192 * @return {Object} size of the specified string
16194 TextTools.prototype.sizeOfString = function(text, styleContextStack) {
16195 text = text.replace('\t', ' ');
16197 //TODO: refactor - extract from measure
16198 var fontName = getStyleProperty({}, styleContextStack, 'font', 'Roboto');
16199 var fontSize = getStyleProperty({}, styleContextStack, 'fontSize', 12);
16200 var bold = getStyleProperty({}, styleContextStack, 'bold', false);
16201 var italics = getStyleProperty({}, styleContextStack, 'italics', false);
16202 var lineHeight = getStyleProperty({}, styleContextStack, 'lineHeight', 1);
16204 var font = this.fontProvider.provideFont(fontName, bold, italics);
16207 width: font.widthOfString(removeDiacritics(text), fontSize),
16208 height: font.lineHeight(fontSize) * lineHeight,
16209 fontSize: fontSize,
16210 lineHeight: lineHeight,
16211 ascender: font.ascender / 1000 * fontSize,
16212 decender: font.decender / 1000 * fontSize
16216 function splitWords(text, noWrap) {
16218 text = text.replace('\t', ' ');
16222 array = [ text, "" ];
16224 array = text.match(WORD_RE);
16226 // i < l - 1, because the last match is always an empty string
16227 // other empty strings however are treated as new-lines
16228 for(var i = 0, l = array.length; i < l - 1; i++) {
16229 var item = array[i];
16231 var isNewLine = item.length === 0;
16234 results.push({text: item});
16237 var shouldAddLine = (results.length === 0 || results[results.length - 1].lineEnd);
16239 if (shouldAddLine) {
16240 results.push({ text: '', lineEnd: true });
16243 results[results.length - 1].lineEnd = true;
16250 function copyStyle(source, destination) {
16251 destination = destination || {};
16252 source = source || {}; //TODO: default style
16254 for(var key in source) {
16255 if (key != 'text' && source.hasOwnProperty(key)) {
16256 destination[key] = source[key];
16260 return destination;
16263 function normalizeTextArray(array) {
16266 if (typeof array == 'string' || array instanceof String) {
16270 for(var i = 0, l = array.length; i < l; i++) {
16271 var item = array[i];
16275 if (typeof item == 'string' || item instanceof String) {
16276 words = splitWords(item);
16278 words = splitWords(item.text, item.noWrap);
16279 style = copyStyle(item);
16282 for(var i2 = 0, l2 = words.length; i2 < l2; i2++) {
16284 text: words[i2].text
16287 if (words[i2].lineEnd) {
16288 result.lineEnd = true;
16291 copyStyle(style, result);
16293 results.push(result);
16300 //TODO: support for other languages (currently only polish is supported)
16301 var diacriticsMap = { 'Ą': 'A', 'Ć': 'C', 'Ę': 'E', 'Ł': 'L', 'Ń': 'N', 'Ó': 'O', 'Ś': 'S', 'Ź': 'Z', 'Ż': 'Z', 'ą': 'a', 'ć': 'c', 'ę': 'e', 'ł': 'l', 'ń': 'n', 'ó': 'o', 'ś': 's', 'ź': 'z', 'ż': 'z' };
16302 // ' << atom.io workaround
16304 function removeDiacritics(text) {
16305 return text.replace(/[^A-Za-z0-9\[\] ]/g, function(a) {
16306 return diacriticsMap[a] || a;
16310 function getStyleProperty(item, styleContextStack, property, defaultValue) {
16313 if (item[property] !== undefined && item[property] !== null) {
16314 // item defines this property
16315 return item[property];
16318 if (!styleContextStack) return defaultValue;
16320 styleContextStack.auto(item, function() {
16321 value = styleContextStack.getProperty(property);
16324 if (value !== null && value !== undefined) {
16327 return defaultValue;
16331 function measure(fontProvider, textArray, styleContextStack) {
16332 var normalized = normalizeTextArray(textArray);
16334 normalized.forEach(function(item) {
16335 var fontName = getStyleProperty(item, styleContextStack, 'font', 'Roboto');
16336 var fontSize = getStyleProperty(item, styleContextStack, 'fontSize', 12);
16337 var bold = getStyleProperty(item, styleContextStack, 'bold', false);
16338 var italics = getStyleProperty(item, styleContextStack, 'italics', false);
16339 var color = getStyleProperty(item, styleContextStack, 'color', 'black');
16340 var decoration = getStyleProperty(item, styleContextStack, 'decoration', null);
16341 var decorationColor = getStyleProperty(item, styleContextStack, 'decorationColor', null);
16342 var decorationStyle = getStyleProperty(item, styleContextStack, 'decorationStyle', null);
16343 var background = getStyleProperty(item, styleContextStack, 'background', null);
16344 var lineHeight = getStyleProperty(item, styleContextStack, 'lineHeight', 1);
16346 var font = fontProvider.provideFont(fontName, bold, italics);
16348 // TODO: character spacing
16349 item.width = font.widthOfString(removeDiacritics(item.text), fontSize);
16350 item.height = font.lineHeight(fontSize) * lineHeight;
16352 var leadingSpaces = item.text.match(LEADING);
16353 var trailingSpaces = item.text.match(TRAILING);
16354 if (leadingSpaces) {
16355 item.leadingCut = font.widthOfString(leadingSpaces[0], fontSize);
16358 item.leadingCut = 0;
16361 if (trailingSpaces) {
16362 item.trailingCut = font.widthOfString(trailingSpaces[0], fontSize);
16365 item.trailingCut = 0;
16368 item.alignment = getStyleProperty(item, styleContextStack, 'alignment', 'left');
16370 item.fontSize = fontSize;
16371 item.color = color;
16372 item.decoration = decoration;
16373 item.decorationColor = decorationColor;
16374 item.decorationStyle = decorationStyle;
16375 item.background = background;
16381 /****TESTS**** (add a leading '/' to uncomment)
16382 TextTools.prototype.splitWords = splitWords;
16383 TextTools.prototype.normalizeTextArray = normalizeTextArray;
16384 TextTools.prototype.measure = measure;
16388 module.exports = TextTools;
16393 /***/ function(module, exports) {
16395 /* jslint node: true */
16399 * Creates an instance of StyleContextStack used for style inheritance and style overrides
16402 * @this {StyleContextStack}
16403 * @param {Object} named styles dictionary
16404 * @param {Object} optional default style definition
16406 function StyleContextStack (styleDictionary, defaultStyle) {
16407 this.defaultStyle = defaultStyle || {};
16408 this.styleDictionary = styleDictionary;
16409 this.styleOverrides = [];
16413 * Creates cloned version of current stack
16414 * @return {StyleContextStack} current stack snapshot
16416 StyleContextStack.prototype.clone = function() {
16417 var stack = new StyleContextStack(this.styleDictionary, this.defaultStyle);
16419 this.styleOverrides.forEach(function(item) {
16420 stack.styleOverrides.push(item);
16427 * Pushes style-name or style-overrides-object onto the stack for future evaluation
16429 * @param {String|Object} styleNameOrOverride style-name (referring to styleDictionary) or
16430 * a new dictionary defining overriding properties
16432 StyleContextStack.prototype.push = function(styleNameOrOverride) {
16433 this.styleOverrides.push(styleNameOrOverride);
16437 * Removes last style-name or style-overrides-object from the stack
16439 * @param {Number} howMany - optional number of elements to be popped (if not specified,
16440 * one element will be removed from the stack)
16442 StyleContextStack.prototype.pop = function(howMany) {
16443 howMany = howMany || 1;
16445 while(howMany-- > 0) {
16446 this.styleOverrides.pop();
16451 * Creates a set of named styles or/and a style-overrides-object based on the item,
16452 * pushes those elements onto the stack for future evaluation and returns the number
16453 * of elements pushed, so they can be easily poped then.
16455 * @param {Object} item - an object with optional style property and/or style overrides
16456 * @return the number of items pushed onto the stack
16458 StyleContextStack.prototype.autopush = function(item) {
16459 if (typeof item === 'string' || item instanceof String) return 0;
16461 var styleNames = [];
16464 if (item.style instanceof Array) {
16465 styleNames = item.style;
16467 styleNames = [ item.style ];
16471 for(var i = 0, l = styleNames.length; i < l; i++) {
16472 this.push(styleNames[i]);
16475 var styleOverrideObject = {};
16476 var pushSOO = false;
16493 //'tableCellPadding'
16495 // 'headerCellBorder',
16496 // 'oddRowCellBorder',
16497 // 'evenRowCellBorder',
16499 ].forEach(function(key) {
16500 if (item[key] !== undefined && item[key] !== null) {
16501 styleOverrideObject[key] = item[key];
16507 this.push(styleOverrideObject);
16510 return styleNames.length + (pushSOO ? 1 : 0);
16514 * Automatically pushes elements onto the stack, using autopush based on item,
16515 * executes callback and then pops elements back. Returns value returned by callback
16517 * @param {Object} item - an object with optional style property and/or style overrides
16518 * @param {Function} function to be called between autopush and pop
16519 * @return {Object} value returned by callback
16521 StyleContextStack.prototype.auto = function(item, callback) {
16522 var pushedItems = this.autopush(item);
16523 var result = callback();
16525 if (pushedItems > 0) {
16526 this.pop(pushedItems);
16533 * Evaluates stack and returns value of a named property
16535 * @param {String} property - property name
16536 * @return property value or null if not found
16538 StyleContextStack.prototype.getProperty = function(property) {
16539 if (this.styleOverrides) {
16540 for(var i = this.styleOverrides.length - 1; i >= 0; i--) {
16541 var item = this.styleOverrides[i];
16543 if (typeof item == 'string' || item instanceof String) {
16544 // named-style-override
16546 var style = this.styleDictionary[item];
16547 if (style && style[property] !== null && style[property] !== undefined) {
16548 return style[property];
16551 // style-overrides-object
16552 if (item[property] !== undefined && item[property] !== null) {
16553 return item[property];
16559 return this.defaultStyle && this.defaultStyle[property];
16562 module.exports = StyleContextStack;
16567 /***/ function(module, exports) {
16569 /* jslint node: true */
16572 function buildColumnWidths(columns, availableWidth) {
16573 var autoColumns = [],
16574 autoMin = 0, autoMax = 0,
16579 initial_availableWidth = availableWidth;
16581 columns.forEach(function(column) {
16582 if (isAutoColumn(column)) {
16583 autoColumns.push(column);
16584 autoMin += column._minWidth;
16585 autoMax += column._maxWidth;
16586 } else if (isStarColumn(column)) {
16587 starColumns.push(column);
16588 starMaxMin = Math.max(starMaxMin, column._minWidth);
16589 starMaxMax = Math.max(starMaxMax, column._maxWidth);
16591 fixedColumns.push(column);
16595 fixedColumns.forEach(function(col) {
16596 // width specified as %
16597 if (typeof col.width === 'string' && /\d+%/.test(col.width) ) {
16598 col.width = parseFloat(col.width)*initial_availableWidth/100;
16600 if (col.width < (col._minWidth) && col.elasticWidth) {
16601 col._calcWidth = col._minWidth;
16603 col._calcWidth = col.width;
16606 availableWidth -= col._calcWidth;
16609 // http://www.freesoft.org/CIE/RFC/1942/18.htm
16610 // http://www.w3.org/TR/CSS2/tables.html#width-layout
16611 // http://dev.w3.org/csswg/css3-tables-algorithms/Overview.src.htm
16612 var minW = autoMin + starMaxMin * starColumns.length;
16613 var maxW = autoMax + starMaxMax * starColumns.length;
16614 if (minW >= availableWidth) {
16615 // case 1 - there's no way to fit all columns within available width
16616 // that's actually pretty bad situation with PDF as we have no horizontal scroll
16617 // no easy workaround (unless we decide, in the future, to split single words)
16618 // currently we simply use minWidths for all columns
16619 autoColumns.forEach(function(col) {
16620 col._calcWidth = col._minWidth;
16623 starColumns.forEach(function(col) {
16624 col._calcWidth = starMaxMin; // starMaxMin already contains padding
16627 if (maxW < availableWidth) {
16628 // case 2 - we can fit rest of the table within available space
16629 autoColumns.forEach(function(col) {
16630 col._calcWidth = col._maxWidth;
16631 availableWidth -= col._calcWidth;
16634 // maxW is too large, but minW fits within available width
16635 var W = availableWidth - minW;
16636 var D = maxW - minW;
16638 autoColumns.forEach(function(col) {
16639 var d = col._maxWidth - col._minWidth;
16640 col._calcWidth = col._minWidth + d * W / D;
16641 availableWidth -= col._calcWidth;
16645 if (starColumns.length > 0) {
16646 var starSize = availableWidth / starColumns.length;
16648 starColumns.forEach(function(col) {
16649 col._calcWidth = starSize;
16655 function isAutoColumn(column) {
16656 return column.width === 'auto';
16659 function isStarColumn(column) {
16660 return column.width === null || column.width === undefined || column.width === '*' || column.width === 'star';
16663 //TODO: refactor and reuse in measureTable
16664 function measureMinMax(columns) {
16665 var result = { min: 0, max: 0 };
16667 var maxStar = { min: 0, max: 0 };
16670 for(var i = 0, l = columns.length; i < l; i++) {
16671 var c = columns[i];
16673 if (isStarColumn(c)) {
16674 maxStar.min = Math.max(maxStar.min, c._minWidth);
16675 maxStar.max = Math.max(maxStar.max, c._maxWidth);
16677 } else if (isAutoColumn(c)) {
16678 result.min += c._minWidth;
16679 result.max += c._maxWidth;
16681 result.min += ((c.width !== undefined && c.width) || c._minWidth);
16682 result.max += ((c.width !== undefined && c.width) || c._maxWidth);
16687 result.min += starCount * maxStar.min;
16688 result.max += starCount * maxStar.max;
16695 * Calculates column widths
16699 buildColumnWidths: buildColumnWidths,
16700 measureMinMax: measureMinMax,
16701 isAutoColumn: isAutoColumn,
16702 isStarColumn: isStarColumn
16708 /***/ function(module, exports) {
16710 /* jslint node: true */
16716 for(var i = 0, l = arguments.length; i < l; i++) {
16717 var obj = arguments[i];
16720 for(var key in obj) {
16721 if (obj.hasOwnProperty(key)) {
16722 result[key] = obj[key];
16731 function offsetVector(vector, x, y) {
16732 switch(vector.type) {
16745 for(var i = 0, l = vector.points.length; i < l; i++) {
16746 vector.points[i].x += x;
16747 vector.points[i].y += y;
16753 function fontStringify(key, val) {
16754 if (key === 'font') {
16760 function isFunction(functionToCheck) {
16762 return functionToCheck && getType.toString.call(functionToCheck) === '[object Function]';
16768 fontStringify: fontStringify,
16769 offsetVector: offsetVector,
16770 isFunction: isFunction
16776 /***/ function(module, exports) {
16778 /* jslint node: true */
16781 /* qr.js -- QR code generator in Javascript (revision 2011-01-19)
16782 * Written by Kang Seonghoon <public+qrjs@mearie.org>.
16784 * This source code is in the public domain; if your jurisdiction does not
16785 * recognize the public domain the terms of Creative Commons CC0 license
16786 * apply. In the other words, you can always do what you want.
16790 // per-version information (cf. JIS X 0510:2004 pp. 30--36, 71)
16792 // [0]: the degree of generator polynomial by ECC levels
16793 // [1]: # of code blocks by ECC levels
16794 // [2]: left-top positions of alignment patterns
16796 // the number in this table (in particular, [0]) does not exactly match with
16797 // the numbers in the specficiation. see augumenteccs below for the reason.
16800 [[10, 7,17,13], [ 1, 1, 1, 1], []],
16801 [[16,10,28,22], [ 1, 1, 1, 1], [4,16]],
16802 [[26,15,22,18], [ 1, 1, 2, 2], [4,20]],
16803 [[18,20,16,26], [ 2, 1, 4, 2], [4,24]],
16804 [[24,26,22,18], [ 2, 1, 4, 4], [4,28]],
16805 [[16,18,28,24], [ 4, 2, 4, 4], [4,32]],
16806 [[18,20,26,18], [ 4, 2, 5, 6], [4,20,36]],
16807 [[22,24,26,22], [ 4, 2, 6, 6], [4,22,40]],
16808 [[22,30,24,20], [ 5, 2, 8, 8], [4,24,44]],
16809 [[26,18,28,24], [ 5, 4, 8, 8], [4,26,48]],
16810 [[30,20,24,28], [ 5, 4,11, 8], [4,28,52]],
16811 [[22,24,28,26], [ 8, 4,11,10], [4,30,56]],
16812 [[22,26,22,24], [ 9, 4,16,12], [4,32,60]],
16813 [[24,30,24,20], [ 9, 4,16,16], [4,24,44,64]],
16814 [[24,22,24,30], [10, 6,18,12], [4,24,46,68]],
16815 [[28,24,30,24], [10, 6,16,17], [4,24,48,72]],
16816 [[28,28,28,28], [11, 6,19,16], [4,28,52,76]],
16817 [[26,30,28,28], [13, 6,21,18], [4,28,54,80]],
16818 [[26,28,26,26], [14, 7,25,21], [4,28,56,84]],
16819 [[26,28,28,30], [16, 8,25,20], [4,32,60,88]],
16820 [[26,28,30,28], [17, 8,25,23], [4,26,48,70,92]],
16821 [[28,28,24,30], [17, 9,34,23], [4,24,48,72,96]],
16822 [[28,30,30,30], [18, 9,30,25], [4,28,52,76,100]],
16823 [[28,30,30,30], [20,10,32,27], [4,26,52,78,104]],
16824 [[28,26,30,30], [21,12,35,29], [4,30,56,82,108]],
16825 [[28,28,30,28], [23,12,37,34], [4,28,56,84,112]],
16826 [[28,30,30,30], [25,12,40,34], [4,32,60,88,116]],
16827 [[28,30,30,30], [26,13,42,35], [4,24,48,72,96,120]],
16828 [[28,30,30,30], [28,14,45,38], [4,28,52,76,100,124]],
16829 [[28,30,30,30], [29,15,48,40], [4,24,50,76,102,128]],
16830 [[28,30,30,30], [31,16,51,43], [4,28,54,80,106,132]],
16831 [[28,30,30,30], [33,17,54,45], [4,32,58,84,110,136]],
16832 [[28,30,30,30], [35,18,57,48], [4,28,56,84,112,140]],
16833 [[28,30,30,30], [37,19,60,51], [4,32,60,88,116,144]],
16834 [[28,30,30,30], [38,19,63,53], [4,28,52,76,100,124,148]],
16835 [[28,30,30,30], [40,20,66,56], [4,22,48,74,100,126,152]],
16836 [[28,30,30,30], [43,21,70,59], [4,26,52,78,104,130,156]],
16837 [[28,30,30,30], [45,22,74,62], [4,30,56,82,108,134,160]],
16838 [[28,30,30,30], [47,24,77,65], [4,24,52,80,108,136,164]],
16839 [[28,30,30,30], [49,25,81,68], [4,28,56,84,112,140,168]]];
16841 // mode constants (cf. Table 2 in JIS X 0510:2004 p. 16)
16842 var MODE_TERMINATOR = 0;
16843 var MODE_NUMERIC = 1, MODE_ALPHANUMERIC = 2, MODE_OCTET = 4, MODE_KANJI = 8;
16845 // validation regexps
16846 var NUMERIC_REGEXP = /^\d*$/;
16847 var ALPHANUMERIC_REGEXP = /^[A-Za-z0-9 $%*+\-./:]*$/;
16848 var ALPHANUMERIC_OUT_REGEXP = /^[A-Z0-9 $%*+\-./:]*$/;
16850 // ECC levels (cf. Table 22 in JIS X 0510:2004 p. 45)
16851 var ECCLEVEL_L = 1, ECCLEVEL_M = 0, ECCLEVEL_Q = 3, ECCLEVEL_H = 2;
16853 // GF(2^8)-to-integer mapping with a reducing polynomial x^8+x^4+x^3+x^2+1
16854 // invariant: GF256_MAP[GF256_INVMAP[i]] == i for all i in [1,256)
16855 var GF256_MAP = [], GF256_INVMAP = [-1];
16856 for (var i = 0, v = 1; i < 255; ++i) {
16858 GF256_INVMAP[v] = i;
16859 v = (v * 2) ^ (v >= 128 ? 0x11d : 0);
16862 // generator polynomials up to degree 30
16863 // (should match with polynomials in JIS X 0510:2004 Appendix A)
16865 // generator polynomial of degree K is product of (x-\alpha^0), (x-\alpha^1),
16866 // ..., (x-\alpha^(K-1)). by convention, we omit the K-th coefficient (always 1)
16867 // from the result; also other coefficients are written in terms of the exponent
16868 // to \alpha to avoid the redundant calculation. (see also calculateecc below.)
16869 var GF256_GENPOLY = [[]];
16870 for (var i = 0; i < 30; ++i) {
16871 var prevpoly = GF256_GENPOLY[i], poly = [];
16872 for (var j = 0; j <= i; ++j) {
16873 var a = (j < i ? GF256_MAP[prevpoly[j]] : 0);
16874 var b = GF256_MAP[(i + (prevpoly[j-1] || 0)) % 255];
16875 poly.push(GF256_INVMAP[a ^ b]);
16877 GF256_GENPOLY.push(poly);
16880 // alphanumeric character mapping (cf. Table 5 in JIS X 0510:2004 p. 19)
16881 var ALPHANUMERIC_MAP = {};
16882 for (var i = 0; i < 45; ++i) {
16883 ALPHANUMERIC_MAP['0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:'.charAt(i)] = i;
16886 // mask functions in terms of row # and column #
16887 // (cf. Table 20 in JIS X 0510:2004 p. 42)
16889 function(i,j) { return (i+j) % 2 === 0; },
16890 function(i,j) { return i % 2 === 0; },
16891 function(i,j) { return j % 3 === 0; },
16892 function(i,j) { return (i+j) % 3 === 0; },
16893 function(i,j) { return (((i/2)|0) + ((j/3)|0)) % 2 === 0; },
16894 function(i,j) { return (i*j) % 2 + (i*j) % 3 === 0; },
16895 function(i,j) { return ((i*j) % 2 + (i*j) % 3) % 2 === 0; },
16896 function(i,j) { return ((i+j) % 2 + (i*j) % 3) % 2 === 0; }];
16898 // returns true when the version information has to be embeded.
16899 var needsverinfo = function(ver) { return ver > 6; };
16901 // returns the size of entire QR code for given version.
16902 var getsizebyver = function(ver) { return 4 * ver + 17; };
16904 // returns the number of bits available for code words in this version.
16905 var nfullbits = function(ver) {
16907 * |<--------------- n --------------->|
16908 * | |<----- n-17 ---->| |
16909 * +-------+ ///+-------+ ----
16911 * | 9x9 | @@@@@ ///| 9x8 | |
16912 * | | # # # @5x5@ # # # | | |
16913 * +-------+ @@@@@ +-------+ |
16917 * @@@@@ @@@@@ @@@@@ | n
16918 * @5x5@ @5x5@ @5x5@ n-17
16919 * @@@@@ @@@@@ @@@@@ | |
16923 * +-------+ @@@@@ @@@@@ |
16924 * | | @5x5@ @5x5@ |
16925 * | 8x9 | @@@@@ @@@@@ |
16929 * when the entire code has n^2 modules and there are m^2-3 alignment
16930 * patterns, we have:
16931 * - 225 (= 9x9 + 9x8 + 8x9) modules for finder patterns and
16932 * format information;
16933 * - 2n-34 (= 2(n-17)) modules for timing patterns;
16934 * - 36 (= 3x6 + 6x3) modules for version information, if any;
16935 * - 25m^2-75 (= (m^2-3)(5x5)) modules for alignment patterns
16936 * if any, but 10m-20 (= 2(m-2)x5) of them overlaps with
16939 var v = VERSIONS[ver];
16940 var nbits = 16*ver*ver + 128*ver + 64; // finder, timing and format info.
16941 if (needsverinfo(ver)) nbits -= 36; // version information
16942 if (v[2].length) { // alignment patterns
16943 nbits -= 25 * v[2].length * v[2].length - 10 * v[2].length - 55;
16948 // returns the number of bits available for data portions (i.e. excludes ECC
16949 // bits but includes mode and length bits) in this version and ECC level.
16950 var ndatabits = function(ver, ecclevel) {
16951 var nbits = nfullbits(ver) & ~7; // no sub-octet code words
16952 var v = VERSIONS[ver];
16953 nbits -= 8 * v[0][ecclevel] * v[1][ecclevel]; // ecc bits
16957 // returns the number of bits required for the length of data.
16958 // (cf. Table 3 in JIS X 0510:2004 p. 16)
16959 var ndatalenbits = function(ver, mode) {
16961 case MODE_NUMERIC: return (ver < 10 ? 10 : ver < 27 ? 12 : 14);
16962 case MODE_ALPHANUMERIC: return (ver < 10 ? 9 : ver < 27 ? 11 : 13);
16963 case MODE_OCTET: return (ver < 10 ? 8 : 16);
16964 case MODE_KANJI: return (ver < 10 ? 8 : ver < 27 ? 10 : 12);
16968 // returns the maximum length of data possible in given configuration.
16969 var getmaxdatalen = function(ver, mode, ecclevel) {
16970 var nbits = ndatabits(ver, ecclevel) - 4 - ndatalenbits(ver, mode); // 4 for mode bits
16973 return ((nbits/10) | 0) * 3 + (nbits%10 < 4 ? 0 : nbits%10 < 7 ? 1 : 2);
16974 case MODE_ALPHANUMERIC:
16975 return ((nbits/11) | 0) * 2 + (nbits%11 < 6 ? 0 : 1);
16977 return (nbits/8) | 0;
16979 return (nbits/13) | 0;
16983 // checks if the given data can be encoded in given mode, and returns
16984 // the converted data for the further processing if possible. otherwise
16987 // this function does not check the length of data; it is a duty of
16988 // encode function below (as it depends on the version and ECC level too).
16989 var validatedata = function(mode, data) {
16992 if (!data.match(NUMERIC_REGEXP)) return null;
16995 case MODE_ALPHANUMERIC:
16996 if (!data.match(ALPHANUMERIC_REGEXP)) return null;
16997 return data.toUpperCase();
17000 if (typeof data === 'string') { // encode as utf-8 string
17002 for (var i = 0; i < data.length; ++i) {
17003 var ch = data.charCodeAt(i);
17006 } else if (ch < 0x800) {
17007 newdata.push(0xc0 | (ch >> 6),
17008 0x80 | (ch & 0x3f));
17009 } else if (ch < 0x10000) {
17010 newdata.push(0xe0 | (ch >> 12),
17011 0x80 | ((ch >> 6) & 0x3f),
17012 0x80 | (ch & 0x3f));
17014 newdata.push(0xf0 | (ch >> 18),
17015 0x80 | ((ch >> 12) & 0x3f),
17016 0x80 | ((ch >> 6) & 0x3f),
17017 0x80 | (ch & 0x3f));
17027 // returns the code words (sans ECC bits) for given data and configurations.
17028 // requires data to be preprocessed by validatedata. no length check is
17029 // performed, and everything has to be checked before calling this function.
17030 var encode = function(ver, mode, data, maxbuflen) {
17032 var bits = 0, remaining = 8;
17033 var datalen = data.length;
17035 // this function is intentionally no-op when n=0.
17036 var pack = function(x, n) {
17037 if (n >= remaining) {
17038 buf.push(bits | (x >> (n -= remaining)));
17039 while (n >= 8) buf.push((x >> (n -= 8)) & 255);
17043 if (n > 0) bits |= (x & ((1 << n) - 1)) << (remaining -= n);
17046 var nlenbits = ndatalenbits(ver, mode);
17048 pack(datalen, nlenbits);
17052 for (var i = 2; i < datalen; i += 3) {
17053 pack(parseInt(data.substring(i-2,i+1), 10), 10);
17055 pack(parseInt(data.substring(i-2), 10), [0,4,7][datalen%3]);
17058 case MODE_ALPHANUMERIC:
17059 for (var i = 1; i < datalen; i += 2) {
17060 pack(ALPHANUMERIC_MAP[data.charAt(i-1)] * 45 +
17061 ALPHANUMERIC_MAP[data.charAt(i)], 11);
17063 if (datalen % 2 == 1) {
17064 pack(ALPHANUMERIC_MAP[data.charAt(i-1)], 6);
17069 for (var i = 0; i < datalen; ++i) {
17075 // final bits. it is possible that adding terminator causes the buffer
17076 // to overflow, but then the buffer truncated to the maximum size will
17077 // be valid as the truncated terminator mode bits and padding is
17078 // identical in appearance (cf. JIS X 0510:2004 sec 8.4.8).
17079 pack(MODE_TERMINATOR, 4);
17080 if (remaining < 8) buf.push(bits);
17082 // the padding to fill up the remaining space. we should not add any
17083 // words when the overflow already occurred.
17084 while (buf.length + 1 < maxbuflen) buf.push(0xec, 0x11);
17085 if (buf.length < maxbuflen) buf.push(0xec);
17089 // calculates ECC code words for given code words and generator polynomial.
17091 // this is quite similar to CRC calculation as both Reed-Solomon and CRC use
17092 // the certain kind of cyclic codes, which is effectively the division of
17093 // zero-augumented polynomial by the generator polynomial. the only difference
17094 // is that Reed-Solomon uses GF(2^8), instead of CRC's GF(2), and Reed-Solomon
17095 // uses the different generator polynomial than CRC's.
17096 var calculateecc = function(poly, genpoly) {
17097 var modulus = poly.slice(0);
17098 var polylen = poly.length, genpolylen = genpoly.length;
17099 for (var i = 0; i < genpolylen; ++i) modulus.push(0);
17100 for (var i = 0; i < polylen; ) {
17101 var quotient = GF256_INVMAP[modulus[i++]];
17102 if (quotient >= 0) {
17103 for (var j = 0; j < genpolylen; ++j) {
17104 modulus[i+j] ^= GF256_MAP[(quotient + genpoly[j]) % 255];
17108 return modulus.slice(polylen);
17111 // auguments ECC code words to given code words. the resulting words are
17112 // ready to be encoded in the matrix.
17114 // the much of actual augumenting procedure follows JIS X 0510:2004 sec 8.7.
17115 // the code is simplified using the fact that the size of each code & ECC
17116 // blocks is almost same; for example, when we have 4 blocks and 46 data words
17117 // the number of code words in those blocks are 11, 11, 12, 12 respectively.
17118 var augumenteccs = function(poly, nblocks, genpoly) {
17120 var subsize = (poly.length / nblocks) | 0, subsize0 = 0;
17121 var pivot = nblocks - poly.length % nblocks;
17122 for (var i = 0; i < pivot; ++i) {
17123 subsizes.push(subsize0);
17124 subsize0 += subsize;
17126 for (var i = pivot; i < nblocks; ++i) {
17127 subsizes.push(subsize0);
17128 subsize0 += subsize+1;
17130 subsizes.push(subsize0);
17133 for (var i = 0; i < nblocks; ++i) {
17134 eccs.push(calculateecc(poly.slice(subsizes[i], subsizes[i+1]), genpoly));
17138 var nitemsperblock = (poly.length / nblocks) | 0;
17139 for (var i = 0; i < nitemsperblock; ++i) {
17140 for (var j = 0; j < nblocks; ++j) {
17141 result.push(poly[subsizes[j] + i]);
17144 for (var j = pivot; j < nblocks; ++j) {
17145 result.push(poly[subsizes[j+1] - 1]);
17147 for (var i = 0; i < genpoly.length; ++i) {
17148 for (var j = 0; j < nblocks; ++j) {
17149 result.push(eccs[j][i]);
17155 // auguments BCH(p+q,q) code to the polynomial over GF(2), given the proper
17156 // genpoly. the both input and output are in binary numbers, and unlike
17157 // calculateecc genpoly should include the 1 bit for the highest degree.
17159 // actual polynomials used for this procedure are as follows:
17160 // - p=10, q=5, genpoly=x^10+x^8+x^5+x^4+x^2+x+1 (JIS X 0510:2004 Appendix C)
17161 // - p=18, q=6, genpoly=x^12+x^11+x^10+x^9+x^8+x^5+x^2+1 (ibid. Appendix D)
17162 var augumentbch = function(poly, p, genpoly, q) {
17163 var modulus = poly << q;
17164 for (var i = p - 1; i >= 0; --i) {
17165 if ((modulus >> (q+i)) & 1) modulus ^= genpoly << i;
17167 return (poly << q) | modulus;
17170 // creates the base matrix for given version. it returns two matrices, one of
17171 // them is the actual one and the another represents the "reserved" portion
17172 // (e.g. finder and timing patterns) of the matrix.
17174 // some entries in the matrix may be undefined, rather than 0 or 1. this is
17175 // intentional (no initialization needed!), and putdata below will fill
17176 // the remaining ones.
17177 var makebasematrix = function(ver) {
17178 var v = VERSIONS[ver], n = getsizebyver(ver);
17179 var matrix = [], reserved = [];
17180 for (var i = 0; i < n; ++i) {
17185 var blit = function(y, x, h, w, bits) {
17186 for (var i = 0; i < h; ++i) {
17187 for (var j = 0; j < w; ++j) {
17188 matrix[y+i][x+j] = (bits[i] >> j) & 1;
17189 reserved[y+i][x+j] = 1;
17194 // finder patterns and a part of timing patterns
17195 // will also mark the format information area (not yet written) as reserved.
17196 blit(0, 0, 9, 9, [0x7f, 0x41, 0x5d, 0x5d, 0x5d, 0x41, 0x17f, 0x00, 0x40]);
17197 blit(n-8, 0, 8, 9, [0x100, 0x7f, 0x41, 0x5d, 0x5d, 0x5d, 0x41, 0x7f]);
17198 blit(0, n-8, 9, 8, [0xfe, 0x82, 0xba, 0xba, 0xba, 0x82, 0xfe, 0x00, 0x00]);
17200 // the rest of timing patterns
17201 for (var i = 9; i < n-8; ++i) {
17202 matrix[6][i] = matrix[i][6] = ~i & 1;
17203 reserved[6][i] = reserved[i][6] = 1;
17206 // alignment patterns
17207 var aligns = v[2], m = aligns.length;
17208 for (var i = 0; i < m; ++i) {
17209 var minj = (i===0 || i===m-1 ? 1 : 0), maxj = (i===0 ? m-1 : m);
17210 for (var j = minj; j < maxj; ++j) {
17211 blit(aligns[i], aligns[j], 5, 5, [0x1f, 0x11, 0x15, 0x11, 0x1f]);
17215 // version information
17216 if (needsverinfo(ver)) {
17217 var code = augumentbch(ver, 6, 0x1f25, 12);
17219 for (var i = 0; i < 6; ++i) {
17220 for (var j = 0; j < 3; ++j) {
17221 matrix[i][(n-11)+j] = matrix[(n-11)+j][i] = (code >> k++) & 1;
17222 reserved[i][(n-11)+j] = reserved[(n-11)+j][i] = 1;
17227 return {matrix: matrix, reserved: reserved};
17230 // fills the data portion (i.e. unmarked in reserved) of the matrix with given
17231 // code words. the size of code words should be no more than available bits,
17232 // and remaining bits are padded to 0 (cf. JIS X 0510:2004 sec 8.7.3).
17233 var putdata = function(matrix, reserved, buf) {
17234 var n = matrix.length;
17235 var k = 0, dir = -1;
17236 for (var i = n-1; i >= 0; i -= 2) {
17237 if (i == 6) --i; // skip the entire timing pattern column
17238 var jj = (dir < 0 ? n-1 : 0);
17239 for (var j = 0; j < n; ++j) {
17240 for (var ii = i; ii > i-2; --ii) {
17241 if (!reserved[jj][ii]) {
17242 // may overflow, but (undefined >> x)
17243 // is 0 so it will auto-pad to zero.
17244 matrix[jj][ii] = (buf[k >> 3] >> (~k&7)) & 1;
17255 // XOR-masks the data portion of the matrix. repeating the call with the same
17256 // arguments will revert the prior call (convenient in the matrix evaluation).
17257 var maskdata = function(matrix, reserved, mask) {
17258 var maskf = MASKFUNCS[mask];
17259 var n = matrix.length;
17260 for (var i = 0; i < n; ++i) {
17261 for (var j = 0; j < n; ++j) {
17262 if (!reserved[i][j]) matrix[i][j] ^= maskf(i,j);
17268 // puts the format information.
17269 var putformatinfo = function(matrix, reserved, ecclevel, mask) {
17270 var n = matrix.length;
17271 var code = augumentbch((ecclevel << 3) | mask, 5, 0x537, 10) ^ 0x5412;
17272 for (var i = 0; i < 15; ++i) {
17273 var r = [0,1,2,3,4,5,7,8,n-7,n-6,n-5,n-4,n-3,n-2,n-1][i];
17274 var c = [n-1,n-2,n-3,n-4,n-5,n-6,n-7,n-8,7,5,4,3,2,1,0][i];
17275 matrix[r][8] = matrix[8][c] = (code >> i) & 1;
17276 // we don't have to mark those bits reserved; always done
17277 // in makebasematrix above.
17282 // evaluates the resulting matrix and returns the score (lower is better).
17283 // (cf. JIS X 0510:2004 sec 8.8.2)
17285 // the evaluation procedure tries to avoid the problematic patterns naturally
17286 // occuring from the original matrix. for example, it penaltizes the patterns
17287 // which just look like the finder pattern which will confuse the decoder.
17288 // we choose the mask which results in the lowest score among 8 possible ones.
17290 // note: zxing seems to use the same procedure and in many cases its choice
17291 // agrees to ours, but sometimes it does not. practically it doesn't matter.
17292 var evaluatematrix = function(matrix) {
17293 // N1+(k-5) points for each consecutive row of k same-colored modules,
17294 // where k >= 5. no overlapping row counts.
17295 var PENALTY_CONSECUTIVE = 3;
17296 // N2 points for each 2x2 block of same-colored modules.
17297 // overlapping block does count.
17298 var PENALTY_TWOBYTWO = 3;
17299 // N3 points for each pattern with >4W:1B:1W:3B:1W:1B or
17300 // 1B:1W:3B:1W:1B:>4W, or their multiples (e.g. highly unlikely,
17301 // but 13W:3B:3W:9B:3W:3B counts).
17302 var PENALTY_FINDERLIKE = 40;
17303 // N4*k points for every (5*k)% deviation from 50% black density.
17304 // i.e. k=1 for 55~60% and 40~45%, k=2 for 60~65% and 35~40%, etc.
17305 var PENALTY_DENSITY = 10;
17307 var evaluategroup = function(groups) { // assumes [W,B,W,B,W,...,B,W]
17309 for (var i = 0; i < groups.length; ++i) {
17310 if (groups[i] >= 5) score += PENALTY_CONSECUTIVE + (groups[i]-5);
17312 for (var i = 5; i < groups.length; i += 2) {
17314 if (groups[i-1] == p && groups[i-2] == 3*p && groups[i-3] == p &&
17315 groups[i-4] == p && (groups[i-5] >= 4*p || groups[i+1] >= 4*p)) {
17316 // this part differs from zxing...
17317 score += PENALTY_FINDERLIKE;
17323 var n = matrix.length;
17324 var score = 0, nblacks = 0;
17325 for (var i = 0; i < n; ++i) {
17326 var row = matrix[i];
17329 // evaluate the current row
17330 groups = [0]; // the first empty group of white
17331 for (var j = 0; j < n; ) {
17333 for (k = 0; j < n && row[j]; ++k) ++j;
17335 for (k = 0; j < n && !row[j]; ++k) ++j;
17338 score += evaluategroup(groups);
17340 // evaluate the current column
17342 for (var j = 0; j < n; ) {
17344 for (k = 0; j < n && matrix[j][i]; ++k) ++j;
17346 for (k = 0; j < n && !matrix[j][i]; ++k) ++j;
17349 score += evaluategroup(groups);
17351 // check the 2x2 box and calculate the density
17352 var nextrow = matrix[i+1] || [];
17354 for (var j = 1; j < n; ++j) {
17357 // at least comparison with next row should be strict...
17358 if (row[j-1] == p && nextrow[j] === p && nextrow[j-1] === p) {
17359 score += PENALTY_TWOBYTWO;
17364 score += PENALTY_DENSITY * ((Math.abs(nblacks / n / n - 0.5) / 0.05) | 0);
17368 // returns the fully encoded QR code matrix which contains given data.
17369 // it also chooses the best mask automatically when mask is -1.
17370 var generate = function(data, ver, mode, ecclevel, mask) {
17371 var v = VERSIONS[ver];
17372 var buf = encode(ver, mode, data, ndatabits(ver, ecclevel) >> 3);
17373 buf = augumenteccs(buf, v[1][ecclevel], GF256_GENPOLY[v[0][ecclevel]]);
17375 var result = makebasematrix(ver);
17376 var matrix = result.matrix, reserved = result.reserved;
17377 putdata(matrix, reserved, buf);
17380 // find the best mask
17381 maskdata(matrix, reserved, 0);
17382 putformatinfo(matrix, reserved, ecclevel, 0);
17383 var bestmask = 0, bestscore = evaluatematrix(matrix);
17384 maskdata(matrix, reserved, 0);
17385 for (mask = 1; mask < 8; ++mask) {
17386 maskdata(matrix, reserved, mask);
17387 putformatinfo(matrix, reserved, ecclevel, mask);
17388 var score = evaluatematrix(matrix);
17389 if (bestscore > score) {
17393 maskdata(matrix, reserved, mask);
17398 maskdata(matrix, reserved, mask);
17399 putformatinfo(matrix, reserved, ecclevel, mask);
17403 // the public interface is trivial; the options available are as follows:
17405 // - version: an integer in [1,40]. when omitted (or -1) the smallest possible
17406 // version is chosen.
17407 // - mode: one of 'numeric', 'alphanumeric', 'octet'. when omitted the smallest
17408 // possible mode is chosen.
17409 // - eccLevel: one of 'L', 'M', 'Q', 'H'. defaults to 'L'.
17410 // - mask: an integer in [0,7]. when omitted (or -1) the best mask is chosen.
17413 function generateFrame(data, options) {
17414 var MODES = {'numeric': MODE_NUMERIC, 'alphanumeric': MODE_ALPHANUMERIC,
17415 'octet': MODE_OCTET};
17416 var ECCLEVELS = {'L': ECCLEVEL_L, 'M': ECCLEVEL_M, 'Q': ECCLEVEL_Q,
17419 options = options || {};
17420 var ver = options.version || -1;
17421 var ecclevel = ECCLEVELS[(options.eccLevel || 'L').toUpperCase()];
17422 var mode = options.mode ? MODES[options.mode.toLowerCase()] : -1;
17423 var mask = 'mask' in options ? options.mask : -1;
17426 if (typeof data === 'string') {
17427 if (data.match(NUMERIC_REGEXP)) {
17428 mode = MODE_NUMERIC;
17429 } else if (data.match(ALPHANUMERIC_OUT_REGEXP)) {
17430 // while encode supports case-insensitive encoding, we restrict the data to be uppercased when auto-selecting the mode.
17431 mode = MODE_ALPHANUMERIC;
17438 } else if (!(mode == MODE_NUMERIC || mode == MODE_ALPHANUMERIC ||
17439 mode == MODE_OCTET)) {
17440 throw 'invalid or unsupported mode';
17443 data = validatedata(mode, data);
17444 if (data === null) throw 'invalid data format';
17446 if (ecclevel < 0 || ecclevel > 3) throw 'invalid ECC level';
17449 for (ver = 1; ver <= 40; ++ver) {
17450 if (data.length <= getmaxdatalen(ver, mode, ecclevel)) break;
17452 if (ver > 40) throw 'too large data for the Qr format';
17453 } else if (ver < 1 || ver > 40) {
17454 throw 'invalid Qr version! should be between 1 and 40';
17457 if (mask != -1 && (mask < 0 || mask > 8)) throw 'invalid mask';
17458 //console.log('version:', ver, 'mode:', mode, 'ECC:', ecclevel, 'mask:', mask )
17459 return generate(data, ver, mode, ecclevel, mask);
17464 // - modulesize: a number. this is a size of each modules in pixels, and
17465 // defaults to 5px.
17466 // - margin: a number. this is a size of margin in *modules*, and defaults to
17467 // 4 (white modules). the specficiation mandates the margin no less than 4
17468 // modules, so it is better not to alter this value unless you know what
17470 function buildCanvas(data, options) {
17473 var background = data.background || '#fff';
17474 var foreground = data.foreground || '#000';
17475 //var margin = options.margin || 4;
17476 var matrix = generateFrame(data, options);
17477 var n = matrix.length;
17478 var modSize = Math.floor( options.fit ? options.fit/n : 5 );
17479 var size = n * modSize;
17483 x: 0, y: 0, w: size, h: size, lineWidth: 0, color: background
17486 for (var i = 0; i < n; ++i) {
17487 for (var j = 0; j < n; ++j) {
17509 function measure(node) {
17510 var cd = buildCanvas(node.qr, node);
17511 node._canvas = cd.canvas;
17512 node._width = node._height = node._minWidth = node._maxWidth = node._minHeight = node._maxHeight = cd.size;
17522 /***/ function(module, exports, __webpack_require__) {
17524 /* jslint node: true */
17527 var TraversalTracker = __webpack_require__(12);
17530 * Creates an instance of DocumentContext - a store for current x, y positions and available width/height.
17531 * It facilitates column divisions and vertical sync
17533 function DocumentContext(pageSize, pageMargins) {
17536 this.pageMargins = pageMargins;
17538 this.x = pageMargins.left;
17539 this.availableWidth = pageSize.width - pageMargins.left - pageMargins.right;
17540 this.availableHeight = 0;
17543 this.snapshots = [];
17545 this.endingCell = null;
17547 this.tracker = new TraversalTracker();
17549 this.addPage(pageSize);
17552 DocumentContext.prototype.beginColumnGroup = function() {
17553 this.snapshots.push({
17556 availableHeight: this.availableHeight,
17557 availableWidth: this.availableWidth,
17559 bottomMost: { y: this.y, page: this.page },
17560 endingCell: this.endingCell,
17561 lastColumnWidth: this.lastColumnWidth
17564 this.lastColumnWidth = 0;
17567 DocumentContext.prototype.beginColumn = function(width, offset, endingCell) {
17568 var saved = this.snapshots[this.snapshots.length - 1];
17570 this.calculateBottomMost(saved);
17572 this.endingCell = endingCell;
17573 this.page = saved.page;
17574 this.x = this.x + this.lastColumnWidth + (offset || 0);
17576 this.availableWidth = width; //saved.availableWidth - offset;
17577 this.availableHeight = saved.availableHeight;
17579 this.lastColumnWidth = width;
17582 DocumentContext.prototype.calculateBottomMost = function(destContext) {
17583 if (this.endingCell) {
17584 this.saveContextInEndingCell(this.endingCell);
17585 this.endingCell = null;
17587 destContext.bottomMost = bottomMostContext(this, destContext.bottomMost);
17591 DocumentContext.prototype.markEnding = function(endingCell) {
17592 this.page = endingCell._columnEndingContext.page;
17593 this.x = endingCell._columnEndingContext.x;
17594 this.y = endingCell._columnEndingContext.y;
17595 this.availableWidth = endingCell._columnEndingContext.availableWidth;
17596 this.availableHeight = endingCell._columnEndingContext.availableHeight;
17597 this.lastColumnWidth = endingCell._columnEndingContext.lastColumnWidth;
17600 DocumentContext.prototype.saveContextInEndingCell = function(endingCell) {
17601 endingCell._columnEndingContext = {
17605 availableHeight: this.availableHeight,
17606 availableWidth: this.availableWidth,
17607 lastColumnWidth: this.lastColumnWidth
17611 DocumentContext.prototype.completeColumnGroup = function() {
17612 var saved = this.snapshots.pop();
17614 this.calculateBottomMost(saved);
17616 this.endingCell = null;
17618 this.y = saved.bottomMost.y;
17619 this.page = saved.bottomMost.page;
17620 this.availableWidth = saved.availableWidth;
17621 this.availableHeight = saved.bottomMost.availableHeight;
17622 this.lastColumnWidth = saved.lastColumnWidth;
17625 DocumentContext.prototype.addMargin = function(left, right) {
17627 this.availableWidth -= left + (right || 0);
17630 DocumentContext.prototype.moveDown = function(offset) {
17632 this.availableHeight -= offset;
17634 return this.availableHeight > 0;
17637 DocumentContext.prototype.initializePage = function() {
17638 this.y = this.pageMargins.top;
17639 this.availableHeight = this.getCurrentPage().pageSize.height - this.pageMargins.top - this.pageMargins.bottom;
17640 this.pageSnapshot().availableWidth = this.getCurrentPage().pageSize.width - this.pageMargins.left - this.pageMargins.right;
17643 DocumentContext.prototype.pageSnapshot = function(){
17644 if(this.snapshots[0]){
17645 return this.snapshots[0];
17651 DocumentContext.prototype.moveTo = function(x,y) {
17652 if(x !== undefined && x !== null) {
17654 this.availableWidth = this.getCurrentPage().pageSize.width - this.x - this.pageMargins.right;
17656 if(y !== undefined && y !== null){
17658 this.availableHeight = this.getCurrentPage().pageSize.height - this.y - this.pageMargins.bottom;
17662 DocumentContext.prototype.beginDetachedBlock = function() {
17663 this.snapshots.push({
17666 availableHeight: this.availableHeight,
17667 availableWidth: this.availableWidth,
17669 endingCell: this.endingCell,
17670 lastColumnWidth: this.lastColumnWidth
17674 DocumentContext.prototype.endDetachedBlock = function() {
17675 var saved = this.snapshots.pop();
17679 this.availableWidth = saved.availableWidth;
17680 this.availableHeight = saved.availableHeight;
17681 this.page = saved.page;
17682 this.endingCell = saved.endingCell;
17683 this.lastColumnWidth = saved.lastColumnWidth;
17686 function pageOrientation(pageOrientationString, currentPageOrientation){
17687 if(pageOrientationString === undefined) {
17688 return currentPageOrientation;
17689 } else if(pageOrientationString === 'landscape'){
17690 return 'landscape';
17696 var getPageSize = function (currentPage, newPageOrientation) {
17698 newPageOrientation = pageOrientation(newPageOrientation, currentPage.pageSize.orientation);
17700 if(newPageOrientation !== currentPage.pageSize.orientation) {
17702 orientation: newPageOrientation,
17703 width: currentPage.pageSize.height,
17704 height: currentPage.pageSize.width
17708 orientation: currentPage.pageSize.orientation,
17709 width: currentPage.pageSize.width,
17710 height: currentPage.pageSize.height
17717 DocumentContext.prototype.moveToNextPage = function(pageOrientation) {
17718 var nextPageIndex = this.page + 1;
17720 var prevPage = this.page;
17721 var prevY = this.y;
17723 var createNewPage = nextPageIndex >= this.pages.length;
17724 if (createNewPage) {
17725 this.addPage(getPageSize(this.getCurrentPage(), pageOrientation));
17727 this.page = nextPageIndex;
17728 this.initializePage();
17732 newPageCreated: createNewPage,
17733 prevPage: prevPage,
17740 DocumentContext.prototype.addPage = function(pageSize) {
17741 var page = { items: [], pageSize: pageSize };
17742 this.pages.push(page);
17743 this.page = this.pages.length - 1;
17744 this.initializePage();
17746 this.tracker.emit('pageAdded');
17751 DocumentContext.prototype.getCurrentPage = function() {
17752 if (this.page < 0 || this.page >= this.pages.length) return null;
17754 return this.pages[this.page];
17757 DocumentContext.prototype.getCurrentPosition = function() {
17758 var pageSize = this.getCurrentPage().pageSize;
17759 var innerHeight = pageSize.height - this.pageMargins.top - this.pageMargins.bottom;
17760 var innerWidth = pageSize.width - this.pageMargins.left - this.pageMargins.right;
17763 pageNumber: this.page + 1,
17764 pageOrientation: pageSize.orientation,
17765 pageInnerHeight: innerHeight,
17766 pageInnerWidth: innerWidth,
17769 verticalRatio: ((this.y - this.pageMargins.top) / innerHeight),
17770 horizontalRatio: ((this.x - this.pageMargins.left) / innerWidth)
17774 function bottomMostContext(c1, c2) {
17777 if (c1.page > c2.page) r = c1;
17778 else if (c2.page > c1.page) r = c2;
17779 else r = (c1.y > c2.y) ? c1 : c2;
17785 availableHeight: r.availableHeight,
17786 availableWidth: r.availableWidth
17790 /****TESTS**** (add a leading '/' to uncomment)
17791 DocumentContext.bottomMostContext = bottomMostContext;
17794 module.exports = DocumentContext;
17799 /***/ function(module, exports, __webpack_require__) {
17801 /* jslint node: true */
17804 var ElementWriter = __webpack_require__(21);
17807 * Creates an instance of PageElementWriter - an extended ElementWriter
17808 * which can handle:
17809 * - page-breaks (it adds new pages when there's not enough space left),
17810 * - repeatable fragments (like table-headers, which are repeated everytime
17811 * a page-break occurs)
17812 * - transactions (used for unbreakable-blocks when we want to make sure
17813 * whole block will be rendered on the same page)
17815 function PageElementWriter(context, tracker) {
17816 this.transactionLevel = 0;
17817 this.repeatables = [];
17818 this.tracker = tracker;
17819 this.writer = new ElementWriter(context, tracker);
17822 function fitOnPage(self, addFct){
17823 var position = addFct(self);
17825 self.moveToNextPage();
17826 position = addFct(self);
17831 PageElementWriter.prototype.addLine = function(line, dontUpdateContextPosition, index) {
17832 return fitOnPage(this, function(self){
17833 return self.writer.addLine(line, dontUpdateContextPosition, index);
17837 PageElementWriter.prototype.addImage = function(image, index) {
17838 return fitOnPage(this, function(self){
17839 return self.writer.addImage(image, index);
17843 PageElementWriter.prototype.addQr = function(qr, index) {
17844 return fitOnPage(this, function(self){
17845 return self.writer.addQr(qr, index);
17849 PageElementWriter.prototype.addVector = function(vector, ignoreContextX, ignoreContextY, index) {
17850 return this.writer.addVector(vector, ignoreContextX, ignoreContextY, index);
17853 PageElementWriter.prototype.addFragment = function(fragment, useBlockXOffset, useBlockYOffset, dontUpdateContextPosition) {
17854 if (!this.writer.addFragment(fragment, useBlockXOffset, useBlockYOffset, dontUpdateContextPosition)) {
17855 this.moveToNextPage();
17856 this.writer.addFragment(fragment, useBlockXOffset, useBlockYOffset, dontUpdateContextPosition);
17860 PageElementWriter.prototype.moveToNextPage = function(pageOrientation) {
17862 var nextPage = this.writer.context.moveToNextPage(pageOrientation);
17864 if (nextPage.newPageCreated) {
17865 this.repeatables.forEach(function(rep) {
17866 this.writer.addFragment(rep, true);
17869 this.repeatables.forEach(function(rep) {
17870 this.writer.context.moveDown(rep.height);
17874 this.writer.tracker.emit('pageChanged', {
17875 prevPage: nextPage.prevPage,
17876 prevY: nextPage.prevY,
17881 PageElementWriter.prototype.beginUnbreakableBlock = function(width, height) {
17882 if (this.transactionLevel++ === 0) {
17883 this.originalX = this.writer.context.x;
17884 this.writer.pushContext(width, height);
17888 PageElementWriter.prototype.commitUnbreakableBlock = function(forcedX, forcedY) {
17889 if (--this.transactionLevel === 0) {
17890 var unbreakableContext = this.writer.context;
17891 this.writer.popContext();
17893 var nbPages = unbreakableContext.pages.length;
17895 // no support for multi-page unbreakableBlocks
17896 var fragment = unbreakableContext.pages[0];
17897 fragment.xOffset = forcedX;
17898 fragment.yOffset = forcedY;
17900 //TODO: vectors can influence height in some situations
17902 // on out-of-context blocs (headers, footers, background) height should be the whole DocumentContext height
17903 if (forcedX !== undefined || forcedY !== undefined) {
17904 fragment.height = unbreakableContext.getCurrentPage().pageSize.height - unbreakableContext.pageMargins.top - unbreakableContext.pageMargins.bottom;
17906 fragment.height = this.writer.context.getCurrentPage().pageSize.height - this.writer.context.pageMargins.top - this.writer.context.pageMargins.bottom;
17907 for (var i = 0, l = this.repeatables.length; i < l; i++) {
17908 fragment.height -= this.repeatables[i].height;
17912 fragment.height = unbreakableContext.y;
17915 if (forcedX !== undefined || forcedY !== undefined) {
17916 this.writer.addFragment(fragment, true, true, true);
17918 this.addFragment(fragment);
17924 PageElementWriter.prototype.currentBlockToRepeatable = function() {
17925 var unbreakableContext = this.writer.context;
17926 var rep = { items: [] };
17928 unbreakableContext.pages[0].items.forEach(function(item) {
17929 rep.items.push(item);
17932 rep.xOffset = this.originalX;
17934 //TODO: vectors can influence height in some situations
17935 rep.height = unbreakableContext.y;
17940 PageElementWriter.prototype.pushToRepeatables = function(rep) {
17941 this.repeatables.push(rep);
17944 PageElementWriter.prototype.popFromRepeatables = function() {
17945 this.repeatables.pop();
17948 PageElementWriter.prototype.context = function() {
17949 return this.writer.context;
17952 module.exports = PageElementWriter;
17957 /***/ function(module, exports, __webpack_require__) {
17959 /* jslint node: true */
17962 var Line = __webpack_require__(22);
17963 var pack = __webpack_require__(17).pack;
17964 var offsetVector = __webpack_require__(17).offsetVector;
17965 var DocumentContext = __webpack_require__(19);
17968 * Creates an instance of ElementWriter - a line/vector writer, which adds
17969 * elements to current page and sets their positions based on the context
17971 function ElementWriter(context, tracker) {
17972 this.context = context;
17973 this.contextStack = [];
17974 this.tracker = tracker;
17977 function addPageItem(page, item, index) {
17978 if(index === null || index === undefined || index < 0 || index > page.items.length) {
17979 page.items.push(item);
17981 page.items.splice(index, 0, item);
17985 ElementWriter.prototype.addLine = function(line, dontUpdateContextPosition, index) {
17986 var height = line.getHeight();
17987 var context = this.context;
17988 var page = context.getCurrentPage(),
17989 position = this.getCurrentPositionOnPage();
17991 if (context.availableHeight < height || !page) {
17995 line.x = context.x + (line.x || 0);
17996 line.y = context.y + (line.y || 0);
17998 this.alignLine(line);
18000 addPageItem(page, {
18004 this.tracker.emit('lineAdded', line);
18006 if (!dontUpdateContextPosition) context.moveDown(height);
18011 ElementWriter.prototype.alignLine = function(line) {
18012 var width = this.context.availableWidth;
18013 var lineWidth = line.getWidth();
18015 var alignment = line.inlines && line.inlines.length > 0 && line.inlines[0].alignment;
18018 switch(alignment) {
18020 offset = width - lineWidth;
18023 offset = (width - lineWidth) / 2;
18028 line.x = (line.x || 0) + offset;
18031 if (alignment === 'justify' &&
18032 !line.newLineForced &&
18033 !line.lastLineInParagraph &&
18034 line.inlines.length > 1) {
18035 var additionalSpacing = (width - lineWidth) / (line.inlines.length - 1);
18037 for(var i = 1, l = line.inlines.length; i < l; i++) {
18038 offset = i * additionalSpacing;
18040 line.inlines[i].x += offset;
18045 ElementWriter.prototype.addImage = function(image, index) {
18046 var context = this.context;
18047 var page = context.getCurrentPage(),
18048 position = this.getCurrentPositionOnPage();
18050 if (context.availableHeight < image._height || !page) {
18054 image.x = context.x + (image.x || 0);
18055 image.y = context.y;
18057 this.alignImage(image);
18059 addPageItem(page, {
18064 context.moveDown(image._height);
18069 ElementWriter.prototype.addQr = function(qr, index) {
18070 var context = this.context;
18071 var page = context.getCurrentPage(),
18072 position = this.getCurrentPositionOnPage();
18074 if (context.availableHeight < qr._height || !page) {
18078 qr.x = context.x + (qr.x || 0);
18081 this.alignImage(qr);
18083 for (var i=0, l=qr._canvas.length; i < l; i++) {
18084 var vector = qr._canvas[i];
18087 this.addVector(vector, true, true, index);
18090 context.moveDown(qr._height);
18095 ElementWriter.prototype.alignImage = function(image) {
18096 var width = this.context.availableWidth;
18097 var imageWidth = image._minWidth;
18099 switch(image._alignment) {
18101 offset = width - imageWidth;
18104 offset = (width - imageWidth) / 2;
18109 image.x = (image.x || 0) + offset;
18113 ElementWriter.prototype.addVector = function(vector, ignoreContextX, ignoreContextY, index) {
18114 var context = this.context;
18115 var page = context.getCurrentPage(),
18116 position = this.getCurrentPositionOnPage();
18119 offsetVector(vector, ignoreContextX ? 0 : context.x, ignoreContextY ? 0 : context.y);
18120 addPageItem(page, {
18128 function cloneLine(line) {
18129 var result = new Line(line.maxWidth);
18131 for(var key in line) {
18132 if (line.hasOwnProperty(key)) {
18133 result[key] = line[key];
18140 ElementWriter.prototype.addFragment = function(block, useBlockXOffset, useBlockYOffset, dontUpdateContextPosition) {
18141 var ctx = this.context;
18142 var page = ctx.getCurrentPage();
18144 if (!useBlockXOffset && block.height > ctx.availableHeight) return false;
18146 block.items.forEach(function(item) {
18147 switch(item.type) {
18149 var l = cloneLine(item.item);
18151 l.x = (l.x || 0) + (useBlockXOffset ? (block.xOffset || 0) : ctx.x);
18152 l.y = (l.y || 0) + (useBlockYOffset ? (block.yOffset || 0) : ctx.y);
18161 var v = pack(item.item);
18163 offsetVector(v, useBlockXOffset ? (block.xOffset || 0) : ctx.x, useBlockYOffset ? (block.yOffset || 0) : ctx.y);
18171 var img = pack(item.item);
18173 img.x = (img.x || 0) + (useBlockXOffset ? (block.xOffset || 0) : ctx.x);
18174 img.y = (img.y || 0) + (useBlockYOffset ? (block.yOffset || 0) : ctx.y);
18184 if (!dontUpdateContextPosition) ctx.moveDown(block.height);
18190 * Pushes the provided context onto the stack or creates a new one
18192 * pushContext(context) - pushes the provided context and makes it current
18193 * pushContext(width, height) - creates and pushes a new context with the specified width and height
18194 * pushContext() - creates a new context for unbreakable blocks (with current availableWidth and full-page-height)
18196 ElementWriter.prototype.pushContext = function(contextOrWidth, height) {
18197 if (contextOrWidth === undefined) {
18198 height = this.context.getCurrentPage().height - this.context.pageMargins.top - this.context.pageMargins.bottom;
18199 contextOrWidth = this.context.availableWidth;
18202 if (typeof contextOrWidth === 'number' || contextOrWidth instanceof Number) {
18203 contextOrWidth = new DocumentContext({ width: contextOrWidth, height: height }, { left: 0, right: 0, top: 0, bottom: 0 });
18206 this.contextStack.push(this.context);
18207 this.context = contextOrWidth;
18210 ElementWriter.prototype.popContext = function() {
18211 this.context = this.contextStack.pop();
18214 ElementWriter.prototype.getCurrentPositionOnPage = function(){
18215 return (this.contextStack[0] || this.context).getCurrentPosition();
18219 module.exports = ElementWriter;
18224 /***/ function(module, exports) {
18226 /* jslint node: true */
18230 * Creates an instance of Line
18234 * @param {Number} Maximum width this line can have
18236 function Line(maxWidth) {
18237 this.maxWidth = maxWidth;
18238 this.leadingCut = 0;
18239 this.trailingCut = 0;
18240 this.inlineWidths = 0;
18244 Line.prototype.getAscenderHeight = function() {
18247 this.inlines.forEach(function(inline) {
18248 y = Math.max(y, inline.font.ascender / 1000 * inline.fontSize);
18253 Line.prototype.hasEnoughSpaceForInline = function(inline) {
18254 if (this.inlines.length === 0) return true;
18255 if (this.newLineForced) return false;
18257 return this.inlineWidths + inline.width - this.leadingCut - (inline.trailingCut || 0) <= this.maxWidth;
18260 Line.prototype.addInline = function(inline) {
18261 if (this.inlines.length === 0) {
18262 this.leadingCut = inline.leadingCut || 0;
18264 this.trailingCut = inline.trailingCut || 0;
18266 inline.x = this.inlineWidths - this.leadingCut;
18268 this.inlines.push(inline);
18269 this.inlineWidths += inline.width;
18271 if (inline.lineEnd) {
18272 this.newLineForced = true;
18276 Line.prototype.getWidth = function() {
18277 return this.inlineWidths - this.leadingCut - this.trailingCut;
18281 * Returns line height
18284 Line.prototype.getHeight = function() {
18287 this.inlines.forEach(function(item) {
18288 max = Math.max(max, item.height || 0);
18294 module.exports = Line;
18299 /***/ function(module, exports, __webpack_require__) {
18301 /* jslint node: true */
18304 var ColumnCalculator = __webpack_require__(16);
18306 function TableProcessor(tableNode) {
18307 this.tableNode = tableNode;
18310 TableProcessor.prototype.beginTable = function(writer) {
18312 var availableWidth;
18315 tableNode = this.tableNode;
18316 this.offsets = tableNode._offsets;
18317 this.layout = tableNode._layout;
18319 availableWidth = writer.context().availableWidth - this.offsets.total;
18320 ColumnCalculator.buildColumnWidths(tableNode.table.widths, availableWidth);
18322 this.tableWidth = tableNode._offsets.total + getTableInnerContentWidth();
18323 this.rowSpanData = prepareRowSpanData();
18324 this.cleanUpRepeatables = false;
18326 this.headerRows = tableNode.table.headerRows || 0;
18327 this.rowsWithoutPageBreak = this.headerRows + (tableNode.table.keepWithHeaderRows || 0);
18328 this.dontBreakRows = tableNode.table.dontBreakRows || false;
18330 if (this.rowsWithoutPageBreak) {
18331 writer.beginUnbreakableBlock();
18334 this.drawHorizontalLine(0, writer);
18336 function getTableInnerContentWidth() {
18339 tableNode.table.widths.forEach(function(w) {
18340 width += w._calcWidth;
18346 function prepareRowSpanData() {
18351 rsd.push({ left: 0, rowSpan: 0 });
18353 for(var i = 0, l = self.tableNode.table.body[0].length; i < l; i++) {
18354 var paddings = self.layout.paddingLeft(i, self.tableNode) + self.layout.paddingRight(i, self.tableNode);
18355 var lBorder = self.layout.vLineWidth(i, self.tableNode);
18356 lastWidth = paddings + lBorder + self.tableNode.table.widths[i]._calcWidth;
18357 rsd[rsd.length - 1].width = lastWidth;
18359 rsd.push({ left: x, rowSpan: 0, width: 0 });
18366 TableProcessor.prototype.onRowBreak = function(rowIndex, writer) {
18368 return function() {
18369 //console.log('moving by : ', topLineWidth, rowPaddingTop);
18370 var offset = self.rowPaddingTop + (!self.headerRows ? self.topLineWidth : 0);
18371 writer.context().moveDown(offset);
18376 TableProcessor.prototype.beginRow = function(rowIndex, writer) {
18377 this.topLineWidth = this.layout.hLineWidth(rowIndex, this.tableNode);
18378 this.rowPaddingTop = this.layout.paddingTop(rowIndex, this.tableNode);
18379 this.bottomLineWidth = this.layout.hLineWidth(rowIndex+1, this.tableNode);
18380 this.rowPaddingBottom = this.layout.paddingBottom(rowIndex, this.tableNode);
18382 this.rowCallback = this.onRowBreak(rowIndex, writer);
18383 writer.tracker.startTracking('pageChanged', this.rowCallback );
18384 if(this.dontBreakRows) {
18385 writer.beginUnbreakableBlock();
18387 this.rowTopY = writer.context().y;
18388 this.reservedAtBottom = this.bottomLineWidth + this.rowPaddingBottom;
18390 writer.context().availableHeight -= this.reservedAtBottom;
18392 writer.context().moveDown(this.rowPaddingTop);
18395 TableProcessor.prototype.drawHorizontalLine = function(lineIndex, writer, overrideY) {
18396 var lineWidth = this.layout.hLineWidth(lineIndex, this.tableNode);
18398 var offset = lineWidth / 2;
18399 var currentLine = null;
18401 for(var i = 0, l = this.rowSpanData.length; i < l; i++) {
18402 var data = this.rowSpanData[i];
18403 var shouldDrawLine = !data.rowSpan;
18405 if (!currentLine && shouldDrawLine) {
18406 currentLine = { left: data.left, width: 0 };
18409 if (shouldDrawLine) {
18410 currentLine.width += (data.width || 0);
18413 var y = (overrideY || 0) + offset;
18415 if (!shouldDrawLine || i === l - 1) {
18419 x1: currentLine.left,
18420 x2: currentLine.left + currentLine.width,
18423 lineWidth: lineWidth,
18424 lineColor: typeof this.layout.hLineColor === 'function' ? this.layout.hLineColor(lineIndex, this.tableNode) : this.layout.hLineColor
18425 }, false, overrideY);
18426 currentLine = null;
18431 writer.context().moveDown(lineWidth);
18435 TableProcessor.prototype.drawVerticalLine = function(x, y0, y1, vLineIndex, writer) {
18436 var width = this.layout.vLineWidth(vLineIndex, this.tableNode);
18437 if (width === 0) return;
18445 lineColor: typeof this.layout.vLineColor === 'function' ? this.layout.vLineColor(vLineIndex, this.tableNode) : this.layout.vLineColor
18449 TableProcessor.prototype.endTable = function(writer) {
18450 if (this.cleanUpRepeatables) {
18451 writer.popFromRepeatables();
18455 TableProcessor.prototype.endRow = function(rowIndex, writer, pageBreaks) {
18458 writer.tracker.stopTracking('pageChanged', this.rowCallback);
18459 writer.context().moveDown(this.layout.paddingBottom(rowIndex, this.tableNode));
18460 writer.context().availableHeight += this.reservedAtBottom;
18462 var endingPage = writer.context().page;
18463 var endingY = writer.context().y;
18465 var xs = getLineXs();
18469 var hasBreaks = pageBreaks && pageBreaks.length > 0;
18473 page: hasBreaks ? pageBreaks[0].prevPage : endingPage
18477 for(i = 0, l = pageBreaks.length; i < l; i++) {
18478 var pageBreak = pageBreaks[i];
18479 ys[ys.length - 1].y1 = pageBreak.prevY;
18481 ys.push({y0: pageBreak.y, page: pageBreak.prevPage + 1});
18485 ys[ys.length - 1].y1 = endingY;
18487 var skipOrphanePadding = (ys[0].y1 - ys[0].y0 === this.rowPaddingTop);
18488 for(var yi = (skipOrphanePadding ? 1 : 0), yl = ys.length; yi < yl; yi++) {
18489 var willBreak = yi < ys.length - 1;
18490 var rowBreakWithoutHeader = (yi > 0 && !this.headerRows);
18491 var hzLineOffset = rowBreakWithoutHeader ? 0 : this.topLineWidth;
18492 var y1 = ys[yi].y0;
18493 var y2 = ys[yi].y1;
18496 y2 = y2 + this.rowPaddingBottom;
18499 if (writer.context().page != ys[yi].page) {
18500 writer.context().page = ys[yi].page;
18502 //TODO: buggy, availableHeight should be updated on every pageChanged event
18503 // TableProcessor should be pageChanged listener, instead of processRow
18504 this.reservedAtBottom = 0;
18507 for(i = 0, l = xs.length; i < l; i++) {
18508 this.drawVerticalLine(xs[i].x, y1 - hzLineOffset, y2 + this.bottomLineWidth, xs[i].index, writer);
18510 var colIndex = xs[i].index;
18511 var fillColor= this.tableNode.table.body[rowIndex][colIndex].fillColor;
18513 var wBorder = this.layout.vLineWidth(colIndex, this.tableNode);
18514 var xf = xs[i].x+wBorder;
18515 var yf = y1 - hzLineOffset;
18521 h: y2+this.bottomLineWidth-yf,
18524 }, false, true, 0);
18529 if (willBreak && this.layout.hLineWhenBroken !== false) {
18530 this.drawHorizontalLine(rowIndex + 1, writer, y2);
18532 if(rowBreakWithoutHeader && this.layout.hLineWhenBroken !== false) {
18533 this.drawHorizontalLine(rowIndex, writer, y1);
18537 writer.context().page = endingPage;
18538 writer.context().y = endingY;
18540 var row = this.tableNode.table.body[rowIndex];
18541 for(i = 0, l = row.length; i < l; i++) {
18542 if (row[i].rowSpan) {
18543 this.rowSpanData[i].rowSpan = row[i].rowSpan;
18546 if (row[i].colSpan && row[i].colSpan > 1) {
18547 for(var j = 1; j < row[i].rowSpan; j++) {
18548 this.tableNode.table.body[rowIndex + j][i]._colSpan = row[i].colSpan;
18553 if(this.rowSpanData[i].rowSpan > 0) {
18554 this.rowSpanData[i].rowSpan--;
18558 this.drawHorizontalLine(rowIndex + 1, writer);
18560 if(this.headerRows && rowIndex === this.headerRows - 1) {
18561 this.headerRepeatable = writer.currentBlockToRepeatable();
18564 if(this.dontBreakRows) {
18565 writer.tracker.auto('pageChanged',
18567 self.drawHorizontalLine(rowIndex, writer);
18570 writer.commitUnbreakableBlock();
18571 self.drawHorizontalLine(rowIndex, writer);
18576 if(this.headerRepeatable && (rowIndex === (this.rowsWithoutPageBreak - 1) || rowIndex === this.tableNode.table.body.length - 1)) {
18577 writer.commitUnbreakableBlock();
18578 writer.pushToRepeatables(this.headerRepeatable);
18579 this.cleanUpRepeatables = true;
18580 this.headerRepeatable = null;
18583 function getLineXs() {
18587 for(var i = 0, l = self.tableNode.table.body[rowIndex].length; i < l; i++) {
18589 result.push({ x: self.rowSpanData[i].left, index: i});
18591 var item = self.tableNode.table.body[rowIndex][i];
18592 cols = (item._colSpan || item.colSpan || 0);
18599 result.push({ x: self.rowSpanData[self.rowSpanData.length - 1].left, index: self.rowSpanData.length - 1});
18605 module.exports = TableProcessor;
18610 /***/ function(module, exports, __webpack_require__) {
18612 /* WEBPACK VAR INJECTION */(function(Buffer) {// Generated by CoffeeScript 1.7.1
18615 PDFDocument - represents an entire PDF document
18620 var PDFDocument, PDFObject, PDFPage, PDFReference, fs, stream,
18621 __hasProp = {}.hasOwnProperty,
18622 __extends = 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; };
18624 stream = __webpack_require__(25);
18626 fs = __webpack_require__(44);
18628 PDFObject = __webpack_require__(45);
18630 PDFReference = __webpack_require__(46);
18632 PDFPage = __webpack_require__(64);
18634 PDFDocument = (function(_super) {
18637 __extends(PDFDocument, _super);
18639 function PDFDocument(options) {
18640 var key, val, _ref, _ref1;
18641 this.options = options != null ? options : {};
18642 PDFDocument.__super__.constructor.apply(this, arguments);
18643 this.version = 1.3;
18644 this.compress = (_ref = this.options.compress) != null ? _ref : true;
18645 this._pageBuffer = [];
18646 this._pageBufferStart = 0;
18647 this._offsets = [];
18649 this._ended = false;
18651 this._root = this.ref({
18666 Producer: 'PDFKit',
18668 CreationDate: new Date()
18670 if (this.options.info) {
18671 _ref1 = this.options.info;
18672 for (key in _ref1) {
18674 this.info[key] = val;
18677 this._write("%PDF-" + this.version);
18678 this._write("%\xFF\xFF\xFF\xFF");
18682 mixin = function(methods) {
18683 var method, name, _results;
18685 for (name in methods) {
18686 method = methods[name];
18687 _results.push(PDFDocument.prototype[name] = method);
18692 mixin(__webpack_require__(65));
18694 mixin(__webpack_require__(67));
18696 mixin(__webpack_require__(69));
18698 mixin(__webpack_require__(89));
18700 mixin(__webpack_require__(96));
18702 mixin(__webpack_require__(101));
18704 PDFDocument.prototype.addPage = function(options) {
18706 if (options == null) {
18707 options = this.options;
18709 if (!this.options.bufferPages) {
18712 this.page = new PDFPage(this, options);
18713 this._pageBuffer.push(this.page);
18714 pages = this._root.data.Pages.data;
18715 pages.Kids.push(this.page.dictionary);
18717 this.x = this.page.margins.left;
18718 this.y = this.page.margins.top;
18719 this._ctm = [1, 0, 0, 1, 0, 0];
18720 this.transform(1, 0, 0, -1, 0, this.page.height);
18724 PDFDocument.prototype.bufferedPageRange = function() {
18726 start: this._pageBufferStart,
18727 count: this._pageBuffer.length
18731 PDFDocument.prototype.switchToPage = function(n) {
18733 if (!(page = this._pageBuffer[n - this._pageBufferStart])) {
18734 throw new Error("switchToPage(" + n + ") out of bounds, current buffer covers pages " + this._pageBufferStart + " to " + (this._pageBufferStart + this._pageBuffer.length - 1));
18736 return this.page = page;
18739 PDFDocument.prototype.flushPages = function() {
18740 var page, pages, _i, _len;
18741 pages = this._pageBuffer;
18742 this._pageBuffer = [];
18743 this._pageBufferStart += pages.length;
18744 for (_i = 0, _len = pages.length; _i < _len; _i++) {
18750 PDFDocument.prototype.ref = function(data) {
18752 ref = new PDFReference(this, this._offsets.length + 1, data);
18753 this._offsets.push(null);
18758 PDFDocument.prototype._read = function() {};
18760 PDFDocument.prototype._write = function(data) {
18761 if (!Buffer.isBuffer(data)) {
18762 data = new Buffer(data + '\n', 'binary');
18765 return this._offset += data.length;
18768 PDFDocument.prototype.addContent = function(data) {
18769 this.page.write(data);
18773 PDFDocument.prototype._refEnd = function(ref) {
18774 this._offsets[ref.id - 1] = ref.offset;
18775 if (--this._waiting === 0 && this._ended) {
18777 return this._ended = false;
18781 PDFDocument.prototype.write = function(filename, fn) {
18783 err = new Error('PDFDocument#write is deprecated, and will be removed in a future version of PDFKit. Please pipe the document into a Node stream.');
18784 console.warn(err.stack);
18785 this.pipe(fs.createWriteStream(filename));
18787 return this.once('end', fn);
18790 PDFDocument.prototype.output = function(fn) {
18791 throw new Error('PDFDocument#output is deprecated, and has been removed from PDFKit. Please pipe the document into a Node stream.');
18794 PDFDocument.prototype.end = function() {
18795 var font, key, name, val, _ref, _ref1;
18797 this._info = this.ref();
18799 for (key in _ref) {
18801 if (typeof val === 'string') {
18802 val = new String(val);
18804 this._info.data[key] = val;
18807 _ref1 = this._fontFamilies;
18808 for (name in _ref1) {
18809 font = _ref1[name];
18813 this._root.data.Pages.end();
18814 if (this._waiting === 0) {
18815 return this._finalize();
18817 return this._ended = true;
18821 PDFDocument.prototype._finalize = function(fn) {
18822 var offset, xRefOffset, _i, _len, _ref;
18823 xRefOffset = this._offset;
18824 this._write("xref");
18825 this._write("0 " + (this._offsets.length + 1));
18826 this._write("0000000000 65535 f ");
18827 _ref = this._offsets;
18828 for (_i = 0, _len = _ref.length; _i < _len; _i++) {
18830 offset = ('0000000000' + offset).slice(-10);
18831 this._write(offset + ' 00000 n ');
18833 this._write('trailer');
18834 this._write(PDFObject.convert({
18835 Size: this._offsets.length + 1,
18839 this._write('startxref');
18840 this._write("" + xRefOffset);
18841 this._write('%%EOF');
18842 return this.push(null);
18845 PDFDocument.prototype.toString = function() {
18846 return "[object PDFDocument]";
18849 return PDFDocument;
18851 })(stream.Readable);
18853 module.exports = PDFDocument;
18857 /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2).Buffer))
18861 /***/ function(module, exports, __webpack_require__) {
18863 // Copyright Joyent, Inc. and other Node contributors.
18865 // Permission is hereby granted, free of charge, to any person obtaining a
18866 // copy of this software and associated documentation files (the
18867 // "Software"), to deal in the Software without restriction, including
18868 // without limitation the rights to use, copy, modify, merge, publish,
18869 // distribute, sublicense, and/or sell copies of the Software, and to permit
18870 // persons to whom the Software is furnished to do so, subject to the
18871 // following conditions:
18873 // The above copyright notice and this permission notice shall be included
18874 // in all copies or substantial portions of the Software.
18876 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
18877 // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18878 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
18879 // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18880 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
18881 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
18882 // USE OR OTHER DEALINGS IN THE SOFTWARE.
18884 module.exports = Stream;
18886 var EE = __webpack_require__(26).EventEmitter;
18887 var inherits = __webpack_require__(27);
18889 inherits(Stream, EE);
18890 Stream.Readable = __webpack_require__(28);
18891 Stream.Writable = __webpack_require__(40);
18892 Stream.Duplex = __webpack_require__(41);
18893 Stream.Transform = __webpack_require__(42);
18894 Stream.PassThrough = __webpack_require__(43);
18896 // Backwards-compat with node 0.4.x
18897 Stream.Stream = Stream;
18901 // old-style streams. Note that the pipe method (the only relevant
18902 // part of this class) is overridden in the Readable class.
18904 function Stream() {
18908 Stream.prototype.pipe = function(dest, options) {
18911 function ondata(chunk) {
18912 if (dest.writable) {
18913 if (false === dest.write(chunk) && source.pause) {
18919 source.on('data', ondata);
18921 function ondrain() {
18922 if (source.readable && source.resume) {
18927 dest.on('drain', ondrain);
18929 // If the 'end' option is not supplied, dest.end() will be called when
18930 // source gets the 'end' or 'close' events. Only dest.end() once.
18931 if (!dest._isStdio && (!options || options.end !== false)) {
18932 source.on('end', onend);
18933 source.on('close', onclose);
18936 var didOnEnd = false;
18938 if (didOnEnd) return;
18945 function onclose() {
18946 if (didOnEnd) return;
18949 if (typeof dest.destroy === 'function') dest.destroy();
18952 // don't leave dangling pipes when there are errors.
18953 function onerror(er) {
18955 if (EE.listenerCount(this, 'error') === 0) {
18956 throw er; // Unhandled stream error in pipe.
18960 source.on('error', onerror);
18961 dest.on('error', onerror);
18963 // remove all the event listeners that were added.
18964 function cleanup() {
18965 source.removeListener('data', ondata);
18966 dest.removeListener('drain', ondrain);
18968 source.removeListener('end', onend);
18969 source.removeListener('close', onclose);
18971 source.removeListener('error', onerror);
18972 dest.removeListener('error', onerror);
18974 source.removeListener('end', cleanup);
18975 source.removeListener('close', cleanup);
18977 dest.removeListener('close', cleanup);
18980 source.on('end', cleanup);
18981 source.on('close', cleanup);
18983 dest.on('close', cleanup);
18985 dest.emit('pipe', source);
18987 // Allow for unix-like usage: A.pipe(B).pipe(C)
18994 /***/ function(module, exports) {
18996 // Copyright Joyent, Inc. and other Node contributors.
18998 // Permission is hereby granted, free of charge, to any person obtaining a
18999 // copy of this software and associated documentation files (the
19000 // "Software"), to deal in the Software without restriction, including
19001 // without limitation the rights to use, copy, modify, merge, publish,
19002 // distribute, sublicense, and/or sell copies of the Software, and to permit
19003 // persons to whom the Software is furnished to do so, subject to the
19004 // following conditions:
19006 // The above copyright notice and this permission notice shall be included
19007 // in all copies or substantial portions of the Software.
19009 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
19010 // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
19011 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
19012 // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
19013 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19014 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
19015 // USE OR OTHER DEALINGS IN THE SOFTWARE.
19017 function EventEmitter() {
19018 this._events = this._events || {};
19019 this._maxListeners = this._maxListeners || undefined;
19021 module.exports = EventEmitter;
19023 // Backwards-compat with node 0.10.x
19024 EventEmitter.EventEmitter = EventEmitter;
19026 EventEmitter.prototype._events = undefined;
19027 EventEmitter.prototype._maxListeners = undefined;
19029 // By default EventEmitters will print a warning if more than 10 listeners are
19030 // added to it. This is a useful default which helps finding memory leaks.
19031 EventEmitter.defaultMaxListeners = 10;
19033 // Obviously not all Emitters should be limited to 10. This function allows
19034 // that to be increased. Set to zero for unlimited.
19035 EventEmitter.prototype.setMaxListeners = function(n) {
19036 if (!isNumber(n) || n < 0 || isNaN(n))
19037 throw TypeError('n must be a positive number');
19038 this._maxListeners = n;
19042 EventEmitter.prototype.emit = function(type) {
19043 var er, handler, len, args, i, listeners;
19048 // If there is no 'error' event listener then throw.
19049 if (type === 'error') {
19050 if (!this._events.error ||
19051 (isObject(this._events.error) && !this._events.error.length)) {
19053 if (er instanceof Error) {
19054 throw er; // Unhandled 'error' event
19056 throw TypeError('Uncaught, unspecified "error" event.');
19060 handler = this._events[type];
19062 if (isUndefined(handler))
19065 if (isFunction(handler)) {
19066 switch (arguments.length) {
19069 handler.call(this);
19072 handler.call(this, arguments[1]);
19075 handler.call(this, arguments[1], arguments[2]);
19079 args = Array.prototype.slice.call(arguments, 1);
19080 handler.apply(this, args);
19082 } else if (isObject(handler)) {
19083 args = Array.prototype.slice.call(arguments, 1);
19084 listeners = handler.slice();
19085 len = listeners.length;
19086 for (i = 0; i < len; i++)
19087 listeners[i].apply(this, args);
19093 EventEmitter.prototype.addListener = function(type, listener) {
19096 if (!isFunction(listener))
19097 throw TypeError('listener must be a function');
19102 // To avoid recursion in the case that type === "newListener"! Before
19103 // adding it to the listeners, first emit "newListener".
19104 if (this._events.newListener)
19105 this.emit('newListener', type,
19106 isFunction(listener.listener) ?
19107 listener.listener : listener);
19109 if (!this._events[type])
19110 // Optimize the case of one listener. Don't need the extra array object.
19111 this._events[type] = listener;
19112 else if (isObject(this._events[type]))
19113 // If we've already got an array, just append.
19114 this._events[type].push(listener);
19116 // Adding the second element, need to change to array.
19117 this._events[type] = [this._events[type], listener];
19119 // Check for listener leak
19120 if (isObject(this._events[type]) && !this._events[type].warned) {
19121 if (!isUndefined(this._maxListeners)) {
19122 m = this._maxListeners;
19124 m = EventEmitter.defaultMaxListeners;
19127 if (m && m > 0 && this._events[type].length > m) {
19128 this._events[type].warned = true;
19129 console.error('(node) warning: possible EventEmitter memory ' +
19130 'leak detected. %d listeners added. ' +
19131 'Use emitter.setMaxListeners() to increase limit.',
19132 this._events[type].length);
19133 if (typeof console.trace === 'function') {
19134 // not supported in IE 10
19143 EventEmitter.prototype.on = EventEmitter.prototype.addListener;
19145 EventEmitter.prototype.once = function(type, listener) {
19146 if (!isFunction(listener))
19147 throw TypeError('listener must be a function');
19152 this.removeListener(type, g);
19156 listener.apply(this, arguments);
19160 g.listener = listener;
19166 // emits a 'removeListener' event iff the listener was removed
19167 EventEmitter.prototype.removeListener = function(type, listener) {
19168 var list, position, length, i;
19170 if (!isFunction(listener))
19171 throw TypeError('listener must be a function');
19173 if (!this._events || !this._events[type])
19176 list = this._events[type];
19177 length = list.length;
19180 if (list === listener ||
19181 (isFunction(list.listener) && list.listener === listener)) {
19182 delete this._events[type];
19183 if (this._events.removeListener)
19184 this.emit('removeListener', type, listener);
19186 } else if (isObject(list)) {
19187 for (i = length; i-- > 0;) {
19188 if (list[i] === listener ||
19189 (list[i].listener && list[i].listener === listener)) {
19198 if (list.length === 1) {
19200 delete this._events[type];
19202 list.splice(position, 1);
19205 if (this._events.removeListener)
19206 this.emit('removeListener', type, listener);
19212 EventEmitter.prototype.removeAllListeners = function(type) {
19213 var key, listeners;
19218 // not listening for removeListener, no need to emit
19219 if (!this._events.removeListener) {
19220 if (arguments.length === 0)
19222 else if (this._events[type])
19223 delete this._events[type];
19227 // emit removeListener for all listeners on all events
19228 if (arguments.length === 0) {
19229 for (key in this._events) {
19230 if (key === 'removeListener') continue;
19231 this.removeAllListeners(key);
19233 this.removeAllListeners('removeListener');
19238 listeners = this._events[type];
19240 if (isFunction(listeners)) {
19241 this.removeListener(type, listeners);
19242 } else if (listeners) {
19244 while (listeners.length)
19245 this.removeListener(type, listeners[listeners.length - 1]);
19247 delete this._events[type];
19252 EventEmitter.prototype.listeners = function(type) {
19254 if (!this._events || !this._events[type])
19256 else if (isFunction(this._events[type]))
19257 ret = [this._events[type]];
19259 ret = this._events[type].slice();
19263 EventEmitter.prototype.listenerCount = function(type) {
19264 if (this._events) {
19265 var evlistener = this._events[type];
19267 if (isFunction(evlistener))
19269 else if (evlistener)
19270 return evlistener.length;
19275 EventEmitter.listenerCount = function(emitter, type) {
19276 return emitter.listenerCount(type);
19279 function isFunction(arg) {
19280 return typeof arg === 'function';
19283 function isNumber(arg) {
19284 return typeof arg === 'number';
19287 function isObject(arg) {
19288 return typeof arg === 'object' && arg !== null;
19291 function isUndefined(arg) {
19292 return arg === void 0;
19298 /***/ function(module, exports) {
19300 if (typeof Object.create === 'function') {
19301 // implementation from standard node.js 'util' module
19302 module.exports = function inherits(ctor, superCtor) {
19303 ctor.super_ = superCtor
19304 ctor.prototype = Object.create(superCtor.prototype, {
19314 // old school shim for old browsers
19315 module.exports = function inherits(ctor, superCtor) {
19316 ctor.super_ = superCtor
19317 var TempCtor = function () {}
19318 TempCtor.prototype = superCtor.prototype
19319 ctor.prototype = new TempCtor()
19320 ctor.prototype.constructor = ctor
19327 /***/ function(module, exports, __webpack_require__) {
19329 exports = module.exports = __webpack_require__(29);
19330 exports.Stream = __webpack_require__(25);
19331 exports.Readable = exports;
19332 exports.Writable = __webpack_require__(36);
19333 exports.Duplex = __webpack_require__(35);
19334 exports.Transform = __webpack_require__(38);
19335 exports.PassThrough = __webpack_require__(39);
19340 /***/ function(module, exports, __webpack_require__) {
19342 /* WEBPACK VAR INJECTION */(function(process) {// Copyright Joyent, Inc. and other Node contributors.
19344 // Permission is hereby granted, free of charge, to any person obtaining a
19345 // copy of this software and associated documentation files (the
19346 // "Software"), to deal in the Software without restriction, including
19347 // without limitation the rights to use, copy, modify, merge, publish,
19348 // distribute, sublicense, and/or sell copies of the Software, and to permit
19349 // persons to whom the Software is furnished to do so, subject to the
19350 // following conditions:
19352 // The above copyright notice and this permission notice shall be included
19353 // in all copies or substantial portions of the Software.
19355 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
19356 // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
19357 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
19358 // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
19359 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19360 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
19361 // USE OR OTHER DEALINGS IN THE SOFTWARE.
19363 module.exports = Readable;
19366 var isArray = __webpack_require__(31);
19371 var Buffer = __webpack_require__(2).Buffer;
19374 Readable.ReadableState = ReadableState;
19376 var EE = __webpack_require__(26).EventEmitter;
19379 if (!EE.listenerCount) EE.listenerCount = function(emitter, type) {
19380 return emitter.listeners(type).length;
19384 var Stream = __webpack_require__(25);
19387 var util = __webpack_require__(32);
19388 util.inherits = __webpack_require__(33);
19395 var debug = __webpack_require__(34);
19396 if (debug && debug.debuglog) {
19397 debug = debug.debuglog('stream');
19399 debug = function () {};
19404 util.inherits(Readable, Stream);
19406 function ReadableState(options, stream) {
19407 var Duplex = __webpack_require__(35);
19409 options = options || {};
19411 // the point at which it stops calling _read() to fill the buffer
19412 // Note: 0 is a valid value, means "don't call _read preemptively ever"
19413 var hwm = options.highWaterMark;
19414 var defaultHwm = options.objectMode ? 16 : 16 * 1024;
19415 this.highWaterMark = (hwm || hwm === 0) ? hwm : defaultHwm;
19418 this.highWaterMark = ~~this.highWaterMark;
19423 this.pipesCount = 0;
19424 this.flowing = null;
19425 this.ended = false;
19426 this.endEmitted = false;
19427 this.reading = false;
19429 // a flag to be able to tell if the onwrite cb is called immediately,
19430 // or on a later tick. We set this to true at first, because any
19431 // actions that shouldn't happen until "later" should generally also
19432 // not happen before the first write call.
19435 // whenever we return null, then we set a flag to say
19436 // that we're awaiting a 'readable' event emission.
19437 this.needReadable = false;
19438 this.emittedReadable = false;
19439 this.readableListening = false;
19442 // object stream flag. Used to make read(n) ignore n and to
19443 // make all the buffer merging and length checks go away
19444 this.objectMode = !!options.objectMode;
19446 if (stream instanceof Duplex)
19447 this.objectMode = this.objectMode || !!options.readableObjectMode;
19449 // Crypto is kind of old and crusty. Historically, its default string
19450 // encoding is 'binary' so we have to make this configurable.
19451 // Everything else in the universe uses 'utf8', though.
19452 this.defaultEncoding = options.defaultEncoding || 'utf8';
19454 // when piping, we only care about 'readable' events that happen
19455 // after read()ing all the bytes and not getting any pushback.
19456 this.ranOut = false;
19458 // the number of writers that are awaiting a drain event in .pipe()s
19459 this.awaitDrain = 0;
19461 // if true, a maybeReadMore has been scheduled
19462 this.readingMore = false;
19464 this.decoder = null;
19465 this.encoding = null;
19466 if (options.encoding) {
19467 if (!StringDecoder)
19468 StringDecoder = __webpack_require__(37).StringDecoder;
19469 this.decoder = new StringDecoder(options.encoding);
19470 this.encoding = options.encoding;
19474 function Readable(options) {
19475 var Duplex = __webpack_require__(35);
19477 if (!(this instanceof Readable))
19478 return new Readable(options);
19480 this._readableState = new ReadableState(options, this);
19483 this.readable = true;
19488 // Manually shove something into the read() buffer.
19489 // This returns true if the highWaterMark has not been hit yet,
19490 // similar to how Writable.write() returns true if you should
19491 // write() some more.
19492 Readable.prototype.push = function(chunk, encoding) {
19493 var state = this._readableState;
19495 if (util.isString(chunk) && !state.objectMode) {
19496 encoding = encoding || state.defaultEncoding;
19497 if (encoding !== state.encoding) {
19498 chunk = new Buffer(chunk, encoding);
19503 return readableAddChunk(this, state, chunk, encoding, false);
19506 // Unshift should *always* be something directly out of read()
19507 Readable.prototype.unshift = function(chunk) {
19508 var state = this._readableState;
19509 return readableAddChunk(this, state, chunk, '', true);
19512 function readableAddChunk(stream, state, chunk, encoding, addToFront) {
19513 var er = chunkInvalid(state, chunk);
19515 stream.emit('error', er);
19516 } else if (util.isNullOrUndefined(chunk)) {
19517 state.reading = false;
19519 onEofChunk(stream, state);
19520 } else if (state.objectMode || chunk && chunk.length > 0) {
19521 if (state.ended && !addToFront) {
19522 var e = new Error('stream.push() after EOF');
19523 stream.emit('error', e);
19524 } else if (state.endEmitted && addToFront) {
19525 var e = new Error('stream.unshift() after end event');
19526 stream.emit('error', e);
19528 if (state.decoder && !addToFront && !encoding)
19529 chunk = state.decoder.write(chunk);
19532 state.reading = false;
19534 // if we want the data now, just emit it.
19535 if (state.flowing && state.length === 0 && !state.sync) {
19536 stream.emit('data', chunk);
19539 // update the buffer info.
19540 state.length += state.objectMode ? 1 : chunk.length;
19542 state.buffer.unshift(chunk);
19544 state.buffer.push(chunk);
19546 if (state.needReadable)
19547 emitReadable(stream);
19550 maybeReadMore(stream, state);
19552 } else if (!addToFront) {
19553 state.reading = false;
19556 return needMoreData(state);
19561 // if it's past the high water mark, we can push in some more.
19562 // Also, if we have no data yet, we can stand some
19563 // more bytes. This is to work around cases where hwm=0,
19564 // such as the repl. Also, if the push() triggered a
19565 // readable event, and the user called read(largeNumber) such that
19566 // needReadable was set, then we ought to push more, so that another
19567 // 'readable' event will be triggered.
19568 function needMoreData(state) {
19569 return !state.ended &&
19570 (state.needReadable ||
19571 state.length < state.highWaterMark ||
19572 state.length === 0);
19575 // backwards compatibility.
19576 Readable.prototype.setEncoding = function(enc) {
19577 if (!StringDecoder)
19578 StringDecoder = __webpack_require__(37).StringDecoder;
19579 this._readableState.decoder = new StringDecoder(enc);
19580 this._readableState.encoding = enc;
19584 // Don't raise the hwm > 128MB
19585 var MAX_HWM = 0x800000;
19586 function roundUpToNextPowerOf2(n) {
19587 if (n >= MAX_HWM) {
19590 // Get the next highest power of 2
19592 for (var p = 1; p < 32; p <<= 1) n |= n >> p;
19598 function howMuchToRead(n, state) {
19599 if (state.length === 0 && state.ended)
19602 if (state.objectMode)
19603 return n === 0 ? 0 : 1;
19605 if (isNaN(n) || util.isNull(n)) {
19606 // only flow one buffer at a time
19607 if (state.flowing && state.buffer.length)
19608 return state.buffer[0].length;
19610 return state.length;
19616 // If we're asking for more than the target buffer level,
19617 // then raise the water mark. Bump up to the next highest
19618 // power of 2, to prevent increasing it excessively in tiny
19620 if (n > state.highWaterMark)
19621 state.highWaterMark = roundUpToNextPowerOf2(n);
19623 // don't have that much. return null, unless we've ended.
19624 if (n > state.length) {
19625 if (!state.ended) {
19626 state.needReadable = true;
19629 return state.length;
19635 // you can override either this method, or the async _read(n) below.
19636 Readable.prototype.read = function(n) {
19638 var state = this._readableState;
19641 if (!util.isNumber(n) || n > 0)
19642 state.emittedReadable = false;
19644 // if we're doing read(0) to trigger a readable event, but we
19645 // already have a bunch of data in the buffer, then just trigger
19646 // the 'readable' event and move on.
19648 state.needReadable &&
19649 (state.length >= state.highWaterMark || state.ended)) {
19650 debug('read: emitReadable', state.length, state.ended);
19651 if (state.length === 0 && state.ended)
19654 emitReadable(this);
19658 n = howMuchToRead(n, state);
19660 // if we've ended, and we're now clear, then finish it up.
19661 if (n === 0 && state.ended) {
19662 if (state.length === 0)
19667 // All the actual chunk generation logic needs to be
19668 // *below* the call to _read. The reason is that in certain
19669 // synthetic stream cases, such as passthrough streams, _read
19670 // may be a completely synchronous operation which may change
19671 // the state of the read buffer, providing enough data when
19672 // before there was *not* enough.
19674 // So, the steps are:
19675 // 1. Figure out what the state of things will be after we do
19676 // a read from the buffer.
19678 // 2. If that resulting state will trigger a _read, then call _read.
19679 // Note that this may be asynchronous, or synchronous. Yes, it is
19680 // deeply ugly to write APIs this way, but that still doesn't mean
19681 // that the Readable class should behave improperly, as streams are
19682 // designed to be sync/async agnostic.
19683 // Take note if the _read call is sync or async (ie, if the read call
19684 // has returned yet), so that we know whether or not it's safe to emit
19687 // 3. Actually pull the requested chunks out of the buffer and return.
19689 // if we need a readable event, then we need to do some reading.
19690 var doRead = state.needReadable;
19691 debug('need readable', doRead);
19693 // if we currently have less than the highWaterMark, then also read some
19694 if (state.length === 0 || state.length - n < state.highWaterMark) {
19696 debug('length less than watermark', doRead);
19699 // however, if we've ended, then there's no point, and if we're already
19700 // reading, then it's unnecessary.
19701 if (state.ended || state.reading) {
19703 debug('reading or ended', doRead);
19708 state.reading = true;
19710 // if the length is currently zero, then we *need* a readable event.
19711 if (state.length === 0)
19712 state.needReadable = true;
19713 // call internal read method
19714 this._read(state.highWaterMark);
19715 state.sync = false;
19718 // If _read pushed data synchronously, then `reading` will be false,
19719 // and we need to re-evaluate how much data we can return to the user.
19720 if (doRead && !state.reading)
19721 n = howMuchToRead(nOrig, state);
19725 ret = fromList(n, state);
19729 if (util.isNull(ret)) {
19730 state.needReadable = true;
19736 // If we have nothing in the buffer, then we want to know
19737 // as soon as we *do* get something into the buffer.
19738 if (state.length === 0 && !state.ended)
19739 state.needReadable = true;
19741 // If we tried to read() past the EOF, then emit end on the next tick.
19742 if (nOrig !== n && state.ended && state.length === 0)
19745 if (!util.isNull(ret))
19746 this.emit('data', ret);
19751 function chunkInvalid(state, chunk) {
19753 if (!util.isBuffer(chunk) &&
19754 !util.isString(chunk) &&
19755 !util.isNullOrUndefined(chunk) &&
19756 !state.objectMode) {
19757 er = new TypeError('Invalid non-string/buffer chunk');
19763 function onEofChunk(stream, state) {
19764 if (state.decoder && !state.ended) {
19765 var chunk = state.decoder.end();
19766 if (chunk && chunk.length) {
19767 state.buffer.push(chunk);
19768 state.length += state.objectMode ? 1 : chunk.length;
19771 state.ended = true;
19773 // emit 'readable' now to make sure it gets picked up.
19774 emitReadable(stream);
19777 // Don't emit readable right away in sync mode, because this can trigger
19778 // another read() call => stack overflow. This way, it might trigger
19779 // a nextTick recursion warning, but that's not so bad.
19780 function emitReadable(stream) {
19781 var state = stream._readableState;
19782 state.needReadable = false;
19783 if (!state.emittedReadable) {
19784 debug('emitReadable', state.flowing);
19785 state.emittedReadable = true;
19787 process.nextTick(function() {
19788 emitReadable_(stream);
19791 emitReadable_(stream);
19795 function emitReadable_(stream) {
19796 debug('emit readable');
19797 stream.emit('readable');
19802 // at this point, the user has presumably seen the 'readable' event,
19803 // and called read() to consume some data. that may have triggered
19804 // in turn another _read(n) call, in which case reading = true if
19805 // it's in progress.
19806 // However, if we're not ended, or reading, and the length < hwm,
19807 // then go ahead and try to read some more preemptively.
19808 function maybeReadMore(stream, state) {
19809 if (!state.readingMore) {
19810 state.readingMore = true;
19811 process.nextTick(function() {
19812 maybeReadMore_(stream, state);
19817 function maybeReadMore_(stream, state) {
19818 var len = state.length;
19819 while (!state.reading && !state.flowing && !state.ended &&
19820 state.length < state.highWaterMark) {
19821 debug('maybeReadMore read 0');
19823 if (len === state.length)
19824 // didn't get any data, stop spinning.
19827 len = state.length;
19829 state.readingMore = false;
19832 // abstract method. to be overridden in specific implementation classes.
19833 // call cb(er, data) where data is <= n in length.
19834 // for virtual (non-string, non-buffer) streams, "length" is somewhat
19835 // arbitrary, and perhaps not very meaningful.
19836 Readable.prototype._read = function(n) {
19837 this.emit('error', new Error('not implemented'));
19840 Readable.prototype.pipe = function(dest, pipeOpts) {
19842 var state = this._readableState;
19844 switch (state.pipesCount) {
19846 state.pipes = dest;
19849 state.pipes = [state.pipes, dest];
19852 state.pipes.push(dest);
19855 state.pipesCount += 1;
19856 debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
19858 var doEnd = (!pipeOpts || pipeOpts.end !== false) &&
19859 dest !== process.stdout &&
19860 dest !== process.stderr;
19862 var endFn = doEnd ? onend : cleanup;
19863 if (state.endEmitted)
19864 process.nextTick(endFn);
19866 src.once('end', endFn);
19868 dest.on('unpipe', onunpipe);
19869 function onunpipe(readable) {
19871 if (readable === src) {
19881 // when the dest drains, it reduces the awaitDrain counter
19882 // on the source. This would be more elegant with a .once()
19883 // handler in flow(), but adding and removing repeatedly is
19885 var ondrain = pipeOnDrain(src);
19886 dest.on('drain', ondrain);
19888 function cleanup() {
19890 // cleanup event handlers once the pipe is broken
19891 dest.removeListener('close', onclose);
19892 dest.removeListener('finish', onfinish);
19893 dest.removeListener('drain', ondrain);
19894 dest.removeListener('error', onerror);
19895 dest.removeListener('unpipe', onunpipe);
19896 src.removeListener('end', onend);
19897 src.removeListener('end', cleanup);
19898 src.removeListener('data', ondata);
19900 // if the reader is waiting for a drain event from this
19901 // specific writer, then it would cause it to never start
19903 // So, if this is awaiting a drain, then we just call it now.
19904 // If we don't know, then assume that we are waiting for one.
19905 if (state.awaitDrain &&
19906 (!dest._writableState || dest._writableState.needDrain))
19910 src.on('data', ondata);
19911 function ondata(chunk) {
19913 var ret = dest.write(chunk);
19914 if (false === ret) {
19915 debug('false write response, pause',
19916 src._readableState.awaitDrain);
19917 src._readableState.awaitDrain++;
19922 // if the dest has an error, then stop piping into it.
19923 // however, don't suppress the throwing behavior for this.
19924 function onerror(er) {
19925 debug('onerror', er);
19927 dest.removeListener('error', onerror);
19928 if (EE.listenerCount(dest, 'error') === 0)
19929 dest.emit('error', er);
19931 // This is a brutally ugly hack to make sure that our error handler
19932 // is attached before any userland ones. NEVER DO THIS.
19933 if (!dest._events || !dest._events.error)
19934 dest.on('error', onerror);
19935 else if (isArray(dest._events.error))
19936 dest._events.error.unshift(onerror);
19938 dest._events.error = [onerror, dest._events.error];
19942 // Both close and finish should trigger unpipe, but only once.
19943 function onclose() {
19944 dest.removeListener('finish', onfinish);
19947 dest.once('close', onclose);
19948 function onfinish() {
19950 dest.removeListener('close', onclose);
19953 dest.once('finish', onfinish);
19955 function unpipe() {
19960 // tell the dest that it's being piped to
19961 dest.emit('pipe', src);
19963 // start the flow if it hasn't been started already.
19964 if (!state.flowing) {
19965 debug('pipe resume');
19972 function pipeOnDrain(src) {
19973 return function() {
19974 var state = src._readableState;
19975 debug('pipeOnDrain', state.awaitDrain);
19976 if (state.awaitDrain)
19977 state.awaitDrain--;
19978 if (state.awaitDrain === 0 && EE.listenerCount(src, 'data')) {
19979 state.flowing = true;
19986 Readable.prototype.unpipe = function(dest) {
19987 var state = this._readableState;
19989 // if we're not piping anywhere, then do nothing.
19990 if (state.pipesCount === 0)
19993 // just one destination. most common case.
19994 if (state.pipesCount === 1) {
19995 // passed in one, but it's not the right one.
19996 if (dest && dest !== state.pipes)
20000 dest = state.pipes;
20003 state.pipes = null;
20004 state.pipesCount = 0;
20005 state.flowing = false;
20007 dest.emit('unpipe', this);
20011 // slow case. multiple pipe destinations.
20015 var dests = state.pipes;
20016 var len = state.pipesCount;
20017 state.pipes = null;
20018 state.pipesCount = 0;
20019 state.flowing = false;
20021 for (var i = 0; i < len; i++)
20022 dests[i].emit('unpipe', this);
20026 // try to find the right one.
20027 var i = indexOf(state.pipes, dest);
20031 state.pipes.splice(i, 1);
20032 state.pipesCount -= 1;
20033 if (state.pipesCount === 1)
20034 state.pipes = state.pipes[0];
20036 dest.emit('unpipe', this);
20041 // set up data events if they are asked for
20042 // Ensure readable listeners eventually get something
20043 Readable.prototype.on = function(ev, fn) {
20044 var res = Stream.prototype.on.call(this, ev, fn);
20046 // If listening to data, and it has not explicitly been paused,
20047 // then call resume to start the flow of data on the next tick.
20048 if (ev === 'data' && false !== this._readableState.flowing) {
20052 if (ev === 'readable' && this.readable) {
20053 var state = this._readableState;
20054 if (!state.readableListening) {
20055 state.readableListening = true;
20056 state.emittedReadable = false;
20057 state.needReadable = true;
20058 if (!state.reading) {
20060 process.nextTick(function() {
20061 debug('readable nexttick read 0');
20064 } else if (state.length) {
20065 emitReadable(this, state);
20072 Readable.prototype.addListener = Readable.prototype.on;
20074 // pause() and resume() are remnants of the legacy readable stream API
20075 // If the user uses them, then switch into old mode.
20076 Readable.prototype.resume = function() {
20077 var state = this._readableState;
20078 if (!state.flowing) {
20080 state.flowing = true;
20081 if (!state.reading) {
20082 debug('resume read 0');
20085 resume(this, state);
20090 function resume(stream, state) {
20091 if (!state.resumeScheduled) {
20092 state.resumeScheduled = true;
20093 process.nextTick(function() {
20094 resume_(stream, state);
20099 function resume_(stream, state) {
20100 state.resumeScheduled = false;
20101 stream.emit('resume');
20103 if (state.flowing && !state.reading)
20107 Readable.prototype.pause = function() {
20108 debug('call pause flowing=%j', this._readableState.flowing);
20109 if (false !== this._readableState.flowing) {
20111 this._readableState.flowing = false;
20112 this.emit('pause');
20117 function flow(stream) {
20118 var state = stream._readableState;
20119 debug('flow', state.flowing);
20120 if (state.flowing) {
20122 var chunk = stream.read();
20123 } while (null !== chunk && state.flowing);
20127 // wrap an old-style stream as the async data source.
20128 // This is *not* part of the readable stream interface.
20129 // It is an ugly unfortunate mess of history.
20130 Readable.prototype.wrap = function(stream) {
20131 var state = this._readableState;
20132 var paused = false;
20135 stream.on('end', function() {
20136 debug('wrapped end');
20137 if (state.decoder && !state.ended) {
20138 var chunk = state.decoder.end();
20139 if (chunk && chunk.length)
20146 stream.on('data', function(chunk) {
20147 debug('wrapped data');
20149 chunk = state.decoder.write(chunk);
20150 if (!chunk || !state.objectMode && !chunk.length)
20153 var ret = self.push(chunk);
20160 // proxy all the other methods.
20161 // important when wrapping filters and duplexes.
20162 for (var i in stream) {
20163 if (util.isFunction(stream[i]) && util.isUndefined(this[i])) {
20164 this[i] = function(method) { return function() {
20165 return stream[method].apply(stream, arguments);
20170 // proxy certain important events.
20171 var events = ['error', 'close', 'destroy', 'pause', 'resume'];
20172 forEach(events, function(ev) {
20173 stream.on(ev, self.emit.bind(self, ev));
20176 // when we try to consume some more bytes, simply unpause the
20177 // underlying stream.
20178 self._read = function(n) {
20179 debug('wrapped _read', n);
20191 // exposed for testing purposes only.
20192 Readable._fromList = fromList;
20194 // Pluck off n bytes from an array of buffers.
20195 // Length is the combined lengths of all the buffers in the list.
20196 function fromList(n, state) {
20197 var list = state.buffer;
20198 var length = state.length;
20199 var stringMode = !!state.decoder;
20200 var objectMode = !!state.objectMode;
20203 // nothing in the list, definitely empty.
20204 if (list.length === 0)
20209 else if (objectMode)
20210 ret = list.shift();
20211 else if (!n || n >= length) {
20212 // read it all, truncate the array.
20214 ret = list.join('');
20216 ret = Buffer.concat(list, length);
20219 // read just some of it.
20220 if (n < list[0].length) {
20221 // just take a part of the first list item.
20222 // slice is the same for buffers and strings.
20224 ret = buf.slice(0, n);
20225 list[0] = buf.slice(n);
20226 } else if (n === list[0].length) {
20227 // first list is a perfect match
20228 ret = list.shift();
20231 // we have enough to cover it, but it spans past the first buffer.
20235 ret = new Buffer(n);
20238 for (var i = 0, l = list.length; i < l && c < n; i++) {
20240 var cpy = Math.min(n - c, buf.length);
20243 ret += buf.slice(0, cpy);
20245 buf.copy(ret, c, 0, cpy);
20247 if (cpy < buf.length)
20248 list[0] = buf.slice(cpy);
20260 function endReadable(stream) {
20261 var state = stream._readableState;
20263 // If we get here before consuming all the bytes, then that is a
20264 // bug in node. Should never happen.
20265 if (state.length > 0)
20266 throw new Error('endReadable called on non-empty stream');
20268 if (!state.endEmitted) {
20269 state.ended = true;
20270 process.nextTick(function() {
20271 // Check that we didn't get one last unshift.
20272 if (!state.endEmitted && state.length === 0) {
20273 state.endEmitted = true;
20274 stream.readable = false;
20275 stream.emit('end');
20281 function forEach (xs, f) {
20282 for (var i = 0, l = xs.length; i < l; i++) {
20287 function indexOf (xs, x) {
20288 for (var i = 0, l = xs.length; i < l; i++) {
20289 if (xs[i] === x) return i;
20294 /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(30)))
20298 /***/ function(module, exports) {
20300 // shim for using process in browser
20302 var process = module.exports = {};
20304 var draining = false;
20306 var queueIndex = -1;
20308 function cleanUpNextTick() {
20310 if (currentQueue.length) {
20311 queue = currentQueue.concat(queue);
20315 if (queue.length) {
20320 function drainQueue() {
20324 var timeout = setTimeout(cleanUpNextTick);
20327 var len = queue.length;
20329 currentQueue = queue;
20331 while (++queueIndex < len) {
20332 if (currentQueue) {
20333 currentQueue[queueIndex].run();
20337 len = queue.length;
20339 currentQueue = null;
20341 clearTimeout(timeout);
20344 process.nextTick = function (fun) {
20345 var args = new Array(arguments.length - 1);
20346 if (arguments.length > 1) {
20347 for (var i = 1; i < arguments.length; i++) {
20348 args[i - 1] = arguments[i];
20351 queue.push(new Item(fun, args));
20352 if (queue.length === 1 && !draining) {
20353 setTimeout(drainQueue, 0);
20357 // v8 likes predictible objects
20358 function Item(fun, array) {
20360 this.array = array;
20362 Item.prototype.run = function () {
20363 this.fun.apply(null, this.array);
20365 process.title = 'browser';
20366 process.browser = true;
20369 process.version = ''; // empty string to avoid regexp issues
20370 process.versions = {};
20375 process.addListener = noop;
20376 process.once = noop;
20377 process.off = noop;
20378 process.removeListener = noop;
20379 process.removeAllListeners = noop;
20380 process.emit = noop;
20382 process.binding = function (name) {
20383 throw new Error('process.binding is not supported');
20386 process.cwd = function () { return '/' };
20387 process.chdir = function (dir) {
20388 throw new Error('process.chdir is not supported');
20390 process.umask = function() { return 0; };
20395 /***/ function(module, exports) {
20397 module.exports = Array.isArray || function (arr) {
20398 return Object.prototype.toString.call(arr) == '[object Array]';
20404 /***/ function(module, exports, __webpack_require__) {
20406 /* WEBPACK VAR INJECTION */(function(Buffer) {// Copyright Joyent, Inc. and other Node contributors.
20408 // Permission is hereby granted, free of charge, to any person obtaining a
20409 // copy of this software and associated documentation files (the
20410 // "Software"), to deal in the Software without restriction, including
20411 // without limitation the rights to use, copy, modify, merge, publish,
20412 // distribute, sublicense, and/or sell copies of the Software, and to permit
20413 // persons to whom the Software is furnished to do so, subject to the
20414 // following conditions:
20416 // The above copyright notice and this permission notice shall be included
20417 // in all copies or substantial portions of the Software.
20419 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
20420 // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
20421 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
20422 // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
20423 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
20424 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20425 // USE OR OTHER DEALINGS IN THE SOFTWARE.
20427 // NOTE: These type checking functions intentionally don't use `instanceof`
20428 // because it is fragile and can be easily faked with `Object.create()`.
20429 function isArray(ar) {
20430 return Array.isArray(ar);
20432 exports.isArray = isArray;
20434 function isBoolean(arg) {
20435 return typeof arg === 'boolean';
20437 exports.isBoolean = isBoolean;
20439 function isNull(arg) {
20440 return arg === null;
20442 exports.isNull = isNull;
20444 function isNullOrUndefined(arg) {
20445 return arg == null;
20447 exports.isNullOrUndefined = isNullOrUndefined;
20449 function isNumber(arg) {
20450 return typeof arg === 'number';
20452 exports.isNumber = isNumber;
20454 function isString(arg) {
20455 return typeof arg === 'string';
20457 exports.isString = isString;
20459 function isSymbol(arg) {
20460 return typeof arg === 'symbol';
20462 exports.isSymbol = isSymbol;
20464 function isUndefined(arg) {
20465 return arg === void 0;
20467 exports.isUndefined = isUndefined;
20469 function isRegExp(re) {
20470 return isObject(re) && objectToString(re) === '[object RegExp]';
20472 exports.isRegExp = isRegExp;
20474 function isObject(arg) {
20475 return typeof arg === 'object' && arg !== null;
20477 exports.isObject = isObject;
20479 function isDate(d) {
20480 return isObject(d) && objectToString(d) === '[object Date]';
20482 exports.isDate = isDate;
20484 function isError(e) {
20485 return isObject(e) &&
20486 (objectToString(e) === '[object Error]' || e instanceof Error);
20488 exports.isError = isError;
20490 function isFunction(arg) {
20491 return typeof arg === 'function';
20493 exports.isFunction = isFunction;
20495 function isPrimitive(arg) {
20496 return arg === null ||
20497 typeof arg === 'boolean' ||
20498 typeof arg === 'number' ||
20499 typeof arg === 'string' ||
20500 typeof arg === 'symbol' || // ES6 symbol
20501 typeof arg === 'undefined';
20503 exports.isPrimitive = isPrimitive;
20505 function isBuffer(arg) {
20506 return Buffer.isBuffer(arg);
20508 exports.isBuffer = isBuffer;
20510 function objectToString(o) {
20511 return Object.prototype.toString.call(o);
20513 /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2).Buffer))
20517 /***/ function(module, exports) {
20519 if (typeof Object.create === 'function') {
20520 // implementation from standard node.js 'util' module
20521 module.exports = function inherits(ctor, superCtor) {
20522 ctor.super_ = superCtor
20523 ctor.prototype = Object.create(superCtor.prototype, {
20533 // old school shim for old browsers
20534 module.exports = function inherits(ctor, superCtor) {
20535 ctor.super_ = superCtor
20536 var TempCtor = function () {}
20537 TempCtor.prototype = superCtor.prototype
20538 ctor.prototype = new TempCtor()
20539 ctor.prototype.constructor = ctor
20546 /***/ function(module, exports) {
20552 /***/ function(module, exports, __webpack_require__) {
20554 /* WEBPACK VAR INJECTION */(function(process) {// Copyright Joyent, Inc. and other Node contributors.
20556 // Permission is hereby granted, free of charge, to any person obtaining a
20557 // copy of this software and associated documentation files (the
20558 // "Software"), to deal in the Software without restriction, including
20559 // without limitation the rights to use, copy, modify, merge, publish,
20560 // distribute, sublicense, and/or sell copies of the Software, and to permit
20561 // persons to whom the Software is furnished to do so, subject to the
20562 // following conditions:
20564 // The above copyright notice and this permission notice shall be included
20565 // in all copies or substantial portions of the Software.
20567 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
20568 // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
20569 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
20570 // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
20571 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
20572 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20573 // USE OR OTHER DEALINGS IN THE SOFTWARE.
20575 // a duplex stream is just a stream that is both readable and writable.
20576 // Since JS doesn't have multiple prototypal inheritance, this class
20577 // prototypally inherits from Readable, and then parasitically from
20580 module.exports = Duplex;
20583 var objectKeys = Object.keys || function (obj) {
20585 for (var key in obj) keys.push(key);
20592 var util = __webpack_require__(32);
20593 util.inherits = __webpack_require__(33);
20596 var Readable = __webpack_require__(29);
20597 var Writable = __webpack_require__(36);
20599 util.inherits(Duplex, Readable);
20601 forEach(objectKeys(Writable.prototype), function(method) {
20602 if (!Duplex.prototype[method])
20603 Duplex.prototype[method] = Writable.prototype[method];
20606 function Duplex(options) {
20607 if (!(this instanceof Duplex))
20608 return new Duplex(options);
20610 Readable.call(this, options);
20611 Writable.call(this, options);
20613 if (options && options.readable === false)
20614 this.readable = false;
20616 if (options && options.writable === false)
20617 this.writable = false;
20619 this.allowHalfOpen = true;
20620 if (options && options.allowHalfOpen === false)
20621 this.allowHalfOpen = false;
20623 this.once('end', onend);
20626 // the no-half-open enforcer
20628 // if we allow half-open state, or if the writable side ended,
20630 if (this.allowHalfOpen || this._writableState.ended)
20633 // no more data can be written.
20634 // But allow more writes to happen in this tick.
20635 process.nextTick(this.end.bind(this));
20638 function forEach (xs, f) {
20639 for (var i = 0, l = xs.length; i < l; i++) {
20644 /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(30)))
20648 /***/ function(module, exports, __webpack_require__) {
20650 /* WEBPACK VAR INJECTION */(function(process) {// Copyright Joyent, Inc. and other Node contributors.
20652 // Permission is hereby granted, free of charge, to any person obtaining a
20653 // copy of this software and associated documentation files (the
20654 // "Software"), to deal in the Software without restriction, including
20655 // without limitation the rights to use, copy, modify, merge, publish,
20656 // distribute, sublicense, and/or sell copies of the Software, and to permit
20657 // persons to whom the Software is furnished to do so, subject to the
20658 // following conditions:
20660 // The above copyright notice and this permission notice shall be included
20661 // in all copies or substantial portions of the Software.
20663 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
20664 // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
20665 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
20666 // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
20667 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
20668 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20669 // USE OR OTHER DEALINGS IN THE SOFTWARE.
20671 // A bit simpler than readable streams.
20672 // Implement an async ._write(chunk, cb), and it'll handle all
20673 // the drain event emission and buffering.
20675 module.exports = Writable;
20678 var Buffer = __webpack_require__(2).Buffer;
20681 Writable.WritableState = WritableState;
20685 var util = __webpack_require__(32);
20686 util.inherits = __webpack_require__(33);
20689 var Stream = __webpack_require__(25);
20691 util.inherits(Writable, Stream);
20693 function WriteReq(chunk, encoding, cb) {
20694 this.chunk = chunk;
20695 this.encoding = encoding;
20696 this.callback = cb;
20699 function WritableState(options, stream) {
20700 var Duplex = __webpack_require__(35);
20702 options = options || {};
20704 // the point at which write() starts returning false
20705 // Note: 0 is a valid value, means that we always return false if
20706 // the entire buffer is not flushed immediately on write()
20707 var hwm = options.highWaterMark;
20708 var defaultHwm = options.objectMode ? 16 : 16 * 1024;
20709 this.highWaterMark = (hwm || hwm === 0) ? hwm : defaultHwm;
20711 // object stream flag to indicate whether or not this stream
20712 // contains buffers or objects.
20713 this.objectMode = !!options.objectMode;
20715 if (stream instanceof Duplex)
20716 this.objectMode = this.objectMode || !!options.writableObjectMode;
20719 this.highWaterMark = ~~this.highWaterMark;
20721 this.needDrain = false;
20722 // at the start of calling end()
20723 this.ending = false;
20724 // when end() has been called, and returned
20725 this.ended = false;
20726 // when 'finish' is emitted
20727 this.finished = false;
20729 // should we decode strings into buffers before passing to _write?
20730 // this is here so that some node-core streams can optimize string
20731 // handling at a lower level.
20732 var noDecode = options.decodeStrings === false;
20733 this.decodeStrings = !noDecode;
20735 // Crypto is kind of old and crusty. Historically, its default string
20736 // encoding is 'binary' so we have to make this configurable.
20737 // Everything else in the universe uses 'utf8', though.
20738 this.defaultEncoding = options.defaultEncoding || 'utf8';
20740 // not an actual buffer we keep track of, but a measurement
20741 // of how much we're waiting to get pushed to some underlying
20745 // a flag to see when we're in the middle of a write.
20746 this.writing = false;
20748 // when true all writes will be buffered until .uncork() call
20751 // a flag to be able to tell if the onwrite cb is called immediately,
20752 // or on a later tick. We set this to true at first, because any
20753 // actions that shouldn't happen until "later" should generally also
20754 // not happen before the first write call.
20757 // a flag to know if we're processing previously buffered items, which
20758 // may call the _write() callback in the same tick, so that we don't
20759 // end up in an overlapped onwrite situation.
20760 this.bufferProcessing = false;
20762 // the callback that's passed to _write(chunk,cb)
20763 this.onwrite = function(er) {
20764 onwrite(stream, er);
20767 // the callback that the user supplies to write(chunk,encoding,cb)
20768 this.writecb = null;
20770 // the amount that is being written when _write is called.
20775 // number of pending user-supplied write callbacks
20776 // this must be 0 before 'finish' can be emitted
20777 this.pendingcb = 0;
20779 // emit prefinish if the only thing we're waiting for is _write cbs
20780 // This is relevant for synchronous Transform streams
20781 this.prefinished = false;
20783 // True if the error was already emitted and should not be thrown again
20784 this.errorEmitted = false;
20787 function Writable(options) {
20788 var Duplex = __webpack_require__(35);
20790 // Writable ctor is applied to Duplexes, though they're not
20791 // instanceof Writable, they're instanceof Readable.
20792 if (!(this instanceof Writable) && !(this instanceof Duplex))
20793 return new Writable(options);
20795 this._writableState = new WritableState(options, this);
20798 this.writable = true;
20803 // Otherwise people can pipe Writable streams, which is just wrong.
20804 Writable.prototype.pipe = function() {
20805 this.emit('error', new Error('Cannot pipe. Not readable.'));
20809 function writeAfterEnd(stream, state, cb) {
20810 var er = new Error('write after end');
20811 // TODO: defer error events consistently everywhere, not just the cb
20812 stream.emit('error', er);
20813 process.nextTick(function() {
20818 // If we get something that is not a buffer, string, null, or undefined,
20819 // and we're not in objectMode, then that's an error.
20820 // Otherwise stream chunks are all considered to be of length=1, and the
20821 // watermarks determine how many objects to keep in the buffer, rather than
20822 // how many bytes or characters.
20823 function validChunk(stream, state, chunk, cb) {
20825 if (!util.isBuffer(chunk) &&
20826 !util.isString(chunk) &&
20827 !util.isNullOrUndefined(chunk) &&
20828 !state.objectMode) {
20829 var er = new TypeError('Invalid non-string/buffer chunk');
20830 stream.emit('error', er);
20831 process.nextTick(function() {
20839 Writable.prototype.write = function(chunk, encoding, cb) {
20840 var state = this._writableState;
20843 if (util.isFunction(encoding)) {
20848 if (util.isBuffer(chunk))
20849 encoding = 'buffer';
20850 else if (!encoding)
20851 encoding = state.defaultEncoding;
20853 if (!util.isFunction(cb))
20854 cb = function() {};
20857 writeAfterEnd(this, state, cb);
20858 else if (validChunk(this, state, chunk, cb)) {
20860 ret = writeOrBuffer(this, state, chunk, encoding, cb);
20866 Writable.prototype.cork = function() {
20867 var state = this._writableState;
20872 Writable.prototype.uncork = function() {
20873 var state = this._writableState;
20875 if (state.corked) {
20878 if (!state.writing &&
20881 !state.bufferProcessing &&
20882 state.buffer.length)
20883 clearBuffer(this, state);
20887 function decodeChunk(state, chunk, encoding) {
20888 if (!state.objectMode &&
20889 state.decodeStrings !== false &&
20890 util.isString(chunk)) {
20891 chunk = new Buffer(chunk, encoding);
20896 // if we're already writing something, then just put this
20897 // in the queue, and wait our turn. Otherwise, call _write
20898 // If we return false, then we need a drain event, so set that flag.
20899 function writeOrBuffer(stream, state, chunk, encoding, cb) {
20900 chunk = decodeChunk(state, chunk, encoding);
20901 if (util.isBuffer(chunk))
20902 encoding = 'buffer';
20903 var len = state.objectMode ? 1 : chunk.length;
20905 state.length += len;
20907 var ret = state.length < state.highWaterMark;
20908 // we must ensure that previous needDrain will not be reset to false.
20910 state.needDrain = true;
20912 if (state.writing || state.corked)
20913 state.buffer.push(new WriteReq(chunk, encoding, cb));
20915 doWrite(stream, state, false, len, chunk, encoding, cb);
20920 function doWrite(stream, state, writev, len, chunk, encoding, cb) {
20921 state.writelen = len;
20922 state.writecb = cb;
20923 state.writing = true;
20926 stream._writev(chunk, state.onwrite);
20928 stream._write(chunk, encoding, state.onwrite);
20929 state.sync = false;
20932 function onwriteError(stream, state, sync, er, cb) {
20934 process.nextTick(function() {
20943 stream._writableState.errorEmitted = true;
20944 stream.emit('error', er);
20947 function onwriteStateUpdate(state) {
20948 state.writing = false;
20949 state.writecb = null;
20950 state.length -= state.writelen;
20951 state.writelen = 0;
20954 function onwrite(stream, er) {
20955 var state = stream._writableState;
20956 var sync = state.sync;
20957 var cb = state.writecb;
20959 onwriteStateUpdate(state);
20962 onwriteError(stream, state, sync, er, cb);
20964 // Check if we're actually ready to finish, but don't emit yet
20965 var finished = needFinish(stream, state);
20969 !state.bufferProcessing &&
20970 state.buffer.length) {
20971 clearBuffer(stream, state);
20975 process.nextTick(function() {
20976 afterWrite(stream, state, finished, cb);
20979 afterWrite(stream, state, finished, cb);
20984 function afterWrite(stream, state, finished, cb) {
20986 onwriteDrain(stream, state);
20989 finishMaybe(stream, state);
20992 // Must force callback to be called on nextTick, so that we don't
20993 // emit 'drain' before the write() consumer gets the 'false' return
20994 // value, and has a chance to attach a 'drain' listener.
20995 function onwriteDrain(stream, state) {
20996 if (state.length === 0 && state.needDrain) {
20997 state.needDrain = false;
20998 stream.emit('drain');
21003 // if there's something in the buffer waiting, then process it
21004 function clearBuffer(stream, state) {
21005 state.bufferProcessing = true;
21007 if (stream._writev && state.buffer.length > 1) {
21008 // Fast case, write everything using _writev()
21010 for (var c = 0; c < state.buffer.length; c++)
21011 cbs.push(state.buffer[c].callback);
21013 // count the one we are adding, as well.
21014 // TODO(isaacs) clean this up
21016 doWrite(stream, state, true, state.length, state.buffer, '', function(err) {
21017 for (var i = 0; i < cbs.length; i++) {
21026 // Slow case, write chunks one-by-one
21027 for (var c = 0; c < state.buffer.length; c++) {
21028 var entry = state.buffer[c];
21029 var chunk = entry.chunk;
21030 var encoding = entry.encoding;
21031 var cb = entry.callback;
21032 var len = state.objectMode ? 1 : chunk.length;
21034 doWrite(stream, state, false, len, chunk, encoding, cb);
21036 // if we didn't call the onwrite immediately, then
21037 // it means that we need to wait until it does.
21038 // also, that means that the chunk and cb are currently
21039 // being processed, so move the buffer counter past them.
21040 if (state.writing) {
21046 if (c < state.buffer.length)
21047 state.buffer = state.buffer.slice(c);
21049 state.buffer.length = 0;
21052 state.bufferProcessing = false;
21055 Writable.prototype._write = function(chunk, encoding, cb) {
21056 cb(new Error('not implemented'));
21060 Writable.prototype._writev = null;
21062 Writable.prototype.end = function(chunk, encoding, cb) {
21063 var state = this._writableState;
21065 if (util.isFunction(chunk)) {
21069 } else if (util.isFunction(encoding)) {
21074 if (!util.isNullOrUndefined(chunk))
21075 this.write(chunk, encoding);
21077 // .end() fully uncorks
21078 if (state.corked) {
21083 // ignore unnecessary end() calls.
21084 if (!state.ending && !state.finished)
21085 endWritable(this, state, cb);
21089 function needFinish(stream, state) {
21090 return (state.ending &&
21091 state.length === 0 &&
21096 function prefinish(stream, state) {
21097 if (!state.prefinished) {
21098 state.prefinished = true;
21099 stream.emit('prefinish');
21103 function finishMaybe(stream, state) {
21104 var need = needFinish(stream, state);
21106 if (state.pendingcb === 0) {
21107 prefinish(stream, state);
21108 state.finished = true;
21109 stream.emit('finish');
21111 prefinish(stream, state);
21116 function endWritable(stream, state, cb) {
21117 state.ending = true;
21118 finishMaybe(stream, state);
21120 if (state.finished)
21121 process.nextTick(cb);
21123 stream.once('finish', cb);
21125 state.ended = true;
21128 /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(30)))
21132 /***/ function(module, exports, __webpack_require__) {
21134 // Copyright Joyent, Inc. and other Node contributors.
21136 // Permission is hereby granted, free of charge, to any person obtaining a
21137 // copy of this software and associated documentation files (the
21138 // "Software"), to deal in the Software without restriction, including
21139 // without limitation the rights to use, copy, modify, merge, publish,
21140 // distribute, sublicense, and/or sell copies of the Software, and to permit
21141 // persons to whom the Software is furnished to do so, subject to the
21142 // following conditions:
21144 // The above copyright notice and this permission notice shall be included
21145 // in all copies or substantial portions of the Software.
21147 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
21148 // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
21149 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
21150 // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
21151 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
21152 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
21153 // USE OR OTHER DEALINGS IN THE SOFTWARE.
21155 var Buffer = __webpack_require__(2).Buffer;
21157 var isBufferEncoding = Buffer.isEncoding
21158 || function(encoding) {
21159 switch (encoding && encoding.toLowerCase()) {
21160 case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': case 'raw': return true;
21161 default: return false;
21166 function assertEncoding(encoding) {
21167 if (encoding && !isBufferEncoding(encoding)) {
21168 throw new Error('Unknown encoding: ' + encoding);
21172 // StringDecoder provides an interface for efficiently splitting a series of
21173 // buffers into a series of JS strings without breaking apart multi-byte
21174 // characters. CESU-8 is handled as part of the UTF-8 encoding.
21176 // @TODO Handling all encodings inside a single object makes it very difficult
21177 // to reason about this code, so it should be split up in the future.
21178 // @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code
21179 // points as used by CESU-8.
21180 var StringDecoder = exports.StringDecoder = function(encoding) {
21181 this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, '');
21182 assertEncoding(encoding);
21183 switch (this.encoding) {
21185 // CESU-8 represents each of Surrogate Pair by 3-bytes
21186 this.surrogateSize = 3;
21190 // UTF-16 represents each of Surrogate Pair by 2-bytes
21191 this.surrogateSize = 2;
21192 this.detectIncompleteChar = utf16DetectIncompleteChar;
21195 // Base-64 stores 3 bytes in 4 chars, and pads the remainder.
21196 this.surrogateSize = 3;
21197 this.detectIncompleteChar = base64DetectIncompleteChar;
21200 this.write = passThroughWrite;
21204 // Enough space to store all bytes of a single character. UTF-8 needs 4
21205 // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate).
21206 this.charBuffer = new Buffer(6);
21207 // Number of bytes received for the current incomplete multi-byte character.
21208 this.charReceived = 0;
21209 // Number of bytes expected for the current incomplete multi-byte character.
21210 this.charLength = 0;
21214 // write decodes the given buffer and returns it as JS string that is
21215 // guaranteed to not contain any partial multi-byte characters. Any partial
21216 // character found at the end of the buffer is buffered up, and will be
21217 // returned when calling write again with the remaining bytes.
21219 // Note: Converting a Buffer containing an orphan surrogate to a String
21220 // currently works, but converting a String to a Buffer (via `new Buffer`, or
21221 // Buffer#write) will replace incomplete surrogates with the unicode
21222 // replacement character. See https://codereview.chromium.org/121173009/ .
21223 StringDecoder.prototype.write = function(buffer) {
21225 // if our last write ended with an incomplete multibyte character
21226 while (this.charLength) {
21227 // determine how many remaining bytes this buffer has to offer for this char
21228 var available = (buffer.length >= this.charLength - this.charReceived) ?
21229 this.charLength - this.charReceived :
21232 // add the new bytes to the char buffer
21233 buffer.copy(this.charBuffer, this.charReceived, 0, available);
21234 this.charReceived += available;
21236 if (this.charReceived < this.charLength) {
21237 // still not enough chars in this buffer? wait for more ...
21241 // remove bytes belonging to the current character from the buffer
21242 buffer = buffer.slice(available, buffer.length);
21244 // get the character that was split
21245 charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding);
21247 // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character
21248 var charCode = charStr.charCodeAt(charStr.length - 1);
21249 if (charCode >= 0xD800 && charCode <= 0xDBFF) {
21250 this.charLength += this.surrogateSize;
21254 this.charReceived = this.charLength = 0;
21256 // if there are no more bytes in this buffer, just emit our char
21257 if (buffer.length === 0) {
21263 // determine and set charLength / charReceived
21264 this.detectIncompleteChar(buffer);
21266 var end = buffer.length;
21267 if (this.charLength) {
21268 // buffer the incomplete character bytes we got
21269 buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end);
21270 end -= this.charReceived;
21273 charStr += buffer.toString(this.encoding, 0, end);
21275 var end = charStr.length - 1;
21276 var charCode = charStr.charCodeAt(end);
21277 // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character
21278 if (charCode >= 0xD800 && charCode <= 0xDBFF) {
21279 var size = this.surrogateSize;
21280 this.charLength += size;
21281 this.charReceived += size;
21282 this.charBuffer.copy(this.charBuffer, size, 0, size);
21283 buffer.copy(this.charBuffer, 0, 0, size);
21284 return charStr.substring(0, end);
21287 // or just emit the charStr
21291 // detectIncompleteChar determines if there is an incomplete UTF-8 character at
21292 // the end of the given buffer. If so, it sets this.charLength to the byte
21293 // length that character, and sets this.charReceived to the number of bytes
21294 // that are available for this character.
21295 StringDecoder.prototype.detectIncompleteChar = function(buffer) {
21296 // determine how many bytes we have to check at the end of this buffer
21297 var i = (buffer.length >= 3) ? 3 : buffer.length;
21299 // Figure out if one of the last i bytes of our buffer announces an
21300 // incomplete char.
21301 for (; i > 0; i--) {
21302 var c = buffer[buffer.length - i];
21304 // See http://en.wikipedia.org/wiki/UTF-8#Description
21307 if (i == 1 && c >> 5 == 0x06) {
21308 this.charLength = 2;
21313 if (i <= 2 && c >> 4 == 0x0E) {
21314 this.charLength = 3;
21319 if (i <= 3 && c >> 3 == 0x1E) {
21320 this.charLength = 4;
21324 this.charReceived = i;
21327 StringDecoder.prototype.end = function(buffer) {
21329 if (buffer && buffer.length)
21330 res = this.write(buffer);
21332 if (this.charReceived) {
21333 var cr = this.charReceived;
21334 var buf = this.charBuffer;
21335 var enc = this.encoding;
21336 res += buf.slice(0, cr).toString(enc);
21342 function passThroughWrite(buffer) {
21343 return buffer.toString(this.encoding);
21346 function utf16DetectIncompleteChar(buffer) {
21347 this.charReceived = buffer.length % 2;
21348 this.charLength = this.charReceived ? 2 : 0;
21351 function base64DetectIncompleteChar(buffer) {
21352 this.charReceived = buffer.length % 3;
21353 this.charLength = this.charReceived ? 3 : 0;
21359 /***/ function(module, exports, __webpack_require__) {
21361 // Copyright Joyent, Inc. and other Node contributors.
21363 // Permission is hereby granted, free of charge, to any person obtaining a
21364 // copy of this software and associated documentation files (the
21365 // "Software"), to deal in the Software without restriction, including
21366 // without limitation the rights to use, copy, modify, merge, publish,
21367 // distribute, sublicense, and/or sell copies of the Software, and to permit
21368 // persons to whom the Software is furnished to do so, subject to the
21369 // following conditions:
21371 // The above copyright notice and this permission notice shall be included
21372 // in all copies or substantial portions of the Software.
21374 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
21375 // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
21376 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
21377 // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
21378 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
21379 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
21380 // USE OR OTHER DEALINGS IN THE SOFTWARE.
21383 // a transform stream is a readable/writable stream where you do
21384 // something with the data. Sometimes it's called a "filter",
21385 // but that's not a great name for it, since that implies a thing where
21386 // some bits pass through, and others are simply ignored. (That would
21387 // be a valid example of a transform, of course.)
21389 // While the output is causally related to the input, it's not a
21390 // necessarily symmetric or synchronous transformation. For example,
21391 // a zlib stream might take multiple plain-text writes(), and then
21392 // emit a single compressed chunk some time in the future.
21394 // Here's how this works:
21396 // The Transform stream has all the aspects of the readable and writable
21397 // stream classes. When you write(chunk), that calls _write(chunk,cb)
21398 // internally, and returns false if there's a lot of pending writes
21399 // buffered up. When you call read(), that calls _read(n) until
21400 // there's enough pending readable data buffered up.
21402 // In a transform stream, the written data is placed in a buffer. When
21403 // _read(n) is called, it transforms the queued up data, calling the
21404 // buffered _write cb's as it consumes chunks. If consuming a single
21405 // written chunk would result in multiple output chunks, then the first
21406 // outputted bit calls the readcb, and subsequent chunks just go into
21407 // the read buffer, and will cause it to emit 'readable' if necessary.
21409 // This way, back-pressure is actually determined by the reading side,
21410 // since _read has to be called to start processing a new chunk. However,
21411 // a pathological inflate type of transform can cause excessive buffering
21412 // here. For example, imagine a stream where every byte of input is
21413 // interpreted as an integer from 0-255, and then results in that many
21414 // bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
21415 // 1kb of data being output. In this case, you could write a very small
21416 // amount of input, and end up with a very large amount of output. In
21417 // such a pathological inflating mechanism, there'd be no way to tell
21418 // the system to stop doing the transform. A single 4MB write could
21419 // cause the system to run out of memory.
21421 // However, even in such a pathological case, only a single written chunk
21422 // would be consumed, and then the rest would wait (un-transformed) until
21423 // the results of the previous transformed chunk were consumed.
21425 module.exports = Transform;
21427 var Duplex = __webpack_require__(35);
21430 var util = __webpack_require__(32);
21431 util.inherits = __webpack_require__(33);
21434 util.inherits(Transform, Duplex);
21437 function TransformState(options, stream) {
21438 this.afterTransform = function(er, data) {
21439 return afterTransform(stream, er, data);
21442 this.needTransform = false;
21443 this.transforming = false;
21444 this.writecb = null;
21445 this.writechunk = null;
21448 function afterTransform(stream, er, data) {
21449 var ts = stream._transformState;
21450 ts.transforming = false;
21452 var cb = ts.writecb;
21455 return stream.emit('error', new Error('no writecb in Transform class'));
21457 ts.writechunk = null;
21460 if (!util.isNullOrUndefined(data))
21466 var rs = stream._readableState;
21467 rs.reading = false;
21468 if (rs.needReadable || rs.length < rs.highWaterMark) {
21469 stream._read(rs.highWaterMark);
21474 function Transform(options) {
21475 if (!(this instanceof Transform))
21476 return new Transform(options);
21478 Duplex.call(this, options);
21480 this._transformState = new TransformState(options, this);
21482 // when the writable side finishes, then flush out anything remaining.
21485 // start out asking for a readable event once data is transformed.
21486 this._readableState.needReadable = true;
21488 // we have implemented the _read method, and done the other things
21489 // that Readable wants before the first _read call, so unset the
21490 // sync guard flag.
21491 this._readableState.sync = false;
21493 this.once('prefinish', function() {
21494 if (util.isFunction(this._flush))
21495 this._flush(function(er) {
21503 Transform.prototype.push = function(chunk, encoding) {
21504 this._transformState.needTransform = false;
21505 return Duplex.prototype.push.call(this, chunk, encoding);
21508 // This is the part where you do stuff!
21509 // override this function in implementation classes.
21510 // 'chunk' is an input chunk.
21512 // Call `push(newChunk)` to pass along transformed output
21513 // to the readable side. You may call 'push' zero or more times.
21515 // Call `cb(err)` when you are done with this chunk. If you pass
21516 // an error, then that'll put the hurt on the whole operation. If you
21517 // never call cb(), then you'll never get another chunk.
21518 Transform.prototype._transform = function(chunk, encoding, cb) {
21519 throw new Error('not implemented');
21522 Transform.prototype._write = function(chunk, encoding, cb) {
21523 var ts = this._transformState;
21525 ts.writechunk = chunk;
21526 ts.writeencoding = encoding;
21527 if (!ts.transforming) {
21528 var rs = this._readableState;
21529 if (ts.needTransform ||
21531 rs.length < rs.highWaterMark)
21532 this._read(rs.highWaterMark);
21536 // Doesn't matter what the args are here.
21537 // _transform does all the work.
21538 // That we got here means that the readable side wants more data.
21539 Transform.prototype._read = function(n) {
21540 var ts = this._transformState;
21542 if (!util.isNull(ts.writechunk) && ts.writecb && !ts.transforming) {
21543 ts.transforming = true;
21544 this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
21546 // mark that we need a transform, so that any data that comes in
21547 // will get processed, now that we've asked for it.
21548 ts.needTransform = true;
21553 function done(stream, er) {
21555 return stream.emit('error', er);
21557 // if there's nothing in the write buffer, then that means
21558 // that nothing more will ever be provided
21559 var ws = stream._writableState;
21560 var ts = stream._transformState;
21563 throw new Error('calling transform done when ws.length != 0');
21565 if (ts.transforming)
21566 throw new Error('calling transform done when still transforming');
21568 return stream.push(null);
21574 /***/ function(module, exports, __webpack_require__) {
21576 // Copyright Joyent, Inc. and other Node contributors.
21578 // Permission is hereby granted, free of charge, to any person obtaining a
21579 // copy of this software and associated documentation files (the
21580 // "Software"), to deal in the Software without restriction, including
21581 // without limitation the rights to use, copy, modify, merge, publish,
21582 // distribute, sublicense, and/or sell copies of the Software, and to permit
21583 // persons to whom the Software is furnished to do so, subject to the
21584 // following conditions:
21586 // The above copyright notice and this permission notice shall be included
21587 // in all copies or substantial portions of the Software.
21589 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
21590 // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
21591 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
21592 // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
21593 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
21594 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
21595 // USE OR OTHER DEALINGS IN THE SOFTWARE.
21597 // a passthrough stream.
21598 // basically just the most minimal sort of Transform stream.
21599 // Every written chunk gets output as-is.
21601 module.exports = PassThrough;
21603 var Transform = __webpack_require__(38);
21606 var util = __webpack_require__(32);
21607 util.inherits = __webpack_require__(33);
21610 util.inherits(PassThrough, Transform);
21612 function PassThrough(options) {
21613 if (!(this instanceof PassThrough))
21614 return new PassThrough(options);
21616 Transform.call(this, options);
21619 PassThrough.prototype._transform = function(chunk, encoding, cb) {
21626 /***/ function(module, exports, __webpack_require__) {
21628 module.exports = __webpack_require__(36)
21633 /***/ function(module, exports, __webpack_require__) {
21635 module.exports = __webpack_require__(35)
21640 /***/ function(module, exports, __webpack_require__) {
21642 module.exports = __webpack_require__(38)
21647 /***/ function(module, exports, __webpack_require__) {
21649 module.exports = __webpack_require__(39)
21654 /***/ function(module, exports, __webpack_require__) {
21656 /* WEBPACK VAR INJECTION */(function(Buffer, __dirname) {/* jslint node: true */
21659 // var b64 = require('./base64.js').base64DecToArr;
21660 function VirtualFileSystem() {
21661 this.fileSystem = {};
21662 this.baseSystem = {};
21665 VirtualFileSystem.prototype.readFileSync = function(filename) {
21666 filename = fixFilename(filename);
21668 var base64content = this.baseSystem[filename];
21669 if (base64content) {
21670 return new Buffer(base64content, 'base64');
21673 return this.fileSystem[filename];
21676 VirtualFileSystem.prototype.writeFileSync = function(filename, content) {
21677 this.fileSystem[fixFilename(filename)] = content;
21680 VirtualFileSystem.prototype.bindFS = function(data) {
21681 this.baseSystem = data;
21685 function fixFilename(filename) {
21686 if (filename.indexOf(__dirname) === 0) {
21687 filename = filename.substring(__dirname.length);
21690 if (filename.indexOf('/') === 0) {
21691 filename = filename.substring(1);
21697 module.exports = new VirtualFileSystem();
21699 /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2).Buffer, "/"))
21703 /***/ function(module, exports, __webpack_require__) {
21705 /* WEBPACK VAR INJECTION */(function(Buffer) {// Generated by CoffeeScript 1.7.1
21708 PDFObject - converts JavaScript types into their corrisponding PDF types.
21713 var PDFObject, PDFReference;
21715 PDFObject = (function() {
21716 var escapable, escapableRe, pad, swapBytes;
21718 function PDFObject() {}
21720 pad = function(str, length) {
21721 return (Array(length + 1).join('0') + str).slice(-length);
21724 escapableRe = /[\n\r\t\b\f\(\)\\]/g;
21737 swapBytes = function(buff) {
21738 var a, i, l, _i, _ref;
21741 throw new Error("Buffer length must be even");
21743 for (i = _i = 0, _ref = l - 1; _i < _ref; i = _i += 2) {
21745 buff[i] = buff[i + 1];
21752 PDFObject.convert = function(object) {
21753 var e, i, isUnicode, items, key, out, string, val, _i, _ref;
21754 if (typeof object === 'string') {
21755 return '/' + object;
21756 } else if (object instanceof String) {
21757 string = object.replace(escapableRe, function(c) {
21758 return escapable[c];
21761 for (i = _i = 0, _ref = string.length; _i < _ref; i = _i += 1) {
21762 if (string.charCodeAt(i) > 0x7f) {
21768 string = swapBytes(new Buffer('\ufeff' + string, 'utf16le')).toString('binary');
21770 return '(' + string + ')';
21771 } else if (Buffer.isBuffer(object)) {
21772 return '<' + object.toString('hex') + '>';
21773 } else if (object instanceof PDFReference) {
21774 return object.toString();
21775 } else if (object instanceof Date) {
21776 return '(D:' + pad(object.getUTCFullYear(), 4) + pad(object.getUTCMonth(), 2) + pad(object.getUTCDate(), 2) + pad(object.getUTCHours(), 2) + pad(object.getUTCMinutes(), 2) + pad(object.getUTCSeconds(), 2) + 'Z)';
21777 } else if (Array.isArray(object)) {
21778 items = ((function() {
21779 var _j, _len, _results;
21781 for (_j = 0, _len = object.length; _j < _len; _j++) {
21783 _results.push(PDFObject.convert(e));
21787 return '[' + items + ']';
21788 } else if ({}.toString.call(object) === '[object Object]') {
21790 for (key in object) {
21792 out.push('/' + key + ' ' + PDFObject.convert(val));
21795 return out.join('\n');
21797 return '' + object;
21805 module.exports = PDFObject;
21807 PDFReference = __webpack_require__(46);
21811 /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2).Buffer))
21815 /***/ function(module, exports, __webpack_require__) {
21817 /* WEBPACK VAR INJECTION */(function(Buffer) {// Generated by CoffeeScript 1.7.1
21820 PDFReference - represents a reference to another object in the PDF object heirarchy
21825 var PDFObject, PDFReference, zlib,
21826 __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
21828 zlib = __webpack_require__(47);
21830 PDFReference = (function() {
21831 function PDFReference(document, id, data) {
21832 this.document = document;
21834 this.data = data != null ? data : {};
21835 this.finalize = __bind(this.finalize, this);
21837 this.deflate = null;
21838 this.compress = this.document.compress && !this.data.Filter;
21839 this.uncompressedLength = 0;
21843 PDFReference.prototype.initDeflate = function() {
21844 this.data.Filter = 'FlateDecode';
21845 this.deflate = zlib.createDeflate();
21846 this.deflate.on('data', (function(_this) {
21847 return function(chunk) {
21848 _this.chunks.push(chunk);
21849 return _this.data.Length += chunk.length;
21852 return this.deflate.on('end', this.finalize);
21855 PDFReference.prototype.write = function(chunk) {
21857 if (!Buffer.isBuffer(chunk)) {
21858 chunk = new Buffer(chunk + '\n', 'binary');
21860 this.uncompressedLength += chunk.length;
21861 if ((_base = this.data).Length == null) {
21864 if (this.compress) {
21865 if (!this.deflate) {
21866 this.initDeflate();
21868 return this.deflate.write(chunk);
21870 this.chunks.push(chunk);
21871 return this.data.Length += chunk.length;
21875 PDFReference.prototype.end = function(chunk) {
21876 if (typeof chunk === 'string' || Buffer.isBuffer(chunk)) {
21879 if (this.deflate) {
21880 return this.deflate.end();
21882 return this.finalize();
21886 PDFReference.prototype.finalize = function() {
21887 var chunk, _i, _len, _ref;
21888 this.offset = this.document._offset;
21889 this.document._write("" + this.id + " " + this.gen + " obj");
21890 this.document._write(PDFObject.convert(this.data));
21891 if (this.chunks.length) {
21892 this.document._write('stream');
21893 _ref = this.chunks;
21894 for (_i = 0, _len = _ref.length; _i < _len; _i++) {
21896 this.document._write(chunk);
21898 this.chunks.length = 0;
21899 this.document._write('\nendstream');
21901 this.document._write('endobj');
21902 return this.document._refEnd(this);
21905 PDFReference.prototype.toString = function() {
21906 return "" + this.id + " " + this.gen + " R";
21909 return PDFReference;
21913 module.exports = PDFReference;
21915 PDFObject = __webpack_require__(45);
21919 /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2).Buffer))
21923 /***/ function(module, exports, __webpack_require__) {
21925 /* WEBPACK VAR INJECTION */(function(Buffer, process) {// Copyright Joyent, Inc. and other Node contributors.
21927 // Permission is hereby granted, free of charge, to any person obtaining a
21928 // copy of this software and associated documentation files (the
21929 // "Software"), to deal in the Software without restriction, including
21930 // without limitation the rights to use, copy, modify, merge, publish,
21931 // distribute, sublicense, and/or sell copies of the Software, and to permit
21932 // persons to whom the Software is furnished to do so, subject to the
21933 // following conditions:
21935 // The above copyright notice and this permission notice shall be included
21936 // in all copies or substantial portions of the Software.
21938 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
21939 // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
21940 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
21941 // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
21942 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
21943 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
21944 // USE OR OTHER DEALINGS IN THE SOFTWARE.
21946 var Transform = __webpack_require__(42);
21948 var binding = __webpack_require__(48);
21949 var util = __webpack_require__(60);
21950 var assert = __webpack_require__(63).ok;
21952 // zlib doesn't provide these, so kludge them in following the same
21953 // const naming scheme zlib uses.
21954 binding.Z_MIN_WINDOWBITS = 8;
21955 binding.Z_MAX_WINDOWBITS = 15;
21956 binding.Z_DEFAULT_WINDOWBITS = 15;
21958 // fewer than 64 bytes per chunk is stupid.
21959 // technically it could work with as few as 8, but even 64 bytes
21960 // is absurdly low. Usually a MB or more is best.
21961 binding.Z_MIN_CHUNK = 64;
21962 binding.Z_MAX_CHUNK = Infinity;
21963 binding.Z_DEFAULT_CHUNK = (16 * 1024);
21965 binding.Z_MIN_MEMLEVEL = 1;
21966 binding.Z_MAX_MEMLEVEL = 9;
21967 binding.Z_DEFAULT_MEMLEVEL = 8;
21969 binding.Z_MIN_LEVEL = -1;
21970 binding.Z_MAX_LEVEL = 9;
21971 binding.Z_DEFAULT_LEVEL = binding.Z_DEFAULT_COMPRESSION;
21973 // expose all the zlib constants
21974 Object.keys(binding).forEach(function(k) {
21975 if (k.match(/^Z/)) exports[k] = binding[k];
21978 // translation table for return codes.
21980 Z_OK: binding.Z_OK,
21981 Z_STREAM_END: binding.Z_STREAM_END,
21982 Z_NEED_DICT: binding.Z_NEED_DICT,
21983 Z_ERRNO: binding.Z_ERRNO,
21984 Z_STREAM_ERROR: binding.Z_STREAM_ERROR,
21985 Z_DATA_ERROR: binding.Z_DATA_ERROR,
21986 Z_MEM_ERROR: binding.Z_MEM_ERROR,
21987 Z_BUF_ERROR: binding.Z_BUF_ERROR,
21988 Z_VERSION_ERROR: binding.Z_VERSION_ERROR
21991 Object.keys(exports.codes).forEach(function(k) {
21992 exports.codes[exports.codes[k]] = k;
21995 exports.Deflate = Deflate;
21996 exports.Inflate = Inflate;
21997 exports.Gzip = Gzip;
21998 exports.Gunzip = Gunzip;
21999 exports.DeflateRaw = DeflateRaw;
22000 exports.InflateRaw = InflateRaw;
22001 exports.Unzip = Unzip;
22003 exports.createDeflate = function(o) {
22004 return new Deflate(o);
22007 exports.createInflate = function(o) {
22008 return new Inflate(o);
22011 exports.createDeflateRaw = function(o) {
22012 return new DeflateRaw(o);
22015 exports.createInflateRaw = function(o) {
22016 return new InflateRaw(o);
22019 exports.createGzip = function(o) {
22020 return new Gzip(o);
22023 exports.createGunzip = function(o) {
22024 return new Gunzip(o);
22027 exports.createUnzip = function(o) {
22028 return new Unzip(o);
22032 // Convenience methods.
22033 // compress/decompress a string or buffer in one step.
22034 exports.deflate = function(buffer, opts, callback) {
22035 if (typeof opts === 'function') {
22039 return zlibBuffer(new Deflate(opts), buffer, callback);
22042 exports.deflateSync = function(buffer, opts) {
22043 return zlibBufferSync(new Deflate(opts), buffer);
22046 exports.gzip = function(buffer, opts, callback) {
22047 if (typeof opts === 'function') {
22051 return zlibBuffer(new Gzip(opts), buffer, callback);
22054 exports.gzipSync = function(buffer, opts) {
22055 return zlibBufferSync(new Gzip(opts), buffer);
22058 exports.deflateRaw = function(buffer, opts, callback) {
22059 if (typeof opts === 'function') {
22063 return zlibBuffer(new DeflateRaw(opts), buffer, callback);
22066 exports.deflateRawSync = function(buffer, opts) {
22067 return zlibBufferSync(new DeflateRaw(opts), buffer);
22070 exports.unzip = function(buffer, opts, callback) {
22071 if (typeof opts === 'function') {
22075 return zlibBuffer(new Unzip(opts), buffer, callback);
22078 exports.unzipSync = function(buffer, opts) {
22079 return zlibBufferSync(new Unzip(opts), buffer);
22082 exports.inflate = function(buffer, opts, callback) {
22083 if (typeof opts === 'function') {
22087 return zlibBuffer(new Inflate(opts), buffer, callback);
22090 exports.inflateSync = function(buffer, opts) {
22091 return zlibBufferSync(new Inflate(opts), buffer);
22094 exports.gunzip = function(buffer, opts, callback) {
22095 if (typeof opts === 'function') {
22099 return zlibBuffer(new Gunzip(opts), buffer, callback);
22102 exports.gunzipSync = function(buffer, opts) {
22103 return zlibBufferSync(new Gunzip(opts), buffer);
22106 exports.inflateRaw = function(buffer, opts, callback) {
22107 if (typeof opts === 'function') {
22111 return zlibBuffer(new InflateRaw(opts), buffer, callback);
22114 exports.inflateRawSync = function(buffer, opts) {
22115 return zlibBufferSync(new InflateRaw(opts), buffer);
22118 function zlibBuffer(engine, buffer, callback) {
22122 engine.on('error', onError);
22123 engine.on('end', onEnd);
22125 engine.end(buffer);
22130 while (null !== (chunk = engine.read())) {
22131 buffers.push(chunk);
22132 nread += chunk.length;
22134 engine.once('readable', flow);
22137 function onError(err) {
22138 engine.removeListener('end', onEnd);
22139 engine.removeListener('readable', flow);
22144 var buf = Buffer.concat(buffers, nread);
22146 callback(null, buf);
22151 function zlibBufferSync(engine, buffer) {
22152 if (typeof buffer === 'string')
22153 buffer = new Buffer(buffer);
22154 if (!Buffer.isBuffer(buffer))
22155 throw new TypeError('Not a string or buffer');
22157 var flushFlag = binding.Z_FINISH;
22159 return engine._processChunk(buffer, flushFlag);
22163 // minimal 2-byte header
22164 function Deflate(opts) {
22165 if (!(this instanceof Deflate)) return new Deflate(opts);
22166 Zlib.call(this, opts, binding.DEFLATE);
22169 function Inflate(opts) {
22170 if (!(this instanceof Inflate)) return new Inflate(opts);
22171 Zlib.call(this, opts, binding.INFLATE);
22176 // gzip - bigger header, same deflate compression
22177 function Gzip(opts) {
22178 if (!(this instanceof Gzip)) return new Gzip(opts);
22179 Zlib.call(this, opts, binding.GZIP);
22182 function Gunzip(opts) {
22183 if (!(this instanceof Gunzip)) return new Gunzip(opts);
22184 Zlib.call(this, opts, binding.GUNZIP);
22190 function DeflateRaw(opts) {
22191 if (!(this instanceof DeflateRaw)) return new DeflateRaw(opts);
22192 Zlib.call(this, opts, binding.DEFLATERAW);
22195 function InflateRaw(opts) {
22196 if (!(this instanceof InflateRaw)) return new InflateRaw(opts);
22197 Zlib.call(this, opts, binding.INFLATERAW);
22201 // auto-detect header.
22202 function Unzip(opts) {
22203 if (!(this instanceof Unzip)) return new Unzip(opts);
22204 Zlib.call(this, opts, binding.UNZIP);
22208 // the Zlib class they all inherit from
22209 // This thing manages the queue of requests, and returns
22210 // true or false if there is anything in the queue when
22211 // you call the .write() method.
22213 function Zlib(opts, mode) {
22214 this._opts = opts = opts || {};
22215 this._chunkSize = opts.chunkSize || exports.Z_DEFAULT_CHUNK;
22217 Transform.call(this, opts);
22220 if (opts.flush !== binding.Z_NO_FLUSH &&
22221 opts.flush !== binding.Z_PARTIAL_FLUSH &&
22222 opts.flush !== binding.Z_SYNC_FLUSH &&
22223 opts.flush !== binding.Z_FULL_FLUSH &&
22224 opts.flush !== binding.Z_FINISH &&
22225 opts.flush !== binding.Z_BLOCK) {
22226 throw new Error('Invalid flush flag: ' + opts.flush);
22229 this._flushFlag = opts.flush || binding.Z_NO_FLUSH;
22231 if (opts.chunkSize) {
22232 if (opts.chunkSize < exports.Z_MIN_CHUNK ||
22233 opts.chunkSize > exports.Z_MAX_CHUNK) {
22234 throw new Error('Invalid chunk size: ' + opts.chunkSize);
22238 if (opts.windowBits) {
22239 if (opts.windowBits < exports.Z_MIN_WINDOWBITS ||
22240 opts.windowBits > exports.Z_MAX_WINDOWBITS) {
22241 throw new Error('Invalid windowBits: ' + opts.windowBits);
22246 if (opts.level < exports.Z_MIN_LEVEL ||
22247 opts.level > exports.Z_MAX_LEVEL) {
22248 throw new Error('Invalid compression level: ' + opts.level);
22252 if (opts.memLevel) {
22253 if (opts.memLevel < exports.Z_MIN_MEMLEVEL ||
22254 opts.memLevel > exports.Z_MAX_MEMLEVEL) {
22255 throw new Error('Invalid memLevel: ' + opts.memLevel);
22259 if (opts.strategy) {
22260 if (opts.strategy != exports.Z_FILTERED &&
22261 opts.strategy != exports.Z_HUFFMAN_ONLY &&
22262 opts.strategy != exports.Z_RLE &&
22263 opts.strategy != exports.Z_FIXED &&
22264 opts.strategy != exports.Z_DEFAULT_STRATEGY) {
22265 throw new Error('Invalid strategy: ' + opts.strategy);
22269 if (opts.dictionary) {
22270 if (!Buffer.isBuffer(opts.dictionary)) {
22271 throw new Error('Invalid dictionary: it should be a Buffer instance');
22275 this._binding = new binding.Zlib(mode);
22278 this._hadError = false;
22279 this._binding.onerror = function(message, errno) {
22280 // there is no way to cleanly recover.
22281 // continuing only obscures problems.
22282 self._binding = null;
22283 self._hadError = true;
22285 var error = new Error(message);
22286 error.errno = errno;
22287 error.code = exports.codes[errno];
22288 self.emit('error', error);
22291 var level = exports.Z_DEFAULT_COMPRESSION;
22292 if (typeof opts.level === 'number') level = opts.level;
22294 var strategy = exports.Z_DEFAULT_STRATEGY;
22295 if (typeof opts.strategy === 'number') strategy = opts.strategy;
22297 this._binding.init(opts.windowBits || exports.Z_DEFAULT_WINDOWBITS,
22299 opts.memLevel || exports.Z_DEFAULT_MEMLEVEL,
22303 this._buffer = new Buffer(this._chunkSize);
22305 this._closed = false;
22306 this._level = level;
22307 this._strategy = strategy;
22309 this.once('end', this.close);
22312 util.inherits(Zlib, Transform);
22314 Zlib.prototype.params = function(level, strategy, callback) {
22315 if (level < exports.Z_MIN_LEVEL ||
22316 level > exports.Z_MAX_LEVEL) {
22317 throw new RangeError('Invalid compression level: ' + level);
22319 if (strategy != exports.Z_FILTERED &&
22320 strategy != exports.Z_HUFFMAN_ONLY &&
22321 strategy != exports.Z_RLE &&
22322 strategy != exports.Z_FIXED &&
22323 strategy != exports.Z_DEFAULT_STRATEGY) {
22324 throw new TypeError('Invalid strategy: ' + strategy);
22327 if (this._level !== level || this._strategy !== strategy) {
22329 this.flush(binding.Z_SYNC_FLUSH, function() {
22330 self._binding.params(level, strategy);
22331 if (!self._hadError) {
22332 self._level = level;
22333 self._strategy = strategy;
22334 if (callback) callback();
22338 process.nextTick(callback);
22342 Zlib.prototype.reset = function() {
22343 return this._binding.reset();
22346 // This is the _flush function called by the transform class,
22347 // internally, when the last chunk has been written.
22348 Zlib.prototype._flush = function(callback) {
22349 this._transform(new Buffer(0), '', callback);
22352 Zlib.prototype.flush = function(kind, callback) {
22353 var ws = this._writableState;
22355 if (typeof kind === 'function' || (kind === void 0 && !callback)) {
22357 kind = binding.Z_FULL_FLUSH;
22362 process.nextTick(callback);
22363 } else if (ws.ending) {
22365 this.once('end', callback);
22366 } else if (ws.needDrain) {
22368 this.once('drain', function() {
22369 self.flush(callback);
22372 this._flushFlag = kind;
22373 this.write(new Buffer(0), '', callback);
22377 Zlib.prototype.close = function(callback) {
22379 process.nextTick(callback);
22384 this._closed = true;
22386 this._binding.close();
22389 process.nextTick(function() {
22390 self.emit('close');
22394 Zlib.prototype._transform = function(chunk, encoding, cb) {
22396 var ws = this._writableState;
22397 var ending = ws.ending || ws.ended;
22398 var last = ending && (!chunk || ws.length === chunk.length);
22400 if (!chunk === null && !Buffer.isBuffer(chunk))
22401 return cb(new Error('invalid input'));
22403 // If it's the last chunk, or a final flush, we use the Z_FINISH flush flag.
22404 // If it's explicitly flushing at some other time, then we use
22405 // Z_FULL_FLUSH. Otherwise, use Z_NO_FLUSH for maximum compression
22408 flushFlag = binding.Z_FINISH;
22410 flushFlag = this._flushFlag;
22411 // once we've flushed the last of the queue, stop flushing and
22412 // go back to the normal behavior.
22413 if (chunk.length >= ws.length) {
22414 this._flushFlag = this._opts.flush || binding.Z_NO_FLUSH;
22419 this._processChunk(chunk, flushFlag, cb);
22422 Zlib.prototype._processChunk = function(chunk, flushFlag, cb) {
22423 var availInBefore = chunk && chunk.length;
22424 var availOutBefore = this._chunkSize - this._offset;
22429 var async = typeof cb === 'function';
22436 this.on('error', function(er) {
22441 var res = this._binding.writeSync(flushFlag,
22444 availInBefore, // in_len
22445 this._buffer, // out
22446 this._offset, //out_off
22447 availOutBefore); // out_len
22448 } while (!this._hadError && callback(res[0], res[1]));
22450 if (this._hadError) {
22454 var buf = Buffer.concat(buffers, nread);
22460 var req = this._binding.write(flushFlag,
22463 availInBefore, // in_len
22464 this._buffer, // out
22465 this._offset, //out_off
22466 availOutBefore); // out_len
22468 req.buffer = chunk;
22469 req.callback = callback;
22471 function callback(availInAfter, availOutAfter) {
22472 if (self._hadError)
22475 var have = availOutBefore - availOutAfter;
22476 assert(have >= 0, 'have should not go down');
22479 var out = self._buffer.slice(self._offset, self._offset + have);
22480 self._offset += have;
22481 // serve some output to the consumer.
22486 nread += out.length;
22490 // exhausted the output buffer, or used all the input create a new one.
22491 if (availOutAfter === 0 || self._offset >= self._chunkSize) {
22492 availOutBefore = self._chunkSize;
22494 self._buffer = new Buffer(self._chunkSize);
22497 if (availOutAfter === 0) {
22498 // Not actually done. Need to reprocess.
22499 // Also, update the availInBefore to the availInAfter value,
22500 // so that if we have to hit it a third (fourth, etc.) time,
22501 // it'll have the correct byte counts.
22502 inOff += (availInBefore - availInAfter);
22503 availInBefore = availInAfter;
22508 var newReq = self._binding.write(flushFlag,
22515 newReq.callback = callback; // this same function
22516 newReq.buffer = chunk;
22523 // finished with the chunk.
22528 util.inherits(Deflate, Zlib);
22529 util.inherits(Inflate, Zlib);
22530 util.inherits(Gzip, Zlib);
22531 util.inherits(Gunzip, Zlib);
22532 util.inherits(DeflateRaw, Zlib);
22533 util.inherits(InflateRaw, Zlib);
22534 util.inherits(Unzip, Zlib);
22536 /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2).Buffer, __webpack_require__(30)))
22540 /***/ function(module, exports, __webpack_require__) {
22542 /* WEBPACK VAR INJECTION */(function(process, Buffer) {var msg = __webpack_require__(49);
22543 var zstream = __webpack_require__(50);
22544 var zlib_deflate = __webpack_require__(51);
22545 var zlib_inflate = __webpack_require__(56);
22546 var constants = __webpack_require__(59);
22548 for (var key in constants) {
22549 exports[key] = constants[key];
22554 exports.DEFLATE = 1;
22555 exports.INFLATE = 2;
22557 exports.GUNZIP = 4;
22558 exports.DEFLATERAW = 5;
22559 exports.INFLATERAW = 6;
22563 * Emulate Node's zlib C++ layer for use by the JS layer in index.js
22565 function Zlib(mode) {
22566 if (mode < exports.DEFLATE || mode > exports.UNZIP)
22567 throw new TypeError("Bad argument");
22570 this.init_done = false;
22571 this.write_in_progress = false;
22572 this.pending_close = false;
22573 this.windowBits = 0;
22577 this.dictionary = null;
22580 Zlib.prototype.init = function(windowBits, level, memLevel, strategy, dictionary) {
22581 this.windowBits = windowBits;
22582 this.level = level;
22583 this.memLevel = memLevel;
22584 this.strategy = strategy;
22585 // dictionary not supported.
22587 if (this.mode === exports.GZIP || this.mode === exports.GUNZIP)
22588 this.windowBits += 16;
22590 if (this.mode === exports.UNZIP)
22591 this.windowBits += 32;
22593 if (this.mode === exports.DEFLATERAW || this.mode === exports.INFLATERAW)
22594 this.windowBits = -this.windowBits;
22596 this.strm = new zstream();
22598 switch (this.mode) {
22599 case exports.DEFLATE:
22601 case exports.DEFLATERAW:
22602 var status = zlib_deflate.deflateInit2(
22605 exports.Z_DEFLATED,
22611 case exports.INFLATE:
22612 case exports.GUNZIP:
22613 case exports.INFLATERAW:
22614 case exports.UNZIP:
22615 var status = zlib_inflate.inflateInit2(
22621 throw new Error("Unknown mode " + this.mode);
22624 if (status !== exports.Z_OK) {
22625 this._error(status);
22629 this.write_in_progress = false;
22630 this.init_done = true;
22633 Zlib.prototype.params = function() {
22634 throw new Error("deflateParams Not supported");
22637 Zlib.prototype._writeCheck = function() {
22638 if (!this.init_done)
22639 throw new Error("write before init");
22641 if (this.mode === exports.NONE)
22642 throw new Error("already finalized");
22644 if (this.write_in_progress)
22645 throw new Error("write already in progress");
22647 if (this.pending_close)
22648 throw new Error("close is pending");
22651 Zlib.prototype.write = function(flush, input, in_off, in_len, out, out_off, out_len) {
22652 this._writeCheck();
22653 this.write_in_progress = true;
22656 process.nextTick(function() {
22657 self.write_in_progress = false;
22658 var res = self._write(flush, input, in_off, in_len, out, out_off, out_len);
22659 self.callback(res[0], res[1]);
22661 if (self.pending_close)
22668 // set method for Node buffers, used by pako
22669 function bufferSet(data, offset) {
22670 for (var i = 0; i < data.length; i++) {
22671 this[offset + i] = data[i];
22675 Zlib.prototype.writeSync = function(flush, input, in_off, in_len, out, out_off, out_len) {
22676 this._writeCheck();
22677 return this._write(flush, input, in_off, in_len, out, out_off, out_len);
22680 Zlib.prototype._write = function(flush, input, in_off, in_len, out, out_off, out_len) {
22681 this.write_in_progress = true;
22683 if (flush !== exports.Z_NO_FLUSH &&
22684 flush !== exports.Z_PARTIAL_FLUSH &&
22685 flush !== exports.Z_SYNC_FLUSH &&
22686 flush !== exports.Z_FULL_FLUSH &&
22687 flush !== exports.Z_FINISH &&
22688 flush !== exports.Z_BLOCK) {
22689 throw new Error("Invalid flush value");
22692 if (input == null) {
22693 input = new Buffer(0);
22699 out.set = out._set;
22701 out.set = bufferSet;
22703 var strm = this.strm;
22704 strm.avail_in = in_len;
22705 strm.input = input;
22706 strm.next_in = in_off;
22707 strm.avail_out = out_len;
22709 strm.next_out = out_off;
22711 switch (this.mode) {
22712 case exports.DEFLATE:
22714 case exports.DEFLATERAW:
22715 var status = zlib_deflate.deflate(strm, flush);
22717 case exports.UNZIP:
22718 case exports.INFLATE:
22719 case exports.GUNZIP:
22720 case exports.INFLATERAW:
22721 var status = zlib_inflate.inflate(strm, flush);
22724 throw new Error("Unknown mode " + this.mode);
22727 if (status !== exports.Z_STREAM_END && status !== exports.Z_OK) {
22728 this._error(status);
22731 this.write_in_progress = false;
22732 return [strm.avail_in, strm.avail_out];
22735 Zlib.prototype.close = function() {
22736 if (this.write_in_progress) {
22737 this.pending_close = true;
22741 this.pending_close = false;
22743 if (this.mode === exports.DEFLATE || this.mode === exports.GZIP || this.mode === exports.DEFLATERAW) {
22744 zlib_deflate.deflateEnd(this.strm);
22746 zlib_inflate.inflateEnd(this.strm);
22749 this.mode = exports.NONE;
22752 Zlib.prototype.reset = function() {
22753 switch (this.mode) {
22754 case exports.DEFLATE:
22755 case exports.DEFLATERAW:
22756 var status = zlib_deflate.deflateReset(this.strm);
22758 case exports.INFLATE:
22759 case exports.INFLATERAW:
22760 var status = zlib_inflate.inflateReset(this.strm);
22764 if (status !== exports.Z_OK) {
22765 this._error(status);
22769 Zlib.prototype._error = function(status) {
22770 this.onerror(msg[status] + ': ' + this.strm.msg, status);
22772 this.write_in_progress = false;
22773 if (this.pending_close)
22777 exports.Zlib = Zlib;
22779 /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(30), __webpack_require__(2).Buffer))
22783 /***/ function(module, exports) {
22788 '2': 'need dictionary', /* Z_NEED_DICT 2 */
22789 '1': 'stream end', /* Z_STREAM_END 1 */
22790 '0': '', /* Z_OK 0 */
22791 '-1': 'file error', /* Z_ERRNO (-1) */
22792 '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
22793 '-3': 'data error', /* Z_DATA_ERROR (-3) */
22794 '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
22795 '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
22796 '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
22802 /***/ function(module, exports) {
22807 function ZStream() {
22808 /* next input byte */
22809 this.input = null; // JS specific, because we have no pointers
22811 /* number of bytes available at input */
22813 /* total number of input bytes read so far */
22815 /* next output byte should be put there */
22816 this.output = null; // JS specific, because we have no pointers
22818 /* remaining free space at output */
22819 this.avail_out = 0;
22820 /* total number of bytes output so far */
22821 this.total_out = 0;
22822 /* last error message, NULL if no error */
22823 this.msg = ''/*Z_NULL*/;
22824 /* not visible by applications */
22826 /* best guess about the data type: binary or text */
22827 this.data_type = 2/*Z_UNKNOWN*/;
22828 /* adler32 value of the uncompressed data */
22832 module.exports = ZStream;
22837 /***/ function(module, exports, __webpack_require__) {
22841 var utils = __webpack_require__(52);
22842 var trees = __webpack_require__(53);
22843 var adler32 = __webpack_require__(54);
22844 var crc32 = __webpack_require__(55);
22845 var msg = __webpack_require__(49);
22847 /* Public constants ==========================================================*/
22848 /* ===========================================================================*/
22851 /* Allowed flush values; see deflate() and inflate() below for details */
22852 var Z_NO_FLUSH = 0;
22853 var Z_PARTIAL_FLUSH = 1;
22854 //var Z_SYNC_FLUSH = 2;
22855 var Z_FULL_FLUSH = 3;
22861 /* Return codes for the compression/decompression functions. Negative values
22862 * are errors, positive values are used for special but normal events.
22865 var Z_STREAM_END = 1;
22866 //var Z_NEED_DICT = 2;
22867 //var Z_ERRNO = -1;
22868 var Z_STREAM_ERROR = -2;
22869 var Z_DATA_ERROR = -3;
22870 //var Z_MEM_ERROR = -4;
22871 var Z_BUF_ERROR = -5;
22872 //var Z_VERSION_ERROR = -6;
22875 /* compression levels */
22876 //var Z_NO_COMPRESSION = 0;
22877 //var Z_BEST_SPEED = 1;
22878 //var Z_BEST_COMPRESSION = 9;
22879 var Z_DEFAULT_COMPRESSION = -1;
22882 var Z_FILTERED = 1;
22883 var Z_HUFFMAN_ONLY = 2;
22886 var Z_DEFAULT_STRATEGY = 0;
22888 /* Possible values of the data_type field (though see inflate()) */
22889 //var Z_BINARY = 0;
22891 //var Z_ASCII = 1; // = Z_TEXT
22895 /* The deflate compression method */
22896 var Z_DEFLATED = 8;
22898 /*============================================================================*/
22901 var MAX_MEM_LEVEL = 9;
22902 /* Maximum value for memLevel in deflateInit2 */
22903 var MAX_WBITS = 15;
22904 /* 32K LZ77 window */
22905 var DEF_MEM_LEVEL = 8;
22908 var LENGTH_CODES = 29;
22909 /* number of length codes, not counting the special END_BLOCK code */
22910 var LITERALS = 256;
22911 /* number of literal bytes 0..255 */
22912 var L_CODES = LITERALS + 1 + LENGTH_CODES;
22913 /* number of Literal or Length codes, including the END_BLOCK code */
22915 /* number of distance codes */
22917 /* number of codes used to transfer the bit lengths */
22918 var HEAP_SIZE = 2*L_CODES + 1;
22919 /* maximum heap size */
22921 /* All codes must not exceed MAX_BITS bits */
22924 var MAX_MATCH = 258;
22925 var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
22927 var PRESET_DICT = 0x20;
22929 var INIT_STATE = 42;
22930 var EXTRA_STATE = 69;
22931 var NAME_STATE = 73;
22932 var COMMENT_STATE = 91;
22933 var HCRC_STATE = 103;
22934 var BUSY_STATE = 113;
22935 var FINISH_STATE = 666;
22937 var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
22938 var BS_BLOCK_DONE = 2; /* block flush performed */
22939 var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
22940 var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
22942 var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
22944 function err(strm, errorCode) {
22945 strm.msg = msg[errorCode];
22950 return ((f) << 1) - ((f) > 4 ? 9 : 0);
22953 function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
22956 /* =========================================================================
22957 * Flush as much pending output as possible. All deflate() output goes
22958 * through this function so some applications may wish to modify it
22959 * to avoid allocating a large strm->output buffer and copying into it.
22960 * (See also read_buf()).
22962 function flush_pending(strm) {
22963 var s = strm.state;
22965 //_tr_flush_bits(s);
22966 var len = s.pending;
22967 if (len > strm.avail_out) {
22968 len = strm.avail_out;
22970 if (len === 0) { return; }
22972 utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
22973 strm.next_out += len;
22974 s.pending_out += len;
22975 strm.total_out += len;
22976 strm.avail_out -= len;
22978 if (s.pending === 0) {
22984 function flush_block_only (s, last) {
22985 trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
22986 s.block_start = s.strstart;
22987 flush_pending(s.strm);
22991 function put_byte(s, b) {
22992 s.pending_buf[s.pending++] = b;
22996 /* =========================================================================
22997 * Put a short in the pending buffer. The 16-bit value is put in MSB order.
22998 * IN assertion: the stream state is correct and there is enough room in
23001 function putShortMSB(s, b) {
23002 // put_byte(s, (Byte)(b >> 8));
23003 // put_byte(s, (Byte)(b & 0xff));
23004 s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
23005 s.pending_buf[s.pending++] = b & 0xff;
23009 /* ===========================================================================
23010 * Read a new buffer from the current input stream, update the adler32
23011 * and total number of bytes read. All deflate() input goes through
23012 * this function so some applications may wish to modify it to avoid
23013 * allocating a large strm->input buffer and copying from it.
23014 * (See also flush_pending()).
23016 function read_buf(strm, buf, start, size) {
23017 var len = strm.avail_in;
23019 if (len > size) { len = size; }
23020 if (len === 0) { return 0; }
23022 strm.avail_in -= len;
23024 utils.arraySet(buf, strm.input, strm.next_in, len, start);
23025 if (strm.state.wrap === 1) {
23026 strm.adler = adler32(strm.adler, buf, len, start);
23029 else if (strm.state.wrap === 2) {
23030 strm.adler = crc32(strm.adler, buf, len, start);
23033 strm.next_in += len;
23034 strm.total_in += len;
23040 /* ===========================================================================
23041 * Set match_start to the longest match starting at the given string and
23042 * return its length. Matches shorter or equal to prev_length are discarded,
23043 * in which case the result is equal to prev_length and match_start is
23045 * IN assertions: cur_match is the head of the hash chain for the current
23046 * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
23047 * OUT assertion: the match length is not greater than s->lookahead.
23049 function longest_match(s, cur_match) {
23050 var chain_length = s.max_chain_length; /* max hash chain length */
23051 var scan = s.strstart; /* current string */
23052 var match; /* matched string */
23053 var len; /* length of current match */
23054 var best_len = s.prev_length; /* best match length so far */
23055 var nice_match = s.nice_match; /* stop if match long enough */
23056 var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
23057 s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
23059 var _win = s.window; // shortcut
23061 var wmask = s.w_mask;
23064 /* Stop when cur_match becomes <= limit. To simplify the code,
23065 * we prevent matches with the string of window index 0.
23068 var strend = s.strstart + MAX_MATCH;
23069 var scan_end1 = _win[scan + best_len - 1];
23070 var scan_end = _win[scan + best_len];
23072 /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
23073 * It is easy to get rid of this optimization if necessary.
23075 // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
23077 /* Do not waste too much time if we already have a good match: */
23078 if (s.prev_length >= s.good_match) {
23079 chain_length >>= 2;
23081 /* Do not look for matches beyond the end of the input. This is necessary
23082 * to make deflate deterministic.
23084 if (nice_match > s.lookahead) { nice_match = s.lookahead; }
23086 // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
23089 // Assert(cur_match < s->strstart, "no future");
23092 /* Skip to next match if the match length cannot increase
23093 * or if the match length is less than 2. Note that the checks below
23094 * for insufficient lookahead only occur occasionally for performance
23095 * reasons. Therefore uninitialized memory will be accessed, and
23096 * conditional jumps will be made that depend on those values.
23097 * However the length of the match is limited to the lookahead, so
23098 * the output of deflate is not affected by the uninitialized values.
23101 if (_win[match + best_len] !== scan_end ||
23102 _win[match + best_len - 1] !== scan_end1 ||
23103 _win[match] !== _win[scan] ||
23104 _win[++match] !== _win[scan + 1]) {
23108 /* The check at best_len-1 can be removed because it will be made
23109 * again later. (This heuristic is not always a win.)
23110 * It is not necessary to compare scan[2] and match[2] since they
23111 * are always equal when the other bytes match, given that
23112 * the hash keys are equal and that HASH_BITS >= 8.
23116 // Assert(*scan == *match, "match[2]?");
23118 /* We check for insufficient lookahead only every 8th comparison;
23119 * the 256th check will be made at strstart+258.
23122 /*jshint noempty:false*/
23123 } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
23124 _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
23125 _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
23126 _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
23129 // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
23131 len = MAX_MATCH - (strend - scan);
23132 scan = strend - MAX_MATCH;
23134 if (len > best_len) {
23135 s.match_start = cur_match;
23137 if (len >= nice_match) {
23140 scan_end1 = _win[scan + best_len - 1];
23141 scan_end = _win[scan + best_len];
23143 } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
23145 if (best_len <= s.lookahead) {
23148 return s.lookahead;
23152 /* ===========================================================================
23153 * Fill the window when the lookahead becomes insufficient.
23154 * Updates strstart and lookahead.
23156 * IN assertion: lookahead < MIN_LOOKAHEAD
23157 * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
23158 * At least one byte has been read, or avail_in == 0; reads are
23159 * performed for at least two bytes (required for the zip translate_eol
23160 * option -- not supported here).
23162 function fill_window(s) {
23163 var _w_size = s.w_size;
23164 var p, n, m, more, str;
23166 //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
23169 more = s.window_size - s.lookahead - s.strstart;
23171 // JS ints have 32 bit, block below not needed
23172 /* Deal with !@#$% 64K limit: */
23173 //if (sizeof(int) <= 2) {
23174 // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
23177 // } else if (more == (unsigned)(-1)) {
23178 // /* Very unlikely, but possible on 16 bit machine if
23179 // * strstart == 0 && lookahead == 1 (input done a byte at time)
23186 /* If the window is almost full and there is insufficient lookahead,
23187 * move the upper half to the lower one to make room in the upper half.
23189 if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
23191 utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
23192 s.match_start -= _w_size;
23193 s.strstart -= _w_size;
23194 /* we now have strstart >= MAX_DIST */
23195 s.block_start -= _w_size;
23197 /* Slide the hash table (could be avoided with 32 bit values
23198 at the expense of memory usage). We slide even when level == 0
23199 to keep the hash table consistent if we switch back to level > 0
23200 later. (Using level 0 permanently is not an optimal usage of
23201 zlib, so we don't care about this pathological case.)
23208 s.head[p] = (m >= _w_size ? m - _w_size : 0);
23215 s.prev[p] = (m >= _w_size ? m - _w_size : 0);
23216 /* If n is not on any hash chain, prev[n] is garbage but
23217 * its value will never be used.
23223 if (s.strm.avail_in === 0) {
23227 /* If there was no sliding:
23228 * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
23229 * more == window_size - lookahead - strstart
23230 * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
23231 * => more >= window_size - 2*WSIZE + 2
23232 * In the BIG_MEM or MMAP case (not yet supported),
23233 * window_size == input_size + MIN_LOOKAHEAD &&
23234 * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
23235 * Otherwise, window_size == 2*WSIZE so more >= 2.
23236 * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
23238 //Assert(more >= 2, "more < 2");
23239 n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
23242 /* Initialize the hash value now that we have some input: */
23243 if (s.lookahead + s.insert >= MIN_MATCH) {
23244 str = s.strstart - s.insert;
23245 s.ins_h = s.window[str];
23247 /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
23248 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
23249 //#if MIN_MATCH != 3
23250 // Call update_hash() MIN_MATCH-3 more times
23253 /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
23254 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask;
23256 s.prev[str & s.w_mask] = s.head[s.ins_h];
23257 s.head[s.ins_h] = str;
23260 if (s.lookahead + s.insert < MIN_MATCH) {
23265 /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
23266 * but this is not important since only literal bytes will be emitted.
23269 } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
23271 /* If the WIN_INIT bytes after the end of the current data have never been
23272 * written, then zero those bytes in order to avoid memory check reports of
23273 * the use of uninitialized (or uninitialised as Julian writes) bytes by
23274 * the longest match routines. Update the high water mark for the next
23275 * time through here. WIN_INIT is set to MAX_MATCH since the longest match
23276 * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
23278 // if (s.high_water < s.window_size) {
23279 // var curr = s.strstart + s.lookahead;
23282 // if (s.high_water < curr) {
23283 // /* Previous high water mark below current data -- zero WIN_INIT
23284 // * bytes or up to end of window, whichever is less.
23286 // init = s.window_size - curr;
23287 // if (init > WIN_INIT)
23288 // init = WIN_INIT;
23289 // zmemzero(s->window + curr, (unsigned)init);
23290 // s->high_water = curr + init;
23292 // else if (s->high_water < (ulg)curr + WIN_INIT) {
23293 // /* High water mark at or above current data, but below current data
23294 // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
23295 // * to end of window, whichever is less.
23297 // init = (ulg)curr + WIN_INIT - s->high_water;
23298 // if (init > s->window_size - s->high_water)
23299 // init = s->window_size - s->high_water;
23300 // zmemzero(s->window + s->high_water, (unsigned)init);
23301 // s->high_water += init;
23305 // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
23306 // "not enough room for search");
23309 /* ===========================================================================
23310 * Copy without compression as much as possible from the input stream, return
23311 * the current block state.
23312 * This function does not insert new strings in the dictionary since
23313 * uncompressible data is probably not useful. This function is used
23314 * only for the level=0 compression option.
23315 * NOTE: this function should be optimized to avoid extra copying from
23316 * window to pending_buf.
23318 function deflate_stored(s, flush) {
23319 /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
23320 * to pending_buf_size, and each stored block has a 5 byte header:
23322 var max_block_size = 0xffff;
23324 if (max_block_size > s.pending_buf_size - 5) {
23325 max_block_size = s.pending_buf_size - 5;
23328 /* Copy as much as possible from input to output: */
23330 /* Fill the window as much as possible: */
23331 if (s.lookahead <= 1) {
23333 //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
23334 // s->block_start >= (long)s->w_size, "slide too late");
23335 // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
23336 // s.block_start >= s.w_size)) {
23337 // throw new Error("slide too late");
23341 if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
23342 return BS_NEED_MORE;
23345 if (s.lookahead === 0) {
23348 /* flush the current block */
23350 //Assert(s->block_start >= 0L, "block gone");
23351 // if (s.block_start < 0) throw new Error("block gone");
23353 s.strstart += s.lookahead;
23356 /* Emit a stored block if pending_buf will be full: */
23357 var max_start = s.block_start + max_block_size;
23359 if (s.strstart === 0 || s.strstart >= max_start) {
23360 /* strstart == 0 is possible when wraparound on 16-bit machine */
23361 s.lookahead = s.strstart - max_start;
23362 s.strstart = max_start;
23363 /*** FLUSH_BLOCK(s, 0); ***/
23364 flush_block_only(s, false);
23365 if (s.strm.avail_out === 0) {
23366 return BS_NEED_MORE;
23372 /* Flush if we may have to slide, otherwise block_start may become
23373 * negative and the data will be gone:
23375 if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
23376 /*** FLUSH_BLOCK(s, 0); ***/
23377 flush_block_only(s, false);
23378 if (s.strm.avail_out === 0) {
23379 return BS_NEED_MORE;
23387 if (flush === Z_FINISH) {
23388 /*** FLUSH_BLOCK(s, 1); ***/
23389 flush_block_only(s, true);
23390 if (s.strm.avail_out === 0) {
23391 return BS_FINISH_STARTED;
23394 return BS_FINISH_DONE;
23397 if (s.strstart > s.block_start) {
23398 /*** FLUSH_BLOCK(s, 0); ***/
23399 flush_block_only(s, false);
23400 if (s.strm.avail_out === 0) {
23401 return BS_NEED_MORE;
23406 return BS_NEED_MORE;
23409 /* ===========================================================================
23410 * Compress as much as possible from the input stream, return the current
23412 * This function does not perform lazy evaluation of matches and inserts
23413 * new strings in the dictionary only for unmatched strings or for short
23414 * matches. It is used only for the fast compression options.
23416 function deflate_fast(s, flush) {
23417 var hash_head; /* head of the hash chain */
23418 var bflush; /* set if current block must be flushed */
23421 /* Make sure that we always have enough lookahead, except
23422 * at the end of the input file. We need MAX_MATCH bytes
23423 * for the next match, plus MIN_MATCH bytes to insert the
23424 * string following the next match.
23426 if (s.lookahead < MIN_LOOKAHEAD) {
23428 if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
23429 return BS_NEED_MORE;
23431 if (s.lookahead === 0) {
23432 break; /* flush the current block */
23436 /* Insert the string window[strstart .. strstart+2] in the
23437 * dictionary, and set hash_head to the head of the hash chain:
23439 hash_head = 0/*NIL*/;
23440 if (s.lookahead >= MIN_MATCH) {
23441 /*** INSERT_STRING(s, s.strstart, hash_head); ***/
23442 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
23443 hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
23444 s.head[s.ins_h] = s.strstart;
23448 /* Find the longest match, discarding those <= prev_length.
23449 * At this point we have always match_length < MIN_MATCH
23451 if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
23452 /* To simplify the code, we prevent matches with the string
23453 * of window index 0 (in particular we have to avoid a match
23454 * of the string with itself at the start of the input file).
23456 s.match_length = longest_match(s, hash_head);
23457 /* longest_match() sets match_start */
23459 if (s.match_length >= MIN_MATCH) {
23460 // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
23462 /*** _tr_tally_dist(s, s.strstart - s.match_start,
23463 s.match_length - MIN_MATCH, bflush); ***/
23464 bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
23466 s.lookahead -= s.match_length;
23468 /* Insert new strings in the hash table only if the match length
23469 * is not too large. This saves time but degrades compression.
23471 if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
23472 s.match_length--; /* string at strstart already in table */
23475 /*** INSERT_STRING(s, s.strstart, hash_head); ***/
23476 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
23477 hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
23478 s.head[s.ins_h] = s.strstart;
23480 /* strstart never exceeds WSIZE-MAX_MATCH, so there are
23481 * always MIN_MATCH bytes ahead.
23483 } while (--s.match_length !== 0);
23487 s.strstart += s.match_length;
23488 s.match_length = 0;
23489 s.ins_h = s.window[s.strstart];
23490 /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
23491 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
23493 //#if MIN_MATCH != 3
23494 // Call UPDATE_HASH() MIN_MATCH-3 more times
23496 /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
23497 * matter since it will be recomputed at next deflate call.
23501 /* No match, output a literal byte */
23502 //Tracevv((stderr,"%c", s.window[s.strstart]));
23503 /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
23504 bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
23510 /*** FLUSH_BLOCK(s, 0); ***/
23511 flush_block_only(s, false);
23512 if (s.strm.avail_out === 0) {
23513 return BS_NEED_MORE;
23518 s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1);
23519 if (flush === Z_FINISH) {
23520 /*** FLUSH_BLOCK(s, 1); ***/
23521 flush_block_only(s, true);
23522 if (s.strm.avail_out === 0) {
23523 return BS_FINISH_STARTED;
23526 return BS_FINISH_DONE;
23529 /*** FLUSH_BLOCK(s, 0); ***/
23530 flush_block_only(s, false);
23531 if (s.strm.avail_out === 0) {
23532 return BS_NEED_MORE;
23536 return BS_BLOCK_DONE;
23539 /* ===========================================================================
23540 * Same as above, but achieves better compression. We use a lazy
23541 * evaluation for matches: a match is finally adopted only if there is
23542 * no better match at the next window position.
23544 function deflate_slow(s, flush) {
23545 var hash_head; /* head of hash chain */
23546 var bflush; /* set if current block must be flushed */
23550 /* Process the input block. */
23552 /* Make sure that we always have enough lookahead, except
23553 * at the end of the input file. We need MAX_MATCH bytes
23554 * for the next match, plus MIN_MATCH bytes to insert the
23555 * string following the next match.
23557 if (s.lookahead < MIN_LOOKAHEAD) {
23559 if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
23560 return BS_NEED_MORE;
23562 if (s.lookahead === 0) { break; } /* flush the current block */
23565 /* Insert the string window[strstart .. strstart+2] in the
23566 * dictionary, and set hash_head to the head of the hash chain:
23568 hash_head = 0/*NIL*/;
23569 if (s.lookahead >= MIN_MATCH) {
23570 /*** INSERT_STRING(s, s.strstart, hash_head); ***/
23571 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
23572 hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
23573 s.head[s.ins_h] = s.strstart;
23577 /* Find the longest match, discarding those <= prev_length.
23579 s.prev_length = s.match_length;
23580 s.prev_match = s.match_start;
23581 s.match_length = MIN_MATCH-1;
23583 if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
23584 s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
23585 /* To simplify the code, we prevent matches with the string
23586 * of window index 0 (in particular we have to avoid a match
23587 * of the string with itself at the start of the input file).
23589 s.match_length = longest_match(s, hash_head);
23590 /* longest_match() sets match_start */
23592 if (s.match_length <= 5 &&
23593 (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
23595 /* If prev_match is also MIN_MATCH, match_start is garbage
23596 * but we will ignore the current match anyway.
23598 s.match_length = MIN_MATCH-1;
23601 /* If there was a match at the previous step and the current
23602 * match is not better, output the previous match:
23604 if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
23605 max_insert = s.strstart + s.lookahead - MIN_MATCH;
23606 /* Do not insert strings in hash table beyond this. */
23608 //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
23610 /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
23611 s.prev_length - MIN_MATCH, bflush);***/
23612 bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH);
23613 /* Insert in hash table all strings up to the end of the match.
23614 * strstart-1 and strstart are already inserted. If there is not
23615 * enough lookahead, the last two strings are not inserted in
23618 s.lookahead -= s.prev_length-1;
23619 s.prev_length -= 2;
23621 if (++s.strstart <= max_insert) {
23622 /*** INSERT_STRING(s, s.strstart, hash_head); ***/
23623 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
23624 hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
23625 s.head[s.ins_h] = s.strstart;
23628 } while (--s.prev_length !== 0);
23629 s.match_available = 0;
23630 s.match_length = MIN_MATCH-1;
23634 /*** FLUSH_BLOCK(s, 0); ***/
23635 flush_block_only(s, false);
23636 if (s.strm.avail_out === 0) {
23637 return BS_NEED_MORE;
23642 } else if (s.match_available) {
23643 /* If there was no match at the previous position, output a
23644 * single literal. If there was a match but the current match
23645 * is longer, truncate the previous match to a single literal.
23647 //Tracevv((stderr,"%c", s->window[s->strstart-1]));
23648 /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
23649 bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
23652 /*** FLUSH_BLOCK_ONLY(s, 0) ***/
23653 flush_block_only(s, false);
23658 if (s.strm.avail_out === 0) {
23659 return BS_NEED_MORE;
23662 /* There is no previous match to compare with, wait for
23663 * the next step to decide.
23665 s.match_available = 1;
23670 //Assert (flush != Z_NO_FLUSH, "no flush?");
23671 if (s.match_available) {
23672 //Tracevv((stderr,"%c", s->window[s->strstart-1]));
23673 /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
23674 bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
23676 s.match_available = 0;
23678 s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1;
23679 if (flush === Z_FINISH) {
23680 /*** FLUSH_BLOCK(s, 1); ***/
23681 flush_block_only(s, true);
23682 if (s.strm.avail_out === 0) {
23683 return BS_FINISH_STARTED;
23686 return BS_FINISH_DONE;
23689 /*** FLUSH_BLOCK(s, 0); ***/
23690 flush_block_only(s, false);
23691 if (s.strm.avail_out === 0) {
23692 return BS_NEED_MORE;
23697 return BS_BLOCK_DONE;
23701 /* ===========================================================================
23702 * For Z_RLE, simply look for runs of bytes, generate matches only of distance
23703 * one. Do not maintain a hash table. (It will be regenerated if this run of
23704 * deflate switches away from Z_RLE.)
23706 function deflate_rle(s, flush) {
23707 var bflush; /* set if current block must be flushed */
23708 var prev; /* byte at distance one to match */
23709 var scan, strend; /* scan goes up to strend for length of run */
23711 var _win = s.window;
23714 /* Make sure that we always have enough lookahead, except
23715 * at the end of the input file. We need MAX_MATCH bytes
23716 * for the longest run, plus one for the unrolled loop.
23718 if (s.lookahead <= MAX_MATCH) {
23720 if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
23721 return BS_NEED_MORE;
23723 if (s.lookahead === 0) { break; } /* flush the current block */
23726 /* See how many times the previous byte repeats */
23727 s.match_length = 0;
23728 if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
23729 scan = s.strstart - 1;
23731 if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
23732 strend = s.strstart + MAX_MATCH;
23734 /*jshint noempty:false*/
23735 } while (prev === _win[++scan] && prev === _win[++scan] &&
23736 prev === _win[++scan] && prev === _win[++scan] &&
23737 prev === _win[++scan] && prev === _win[++scan] &&
23738 prev === _win[++scan] && prev === _win[++scan] &&
23740 s.match_length = MAX_MATCH - (strend - scan);
23741 if (s.match_length > s.lookahead) {
23742 s.match_length = s.lookahead;
23745 //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
23748 /* Emit match if have run of MIN_MATCH or longer, else emit literal */
23749 if (s.match_length >= MIN_MATCH) {
23750 //check_match(s, s.strstart, s.strstart - 1, s.match_length);
23752 /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
23753 bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
23755 s.lookahead -= s.match_length;
23756 s.strstart += s.match_length;
23757 s.match_length = 0;
23759 /* No match, output a literal byte */
23760 //Tracevv((stderr,"%c", s->window[s->strstart]));
23761 /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
23762 bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
23768 /*** FLUSH_BLOCK(s, 0); ***/
23769 flush_block_only(s, false);
23770 if (s.strm.avail_out === 0) {
23771 return BS_NEED_MORE;
23777 if (flush === Z_FINISH) {
23778 /*** FLUSH_BLOCK(s, 1); ***/
23779 flush_block_only(s, true);
23780 if (s.strm.avail_out === 0) {
23781 return BS_FINISH_STARTED;
23784 return BS_FINISH_DONE;
23787 /*** FLUSH_BLOCK(s, 0); ***/
23788 flush_block_only(s, false);
23789 if (s.strm.avail_out === 0) {
23790 return BS_NEED_MORE;
23794 return BS_BLOCK_DONE;
23797 /* ===========================================================================
23798 * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
23799 * (It will be regenerated if this run of deflate switches away from Huffman.)
23801 function deflate_huff(s, flush) {
23802 var bflush; /* set if current block must be flushed */
23805 /* Make sure that we have a literal to write. */
23806 if (s.lookahead === 0) {
23808 if (s.lookahead === 0) {
23809 if (flush === Z_NO_FLUSH) {
23810 return BS_NEED_MORE;
23812 break; /* flush the current block */
23816 /* Output a literal byte */
23817 s.match_length = 0;
23818 //Tracevv((stderr,"%c", s->window[s->strstart]));
23819 /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
23820 bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
23824 /*** FLUSH_BLOCK(s, 0); ***/
23825 flush_block_only(s, false);
23826 if (s.strm.avail_out === 0) {
23827 return BS_NEED_MORE;
23833 if (flush === Z_FINISH) {
23834 /*** FLUSH_BLOCK(s, 1); ***/
23835 flush_block_only(s, true);
23836 if (s.strm.avail_out === 0) {
23837 return BS_FINISH_STARTED;
23840 return BS_FINISH_DONE;
23843 /*** FLUSH_BLOCK(s, 0); ***/
23844 flush_block_only(s, false);
23845 if (s.strm.avail_out === 0) {
23846 return BS_NEED_MORE;
23850 return BS_BLOCK_DONE;
23853 /* Values for max_lazy_match, good_match and max_chain_length, depending on
23854 * the desired pack level (0..9). The values given below have been tuned to
23855 * exclude worst case performance for pathological files. Better values may be
23856 * found for specific files.
23858 var Config = function (good_length, max_lazy, nice_length, max_chain, func) {
23859 this.good_length = good_length;
23860 this.max_lazy = max_lazy;
23861 this.nice_length = nice_length;
23862 this.max_chain = max_chain;
23866 var configuration_table;
23868 configuration_table = [
23869 /* good lazy nice chain */
23870 new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
23871 new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
23872 new Config(4, 5, 16, 8, deflate_fast), /* 2 */
23873 new Config(4, 6, 32, 32, deflate_fast), /* 3 */
23875 new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
23876 new Config(8, 16, 32, 32, deflate_slow), /* 5 */
23877 new Config(8, 16, 128, 128, deflate_slow), /* 6 */
23878 new Config(8, 32, 128, 256, deflate_slow), /* 7 */
23879 new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
23880 new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
23884 /* ===========================================================================
23885 * Initialize the "longest match" routines for a new zlib stream
23887 function lm_init(s) {
23888 s.window_size = 2 * s.w_size;
23890 /*** CLEAR_HASH(s); ***/
23891 zero(s.head); // Fill with NIL (= 0);
23893 /* Set the default configuration parameters:
23895 s.max_lazy_match = configuration_table[s.level].max_lazy;
23896 s.good_match = configuration_table[s.level].good_length;
23897 s.nice_match = configuration_table[s.level].nice_length;
23898 s.max_chain_length = configuration_table[s.level].max_chain;
23904 s.match_length = s.prev_length = MIN_MATCH - 1;
23905 s.match_available = 0;
23910 function DeflateState() {
23911 this.strm = null; /* pointer back to this zlib stream */
23912 this.status = 0; /* as the name implies */
23913 this.pending_buf = null; /* output still pending */
23914 this.pending_buf_size = 0; /* size of pending_buf */
23915 this.pending_out = 0; /* next pending byte to output to the stream */
23916 this.pending = 0; /* nb of bytes in the pending buffer */
23917 this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
23918 this.gzhead = null; /* gzip header information to write */
23919 this.gzindex = 0; /* where in extra, name, or comment */
23920 this.method = Z_DEFLATED; /* can only be DEFLATED */
23921 this.last_flush = -1; /* value of flush param for previous deflate call */
23923 this.w_size = 0; /* LZ77 window size (32K by default) */
23924 this.w_bits = 0; /* log2(w_size) (8..16) */
23925 this.w_mask = 0; /* w_size - 1 */
23927 this.window = null;
23928 /* Sliding window. Input bytes are read into the second half of the window,
23929 * and move to the first half later to keep a dictionary of at least wSize
23930 * bytes. With this organization, matches are limited to a distance of
23931 * wSize-MAX_MATCH bytes, but this ensures that IO is always
23932 * performed with a length multiple of the block size.
23935 this.window_size = 0;
23936 /* Actual size of window: 2*wSize, except when the user input buffer
23937 * is directly used as sliding window.
23941 /* Link to older string with same hash index. To limit the size of this
23942 * array to 64K, this link is maintained only for the last 32K strings.
23943 * An index in this array is thus a window index modulo 32K.
23946 this.head = null; /* Heads of the hash chains or NIL. */
23948 this.ins_h = 0; /* hash index of string to be inserted */
23949 this.hash_size = 0; /* number of elements in hash table */
23950 this.hash_bits = 0; /* log2(hash_size) */
23951 this.hash_mask = 0; /* hash_size-1 */
23953 this.hash_shift = 0;
23954 /* Number of bits by which ins_h must be shifted at each input
23955 * step. It must be such that after MIN_MATCH steps, the oldest
23956 * byte no longer takes part in the hash key, that is:
23957 * hash_shift * MIN_MATCH >= hash_bits
23960 this.block_start = 0;
23961 /* Window position at the beginning of the current output block. Gets
23962 * negative when the window is moved backwards.
23965 this.match_length = 0; /* length of best match */
23966 this.prev_match = 0; /* previous match */
23967 this.match_available = 0; /* set if previous match exists */
23968 this.strstart = 0; /* start of string to insert */
23969 this.match_start = 0; /* start of matching string */
23970 this.lookahead = 0; /* number of valid bytes ahead in window */
23972 this.prev_length = 0;
23973 /* Length of the best match at previous step. Matches not greater than this
23974 * are discarded. This is used in the lazy match evaluation.
23977 this.max_chain_length = 0;
23978 /* To speed up deflation, hash chains are never searched beyond this
23979 * length. A higher limit improves compression ratio but degrades the
23983 this.max_lazy_match = 0;
23984 /* Attempt to find a better match only when the current match is strictly
23985 * smaller than this value. This mechanism is used only for compression
23988 // That's alias to max_lazy_match, don't use directly
23989 //this.max_insert_length = 0;
23990 /* Insert new strings in the hash table only if the match length is not
23991 * greater than this length. This saves time but degrades compression.
23992 * max_insert_length is used only for compression levels <= 3.
23995 this.level = 0; /* compression level (1..9) */
23996 this.strategy = 0; /* favor or force Huffman coding*/
23998 this.good_match = 0;
23999 /* Use a faster search when the previous match is longer than this */
24001 this.nice_match = 0; /* Stop searching when current match exceeds this */
24003 /* used by trees.c: */
24005 /* Didn't use ct_data typedef below to suppress compiler warning */
24007 // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
24008 // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
24009 // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
24011 // Use flat array of DOUBLE size, with interleaved fata,
24012 // because JS does not support effective
24013 this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
24014 this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2);
24015 this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2);
24016 zero(this.dyn_ltree);
24017 zero(this.dyn_dtree);
24018 zero(this.bl_tree);
24020 this.l_desc = null; /* desc. for literal tree */
24021 this.d_desc = null; /* desc. for distance tree */
24022 this.bl_desc = null; /* desc. for bit length tree */
24024 //ush bl_count[MAX_BITS+1];
24025 this.bl_count = new utils.Buf16(MAX_BITS+1);
24026 /* number of codes at each bit length for an optimal tree */
24028 //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
24029 this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */
24032 this.heap_len = 0; /* number of elements in the heap */
24033 this.heap_max = 0; /* element of largest frequency */
24034 /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
24035 * The same heap array is used to build all trees.
24038 this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1];
24040 /* Depth of each subtree used as tie breaker for trees of equal frequency
24043 this.l_buf = 0; /* buffer index for literals or lengths */
24045 this.lit_bufsize = 0;
24046 /* Size of match buffer for literals/lengths. There are 4 reasons for
24047 * limiting lit_bufsize to 64K:
24048 * - frequencies can be kept in 16 bit counters
24049 * - if compression is not successful for the first block, all input
24050 * data is still in the window so we can still emit a stored block even
24051 * when input comes from standard input. (This can also be done for
24052 * all blocks if lit_bufsize is not greater than 32K.)
24053 * - if compression is not successful for a file smaller than 64K, we can
24054 * even emit a stored file instead of a stored block (saving 5 bytes).
24055 * This is applicable only for zip (not gzip or zlib).
24056 * - creating new Huffman trees less frequently may not provide fast
24057 * adaptation to changes in the input data statistics. (Take for
24058 * example a binary file with poorly compressible code followed by
24059 * a highly compressible string table.) Smaller buffer sizes give
24060 * fast adaptation but have of course the overhead of transmitting
24061 * trees more frequently.
24062 * - I can't count above 4
24065 this.last_lit = 0; /* running index in l_buf */
24068 /* Buffer index for distances. To simplify the code, d_buf and l_buf have
24069 * the same number of elements. To use different lengths, an extra flag
24070 * array would be necessary.
24073 this.opt_len = 0; /* bit length of current block with optimal trees */
24074 this.static_len = 0; /* bit length of current block with static trees */
24075 this.matches = 0; /* number of string matches in current block */
24076 this.insert = 0; /* bytes at end of window left to insert */
24080 /* Output buffer. bits are inserted starting at the bottom (least
24081 * significant bits).
24084 /* Number of valid bits in bi_buf. All bits above the last valid bit
24088 // Used for window memory init. We safely ignore it for JS. That makes
24089 // sense only for pointers and memory check tools.
24090 //this.high_water = 0;
24091 /* High water mark offset in window for initialized bytes -- bytes above
24092 * this are set to zero in order to avoid memory check warnings when
24093 * longest match routines access bytes past the input. This is then
24094 * updated to the new high water mark.
24099 function deflateResetKeep(strm) {
24102 if (!strm || !strm.state) {
24103 return err(strm, Z_STREAM_ERROR);
24106 strm.total_in = strm.total_out = 0;
24107 strm.data_type = Z_UNKNOWN;
24115 /* was made negative by deflate(..., Z_FINISH); */
24117 s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
24118 strm.adler = (s.wrap === 2) ?
24119 0 // crc32(0, Z_NULL, 0)
24121 1; // adler32(0, Z_NULL, 0)
24122 s.last_flush = Z_NO_FLUSH;
24128 function deflateReset(strm) {
24129 var ret = deflateResetKeep(strm);
24130 if (ret === Z_OK) {
24131 lm_init(strm.state);
24137 function deflateSetHeader(strm, head) {
24138 if (!strm || !strm.state) { return Z_STREAM_ERROR; }
24139 if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
24140 strm.state.gzhead = head;
24145 function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
24146 if (!strm) { // === Z_NULL
24147 return Z_STREAM_ERROR;
24151 if (level === Z_DEFAULT_COMPRESSION) {
24155 if (windowBits < 0) { /* suppress zlib wrapper */
24157 windowBits = -windowBits;
24160 else if (windowBits > 15) {
24161 wrap = 2; /* write gzip wrapper instead */
24166 if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
24167 windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
24168 strategy < 0 || strategy > Z_FIXED) {
24169 return err(strm, Z_STREAM_ERROR);
24173 if (windowBits === 8) {
24176 /* until 256-byte window bug fixed */
24178 var s = new DeflateState();
24185 s.w_bits = windowBits;
24186 s.w_size = 1 << s.w_bits;
24187 s.w_mask = s.w_size - 1;
24189 s.hash_bits = memLevel + 7;
24190 s.hash_size = 1 << s.hash_bits;
24191 s.hash_mask = s.hash_size - 1;
24192 s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
24194 s.window = new utils.Buf8(s.w_size * 2);
24195 s.head = new utils.Buf16(s.hash_size);
24196 s.prev = new utils.Buf16(s.w_size);
24198 // Don't need mem init magic for JS.
24199 //s.high_water = 0; /* nothing written to s->window yet */
24201 s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
24203 s.pending_buf_size = s.lit_bufsize * 4;
24204 s.pending_buf = new utils.Buf8(s.pending_buf_size);
24206 s.d_buf = s.lit_bufsize >> 1;
24207 s.l_buf = (1 + 2) * s.lit_bufsize;
24210 s.strategy = strategy;
24213 return deflateReset(strm);
24216 function deflateInit(strm, level) {
24217 return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
24221 function deflate(strm, flush) {
24223 var beg, val; // for gzip header write only
24225 if (!strm || !strm.state ||
24226 flush > Z_BLOCK || flush < 0) {
24227 return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
24232 if (!strm.output ||
24233 (!strm.input && strm.avail_in !== 0) ||
24234 (s.status === FINISH_STATE && flush !== Z_FINISH)) {
24235 return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
24238 s.strm = strm; /* just in case */
24239 old_flush = s.last_flush;
24240 s.last_flush = flush;
24242 /* Write the header */
24243 if (s.status === INIT_STATE) {
24245 if (s.wrap === 2) { // GZIP header
24246 strm.adler = 0; //crc32(0L, Z_NULL, 0);
24250 if (!s.gzhead) { // s->gzhead == Z_NULL
24256 put_byte(s, s.level === 9 ? 2 :
24257 (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
24259 put_byte(s, OS_CODE);
24260 s.status = BUSY_STATE;
24263 put_byte(s, (s.gzhead.text ? 1 : 0) +
24264 (s.gzhead.hcrc ? 2 : 0) +
24265 (!s.gzhead.extra ? 0 : 4) +
24266 (!s.gzhead.name ? 0 : 8) +
24267 (!s.gzhead.comment ? 0 : 16)
24269 put_byte(s, s.gzhead.time & 0xff);
24270 put_byte(s, (s.gzhead.time >> 8) & 0xff);
24271 put_byte(s, (s.gzhead.time >> 16) & 0xff);
24272 put_byte(s, (s.gzhead.time >> 24) & 0xff);
24273 put_byte(s, s.level === 9 ? 2 :
24274 (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
24276 put_byte(s, s.gzhead.os & 0xff);
24277 if (s.gzhead.extra && s.gzhead.extra.length) {
24278 put_byte(s, s.gzhead.extra.length & 0xff);
24279 put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
24281 if (s.gzhead.hcrc) {
24282 strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
24285 s.status = EXTRA_STATE;
24288 else // DEFLATE header
24290 var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
24291 var level_flags = -1;
24293 if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
24295 } else if (s.level < 6) {
24297 } else if (s.level === 6) {
24302 header |= (level_flags << 6);
24303 if (s.strstart !== 0) { header |= PRESET_DICT; }
24304 header += 31 - (header % 31);
24306 s.status = BUSY_STATE;
24307 putShortMSB(s, header);
24309 /* Save the adler32 of the preset dictionary: */
24310 if (s.strstart !== 0) {
24311 putShortMSB(s, strm.adler >>> 16);
24312 putShortMSB(s, strm.adler & 0xffff);
24314 strm.adler = 1; // adler32(0L, Z_NULL, 0);
24319 if (s.status === EXTRA_STATE) {
24320 if (s.gzhead.extra/* != Z_NULL*/) {
24321 beg = s.pending; /* start of bytes to update crc */
24323 while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
24324 if (s.pending === s.pending_buf_size) {
24325 if (s.gzhead.hcrc && s.pending > beg) {
24326 strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
24328 flush_pending(strm);
24330 if (s.pending === s.pending_buf_size) {
24334 put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
24337 if (s.gzhead.hcrc && s.pending > beg) {
24338 strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
24340 if (s.gzindex === s.gzhead.extra.length) {
24342 s.status = NAME_STATE;
24346 s.status = NAME_STATE;
24349 if (s.status === NAME_STATE) {
24350 if (s.gzhead.name/* != Z_NULL*/) {
24351 beg = s.pending; /* start of bytes to update crc */
24355 if (s.pending === s.pending_buf_size) {
24356 if (s.gzhead.hcrc && s.pending > beg) {
24357 strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
24359 flush_pending(strm);
24361 if (s.pending === s.pending_buf_size) {
24366 // JS specific: little magic to add zero terminator to end of string
24367 if (s.gzindex < s.gzhead.name.length) {
24368 val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
24373 } while (val !== 0);
24375 if (s.gzhead.hcrc && s.pending > beg) {
24376 strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
24380 s.status = COMMENT_STATE;
24384 s.status = COMMENT_STATE;
24387 if (s.status === COMMENT_STATE) {
24388 if (s.gzhead.comment/* != Z_NULL*/) {
24389 beg = s.pending; /* start of bytes to update crc */
24393 if (s.pending === s.pending_buf_size) {
24394 if (s.gzhead.hcrc && s.pending > beg) {
24395 strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
24397 flush_pending(strm);
24399 if (s.pending === s.pending_buf_size) {
24404 // JS specific: little magic to add zero terminator to end of string
24405 if (s.gzindex < s.gzhead.comment.length) {
24406 val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
24411 } while (val !== 0);
24413 if (s.gzhead.hcrc && s.pending > beg) {
24414 strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
24417 s.status = HCRC_STATE;
24421 s.status = HCRC_STATE;
24424 if (s.status === HCRC_STATE) {
24425 if (s.gzhead.hcrc) {
24426 if (s.pending + 2 > s.pending_buf_size) {
24427 flush_pending(strm);
24429 if (s.pending + 2 <= s.pending_buf_size) {
24430 put_byte(s, strm.adler & 0xff);
24431 put_byte(s, (strm.adler >> 8) & 0xff);
24432 strm.adler = 0; //crc32(0L, Z_NULL, 0);
24433 s.status = BUSY_STATE;
24437 s.status = BUSY_STATE;
24442 /* Flush as much pending output as possible */
24443 if (s.pending !== 0) {
24444 flush_pending(strm);
24445 if (strm.avail_out === 0) {
24446 /* Since avail_out is 0, deflate will be called again with
24447 * more output space, but possibly with both pending and
24448 * avail_in equal to zero. There won't be anything to do,
24449 * but this is not an error situation so make sure we
24450 * return OK instead of BUF_ERROR at next call of deflate:
24456 /* Make sure there is something to do and avoid duplicate consecutive
24457 * flushes. For repeated and useless calls with Z_FINISH, we keep
24458 * returning Z_STREAM_END instead of Z_BUF_ERROR.
24460 } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
24461 flush !== Z_FINISH) {
24462 return err(strm, Z_BUF_ERROR);
24465 /* User must not provide more input after the first FINISH: */
24466 if (s.status === FINISH_STATE && strm.avail_in !== 0) {
24467 return err(strm, Z_BUF_ERROR);
24470 /* Start a new block or continue the current one.
24472 if (strm.avail_in !== 0 || s.lookahead !== 0 ||
24473 (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
24474 var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
24475 (s.strategy === Z_RLE ? deflate_rle(s, flush) :
24476 configuration_table[s.level].func(s, flush));
24478 if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
24479 s.status = FINISH_STATE;
24481 if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
24482 if (strm.avail_out === 0) {
24484 /* avoid BUF_ERROR next call, see above */
24487 /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
24488 * of deflate should use the same flush parameter to make sure
24489 * that the flush is complete. So we don't have to output an
24490 * empty block here, this will be done at next call. This also
24491 * ensures that for a very small output buffer, we emit at most
24495 if (bstate === BS_BLOCK_DONE) {
24496 if (flush === Z_PARTIAL_FLUSH) {
24497 trees._tr_align(s);
24499 else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
24501 trees._tr_stored_block(s, 0, 0, false);
24502 /* For a full flush, this empty block will be recognized
24503 * as a special marker by inflate_sync().
24505 if (flush === Z_FULL_FLUSH) {
24506 /*** CLEAR_HASH(s); ***/ /* forget history */
24507 zero(s.head); // Fill with NIL (= 0);
24509 if (s.lookahead === 0) {
24516 flush_pending(strm);
24517 if (strm.avail_out === 0) {
24518 s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
24523 //Assert(strm->avail_out > 0, "bug2");
24524 //if (strm.avail_out <= 0) { throw new Error("bug2");}
24526 if (flush !== Z_FINISH) { return Z_OK; }
24527 if (s.wrap <= 0) { return Z_STREAM_END; }
24529 /* Write the trailer */
24530 if (s.wrap === 2) {
24531 put_byte(s, strm.adler & 0xff);
24532 put_byte(s, (strm.adler >> 8) & 0xff);
24533 put_byte(s, (strm.adler >> 16) & 0xff);
24534 put_byte(s, (strm.adler >> 24) & 0xff);
24535 put_byte(s, strm.total_in & 0xff);
24536 put_byte(s, (strm.total_in >> 8) & 0xff);
24537 put_byte(s, (strm.total_in >> 16) & 0xff);
24538 put_byte(s, (strm.total_in >> 24) & 0xff);
24542 putShortMSB(s, strm.adler >>> 16);
24543 putShortMSB(s, strm.adler & 0xffff);
24546 flush_pending(strm);
24547 /* If avail_out is zero, the application will call deflate again
24548 * to flush the rest.
24550 if (s.wrap > 0) { s.wrap = -s.wrap; }
24551 /* write the trailer only once! */
24552 return s.pending !== 0 ? Z_OK : Z_STREAM_END;
24555 function deflateEnd(strm) {
24558 if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
24559 return Z_STREAM_ERROR;
24562 status = strm.state.status;
24563 if (status !== INIT_STATE &&
24564 status !== EXTRA_STATE &&
24565 status !== NAME_STATE &&
24566 status !== COMMENT_STATE &&
24567 status !== HCRC_STATE &&
24568 status !== BUSY_STATE &&
24569 status !== FINISH_STATE
24571 return err(strm, Z_STREAM_ERROR);
24576 return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
24579 /* =========================================================================
24580 * Copy the source state to the destination state
24582 //function deflateCopy(dest, source) {
24586 exports.deflateInit = deflateInit;
24587 exports.deflateInit2 = deflateInit2;
24588 exports.deflateReset = deflateReset;
24589 exports.deflateResetKeep = deflateResetKeep;
24590 exports.deflateSetHeader = deflateSetHeader;
24591 exports.deflate = deflate;
24592 exports.deflateEnd = deflateEnd;
24593 exports.deflateInfo = 'pako deflate (from Nodeca project)';
24596 exports.deflateBound = deflateBound;
24597 exports.deflateCopy = deflateCopy;
24598 exports.deflateSetDictionary = deflateSetDictionary;
24599 exports.deflateParams = deflateParams;
24600 exports.deflatePending = deflatePending;
24601 exports.deflatePrime = deflatePrime;
24602 exports.deflateTune = deflateTune;
24608 /***/ function(module, exports) {
24613 var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
24614 (typeof Uint16Array !== 'undefined') &&
24615 (typeof Int32Array !== 'undefined');
24618 exports.assign = function (obj /*from1, from2, from3, ...*/) {
24619 var sources = Array.prototype.slice.call(arguments, 1);
24620 while (sources.length) {
24621 var source = sources.shift();
24622 if (!source) { continue; }
24624 if (typeof source !== 'object') {
24625 throw new TypeError(source + 'must be non-object');
24628 for (var p in source) {
24629 if (source.hasOwnProperty(p)) {
24630 obj[p] = source[p];
24639 // reduce buffer size, avoiding mem copy
24640 exports.shrinkBuf = function (buf, size) {
24641 if (buf.length === size) { return buf; }
24642 if (buf.subarray) { return buf.subarray(0, size); }
24649 arraySet: function (dest, src, src_offs, len, dest_offs) {
24650 if (src.subarray && dest.subarray) {
24651 dest.set(src.subarray(src_offs, src_offs+len), dest_offs);
24654 // Fallback to ordinary array
24655 for (var i=0; i<len; i++) {
24656 dest[dest_offs + i] = src[src_offs + i];
24659 // Join array of chunks to single array.
24660 flattenChunks: function(chunks) {
24661 var i, l, len, pos, chunk, result;
24663 // calculate data length
24665 for (i=0, l=chunks.length; i<l; i++) {
24666 len += chunks[i].length;
24670 result = new Uint8Array(len);
24672 for (i=0, l=chunks.length; i<l; i++) {
24674 result.set(chunk, pos);
24675 pos += chunk.length;
24683 arraySet: function (dest, src, src_offs, len, dest_offs) {
24684 for (var i=0; i<len; i++) {
24685 dest[dest_offs + i] = src[src_offs + i];
24688 // Join array of chunks to single array.
24689 flattenChunks: function(chunks) {
24690 return [].concat.apply([], chunks);
24695 // Enable/Disable typed arrays use, for testing
24697 exports.setTyped = function (on) {
24699 exports.Buf8 = Uint8Array;
24700 exports.Buf16 = Uint16Array;
24701 exports.Buf32 = Int32Array;
24702 exports.assign(exports, fnTyped);
24704 exports.Buf8 = Array;
24705 exports.Buf16 = Array;
24706 exports.Buf32 = Array;
24707 exports.assign(exports, fnUntyped);
24711 exports.setTyped(TYPED_OK);
24716 /***/ function(module, exports, __webpack_require__) {
24721 var utils = __webpack_require__(52);
24723 /* Public constants ==========================================================*/
24724 /* ===========================================================================*/
24727 //var Z_FILTERED = 1;
24728 //var Z_HUFFMAN_ONLY = 2;
24731 //var Z_DEFAULT_STRATEGY = 0;
24733 /* Possible values of the data_type field (though see inflate()) */
24736 //var Z_ASCII = 1; // = Z_TEXT
24739 /*============================================================================*/
24742 function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
24746 var STORED_BLOCK = 0;
24747 var STATIC_TREES = 1;
24749 /* The three kinds of block type */
24752 var MAX_MATCH = 258;
24753 /* The minimum and maximum match lengths */
24756 /* ===========================================================================
24757 * Internal compression state.
24760 var LENGTH_CODES = 29;
24761 /* number of length codes, not counting the special END_BLOCK code */
24763 var LITERALS = 256;
24764 /* number of literal bytes 0..255 */
24766 var L_CODES = LITERALS + 1 + LENGTH_CODES;
24767 /* number of Literal or Length codes, including the END_BLOCK code */
24770 /* number of distance codes */
24773 /* number of codes used to transfer the bit lengths */
24775 var HEAP_SIZE = 2*L_CODES + 1;
24776 /* maximum heap size */
24779 /* All codes must not exceed MAX_BITS bits */
24782 /* size of bit buffer in bi_buf */
24785 /* ===========================================================================
24789 var MAX_BL_BITS = 7;
24790 /* Bit length codes must not exceed MAX_BL_BITS bits */
24792 var END_BLOCK = 256;
24793 /* end of block literal code */
24796 /* repeat previous bit length 3-6 times (2 bits of repeat count) */
24798 var REPZ_3_10 = 17;
24799 /* repeat a zero length 3-10 times (3 bits of repeat count) */
24801 var REPZ_11_138 = 18;
24802 /* repeat a zero length 11-138 times (7 bits of repeat count) */
24804 var extra_lbits = /* extra bits for each length code */
24805 [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];
24807 var extra_dbits = /* extra bits for each distance code */
24808 [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];
24810 var extra_blbits = /* extra bits for each bit length code */
24811 [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
24814 [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
24815 /* The lengths of the bit length codes are sent in order of decreasing
24816 * probability, to avoid transmitting the lengths for unused bit length codes.
24819 /* ===========================================================================
24820 * Local data. These are initialized only once.
24823 // We pre-fill arrays with 0 to avoid uninitialized gaps
24825 var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
24827 // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
24828 var static_ltree = new Array((L_CODES+2) * 2);
24829 zero(static_ltree);
24830 /* The static literal tree. Since the bit lengths are imposed, there is no
24831 * need for the L_CODES extra codes used during heap construction. However
24832 * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
24836 var static_dtree = new Array(D_CODES * 2);
24837 zero(static_dtree);
24838 /* The static distance tree. (Actually a trivial tree since all codes use
24842 var _dist_code = new Array(DIST_CODE_LEN);
24844 /* Distance codes. The first 256 values correspond to the distances
24845 * 3 .. 258, the last 256 values correspond to the top 8 bits of
24846 * the 15 bit distances.
24849 var _length_code = new Array(MAX_MATCH-MIN_MATCH+1);
24850 zero(_length_code);
24851 /* length code for each normalized match length (0 == MIN_MATCH) */
24853 var base_length = new Array(LENGTH_CODES);
24855 /* First normalized length for each code (0 = MIN_MATCH) */
24857 var base_dist = new Array(D_CODES);
24859 /* First normalized distance for each code (0 = distance of 1) */
24862 var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) {
24864 this.static_tree = static_tree; /* static tree or NULL */
24865 this.extra_bits = extra_bits; /* extra bits for each code or NULL */
24866 this.extra_base = extra_base; /* base index for extra_bits */
24867 this.elems = elems; /* max number of elements in the tree */
24868 this.max_length = max_length; /* max bit length for the codes */
24870 // show if `static_tree` has data or dummy - needed for monomorphic objects
24871 this.has_stree = static_tree && static_tree.length;
24877 var static_bl_desc;
24880 var TreeDesc = function(dyn_tree, stat_desc) {
24881 this.dyn_tree = dyn_tree; /* the dynamic tree */
24882 this.max_code = 0; /* largest code with non zero frequency */
24883 this.stat_desc = stat_desc; /* the corresponding static tree */
24888 function d_code(dist) {
24889 return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
24893 /* ===========================================================================
24894 * Output a short LSB first on the stream.
24895 * IN assertion: there is enough room in pendingBuf.
24897 function put_short (s, w) {
24898 // put_byte(s, (uch)((w) & 0xff));
24899 // put_byte(s, (uch)((ush)(w) >> 8));
24900 s.pending_buf[s.pending++] = (w) & 0xff;
24901 s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
24905 /* ===========================================================================
24906 * Send a value on a given number of bits.
24907 * IN assertion: length <= 16 and value fits in length bits.
24909 function send_bits(s, value, length) {
24910 if (s.bi_valid > (Buf_size - length)) {
24911 s.bi_buf |= (value << s.bi_valid) & 0xffff;
24912 put_short(s, s.bi_buf);
24913 s.bi_buf = value >> (Buf_size - s.bi_valid);
24914 s.bi_valid += length - Buf_size;
24916 s.bi_buf |= (value << s.bi_valid) & 0xffff;
24917 s.bi_valid += length;
24922 function send_code(s, c, tree) {
24923 send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/);
24927 /* ===========================================================================
24928 * Reverse the first len bits of a code, using straightforward code (a faster
24929 * method would use a table)
24930 * IN assertion: 1 <= len <= 15
24932 function bi_reverse(code, len) {
24938 } while (--len > 0);
24943 /* ===========================================================================
24944 * Flush the bit buffer, keeping at most 7 bits in it.
24946 function bi_flush(s) {
24947 if (s.bi_valid === 16) {
24948 put_short(s, s.bi_buf);
24952 } else if (s.bi_valid >= 8) {
24953 s.pending_buf[s.pending++] = s.bi_buf & 0xff;
24960 /* ===========================================================================
24961 * Compute the optimal bit lengths for a tree and update the total bit length
24962 * for the current block.
24963 * IN assertion: the fields freq and dad are set, heap[heap_max] and
24964 * above are the tree nodes sorted by increasing frequency.
24965 * OUT assertions: the field len is set to the optimal bit length, the
24966 * array bl_count contains the frequencies for each bit length.
24967 * The length opt_len is updated; static_len is also updated if stree is
24970 function gen_bitlen(s, desc)
24971 // deflate_state *s;
24972 // tree_desc *desc; /* the tree descriptor */
24974 var tree = desc.dyn_tree;
24975 var max_code = desc.max_code;
24976 var stree = desc.stat_desc.static_tree;
24977 var has_stree = desc.stat_desc.has_stree;
24978 var extra = desc.stat_desc.extra_bits;
24979 var base = desc.stat_desc.extra_base;
24980 var max_length = desc.stat_desc.max_length;
24981 var h; /* heap index */
24982 var n, m; /* iterate over the tree elements */
24983 var bits; /* bit length */
24984 var xbits; /* extra bits */
24985 var f; /* frequency */
24986 var overflow = 0; /* number of elements with bit length too large */
24988 for (bits = 0; bits <= MAX_BITS; bits++) {
24989 s.bl_count[bits] = 0;
24992 /* In a first pass, compute the optimal bit lengths (which may
24993 * overflow in the case of the bit length tree).
24995 tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */
24997 for (h = s.heap_max+1; h < HEAP_SIZE; h++) {
24999 bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
25000 if (bits > max_length) {
25004 tree[n*2 + 1]/*.Len*/ = bits;
25005 /* We overwrite tree[n].Dad which is no longer needed */
25007 if (n > max_code) { continue; } /* not a leaf node */
25009 s.bl_count[bits]++;
25012 xbits = extra[n-base];
25014 f = tree[n * 2]/*.Freq*/;
25015 s.opt_len += f * (bits + xbits);
25017 s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits);
25020 if (overflow === 0) { return; }
25022 // Trace((stderr,"\nbit length overflow\n"));
25023 /* This happens for example on obj2 and pic of the Calgary corpus */
25025 /* Find the first bit length which could increase: */
25027 bits = max_length-1;
25028 while (s.bl_count[bits] === 0) { bits--; }
25029 s.bl_count[bits]--; /* move one leaf down the tree */
25030 s.bl_count[bits+1] += 2; /* move one overflow item as its brother */
25031 s.bl_count[max_length]--;
25032 /* The brother of the overflow item also moves one step up,
25033 * but this does not affect bl_count[max_length]
25036 } while (overflow > 0);
25038 /* Now recompute all bit lengths, scanning in increasing frequency.
25039 * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
25040 * lengths instead of fixing only the wrong ones. This idea is taken
25041 * from 'ar' written by Haruhiko Okumura.)
25043 for (bits = max_length; bits !== 0; bits--) {
25044 n = s.bl_count[bits];
25047 if (m > max_code) { continue; }
25048 if (tree[m*2 + 1]/*.Len*/ !== bits) {
25049 // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
25050 s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/;
25051 tree[m*2 + 1]/*.Len*/ = bits;
25059 /* ===========================================================================
25060 * Generate the codes for a given tree and bit counts (which need not be
25062 * IN assertion: the array bl_count contains the bit length statistics for
25063 * the given tree and the field len is set for all tree elements.
25064 * OUT assertion: the field code is set for all tree elements of non
25065 * zero code length.
25067 function gen_codes(tree, max_code, bl_count)
25068 // ct_data *tree; /* the tree to decorate */
25069 // int max_code; /* largest code with non zero frequency */
25070 // ushf *bl_count; /* number of codes at each bit length */
25072 var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */
25073 var code = 0; /* running code value */
25074 var bits; /* bit index */
25075 var n; /* code index */
25077 /* The distribution counts are first used to generate the code values
25078 * without bit reversal.
25080 for (bits = 1; bits <= MAX_BITS; bits++) {
25081 next_code[bits] = code = (code + bl_count[bits-1]) << 1;
25083 /* Check that the bit counts in bl_count are consistent. The last code
25084 * must be all ones.
25086 //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
25087 // "inconsistent bit counts");
25088 //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
25090 for (n = 0; n <= max_code; n++) {
25091 var len = tree[n*2 + 1]/*.Len*/;
25092 if (len === 0) { continue; }
25093 /* Now reverse the bits */
25094 tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len);
25096 //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
25097 // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
25102 /* ===========================================================================
25103 * Initialize the various 'constant' tables.
25105 function tr_static_init() {
25106 var n; /* iterates over tree elements */
25107 var bits; /* bit counter */
25108 var length; /* length value */
25109 var code; /* code value */
25110 var dist; /* distance index */
25111 var bl_count = new Array(MAX_BITS+1);
25112 /* number of codes at each bit length for an optimal tree */
25114 // do check in _tr_init()
25115 //if (static_init_done) return;
25117 /* For some embedded targets, global variables are not initialized: */
25118 /*#ifdef NO_INIT_GLOBAL_POINTERS
25119 static_l_desc.static_tree = static_ltree;
25120 static_l_desc.extra_bits = extra_lbits;
25121 static_d_desc.static_tree = static_dtree;
25122 static_d_desc.extra_bits = extra_dbits;
25123 static_bl_desc.extra_bits = extra_blbits;
25126 /* Initialize the mapping length (0..255) -> length code (0..28) */
25128 for (code = 0; code < LENGTH_CODES-1; code++) {
25129 base_length[code] = length;
25130 for (n = 0; n < (1<<extra_lbits[code]); n++) {
25131 _length_code[length++] = code;
25134 //Assert (length == 256, "tr_static_init: length != 256");
25135 /* Note that the length 255 (match length 258) can be represented
25136 * in two different ways: code 284 + 5 bits or code 285, so we
25137 * overwrite length_code[255] to use the best encoding:
25139 _length_code[length-1] = code;
25141 /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
25143 for (code = 0 ; code < 16; code++) {
25144 base_dist[code] = dist;
25145 for (n = 0; n < (1<<extra_dbits[code]); n++) {
25146 _dist_code[dist++] = code;
25149 //Assert (dist == 256, "tr_static_init: dist != 256");
25150 dist >>= 7; /* from now on, all distances are divided by 128 */
25151 for (; code < D_CODES; code++) {
25152 base_dist[code] = dist << 7;
25153 for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
25154 _dist_code[256 + dist++] = code;
25157 //Assert (dist == 256, "tr_static_init: 256+dist != 512");
25159 /* Construct the codes of the static literal tree */
25160 for (bits = 0; bits <= MAX_BITS; bits++) {
25161 bl_count[bits] = 0;
25166 static_ltree[n*2 + 1]/*.Len*/ = 8;
25171 static_ltree[n*2 + 1]/*.Len*/ = 9;
25176 static_ltree[n*2 + 1]/*.Len*/ = 7;
25181 static_ltree[n*2 + 1]/*.Len*/ = 8;
25185 /* Codes 286 and 287 do not exist, but we must include them in the
25186 * tree construction to get a canonical Huffman tree (longest code
25189 gen_codes(static_ltree, L_CODES+1, bl_count);
25191 /* The static distance tree is trivial: */
25192 for (n = 0; n < D_CODES; n++) {
25193 static_dtree[n*2 + 1]/*.Len*/ = 5;
25194 static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5);
25197 // Now data ready and we can init static trees
25198 static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS);
25199 static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
25200 static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
25202 //static_init_done = true;
25206 /* ===========================================================================
25207 * Initialize a new block.
25209 function init_block(s) {
25210 var n; /* iterates over tree elements */
25212 /* Initialize the trees. */
25213 for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; }
25214 for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; }
25215 for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; }
25217 s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1;
25218 s.opt_len = s.static_len = 0;
25219 s.last_lit = s.matches = 0;
25223 /* ===========================================================================
25224 * Flush the bit buffer and align the output on a byte boundary
25226 function bi_windup(s)
25228 if (s.bi_valid > 8) {
25229 put_short(s, s.bi_buf);
25230 } else if (s.bi_valid > 0) {
25231 //put_byte(s, (Byte)s->bi_buf);
25232 s.pending_buf[s.pending++] = s.bi_buf;
25238 /* ===========================================================================
25239 * Copy a stored block, storing first the length and its
25240 * one's complement if requested.
25242 function copy_block(s, buf, len, header)
25244 //charf *buf; /* the input data */
25245 //unsigned len; /* its length */
25246 //int header; /* true if block header must be written */
25248 bi_windup(s); /* align on byte boundary */
25252 put_short(s, ~len);
25255 // put_byte(s, *buf++);
25257 utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
25261 /* ===========================================================================
25262 * Compares to subtrees, using the tree depth as tie breaker when
25263 * the subtrees have equal frequency. This minimizes the worst case length.
25265 function smaller(tree, n, m, depth) {
25268 return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
25269 (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
25272 /* ===========================================================================
25273 * Restore the heap property by moving down the tree starting at node k,
25274 * exchanging a node with the smallest of its two sons if necessary, stopping
25275 * when the heap property is re-established (each father smaller than its
25278 function pqdownheap(s, tree, k)
25279 // deflate_state *s;
25280 // ct_data *tree; /* the tree to restore */
25281 // int k; /* node to move down */
25284 var j = k << 1; /* left son of k */
25285 while (j <= s.heap_len) {
25286 /* Set j to the smallest of the two sons: */
25287 if (j < s.heap_len &&
25288 smaller(tree, s.heap[j+1], s.heap[j], s.depth)) {
25291 /* Exit if v is smaller than both sons */
25292 if (smaller(tree, v, s.heap[j], s.depth)) { break; }
25294 /* Exchange v with the smallest son */
25295 s.heap[k] = s.heap[j];
25298 /* And continue down the tree, setting j to the left son of k */
25305 // inlined manually
25306 // var SMALLEST = 1;
25308 /* ===========================================================================
25309 * Send the block data compressed using the given Huffman trees
25311 function compress_block(s, ltree, dtree)
25312 // deflate_state *s;
25313 // const ct_data *ltree; /* literal tree */
25314 // const ct_data *dtree; /* distance tree */
25316 var dist; /* distance of matched string */
25317 var lc; /* match length or unmatched char (if dist == 0) */
25318 var lx = 0; /* running index in l_buf */
25319 var code; /* the code to send */
25320 var extra; /* number of extra bits to send */
25322 if (s.last_lit !== 0) {
25324 dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]);
25325 lc = s.pending_buf[s.l_buf + lx];
25329 send_code(s, lc, ltree); /* send a literal byte */
25330 //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
25332 /* Here, lc is the match length - MIN_MATCH */
25333 code = _length_code[lc];
25334 send_code(s, code+LITERALS+1, ltree); /* send the length code */
25335 extra = extra_lbits[code];
25337 lc -= base_length[code];
25338 send_bits(s, lc, extra); /* send the extra length bits */
25340 dist--; /* dist is now the match distance - 1 */
25341 code = d_code(dist);
25342 //Assert (code < D_CODES, "bad d_code");
25344 send_code(s, code, dtree); /* send the distance code */
25345 extra = extra_dbits[code];
25347 dist -= base_dist[code];
25348 send_bits(s, dist, extra); /* send the extra distance bits */
25350 } /* literal or match pair ? */
25352 /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
25353 //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
25354 // "pendingBuf overflow");
25356 } while (lx < s.last_lit);
25359 send_code(s, END_BLOCK, ltree);
25363 /* ===========================================================================
25364 * Construct one Huffman tree and assigns the code bit strings and lengths.
25365 * Update the total bit length for the current block.
25366 * IN assertion: the field freq is set for all tree elements.
25367 * OUT assertions: the fields len and code are set to the optimal bit length
25368 * and corresponding code. The length opt_len is updated; static_len is
25369 * also updated if stree is not null. The field max_code is set.
25371 function build_tree(s, desc)
25372 // deflate_state *s;
25373 // tree_desc *desc; /* the tree descriptor */
25375 var tree = desc.dyn_tree;
25376 var stree = desc.stat_desc.static_tree;
25377 var has_stree = desc.stat_desc.has_stree;
25378 var elems = desc.stat_desc.elems;
25379 var n, m; /* iterate over heap elements */
25380 var max_code = -1; /* largest code with non zero frequency */
25381 var node; /* new node being created */
25383 /* Construct the initial heap, with least frequent element in
25384 * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
25385 * heap[0] is not used.
25388 s.heap_max = HEAP_SIZE;
25390 for (n = 0; n < elems; n++) {
25391 if (tree[n * 2]/*.Freq*/ !== 0) {
25392 s.heap[++s.heap_len] = max_code = n;
25396 tree[n*2 + 1]/*.Len*/ = 0;
25400 /* The pkzip format requires that at least one distance code exists,
25401 * and that at least one bit should be sent even if there is only one
25402 * possible code. So to avoid special checks later on we force at least
25403 * two codes of non zero frequency.
25405 while (s.heap_len < 2) {
25406 node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
25407 tree[node * 2]/*.Freq*/ = 1;
25412 s.static_len -= stree[node*2 + 1]/*.Len*/;
25414 /* node is 0 or 1 so it does not have extra bits */
25416 desc.max_code = max_code;
25418 /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
25419 * establish sub-heaps of increasing lengths:
25421 for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
25423 /* Construct the Huffman tree by repeatedly combining the least two
25426 node = elems; /* next internal node of the tree */
25428 //pqremove(s, tree, n); /* n = node of least frequency */
25430 n = s.heap[1/*SMALLEST*/];
25431 s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
25432 pqdownheap(s, tree, 1/*SMALLEST*/);
25435 m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
25437 s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
25438 s.heap[--s.heap_max] = m;
25440 /* Create a new node father of n and m */
25441 tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
25442 s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
25443 tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node;
25445 /* and insert the new node in the heap */
25446 s.heap[1/*SMALLEST*/] = node++;
25447 pqdownheap(s, tree, 1/*SMALLEST*/);
25449 } while (s.heap_len >= 2);
25451 s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
25453 /* At this point, the fields freq and dad are set. We can now
25454 * generate the bit lengths.
25456 gen_bitlen(s, desc);
25458 /* The field len is now set, we can generate the bit codes */
25459 gen_codes(tree, max_code, s.bl_count);
25463 /* ===========================================================================
25464 * Scan a literal or distance tree to determine the frequencies of the codes
25465 * in the bit length tree.
25467 function scan_tree(s, tree, max_code)
25468 // deflate_state *s;
25469 // ct_data *tree; /* the tree to be scanned */
25470 // int max_code; /* and its largest code of non zero frequency */
25472 var n; /* iterates over all tree elements */
25473 var prevlen = -1; /* last emitted length */
25474 var curlen; /* length of current code */
25476 var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
25478 var count = 0; /* repeat count of the current code */
25479 var max_count = 7; /* max repeat count */
25480 var min_count = 4; /* min repeat count */
25482 if (nextlen === 0) {
25486 tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */
25488 for (n = 0; n <= max_code; n++) {
25490 nextlen = tree[(n+1)*2 + 1]/*.Len*/;
25492 if (++count < max_count && curlen === nextlen) {
25495 } else if (count < min_count) {
25496 s.bl_tree[curlen * 2]/*.Freq*/ += count;
25498 } else if (curlen !== 0) {
25500 if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
25501 s.bl_tree[REP_3_6*2]/*.Freq*/++;
25503 } else if (count <= 10) {
25504 s.bl_tree[REPZ_3_10*2]/*.Freq*/++;
25507 s.bl_tree[REPZ_11_138*2]/*.Freq*/++;
25513 if (nextlen === 0) {
25517 } else if (curlen === nextlen) {
25529 /* ===========================================================================
25530 * Send a literal or distance tree in compressed form, using the codes in
25533 function send_tree(s, tree, max_code)
25534 // deflate_state *s;
25535 // ct_data *tree; /* the tree to be scanned */
25536 // int max_code; /* and its largest code of non zero frequency */
25538 var n; /* iterates over all tree elements */
25539 var prevlen = -1; /* last emitted length */
25540 var curlen; /* length of current code */
25542 var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
25544 var count = 0; /* repeat count of the current code */
25545 var max_count = 7; /* max repeat count */
25546 var min_count = 4; /* min repeat count */
25548 /* tree[max_code+1].Len = -1; */ /* guard already set */
25549 if (nextlen === 0) {
25554 for (n = 0; n <= max_code; n++) {
25556 nextlen = tree[(n+1)*2 + 1]/*.Len*/;
25558 if (++count < max_count && curlen === nextlen) {
25561 } else if (count < min_count) {
25562 do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
25564 } else if (curlen !== 0) {
25565 if (curlen !== prevlen) {
25566 send_code(s, curlen, s.bl_tree);
25569 //Assert(count >= 3 && count <= 6, " 3_6?");
25570 send_code(s, REP_3_6, s.bl_tree);
25571 send_bits(s, count-3, 2);
25573 } else if (count <= 10) {
25574 send_code(s, REPZ_3_10, s.bl_tree);
25575 send_bits(s, count-3, 3);
25578 send_code(s, REPZ_11_138, s.bl_tree);
25579 send_bits(s, count-11, 7);
25584 if (nextlen === 0) {
25588 } else if (curlen === nextlen) {
25600 /* ===========================================================================
25601 * Construct the Huffman tree for the bit lengths and return the index in
25602 * bl_order of the last bit length code to send.
25604 function build_bl_tree(s) {
25605 var max_blindex; /* index of last bit length code of non zero freq */
25607 /* Determine the bit length frequencies for literal and distance trees */
25608 scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
25609 scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
25611 /* Build the bit length tree: */
25612 build_tree(s, s.bl_desc);
25613 /* opt_len now includes the length of the tree representations, except
25614 * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
25617 /* Determine the number of bit length codes to send. The pkzip format
25618 * requires that at least 4 bit length codes be sent. (appnote.txt says
25619 * 3 but the actual value used is 4.)
25621 for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
25622 if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) {
25626 /* Update opt_len to include the bit length tree and counts */
25627 s.opt_len += 3*(max_blindex+1) + 5+5+4;
25628 //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
25629 // s->opt_len, s->static_len));
25631 return max_blindex;
25635 /* ===========================================================================
25636 * Send the header for a block using dynamic Huffman trees: the counts, the
25637 * lengths of the bit length codes, the literal tree and the distance tree.
25638 * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
25640 function send_all_trees(s, lcodes, dcodes, blcodes)
25641 // deflate_state *s;
25642 // int lcodes, dcodes, blcodes; /* number of codes for each tree */
25644 var rank; /* index in bl_order */
25646 //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
25647 //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
25648 // "too many codes");
25649 //Tracev((stderr, "\nbl counts: "));
25650 send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
25651 send_bits(s, dcodes-1, 5);
25652 send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
25653 for (rank = 0; rank < blcodes; rank++) {
25654 //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
25655 send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3);
25657 //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
25659 send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */
25660 //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
25662 send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */
25663 //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
25667 /* ===========================================================================
25668 * Check if the data type is TEXT or BINARY, using the following algorithm:
25669 * - TEXT if the two conditions below are satisfied:
25670 * a) There are no non-portable control characters belonging to the
25671 * "black list" (0..6, 14..25, 28..31).
25672 * b) There is at least one printable character belonging to the
25673 * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
25674 * - BINARY otherwise.
25675 * - The following partially-portable control characters form a
25676 * "gray list" that is ignored in this detection algorithm:
25677 * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
25678 * IN assertion: the fields Freq of dyn_ltree are set.
25680 function detect_data_type(s) {
25681 /* black_mask is the bit mask of black-listed bytes
25682 * set bits 0..6, 14..25, and 28..31
25683 * 0xf3ffc07f = binary 11110011111111111100000001111111
25685 var black_mask = 0xf3ffc07f;
25688 /* Check for non-textual ("black-listed") bytes. */
25689 for (n = 0; n <= 31; n++, black_mask >>>= 1) {
25690 if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) {
25695 /* Check for textual ("white-listed") bytes. */
25696 if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
25697 s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
25700 for (n = 32; n < LITERALS; n++) {
25701 if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
25706 /* There are no "black-listed" or "white-listed" bytes:
25707 * this stream either is empty or has tolerated ("gray-listed") bytes only.
25713 var static_init_done = false;
25715 /* ===========================================================================
25716 * Initialize the tree data structures for a new zlib stream.
25718 function _tr_init(s)
25721 if (!static_init_done) {
25723 static_init_done = true;
25726 s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
25727 s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
25728 s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
25733 /* Initialize the first block of the first file: */
25738 /* ===========================================================================
25739 * Send a stored block
25741 function _tr_stored_block(s, buf, stored_len, last)
25743 //charf *buf; /* input block */
25744 //ulg stored_len; /* length of input block */
25745 //int last; /* one if this is the last block for a file */
25747 send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */
25748 copy_block(s, buf, stored_len, true); /* with header */
25752 /* ===========================================================================
25753 * Send one empty static block to give enough lookahead for inflate.
25754 * This takes 10 bits, of which 7 may remain in the bit buffer.
25756 function _tr_align(s) {
25757 send_bits(s, STATIC_TREES<<1, 3);
25758 send_code(s, END_BLOCK, static_ltree);
25763 /* ===========================================================================
25764 * Determine the best encoding for the current block: dynamic trees, static
25765 * trees or store, and output the encoded block to the zip file.
25767 function _tr_flush_block(s, buf, stored_len, last)
25769 //charf *buf; /* input block, or NULL if too old */
25770 //ulg stored_len; /* length of input block */
25771 //int last; /* one if this is the last block for a file */
25773 var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
25774 var max_blindex = 0; /* index of last bit length code of non zero freq */
25776 /* Build the Huffman trees unless a stored block is forced */
25779 /* Check if the file is binary or text */
25780 if (s.strm.data_type === Z_UNKNOWN) {
25781 s.strm.data_type = detect_data_type(s);
25784 /* Construct the literal and distance trees */
25785 build_tree(s, s.l_desc);
25786 // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
25787 // s->static_len));
25789 build_tree(s, s.d_desc);
25790 // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
25791 // s->static_len));
25792 /* At this point, opt_len and static_len are the total bit lengths of
25793 * the compressed block data, excluding the tree representations.
25796 /* Build the bit length tree for the above two trees, and get the index
25797 * in bl_order of the last bit length code to send.
25799 max_blindex = build_bl_tree(s);
25801 /* Determine the best encoding. Compute the block lengths in bytes. */
25802 opt_lenb = (s.opt_len+3+7) >>> 3;
25803 static_lenb = (s.static_len+3+7) >>> 3;
25805 // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
25806 // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
25809 if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
25812 // Assert(buf != (char*)0, "lost buf");
25813 opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
25816 if ((stored_len+4 <= opt_lenb) && (buf !== -1)) {
25817 /* 4: two words for the lengths */
25819 /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
25820 * Otherwise we can't have processed more than WSIZE input bytes since
25821 * the last block flush, because compression would have been
25822 * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
25823 * transform a block into a stored block.
25825 _tr_stored_block(s, buf, stored_len, last);
25827 } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
25829 send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3);
25830 compress_block(s, static_ltree, static_dtree);
25833 send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3);
25834 send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1);
25835 compress_block(s, s.dyn_ltree, s.dyn_dtree);
25837 // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
25838 /* The above check is made mod 2^32, for files larger than 512 MB
25839 * and uLong implemented on 32 bits.
25846 // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
25847 // s->compressed_len-7*last));
25850 /* ===========================================================================
25851 * Save the match info and tally the frequency counts. Return true if
25852 * the current block must be flushed.
25854 function _tr_tally(s, dist, lc)
25855 // deflate_state *s;
25856 // unsigned dist; /* distance of matched string */
25857 // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
25859 //var out_length, in_length, dcode;
25861 s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
25862 s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
25864 s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
25868 /* lc is the unmatched char */
25869 s.dyn_ltree[lc*2]/*.Freq*/++;
25872 /* Here, lc is the match length - MIN_MATCH */
25873 dist--; /* dist = match distance - 1 */
25874 //Assert((ush)dist < (ush)MAX_DIST(s) &&
25875 // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
25876 // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
25878 s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++;
25879 s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
25882 // (!) This block is disabled in zlib defailts,
25883 // don't enable it for binary compatibility
25885 //#ifdef TRUNCATE_BLOCK
25886 // /* Try to guess if it is profitable to stop the current block here */
25887 // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
25888 // /* Compute an upper bound for the compressed length */
25889 // out_length = s.last_lit*8;
25890 // in_length = s.strstart - s.block_start;
25892 // for (dcode = 0; dcode < D_CODES; dcode++) {
25893 // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
25895 // out_length >>>= 3;
25896 // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
25897 // // s->last_lit, in_length, out_length,
25898 // // 100L - out_length*100L/in_length));
25899 // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
25905 return (s.last_lit === s.lit_bufsize-1);
25906 /* We avoid equality with lit_bufsize because of wraparound at 64K
25907 * on 16 bit machines and because stored blocks are restricted to
25912 exports._tr_init = _tr_init;
25913 exports._tr_stored_block = _tr_stored_block;
25914 exports._tr_flush_block = _tr_flush_block;
25915 exports._tr_tally = _tr_tally;
25916 exports._tr_align = _tr_align;
25921 /***/ function(module, exports) {
25925 // Note: adler32 takes 12% for level 0 and 2% for level 6.
25926 // It doesn't worth to make additional optimizationa as in original.
25927 // Small size is preferable.
25929 function adler32(adler, buf, len, pos) {
25930 var s1 = (adler & 0xffff) |0,
25931 s2 = ((adler >>> 16) & 0xffff) |0,
25934 while (len !== 0) {
25935 // Set limit ~ twice less than 5552, to keep
25936 // s2 in 31-bits, because we force signed ints.
25937 // in other case %= will fail.
25938 n = len > 2000 ? 2000 : len;
25942 s1 = (s1 + buf[pos++]) |0;
25950 return (s1 | (s2 << 16)) |0;
25954 module.exports = adler32;
25959 /***/ function(module, exports) {
25963 // Note: we can't get significant speed boost here.
25964 // So write code to minimize size - no pregenerated tables
25965 // and array tools dependencies.
25968 // Use ordinary array, since untyped makes no boost here
25969 function makeTable() {
25972 for (var n =0; n < 256; n++) {
25974 for (var k =0; k < 8; k++) {
25975 c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
25983 // Create table on load. Just 255 signed longs. Not a problem.
25984 var crcTable = makeTable();
25987 function crc32(crc, buf, len, pos) {
25993 for (var i = pos; i < end; i++) {
25994 crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
25997 return (crc ^ (-1)); // >>> 0;
26001 module.exports = crc32;
26006 /***/ function(module, exports, __webpack_require__) {
26011 var utils = __webpack_require__(52);
26012 var adler32 = __webpack_require__(54);
26013 var crc32 = __webpack_require__(55);
26014 var inflate_fast = __webpack_require__(57);
26015 var inflate_table = __webpack_require__(58);
26021 /* Public constants ==========================================================*/
26022 /* ===========================================================================*/
26025 /* Allowed flush values; see deflate() and inflate() below for details */
26026 //var Z_NO_FLUSH = 0;
26027 //var Z_PARTIAL_FLUSH = 1;
26028 //var Z_SYNC_FLUSH = 2;
26029 //var Z_FULL_FLUSH = 3;
26035 /* Return codes for the compression/decompression functions. Negative values
26036 * are errors, positive values are used for special but normal events.
26039 var Z_STREAM_END = 1;
26040 var Z_NEED_DICT = 2;
26041 //var Z_ERRNO = -1;
26042 var Z_STREAM_ERROR = -2;
26043 var Z_DATA_ERROR = -3;
26044 var Z_MEM_ERROR = -4;
26045 var Z_BUF_ERROR = -5;
26046 //var Z_VERSION_ERROR = -6;
26048 /* The deflate compression method */
26049 var Z_DEFLATED = 8;
26052 /* STATES ====================================================================*/
26053 /* ===========================================================================*/
26056 var HEAD = 1; /* i: waiting for magic header */
26057 var FLAGS = 2; /* i: waiting for method and flags (gzip) */
26058 var TIME = 3; /* i: waiting for modification time (gzip) */
26059 var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
26060 var EXLEN = 5; /* i: waiting for extra length (gzip) */
26061 var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
26062 var NAME = 7; /* i: waiting for end of file name (gzip) */
26063 var COMMENT = 8; /* i: waiting for end of comment (gzip) */
26064 var HCRC = 9; /* i: waiting for header crc (gzip) */
26065 var DICTID = 10; /* i: waiting for dictionary check value */
26066 var DICT = 11; /* waiting for inflateSetDictionary() call */
26067 var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
26068 var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
26069 var STORED = 14; /* i: waiting for stored size (length and complement) */
26070 var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
26071 var COPY = 16; /* i/o: waiting for input or output to copy stored block */
26072 var TABLE = 17; /* i: waiting for dynamic block table lengths */
26073 var LENLENS = 18; /* i: waiting for code length code lengths */
26074 var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
26075 var LEN_ = 20; /* i: same as LEN below, but only first time in */
26076 var LEN = 21; /* i: waiting for length/lit/eob code */
26077 var LENEXT = 22; /* i: waiting for length extra bits */
26078 var DIST = 23; /* i: waiting for distance code */
26079 var DISTEXT = 24; /* i: waiting for distance extra bits */
26080 var MATCH = 25; /* o: waiting for output space to copy string */
26081 var LIT = 26; /* o: waiting for output space to write literal */
26082 var CHECK = 27; /* i: waiting for 32-bit check value */
26083 var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
26084 var DONE = 29; /* finished check, done -- remain here until reset */
26085 var BAD = 30; /* got a data error -- remain here until reset */
26086 var MEM = 31; /* got an inflate() memory error -- remain here until reset */
26087 var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
26089 /* ===========================================================================*/
26093 var ENOUGH_LENS = 852;
26094 var ENOUGH_DISTS = 592;
26095 //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
26097 var MAX_WBITS = 15;
26098 /* 32K LZ77 window */
26099 var DEF_WBITS = MAX_WBITS;
26102 function ZSWAP32(q) {
26103 return (((q >>> 24) & 0xff) +
26104 ((q >>> 8) & 0xff00) +
26105 ((q & 0xff00) << 8) +
26106 ((q & 0xff) << 24));
26110 function InflateState() {
26111 this.mode = 0; /* current inflate mode */
26112 this.last = false; /* true if processing last block */
26113 this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
26114 this.havedict = false; /* true if dictionary provided */
26115 this.flags = 0; /* gzip header method and flags (0 if zlib) */
26116 this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
26117 this.check = 0; /* protected copy of check value */
26118 this.total = 0; /* protected copy of output count */
26120 this.head = null; /* where to save gzip header information */
26122 /* sliding window */
26123 this.wbits = 0; /* log base 2 of requested window size */
26124 this.wsize = 0; /* window size or zero if not using window */
26125 this.whave = 0; /* valid bytes in the window */
26126 this.wnext = 0; /* window write index */
26127 this.window = null; /* allocated sliding window, if needed */
26129 /* bit accumulator */
26130 this.hold = 0; /* input bit accumulator */
26131 this.bits = 0; /* number of bits in "in" */
26133 /* for string and stored block copying */
26134 this.length = 0; /* literal or length of data to copy */
26135 this.offset = 0; /* distance back to copy string from */
26137 /* for table and code decoding */
26138 this.extra = 0; /* extra bits needed */
26140 /* fixed and dynamic code tables */
26141 this.lencode = null; /* starting table for length/literal codes */
26142 this.distcode = null; /* starting table for distance codes */
26143 this.lenbits = 0; /* index bits for lencode */
26144 this.distbits = 0; /* index bits for distcode */
26146 /* dynamic table building */
26147 this.ncode = 0; /* number of code length code lengths */
26148 this.nlen = 0; /* number of length code lengths */
26149 this.ndist = 0; /* number of distance code lengths */
26150 this.have = 0; /* number of code lengths in lens[] */
26151 this.next = null; /* next available space in codes[] */
26153 this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
26154 this.work = new utils.Buf16(288); /* work area for code table building */
26157 because we don't have pointers in js, we use lencode and distcode directly
26158 as buffers so we don't need codes
26160 //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
26161 this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
26162 this.distdyn = null; /* dynamic table for distance codes (JS specific) */
26163 this.sane = 0; /* if false, allow invalid distance too far */
26164 this.back = 0; /* bits back of last unprocessed length/lit */
26165 this.was = 0; /* initial length of match */
26168 function inflateResetKeep(strm) {
26171 if (!strm || !strm.state) { return Z_STREAM_ERROR; }
26172 state = strm.state;
26173 strm.total_in = strm.total_out = state.total = 0;
26174 strm.msg = ''; /*Z_NULL*/
26175 if (state.wrap) { /* to support ill-conceived Java test suite */
26176 strm.adler = state.wrap & 1;
26180 state.havedict = 0;
26181 state.dmax = 32768;
26182 state.head = null/*Z_NULL*/;
26185 //state.lencode = state.distcode = state.next = state.codes;
26186 state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
26187 state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
26191 //Tracev((stderr, "inflate: reset\n"));
26195 function inflateReset(strm) {
26198 if (!strm || !strm.state) { return Z_STREAM_ERROR; }
26199 state = strm.state;
26203 return inflateResetKeep(strm);
26207 function inflateReset2(strm, windowBits) {
26211 /* get the state */
26212 if (!strm || !strm.state) { return Z_STREAM_ERROR; }
26213 state = strm.state;
26215 /* extract wrap request from windowBits parameter */
26216 if (windowBits < 0) {
26218 windowBits = -windowBits;
26221 wrap = (windowBits >> 4) + 1;
26222 if (windowBits < 48) {
26227 /* set number of window bits, free window if different */
26228 if (windowBits && (windowBits < 8 || windowBits > 15)) {
26229 return Z_STREAM_ERROR;
26231 if (state.window !== null && state.wbits !== windowBits) {
26232 state.window = null;
26235 /* update state and reset the rest of it */
26237 state.wbits = windowBits;
26238 return inflateReset(strm);
26241 function inflateInit2(strm, windowBits) {
26245 if (!strm) { return Z_STREAM_ERROR; }
26246 //strm.msg = Z_NULL; /* in case we return an error */
26248 state = new InflateState();
26250 //if (state === Z_NULL) return Z_MEM_ERROR;
26251 //Tracev((stderr, "inflate: allocated\n"));
26252 strm.state = state;
26253 state.window = null/*Z_NULL*/;
26254 ret = inflateReset2(strm, windowBits);
26255 if (ret !== Z_OK) {
26256 strm.state = null/*Z_NULL*/;
26261 function inflateInit(strm) {
26262 return inflateInit2(strm, DEF_WBITS);
26267 Return state with length and distance decoding tables and index sizes set to
26268 fixed code decoding. Normally this returns fixed tables from inffixed.h.
26269 If BUILDFIXED is defined, then instead this routine builds the tables the
26270 first time it's called, and returns those tables the first time and
26271 thereafter. This reduces the size of the code by about 2K bytes, in
26272 exchange for a little execution time. However, BUILDFIXED should not be
26273 used for threaded applications, since the rewriting of the tables and virgin
26274 may not be thread-safe.
26278 var lenfix, distfix; // We have no pointers in JS, so keep tables separate
26280 function fixedtables(state) {
26281 /* build fixed huffman tables if first call (may not be thread safe) */
26285 lenfix = new utils.Buf32(512);
26286 distfix = new utils.Buf32(32);
26288 /* literal/length table */
26290 while (sym < 144) { state.lens[sym++] = 8; }
26291 while (sym < 256) { state.lens[sym++] = 9; }
26292 while (sym < 280) { state.lens[sym++] = 7; }
26293 while (sym < 288) { state.lens[sym++] = 8; }
26295 inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9});
26297 /* distance table */
26299 while (sym < 32) { state.lens[sym++] = 5; }
26301 inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5});
26303 /* do this just once */
26307 state.lencode = lenfix;
26309 state.distcode = distfix;
26310 state.distbits = 5;
26315 Update the window with the last wsize (normally 32K) bytes written before
26316 returning. If window does not exist yet, create it. This is only called
26317 when a window is already in use, or when output has been written during this
26318 inflate call, but the end of the deflate stream has not been reached yet.
26319 It is also called to create a window for dictionary data when a dictionary
26322 Providing output buffers larger than 32K to inflate() should provide a speed
26323 advantage, since only the last 32K of output is copied to the sliding window
26324 upon return from inflate(), and since all distances after the first 32K of
26325 output will fall in the output data, making match copies simpler and faster.
26326 The advantage may be dependent on the size of the processor's data caches.
26328 function updatewindow(strm, src, end, copy) {
26330 var state = strm.state;
26332 /* if it hasn't been done already, allocate space for the window */
26333 if (state.window === null) {
26334 state.wsize = 1 << state.wbits;
26338 state.window = new utils.Buf8(state.wsize);
26341 /* copy state->wsize or less output bytes into the circular window */
26342 if (copy >= state.wsize) {
26343 utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);
26345 state.whave = state.wsize;
26348 dist = state.wsize - state.wnext;
26352 //zmemcpy(state->window + state->wnext, end - copy, dist);
26353 utils.arraySet(state.window,src, end - copy, dist, state.wnext);
26356 //zmemcpy(state->window, end - copy, copy);
26357 utils.arraySet(state.window,src, end - copy, copy, 0);
26358 state.wnext = copy;
26359 state.whave = state.wsize;
26362 state.wnext += dist;
26363 if (state.wnext === state.wsize) { state.wnext = 0; }
26364 if (state.whave < state.wsize) { state.whave += dist; }
26370 function inflate(strm, flush) {
26372 var input, output; // input/output buffers
26373 var next; /* next input INDEX */
26374 var put; /* next output INDEX */
26375 var have, left; /* available input and output */
26376 var hold; /* bit buffer */
26377 var bits; /* bits in bit buffer */
26378 var _in, _out; /* save starting available input and output */
26379 var copy; /* number of stored or match bytes to copy */
26380 var from; /* where to copy match bytes from */
26382 var here = 0; /* current decoding table entry */
26383 var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
26384 //var last; /* parent table entry */
26385 var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
26386 var len; /* length to copy for repeats, bits to drop */
26387 var ret; /* return code */
26388 var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
26391 var n; // temporary var for NEED_BITS
26393 var order = /* permutation of code lengths */
26394 [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
26397 if (!strm || !strm.state || !strm.output ||
26398 (!strm.input && strm.avail_in !== 0)) {
26399 return Z_STREAM_ERROR;
26402 state = strm.state;
26403 if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
26407 put = strm.next_out;
26408 output = strm.output;
26409 left = strm.avail_out;
26410 next = strm.next_in;
26411 input = strm.input;
26412 have = strm.avail_in;
26421 inf_leave: // goto emulation
26423 switch (state.mode) {
26425 if (state.wrap === 0) {
26426 state.mode = TYPEDO;
26429 //=== NEEDBITS(16);
26430 while (bits < 16) {
26431 if (have === 0) { break inf_leave; }
26433 hold += input[next++] << bits;
26437 if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
26438 state.check = 0/*crc32(0L, Z_NULL, 0)*/;
26439 //=== CRC2(state.check, hold);
26440 hbuf[0] = hold & 0xff;
26441 hbuf[1] = (hold >>> 8) & 0xff;
26442 state.check = crc32(state.check, hbuf, 2, 0);
26449 state.mode = FLAGS;
26452 state.flags = 0; /* expect zlib header */
26454 state.head.done = false;
26456 if (!(state.wrap & 1) || /* check if zlib header allowed */
26457 (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
26458 strm.msg = 'incorrect header check';
26462 if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
26463 strm.msg = 'unknown compression method';
26467 //--- DROPBITS(4) ---//
26471 len = (hold & 0x0f)/*BITS(4)*/ + 8;
26472 if (state.wbits === 0) {
26475 else if (len > state.wbits) {
26476 strm.msg = 'invalid window size';
26480 state.dmax = 1 << len;
26481 //Tracev((stderr, "inflate: zlib header ok\n"));
26482 strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
26483 state.mode = hold & 0x200 ? DICTID : TYPE;
26490 //=== NEEDBITS(16); */
26491 while (bits < 16) {
26492 if (have === 0) { break inf_leave; }
26494 hold += input[next++] << bits;
26498 state.flags = hold;
26499 if ((state.flags & 0xff) !== Z_DEFLATED) {
26500 strm.msg = 'unknown compression method';
26504 if (state.flags & 0xe000) {
26505 strm.msg = 'unknown header flags set';
26510 state.head.text = ((hold >> 8) & 1);
26512 if (state.flags & 0x0200) {
26513 //=== CRC2(state.check, hold);
26514 hbuf[0] = hold & 0xff;
26515 hbuf[1] = (hold >>> 8) & 0xff;
26516 state.check = crc32(state.check, hbuf, 2, 0);
26524 /* falls through */
26526 //=== NEEDBITS(32); */
26527 while (bits < 32) {
26528 if (have === 0) { break inf_leave; }
26530 hold += input[next++] << bits;
26535 state.head.time = hold;
26537 if (state.flags & 0x0200) {
26538 //=== CRC4(state.check, hold)
26539 hbuf[0] = hold & 0xff;
26540 hbuf[1] = (hold >>> 8) & 0xff;
26541 hbuf[2] = (hold >>> 16) & 0xff;
26542 hbuf[3] = (hold >>> 24) & 0xff;
26543 state.check = crc32(state.check, hbuf, 4, 0);
26551 /* falls through */
26553 //=== NEEDBITS(16); */
26554 while (bits < 16) {
26555 if (have === 0) { break inf_leave; }
26557 hold += input[next++] << bits;
26562 state.head.xflags = (hold & 0xff);
26563 state.head.os = (hold >> 8);
26565 if (state.flags & 0x0200) {
26566 //=== CRC2(state.check, hold);
26567 hbuf[0] = hold & 0xff;
26568 hbuf[1] = (hold >>> 8) & 0xff;
26569 state.check = crc32(state.check, hbuf, 2, 0);
26576 state.mode = EXLEN;
26577 /* falls through */
26579 if (state.flags & 0x0400) {
26580 //=== NEEDBITS(16); */
26581 while (bits < 16) {
26582 if (have === 0) { break inf_leave; }
26584 hold += input[next++] << bits;
26588 state.length = hold;
26590 state.head.extra_len = hold;
26592 if (state.flags & 0x0200) {
26593 //=== CRC2(state.check, hold);
26594 hbuf[0] = hold & 0xff;
26595 hbuf[1] = (hold >>> 8) & 0xff;
26596 state.check = crc32(state.check, hbuf, 2, 0);
26604 else if (state.head) {
26605 state.head.extra = null/*Z_NULL*/;
26607 state.mode = EXTRA;
26608 /* falls through */
26610 if (state.flags & 0x0400) {
26611 copy = state.length;
26612 if (copy > have) { copy = have; }
26615 len = state.head.extra_len - state.length;
26616 if (!state.head.extra) {
26617 // Use untyped array for more conveniend processing later
26618 state.head.extra = new Array(state.head.extra_len);
26624 // extra field is limited to 65536 bytes
26625 // - no need for additional size check
26627 /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
26630 //zmemcpy(state.head.extra + len, next,
26631 // len + copy > state.head.extra_max ?
26632 // state.head.extra_max - len : copy);
26634 if (state.flags & 0x0200) {
26635 state.check = crc32(state.check, input, copy, next);
26639 state.length -= copy;
26641 if (state.length) { break inf_leave; }
26645 /* falls through */
26647 if (state.flags & 0x0800) {
26648 if (have === 0) { break inf_leave; }
26651 // TODO: 2 or 1 bytes?
26652 len = input[next + copy++];
26653 /* use constant limit because in js we should not preallocate memory */
26654 if (state.head && len &&
26655 (state.length < 65536 /*state.head.name_max*/)) {
26656 state.head.name += String.fromCharCode(len);
26658 } while (len && copy < have);
26660 if (state.flags & 0x0200) {
26661 state.check = crc32(state.check, input, copy, next);
26665 if (len) { break inf_leave; }
26667 else if (state.head) {
26668 state.head.name = null;
26671 state.mode = COMMENT;
26672 /* falls through */
26674 if (state.flags & 0x1000) {
26675 if (have === 0) { break inf_leave; }
26678 len = input[next + copy++];
26679 /* use constant limit because in js we should not preallocate memory */
26680 if (state.head && len &&
26681 (state.length < 65536 /*state.head.comm_max*/)) {
26682 state.head.comment += String.fromCharCode(len);
26684 } while (len && copy < have);
26685 if (state.flags & 0x0200) {
26686 state.check = crc32(state.check, input, copy, next);
26690 if (len) { break inf_leave; }
26692 else if (state.head) {
26693 state.head.comment = null;
26696 /* falls through */
26698 if (state.flags & 0x0200) {
26699 //=== NEEDBITS(16); */
26700 while (bits < 16) {
26701 if (have === 0) { break inf_leave; }
26703 hold += input[next++] << bits;
26707 if (hold !== (state.check & 0xffff)) {
26708 strm.msg = 'header crc mismatch';
26718 state.head.hcrc = ((state.flags >> 9) & 1);
26719 state.head.done = true;
26721 strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/;
26725 //=== NEEDBITS(32); */
26726 while (bits < 32) {
26727 if (have === 0) { break inf_leave; }
26729 hold += input[next++] << bits;
26733 strm.adler = state.check = ZSWAP32(hold);
26739 /* falls through */
26741 if (state.havedict === 0) {
26742 //--- RESTORE() ---
26743 strm.next_out = put;
26744 strm.avail_out = left;
26745 strm.next_in = next;
26746 strm.avail_in = have;
26750 return Z_NEED_DICT;
26752 strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
26754 /* falls through */
26756 if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
26757 /* falls through */
26760 //--- BYTEBITS() ---//
26761 hold >>>= bits & 7;
26764 state.mode = CHECK;
26767 //=== NEEDBITS(3); */
26769 if (have === 0) { break inf_leave; }
26771 hold += input[next++] << bits;
26775 state.last = (hold & 0x01)/*BITS(1)*/;
26776 //--- DROPBITS(1) ---//
26781 switch ((hold & 0x03)/*BITS(2)*/) {
26782 case 0: /* stored block */
26783 //Tracev((stderr, "inflate: stored block%s\n",
26784 // state.last ? " (last)" : ""));
26785 state.mode = STORED;
26787 case 1: /* fixed block */
26788 fixedtables(state);
26789 //Tracev((stderr, "inflate: fixed codes block%s\n",
26790 // state.last ? " (last)" : ""));
26791 state.mode = LEN_; /* decode codes */
26792 if (flush === Z_TREES) {
26793 //--- DROPBITS(2) ---//
26800 case 2: /* dynamic block */
26801 //Tracev((stderr, "inflate: dynamic codes block%s\n",
26802 // state.last ? " (last)" : ""));
26803 state.mode = TABLE;
26806 strm.msg = 'invalid block type';
26809 //--- DROPBITS(2) ---//
26815 //--- BYTEBITS() ---// /* go to byte boundary */
26816 hold >>>= bits & 7;
26819 //=== NEEDBITS(32); */
26820 while (bits < 32) {
26821 if (have === 0) { break inf_leave; }
26823 hold += input[next++] << bits;
26827 if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
26828 strm.msg = 'invalid stored block lengths';
26832 state.length = hold & 0xffff;
26833 //Tracev((stderr, "inflate: stored length %u\n",
26839 state.mode = COPY_;
26840 if (flush === Z_TREES) { break inf_leave; }
26841 /* falls through */
26844 /* falls through */
26846 copy = state.length;
26848 if (copy > have) { copy = have; }
26849 if (copy > left) { copy = left; }
26850 if (copy === 0) { break inf_leave; }
26851 //--- zmemcpy(put, next, copy); ---
26852 utils.arraySet(output, input, next, copy, put);
26858 state.length -= copy;
26861 //Tracev((stderr, "inflate: stored end\n"));
26865 //=== NEEDBITS(14); */
26866 while (bits < 14) {
26867 if (have === 0) { break inf_leave; }
26869 hold += input[next++] << bits;
26873 state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
26874 //--- DROPBITS(5) ---//
26878 state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
26879 //--- DROPBITS(5) ---//
26883 state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
26884 //--- DROPBITS(4) ---//
26888 //#ifndef PKZIP_BUG_WORKAROUND
26889 if (state.nlen > 286 || state.ndist > 30) {
26890 strm.msg = 'too many length or distance symbols';
26895 //Tracev((stderr, "inflate: table sizes ok\n"));
26897 state.mode = LENLENS;
26898 /* falls through */
26900 while (state.have < state.ncode) {
26903 if (have === 0) { break inf_leave; }
26905 hold += input[next++] << bits;
26909 state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
26910 //--- DROPBITS(3) ---//
26915 while (state.have < 19) {
26916 state.lens[order[state.have++]] = 0;
26918 // We have separate tables & no pointers. 2 commented lines below not needed.
26919 //state.next = state.codes;
26920 //state.lencode = state.next;
26921 // Switch to use dynamic table
26922 state.lencode = state.lendyn;
26925 opts = {bits: state.lenbits};
26926 ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
26927 state.lenbits = opts.bits;
26930 strm.msg = 'invalid code lengths set';
26934 //Tracev((stderr, "inflate: code lengths ok\n"));
26936 state.mode = CODELENS;
26937 /* falls through */
26939 while (state.have < state.nlen + state.ndist) {
26941 here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
26942 here_bits = here >>> 24;
26943 here_op = (here >>> 16) & 0xff;
26944 here_val = here & 0xffff;
26946 if ((here_bits) <= bits) { break; }
26947 //--- PULLBYTE() ---//
26948 if (have === 0) { break inf_leave; }
26950 hold += input[next++] << bits;
26954 if (here_val < 16) {
26955 //--- DROPBITS(here.bits) ---//
26956 hold >>>= here_bits;
26959 state.lens[state.have++] = here_val;
26962 if (here_val === 16) {
26963 //=== NEEDBITS(here.bits + 2);
26966 if (have === 0) { break inf_leave; }
26968 hold += input[next++] << bits;
26972 //--- DROPBITS(here.bits) ---//
26973 hold >>>= here_bits;
26976 if (state.have === 0) {
26977 strm.msg = 'invalid bit length repeat';
26981 len = state.lens[state.have - 1];
26982 copy = 3 + (hold & 0x03);//BITS(2);
26983 //--- DROPBITS(2) ---//
26988 else if (here_val === 17) {
26989 //=== NEEDBITS(here.bits + 3);
26992 if (have === 0) { break inf_leave; }
26994 hold += input[next++] << bits;
26998 //--- DROPBITS(here.bits) ---//
26999 hold >>>= here_bits;
27003 copy = 3 + (hold & 0x07);//BITS(3);
27004 //--- DROPBITS(3) ---//
27010 //=== NEEDBITS(here.bits + 7);
27013 if (have === 0) { break inf_leave; }
27015 hold += input[next++] << bits;
27019 //--- DROPBITS(here.bits) ---//
27020 hold >>>= here_bits;
27024 copy = 11 + (hold & 0x7f);//BITS(7);
27025 //--- DROPBITS(7) ---//
27030 if (state.have + copy > state.nlen + state.ndist) {
27031 strm.msg = 'invalid bit length repeat';
27036 state.lens[state.have++] = len;
27041 /* handle error breaks in while */
27042 if (state.mode === BAD) { break; }
27044 /* check for end-of-block code (better have one) */
27045 if (state.lens[256] === 0) {
27046 strm.msg = 'invalid code -- missing end-of-block';
27051 /* build code tables -- note: do not change the lenbits or distbits
27052 values here (9 and 6) without reading the comments in inftrees.h
27053 concerning the ENOUGH constants, which depend on those values */
27056 opts = {bits: state.lenbits};
27057 ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
27058 // We have separate tables & no pointers. 2 commented lines below not needed.
27059 // state.next_index = opts.table_index;
27060 state.lenbits = opts.bits;
27061 // state.lencode = state.next;
27064 strm.msg = 'invalid literal/lengths set';
27069 state.distbits = 6;
27070 //state.distcode.copy(state.codes);
27071 // Switch to use dynamic table
27072 state.distcode = state.distdyn;
27073 opts = {bits: state.distbits};
27074 ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
27075 // We have separate tables & no pointers. 2 commented lines below not needed.
27076 // state.next_index = opts.table_index;
27077 state.distbits = opts.bits;
27078 // state.distcode = state.next;
27081 strm.msg = 'invalid distances set';
27085 //Tracev((stderr, 'inflate: codes ok\n'));
27087 if (flush === Z_TREES) { break inf_leave; }
27088 /* falls through */
27091 /* falls through */
27093 if (have >= 6 && left >= 258) {
27094 //--- RESTORE() ---
27095 strm.next_out = put;
27096 strm.avail_out = left;
27097 strm.next_in = next;
27098 strm.avail_in = have;
27102 inflate_fast(strm, _out);
27104 put = strm.next_out;
27105 output = strm.output;
27106 left = strm.avail_out;
27107 next = strm.next_in;
27108 input = strm.input;
27109 have = strm.avail_in;
27114 if (state.mode === TYPE) {
27121 here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/
27122 here_bits = here >>> 24;
27123 here_op = (here >>> 16) & 0xff;
27124 here_val = here & 0xffff;
27126 if (here_bits <= bits) { break; }
27127 //--- PULLBYTE() ---//
27128 if (have === 0) { break inf_leave; }
27130 hold += input[next++] << bits;
27134 if (here_op && (here_op & 0xf0) === 0) {
27135 last_bits = here_bits;
27137 last_val = here_val;
27139 here = state.lencode[last_val +
27140 ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
27141 here_bits = here >>> 24;
27142 here_op = (here >>> 16) & 0xff;
27143 here_val = here & 0xffff;
27145 if ((last_bits + here_bits) <= bits) { break; }
27146 //--- PULLBYTE() ---//
27147 if (have === 0) { break inf_leave; }
27149 hold += input[next++] << bits;
27153 //--- DROPBITS(last.bits) ---//
27154 hold >>>= last_bits;
27157 state.back += last_bits;
27159 //--- DROPBITS(here.bits) ---//
27160 hold >>>= here_bits;
27163 state.back += here_bits;
27164 state.length = here_val;
27165 if (here_op === 0) {
27166 //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
27167 // "inflate: literal '%c'\n" :
27168 // "inflate: literal 0x%02x\n", here.val));
27172 if (here_op & 32) {
27173 //Tracevv((stderr, "inflate: end of block\n"));
27178 if (here_op & 64) {
27179 strm.msg = 'invalid literal/length code';
27183 state.extra = here_op & 15;
27184 state.mode = LENEXT;
27185 /* falls through */
27188 //=== NEEDBITS(state.extra);
27191 if (have === 0) { break inf_leave; }
27193 hold += input[next++] << bits;
27197 state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
27198 //--- DROPBITS(state.extra) ---//
27199 hold >>>= state.extra;
27200 bits -= state.extra;
27202 state.back += state.extra;
27204 //Tracevv((stderr, "inflate: length %u\n", state.length));
27205 state.was = state.length;
27207 /* falls through */
27210 here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/
27211 here_bits = here >>> 24;
27212 here_op = (here >>> 16) & 0xff;
27213 here_val = here & 0xffff;
27215 if ((here_bits) <= bits) { break; }
27216 //--- PULLBYTE() ---//
27217 if (have === 0) { break inf_leave; }
27219 hold += input[next++] << bits;
27223 if ((here_op & 0xf0) === 0) {
27224 last_bits = here_bits;
27226 last_val = here_val;
27228 here = state.distcode[last_val +
27229 ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
27230 here_bits = here >>> 24;
27231 here_op = (here >>> 16) & 0xff;
27232 here_val = here & 0xffff;
27234 if ((last_bits + here_bits) <= bits) { break; }
27235 //--- PULLBYTE() ---//
27236 if (have === 0) { break inf_leave; }
27238 hold += input[next++] << bits;
27242 //--- DROPBITS(last.bits) ---//
27243 hold >>>= last_bits;
27246 state.back += last_bits;
27248 //--- DROPBITS(here.bits) ---//
27249 hold >>>= here_bits;
27252 state.back += here_bits;
27253 if (here_op & 64) {
27254 strm.msg = 'invalid distance code';
27258 state.offset = here_val;
27259 state.extra = (here_op) & 15;
27260 state.mode = DISTEXT;
27261 /* falls through */
27264 //=== NEEDBITS(state.extra);
27267 if (have === 0) { break inf_leave; }
27269 hold += input[next++] << bits;
27273 state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
27274 //--- DROPBITS(state.extra) ---//
27275 hold >>>= state.extra;
27276 bits -= state.extra;
27278 state.back += state.extra;
27280 //#ifdef INFLATE_STRICT
27281 if (state.offset > state.dmax) {
27282 strm.msg = 'invalid distance too far back';
27287 //Tracevv((stderr, "inflate: distance %u\n", state.offset));
27288 state.mode = MATCH;
27289 /* falls through */
27291 if (left === 0) { break inf_leave; }
27292 copy = _out - left;
27293 if (state.offset > copy) { /* copy from window */
27294 copy = state.offset - copy;
27295 if (copy > state.whave) {
27297 strm.msg = 'invalid distance too far back';
27301 // (!) This block is disabled in zlib defailts,
27302 // don't enable it for binary compatibility
27303 //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
27304 // Trace((stderr, "inflate.c too far\n"));
27305 // copy -= state.whave;
27306 // if (copy > state.length) { copy = state.length; }
27307 // if (copy > left) { copy = left; }
27309 // state.length -= copy;
27311 // output[put++] = 0;
27312 // } while (--copy);
27313 // if (state.length === 0) { state.mode = LEN; }
27317 if (copy > state.wnext) {
27318 copy -= state.wnext;
27319 from = state.wsize - copy;
27322 from = state.wnext - copy;
27324 if (copy > state.length) { copy = state.length; }
27325 from_source = state.window;
27327 else { /* copy from output */
27328 from_source = output;
27329 from = put - state.offset;
27330 copy = state.length;
27332 if (copy > left) { copy = left; }
27334 state.length -= copy;
27336 output[put++] = from_source[from++];
27338 if (state.length === 0) { state.mode = LEN; }
27341 if (left === 0) { break inf_leave; }
27342 output[put++] = state.length;
27348 //=== NEEDBITS(32);
27349 while (bits < 32) {
27350 if (have === 0) { break inf_leave; }
27352 // Use '|' insdead of '+' to make sure that result is signed
27353 hold |= input[next++] << bits;
27358 strm.total_out += _out;
27359 state.total += _out;
27361 strm.adler = state.check =
27362 /*UPDATE(state.check, put - _out, _out);*/
27363 (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
27367 // NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too
27368 if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) {
27369 strm.msg = 'incorrect data check';
27377 //Tracev((stderr, "inflate: check matches trailer\n"));
27379 state.mode = LENGTH;
27380 /* falls through */
27382 if (state.wrap && state.flags) {
27383 //=== NEEDBITS(32);
27384 while (bits < 32) {
27385 if (have === 0) { break inf_leave; }
27387 hold += input[next++] << bits;
27391 if (hold !== (state.total & 0xffffffff)) {
27392 strm.msg = 'incorrect length check';
27400 //Tracev((stderr, "inflate: length matches trailer\n"));
27403 /* falls through */
27405 ret = Z_STREAM_END;
27408 ret = Z_DATA_ERROR;
27411 return Z_MEM_ERROR;
27413 /* falls through */
27415 return Z_STREAM_ERROR;
27419 // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
27422 Return from inflate(), updating the total counts and the check value.
27423 If there was no progress during the inflate() call, return a buffer
27424 error. Call updatewindow() to create and/or update the window state.
27425 Note: a memory error from inflate() is non-recoverable.
27428 //--- RESTORE() ---
27429 strm.next_out = put;
27430 strm.avail_out = left;
27431 strm.next_in = next;
27432 strm.avail_in = have;
27437 if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
27438 (state.mode < CHECK || flush !== Z_FINISH))) {
27439 if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
27441 return Z_MEM_ERROR;
27444 _in -= strm.avail_in;
27445 _out -= strm.avail_out;
27446 strm.total_in += _in;
27447 strm.total_out += _out;
27448 state.total += _out;
27449 if (state.wrap && _out) {
27450 strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
27451 (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
27453 strm.data_type = state.bits + (state.last ? 64 : 0) +
27454 (state.mode === TYPE ? 128 : 0) +
27455 (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
27456 if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
27462 function inflateEnd(strm) {
27464 if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
27465 return Z_STREAM_ERROR;
27468 var state = strm.state;
27469 if (state.window) {
27470 state.window = null;
27476 function inflateGetHeader(strm, head) {
27480 if (!strm || !strm.state) { return Z_STREAM_ERROR; }
27481 state = strm.state;
27482 if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
27484 /* save header structure */
27491 exports.inflateReset = inflateReset;
27492 exports.inflateReset2 = inflateReset2;
27493 exports.inflateResetKeep = inflateResetKeep;
27494 exports.inflateInit = inflateInit;
27495 exports.inflateInit2 = inflateInit2;
27496 exports.inflate = inflate;
27497 exports.inflateEnd = inflateEnd;
27498 exports.inflateGetHeader = inflateGetHeader;
27499 exports.inflateInfo = 'pako inflate (from Nodeca project)';
27502 exports.inflateCopy = inflateCopy;
27503 exports.inflateGetDictionary = inflateGetDictionary;
27504 exports.inflateMark = inflateMark;
27505 exports.inflatePrime = inflatePrime;
27506 exports.inflateSetDictionary = inflateSetDictionary;
27507 exports.inflateSync = inflateSync;
27508 exports.inflateSyncPoint = inflateSyncPoint;
27509 exports.inflateUndermine = inflateUndermine;
27515 /***/ function(module, exports) {
27519 // See state defs from inflate.js
27520 var BAD = 30; /* got a data error -- remain here until reset */
27521 var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
27524 Decode literal, length, and distance codes and write out the resulting
27525 literal and match bytes until either not enough input or output is
27526 available, an end-of-block is encountered, or a data error is encountered.
27527 When large enough input and output buffers are supplied to inflate(), for
27528 example, a 16K input buffer and a 64K output buffer, more than 95% of the
27529 inflate execution time is spent in this routine.
27535 strm.avail_out >= 258
27536 start >= strm.avail_out
27539 On return, state.mode is one of:
27541 LEN -- ran out of enough output space or enough available input
27542 TYPE -- reached end of block code, inflate() to interpret next block
27543 BAD -- error in block data
27547 - The maximum input bits used by a length/distance pair is 15 bits for the
27548 length code, 5 bits for the length extra, 15 bits for the distance code,
27549 and 13 bits for the distance extra. This totals 48 bits, or six bytes.
27550 Therefore if strm.avail_in >= 6, then there is enough input to avoid
27551 checking for available input while decoding.
27553 - The maximum bytes that a single length/distance pair can output is 258
27554 bytes, which is the maximum length that can be coded. inflate_fast()
27555 requires strm.avail_out >= 258 for each loop to avoid checking for
27558 module.exports = function inflate_fast(strm, start) {
27560 var _in; /* local strm.input */
27561 var last; /* have enough input while in < last */
27562 var _out; /* local strm.output */
27563 var beg; /* inflate()'s initial strm.output */
27564 var end; /* while out < end, enough space available */
27565 //#ifdef INFLATE_STRICT
27566 var dmax; /* maximum distance from zlib header */
27568 var wsize; /* window size or zero if not using window */
27569 var whave; /* valid bytes in the window */
27570 var wnext; /* window write index */
27571 // Use `s_window` instead `window`, avoid conflict with instrumentation tools
27572 var s_window; /* allocated sliding window, if wsize != 0 */
27573 var hold; /* local strm.hold */
27574 var bits; /* local strm.bits */
27575 var lcode; /* local strm.lencode */
27576 var dcode; /* local strm.distcode */
27577 var lmask; /* mask for first level of length codes */
27578 var dmask; /* mask for first level of distance codes */
27579 var here; /* retrieved table entry */
27580 var op; /* code bits, operation, extra bits, or */
27581 /* window position, window bytes to copy */
27582 var len; /* match length, unused bytes */
27583 var dist; /* match distance */
27584 var from; /* where to copy match from */
27588 var input, output; // JS specific, because we have no pointers
27590 /* copy state to local variables */
27591 state = strm.state;
27592 //here = state.here;
27593 _in = strm.next_in;
27594 input = strm.input;
27595 last = _in + (strm.avail_in - 5);
27596 _out = strm.next_out;
27597 output = strm.output;
27598 beg = _out - (start - strm.avail_out);
27599 end = _out + (strm.avail_out - 257);
27600 //#ifdef INFLATE_STRICT
27603 wsize = state.wsize;
27604 whave = state.whave;
27605 wnext = state.wnext;
27606 s_window = state.window;
27609 lcode = state.lencode;
27610 dcode = state.distcode;
27611 lmask = (1 << state.lenbits) - 1;
27612 dmask = (1 << state.distbits) - 1;
27615 /* decode literals and length/distances until end-of-block or not enough
27616 input data or output space */
27621 hold += input[_in++] << bits;
27623 hold += input[_in++] << bits;
27627 here = lcode[hold & lmask];
27630 for (;;) { // Goto emulation
27631 op = here >>> 24/*here.bits*/;
27634 op = (here >>> 16) & 0xff/*here.op*/;
27635 if (op === 0) { /* literal */
27636 //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
27637 // "inflate: literal '%c'\n" :
27638 // "inflate: literal 0x%02x\n", here.val));
27639 output[_out++] = here & 0xffff/*here.val*/;
27641 else if (op & 16) { /* length base */
27642 len = here & 0xffff/*here.val*/;
27643 op &= 15; /* number of extra bits */
27646 hold += input[_in++] << bits;
27649 len += hold & ((1 << op) - 1);
27653 //Tracevv((stderr, "inflate: length %u\n", len));
27655 hold += input[_in++] << bits;
27657 hold += input[_in++] << bits;
27660 here = dcode[hold & dmask];
27663 for (;;) { // goto emulation
27664 op = here >>> 24/*here.bits*/;
27667 op = (here >>> 16) & 0xff/*here.op*/;
27669 if (op & 16) { /* distance base */
27670 dist = here & 0xffff/*here.val*/;
27671 op &= 15; /* number of extra bits */
27673 hold += input[_in++] << bits;
27676 hold += input[_in++] << bits;
27680 dist += hold & ((1 << op) - 1);
27681 //#ifdef INFLATE_STRICT
27683 strm.msg = 'invalid distance too far back';
27690 //Tracevv((stderr, "inflate: distance %u\n", dist));
27691 op = _out - beg; /* max distance in output */
27692 if (dist > op) { /* see if copy from window */
27693 op = dist - op; /* distance back in window */
27696 strm.msg = 'invalid distance too far back';
27701 // (!) This block is disabled in zlib defailts,
27702 // don't enable it for binary compatibility
27703 //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
27704 // if (len <= op - whave) {
27706 // output[_out++] = 0;
27707 // } while (--len);
27710 // len -= op - whave;
27712 // output[_out++] = 0;
27713 // } while (--op > whave);
27715 // from = _out - dist;
27717 // output[_out++] = output[from++];
27718 // } while (--len);
27723 from = 0; // window index
27724 from_source = s_window;
27725 if (wnext === 0) { /* very common case */
27726 from += wsize - op;
27727 if (op < len) { /* some from window */
27730 output[_out++] = s_window[from++];
27732 from = _out - dist; /* rest from output */
27733 from_source = output;
27736 else if (wnext < op) { /* wrap around window */
27737 from += wsize + wnext - op;
27739 if (op < len) { /* some from end of window */
27742 output[_out++] = s_window[from++];
27745 if (wnext < len) { /* some from start of window */
27749 output[_out++] = s_window[from++];
27751 from = _out - dist; /* rest from output */
27752 from_source = output;
27756 else { /* contiguous in window */
27757 from += wnext - op;
27758 if (op < len) { /* some from window */
27761 output[_out++] = s_window[from++];
27763 from = _out - dist; /* rest from output */
27764 from_source = output;
27768 output[_out++] = from_source[from++];
27769 output[_out++] = from_source[from++];
27770 output[_out++] = from_source[from++];
27774 output[_out++] = from_source[from++];
27776 output[_out++] = from_source[from++];
27781 from = _out - dist; /* copy direct from output */
27782 do { /* minimum length is three */
27783 output[_out++] = output[from++];
27784 output[_out++] = output[from++];
27785 output[_out++] = output[from++];
27789 output[_out++] = output[from++];
27791 output[_out++] = output[from++];
27796 else if ((op & 64) === 0) { /* 2nd level distance code */
27797 here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
27801 strm.msg = 'invalid distance code';
27806 break; // need to emulate goto via "continue"
27809 else if ((op & 64) === 0) { /* 2nd level length code */
27810 here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
27813 else if (op & 32) { /* end-of-block */
27814 //Tracevv((stderr, "inflate: end of block\n"));
27819 strm.msg = 'invalid literal/length code';
27824 break; // need to emulate goto via "continue"
27826 } while (_in < last && _out < end);
27828 /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
27832 hold &= (1 << bits) - 1;
27834 /* update state and return */
27835 strm.next_in = _in;
27836 strm.next_out = _out;
27837 strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
27838 strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
27847 /***/ function(module, exports, __webpack_require__) {
27852 var utils = __webpack_require__(52);
27855 var ENOUGH_LENS = 852;
27856 var ENOUGH_DISTS = 592;
27857 //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
27863 var lbase = [ /* Length codes 257..285 base */
27864 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
27865 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
27868 var lext = [ /* Length codes 257..285 extra */
27869 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
27870 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
27873 var dbase = [ /* Distance codes 0..29 base */
27874 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
27875 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
27876 8193, 12289, 16385, 24577, 0, 0
27879 var dext = [ /* Distance codes 0..29 extra */
27880 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
27881 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
27882 28, 28, 29, 29, 64, 64
27885 module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
27887 var bits = opts.bits;
27888 //here = opts.here; /* table entry for duplication */
27890 var len = 0; /* a code's length in bits */
27891 var sym = 0; /* index of code symbols */
27892 var min = 0, max = 0; /* minimum and maximum code lengths */
27893 var root = 0; /* number of index bits for root table */
27894 var curr = 0; /* number of index bits for current table */
27895 var drop = 0; /* code bits to drop for sub-table */
27896 var left = 0; /* number of prefix codes available */
27897 var used = 0; /* code entries in table used */
27898 var huff = 0; /* Huffman code */
27899 var incr; /* for incrementing code, index */
27900 var fill; /* index for replicating entries */
27901 var low; /* low bits for current root entry */
27902 var mask; /* mask for low root bits */
27903 var next; /* next available space in table */
27904 var base = null; /* base value table to use */
27905 var base_index = 0;
27906 // var shoextra; /* extra bits table to use */
27907 var end; /* use base and extra for symbol > end */
27908 var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */
27909 var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */
27911 var extra_index = 0;
27913 var here_bits, here_op, here_val;
27916 Process a set of code lengths to create a canonical Huffman code. The
27917 code lengths are lens[0..codes-1]. Each length corresponds to the
27918 symbols 0..codes-1. The Huffman code is generated by first sorting the
27919 symbols by length from short to long, and retaining the symbol order
27920 for codes with equal lengths. Then the code starts with all zero bits
27921 for the first code of the shortest length, and the codes are integer
27922 increments for the same length, and zeros are appended as the length
27923 increases. For the deflate format, these bits are stored backwards
27924 from their more natural integer increment ordering, and so when the
27925 decoding tables are built in the large loop below, the integer codes
27926 are incremented backwards.
27928 This routine assumes, but does not check, that all of the entries in
27929 lens[] are in the range 0..MAXBITS. The caller must assure this.
27930 1..MAXBITS is interpreted as that code length. zero means that that
27931 symbol does not occur in this code.
27933 The codes are sorted by computing a count of codes for each length,
27934 creating from that a table of starting indices for each length in the
27935 sorted table, and then entering the symbols in order in the sorted
27936 table. The sorted table is work[], with that space being provided by
27939 The length counts are used for other purposes as well, i.e. finding
27940 the minimum and maximum length codes, determining if there are any
27941 codes at all, checking for a valid set of lengths, and looking ahead
27942 at length counts to determine sub-table sizes when building the
27946 /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
27947 for (len = 0; len <= MAXBITS; len++) {
27950 for (sym = 0; sym < codes; sym++) {
27951 count[lens[lens_index + sym]]++;
27954 /* bound code lengths, force root to be within code lengths */
27956 for (max = MAXBITS; max >= 1; max--) {
27957 if (count[max] !== 0) { break; }
27962 if (max === 0) { /* no symbols to code at all */
27963 //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
27964 //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
27965 //table.val[opts.table_index++] = 0; //here.val = (var short)0;
27966 table[table_index++] = (1 << 24) | (64 << 16) | 0;
27969 //table.op[opts.table_index] = 64;
27970 //table.bits[opts.table_index] = 1;
27971 //table.val[opts.table_index++] = 0;
27972 table[table_index++] = (1 << 24) | (64 << 16) | 0;
27975 return 0; /* no symbols, but wait for decoding to report error */
27977 for (min = 1; min < max; min++) {
27978 if (count[min] !== 0) { break; }
27984 /* check for an over-subscribed or incomplete set of lengths */
27986 for (len = 1; len <= MAXBITS; len++) {
27988 left -= count[len];
27991 } /* over-subscribed */
27993 if (left > 0 && (type === CODES || max !== 1)) {
27994 return -1; /* incomplete set */
27997 /* generate offsets into symbol table for each length for sorting */
27999 for (len = 1; len < MAXBITS; len++) {
28000 offs[len + 1] = offs[len] + count[len];
28003 /* sort symbols by length, by symbol order within each length */
28004 for (sym = 0; sym < codes; sym++) {
28005 if (lens[lens_index + sym] !== 0) {
28006 work[offs[lens[lens_index + sym]]++] = sym;
28011 Create and fill in decoding tables. In this loop, the table being
28012 filled is at next and has curr index bits. The code being used is huff
28013 with length len. That code is converted to an index by dropping drop
28014 bits off of the bottom. For codes where len is less than drop + curr,
28015 those top drop + curr - len bits are incremented through all values to
28016 fill the table with replicated entries.
28018 root is the number of index bits for the root table. When len exceeds
28019 root, sub-tables are created pointed to by the root entry with an index
28020 of the low root bits of huff. This is saved in low to check for when a
28021 new sub-table should be started. drop is zero when the root table is
28022 being filled, and drop is root when sub-tables are being filled.
28024 When a new sub-table is needed, it is necessary to look ahead in the
28025 code lengths to determine what size sub-table is needed. The length
28026 counts are used for this, and so count[] is decremented as codes are
28027 entered in the tables.
28029 used keeps track of how many table entries have been allocated from the
28030 provided *table space. It is checked for LENS and DIST tables against
28031 the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
28032 the initial root table size constants. See the comments in inftrees.h
28033 for more information.
28035 sym increments through all symbols, and the loop terminates when
28036 all codes of length max, i.e. all codes, have been processed. This
28037 routine permits incomplete codes, so another loop after this one fills
28038 in the rest of the decoding tables with invalid code markers.
28041 /* set up for code type */
28042 // poor man optimization - use if-else instead of switch,
28043 // to avoid deopts in old v8
28044 if (type === CODES) {
28045 base = extra = work; /* dummy value--not used */
28048 } else if (type === LENS) {
28052 extra_index -= 257;
28055 } else { /* DISTS */
28061 /* initialize opts for loop */
28062 huff = 0; /* starting code */
28063 sym = 0; /* starting code symbol */
28064 len = min; /* starting code length */
28065 next = table_index; /* current table to fill in */
28066 curr = root; /* current table index bits */
28067 drop = 0; /* current bits to drop from code for index */
28068 low = -1; /* trigger new sub-table when len > root */
28069 used = 1 << root; /* use root table entries */
28070 mask = used - 1; /* mask for comparing low */
28072 /* check available table space */
28073 if ((type === LENS && used > ENOUGH_LENS) ||
28074 (type === DISTS && used > ENOUGH_DISTS)) {
28079 /* process all codes and make table entries */
28082 /* create table entry */
28083 here_bits = len - drop;
28084 if (work[sym] < end) {
28086 here_val = work[sym];
28088 else if (work[sym] > end) {
28089 here_op = extra[extra_index + work[sym]];
28090 here_val = base[base_index + work[sym]];
28093 here_op = 32 + 64; /* end of block */
28097 /* replicate for those indices with low len bits equal to huff */
28098 incr = 1 << (len - drop);
28100 min = fill; /* save offset to next table */
28103 table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
28104 } while (fill !== 0);
28106 /* backwards increment the len-bit code huff */
28107 incr = 1 << (len - 1);
28108 while (huff & incr) {
28118 /* go to next symbol, update count, len */
28120 if (--count[len] === 0) {
28121 if (len === max) { break; }
28122 len = lens[lens_index + work[sym]];
28125 /* create new sub-table if needed */
28126 if (len > root && (huff & mask) !== low) {
28127 /* if first time, transition to sub-tables */
28132 /* increment past last table */
28133 next += min; /* here min is 1 << curr */
28135 /* determine length of next table */
28138 while (curr + drop < max) {
28139 left -= count[curr + drop];
28140 if (left <= 0) { break; }
28145 /* check for enough space */
28147 if ((type === LENS && used > ENOUGH_LENS) ||
28148 (type === DISTS && used > ENOUGH_DISTS)) {
28152 /* point entry in root table to sub-table */
28154 /*table.op[low] = curr;
28155 table.bits[low] = root;
28156 table.val[low] = next - opts.table_index;*/
28157 table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
28161 /* fill in remaining table entry if code is incomplete (guaranteed to have
28162 at most one remaining entry, since if the code is incomplete, the
28163 maximum code length that was allowed to get this far is one bit) */
28165 //table.op[next + huff] = 64; /* invalid code marker */
28166 //table.bits[next + huff] = len - drop;
28167 //table.val[next + huff] = 0;
28168 table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
28171 /* set return parameters */
28172 //opts.table_index += used;
28180 /***/ function(module, exports) {
28184 /* Allowed flush values; see deflate() and inflate() below for details */
28186 Z_PARTIAL_FLUSH: 1,
28193 /* Return codes for the compression/decompression functions. Negative values
28194 * are errors, positive values are used for special but normal events.
28200 Z_STREAM_ERROR: -2,
28204 //Z_VERSION_ERROR: -6,
28206 /* compression levels */
28207 Z_NO_COMPRESSION: 0,
28209 Z_BEST_COMPRESSION: 9,
28210 Z_DEFAULT_COMPRESSION: -1,
28217 Z_DEFAULT_STRATEGY: 0,
28219 /* Possible values of the data_type field (though see inflate()) */
28222 //Z_ASCII: 1, // = Z_TEXT (deprecated)
28225 /* The deflate compression method */
28227 //Z_NULL: null // Use -1 or null inline, depending on var type
28233 /***/ function(module, exports, __webpack_require__) {
28235 /* WEBPACK VAR INJECTION */(function(global, process) {// Copyright Joyent, Inc. and other Node contributors.
28237 // Permission is hereby granted, free of charge, to any person obtaining a
28238 // copy of this software and associated documentation files (the
28239 // "Software"), to deal in the Software without restriction, including
28240 // without limitation the rights to use, copy, modify, merge, publish,
28241 // distribute, sublicense, and/or sell copies of the Software, and to permit
28242 // persons to whom the Software is furnished to do so, subject to the
28243 // following conditions:
28245 // The above copyright notice and this permission notice shall be included
28246 // in all copies or substantial portions of the Software.
28248 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
28249 // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
28250 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
28251 // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
28252 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
28253 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
28254 // USE OR OTHER DEALINGS IN THE SOFTWARE.
28256 var formatRegExp = /%[sdj%]/g;
28257 exports.format = function(f) {
28258 if (!isString(f)) {
28260 for (var i = 0; i < arguments.length; i++) {
28261 objects.push(inspect(arguments[i]));
28263 return objects.join(' ');
28267 var args = arguments;
28268 var len = args.length;
28269 var str = String(f).replace(formatRegExp, function(x) {
28270 if (x === '%%') return '%';
28271 if (i >= len) return x;
28273 case '%s': return String(args[i++]);
28274 case '%d': return Number(args[i++]);
28277 return JSON.stringify(args[i++]);
28279 return '[Circular]';
28285 for (var x = args[i]; i < len; x = args[++i]) {
28286 if (isNull(x) || !isObject(x)) {
28289 str += ' ' + inspect(x);
28296 // Mark that a method should not be used.
28297 // Returns a modified function which warns once by default.
28298 // If --no-deprecation is set, then it is a no-op.
28299 exports.deprecate = function(fn, msg) {
28300 // Allow for deprecating things in the process of starting up.
28301 if (isUndefined(global.process)) {
28302 return function() {
28303 return exports.deprecate(fn, msg).apply(this, arguments);
28307 if (process.noDeprecation === true) {
28311 var warned = false;
28312 function deprecated() {
28314 if (process.throwDeprecation) {
28315 throw new Error(msg);
28316 } else if (process.traceDeprecation) {
28317 console.trace(msg);
28319 console.error(msg);
28323 return fn.apply(this, arguments);
28332 exports.debuglog = function(set) {
28333 if (isUndefined(debugEnviron))
28334 debugEnviron = process.env.NODE_DEBUG || '';
28335 set = set.toUpperCase();
28336 if (!debugs[set]) {
28337 if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
28338 var pid = process.pid;
28339 debugs[set] = function() {
28340 var msg = exports.format.apply(exports, arguments);
28341 console.error('%s %d: %s', set, pid, msg);
28344 debugs[set] = function() {};
28347 return debugs[set];
28352 * Echos the value of a value. Trys to print the value out
28353 * in the best way possible given the different types.
28355 * @param {Object} obj The object to print out.
28356 * @param {Object} opts Optional options object that alters the output.
28358 /* legacy: obj, showHidden, depth, colors*/
28359 function inspect(obj, opts) {
28363 stylize: stylizeNoColor
28366 if (arguments.length >= 3) ctx.depth = arguments[2];
28367 if (arguments.length >= 4) ctx.colors = arguments[3];
28368 if (isBoolean(opts)) {
28370 ctx.showHidden = opts;
28372 // got an "options" object
28373 exports._extend(ctx, opts);
28375 // set default options
28376 if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
28377 if (isUndefined(ctx.depth)) ctx.depth = 2;
28378 if (isUndefined(ctx.colors)) ctx.colors = false;
28379 if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
28380 if (ctx.colors) ctx.stylize = stylizeWithColor;
28381 return formatValue(ctx, obj, ctx.depth);
28383 exports.inspect = inspect;
28386 // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
28389 'italic' : [3, 23],
28390 'underline' : [4, 24],
28391 'inverse' : [7, 27],
28392 'white' : [37, 39],
28394 'black' : [30, 39],
28397 'green' : [32, 39],
28398 'magenta' : [35, 39],
28400 'yellow' : [33, 39]
28403 // Don't use 'blue' not visible on cmd.exe
28406 'number': 'yellow',
28407 'boolean': 'yellow',
28408 'undefined': 'grey',
28412 // "name": intentionally not styling
28417 function stylizeWithColor(str, styleType) {
28418 var style = inspect.styles[styleType];
28421 return '\u001b[' + inspect.colors[style][0] + 'm' + str +
28422 '\u001b[' + inspect.colors[style][1] + 'm';
28429 function stylizeNoColor(str, styleType) {
28434 function arrayToHash(array) {
28437 array.forEach(function(val, idx) {
28445 function formatValue(ctx, value, recurseTimes) {
28446 // Provide a hook for user-specified inspect functions.
28447 // Check that value is an object with an inspect function on it
28448 if (ctx.customInspect &&
28450 isFunction(value.inspect) &&
28451 // Filter out the util module, it's inspect function is special
28452 value.inspect !== exports.inspect &&
28453 // Also filter out any prototype objects using the circular check.
28454 !(value.constructor && value.constructor.prototype === value)) {
28455 var ret = value.inspect(recurseTimes, ctx);
28456 if (!isString(ret)) {
28457 ret = formatValue(ctx, ret, recurseTimes);
28462 // Primitive types cannot have properties
28463 var primitive = formatPrimitive(ctx, value);
28468 // Look up the keys of the object.
28469 var keys = Object.keys(value);
28470 var visibleKeys = arrayToHash(keys);
28472 if (ctx.showHidden) {
28473 keys = Object.getOwnPropertyNames(value);
28476 // IE doesn't make error fields non-enumerable
28477 // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
28479 && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
28480 return formatError(value);
28483 // Some type of object without properties can be shortcutted.
28484 if (keys.length === 0) {
28485 if (isFunction(value)) {
28486 var name = value.name ? ': ' + value.name : '';
28487 return ctx.stylize('[Function' + name + ']', 'special');
28489 if (isRegExp(value)) {
28490 return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
28492 if (isDate(value)) {
28493 return ctx.stylize(Date.prototype.toString.call(value), 'date');
28495 if (isError(value)) {
28496 return formatError(value);
28500 var base = '', array = false, braces = ['{', '}'];
28502 // Make Array say that they are Array
28503 if (isArray(value)) {
28505 braces = ['[', ']'];
28508 // Make functions say that they are functions
28509 if (isFunction(value)) {
28510 var n = value.name ? ': ' + value.name : '';
28511 base = ' [Function' + n + ']';
28514 // Make RegExps say that they are RegExps
28515 if (isRegExp(value)) {
28516 base = ' ' + RegExp.prototype.toString.call(value);
28519 // Make dates with properties first say the date
28520 if (isDate(value)) {
28521 base = ' ' + Date.prototype.toUTCString.call(value);
28524 // Make error with message first say the error
28525 if (isError(value)) {
28526 base = ' ' + formatError(value);
28529 if (keys.length === 0 && (!array || value.length == 0)) {
28530 return braces[0] + base + braces[1];
28533 if (recurseTimes < 0) {
28534 if (isRegExp(value)) {
28535 return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
28537 return ctx.stylize('[Object]', 'special');
28541 ctx.seen.push(value);
28545 output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
28547 output = keys.map(function(key) {
28548 return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
28554 return reduceToSingleString(output, base, braces);
28558 function formatPrimitive(ctx, value) {
28559 if (isUndefined(value))
28560 return ctx.stylize('undefined', 'undefined');
28561 if (isString(value)) {
28562 var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
28563 .replace(/'/g, "\\'")
28564 .replace(/\\"/g, '"') + '\'';
28565 return ctx.stylize(simple, 'string');
28567 if (isNumber(value))
28568 return ctx.stylize('' + value, 'number');
28569 if (isBoolean(value))
28570 return ctx.stylize('' + value, 'boolean');
28571 // For some reason typeof null is "object", so special case here.
28573 return ctx.stylize('null', 'null');
28577 function formatError(value) {
28578 return '[' + Error.prototype.toString.call(value) + ']';
28582 function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
28584 for (var i = 0, l = value.length; i < l; ++i) {
28585 if (hasOwnProperty(value, String(i))) {
28586 output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
28592 keys.forEach(function(key) {
28593 if (!key.match(/^\d+$/)) {
28594 output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
28602 function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
28603 var name, str, desc;
28604 desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
28607 str = ctx.stylize('[Getter/Setter]', 'special');
28609 str = ctx.stylize('[Getter]', 'special');
28613 str = ctx.stylize('[Setter]', 'special');
28616 if (!hasOwnProperty(visibleKeys, key)) {
28617 name = '[' + key + ']';
28620 if (ctx.seen.indexOf(desc.value) < 0) {
28621 if (isNull(recurseTimes)) {
28622 str = formatValue(ctx, desc.value, null);
28624 str = formatValue(ctx, desc.value, recurseTimes - 1);
28626 if (str.indexOf('\n') > -1) {
28628 str = str.split('\n').map(function(line) {
28630 }).join('\n').substr(2);
28632 str = '\n' + str.split('\n').map(function(line) {
28638 str = ctx.stylize('[Circular]', 'special');
28641 if (isUndefined(name)) {
28642 if (array && key.match(/^\d+$/)) {
28645 name = JSON.stringify('' + key);
28646 if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
28647 name = name.substr(1, name.length - 2);
28648 name = ctx.stylize(name, 'name');
28650 name = name.replace(/'/g, "\\'")
28651 .replace(/\\"/g, '"')
28652 .replace(/(^"|"$)/g, "'");
28653 name = ctx.stylize(name, 'string');
28657 return name + ': ' + str;
28661 function reduceToSingleString(output, base, braces) {
28662 var numLinesEst = 0;
28663 var length = output.reduce(function(prev, cur) {
28665 if (cur.indexOf('\n') >= 0) numLinesEst++;
28666 return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
28671 (base === '' ? '' : base + '\n ') +
28673 output.join(',\n ') +
28678 return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
28682 // NOTE: These type checking functions intentionally don't use `instanceof`
28683 // because it is fragile and can be easily faked with `Object.create()`.
28684 function isArray(ar) {
28685 return Array.isArray(ar);
28687 exports.isArray = isArray;
28689 function isBoolean(arg) {
28690 return typeof arg === 'boolean';
28692 exports.isBoolean = isBoolean;
28694 function isNull(arg) {
28695 return arg === null;
28697 exports.isNull = isNull;
28699 function isNullOrUndefined(arg) {
28700 return arg == null;
28702 exports.isNullOrUndefined = isNullOrUndefined;
28704 function isNumber(arg) {
28705 return typeof arg === 'number';
28707 exports.isNumber = isNumber;
28709 function isString(arg) {
28710 return typeof arg === 'string';
28712 exports.isString = isString;
28714 function isSymbol(arg) {
28715 return typeof arg === 'symbol';
28717 exports.isSymbol = isSymbol;
28719 function isUndefined(arg) {
28720 return arg === void 0;
28722 exports.isUndefined = isUndefined;
28724 function isRegExp(re) {
28725 return isObject(re) && objectToString(re) === '[object RegExp]';
28727 exports.isRegExp = isRegExp;
28729 function isObject(arg) {
28730 return typeof arg === 'object' && arg !== null;
28732 exports.isObject = isObject;
28734 function isDate(d) {
28735 return isObject(d) && objectToString(d) === '[object Date]';
28737 exports.isDate = isDate;
28739 function isError(e) {
28740 return isObject(e) &&
28741 (objectToString(e) === '[object Error]' || e instanceof Error);
28743 exports.isError = isError;
28745 function isFunction(arg) {
28746 return typeof arg === 'function';
28748 exports.isFunction = isFunction;
28750 function isPrimitive(arg) {
28751 return arg === null ||
28752 typeof arg === 'boolean' ||
28753 typeof arg === 'number' ||
28754 typeof arg === 'string' ||
28755 typeof arg === 'symbol' || // ES6 symbol
28756 typeof arg === 'undefined';
28758 exports.isPrimitive = isPrimitive;
28760 exports.isBuffer = __webpack_require__(61);
28762 function objectToString(o) {
28763 return Object.prototype.toString.call(o);
28768 return n < 10 ? '0' + n.toString(10) : n.toString(10);
28772 var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
28773 'Oct', 'Nov', 'Dec'];
28776 function timestamp() {
28777 var d = new Date();
28778 var time = [pad(d.getHours()),
28779 pad(d.getMinutes()),
28780 pad(d.getSeconds())].join(':');
28781 return [d.getDate(), months[d.getMonth()], time].join(' ');
28785 // log is just a thin wrapper to console.log that prepends a timestamp
28786 exports.log = function() {
28787 console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
28792 * Inherit the prototype methods from one constructor into another.
28794 * The Function.prototype.inherits from lang.js rewritten as a standalone
28795 * function (not on Function.prototype). NOTE: If this file is to be loaded
28796 * during bootstrapping this function needs to be rewritten using some native
28797 * functions as prototype setup using normal JavaScript does not work as
28798 * expected during bootstrapping (see mirror.js in r114903).
28800 * @param {function} ctor Constructor function which needs to inherit the
28802 * @param {function} superCtor Constructor function to inherit prototype from.
28804 exports.inherits = __webpack_require__(62);
28806 exports._extend = function(origin, add) {
28807 // Don't do anything if add isn't an object
28808 if (!add || !isObject(add)) return origin;
28810 var keys = Object.keys(add);
28811 var i = keys.length;
28813 origin[keys[i]] = add[keys[i]];
28818 function hasOwnProperty(obj, prop) {
28819 return Object.prototype.hasOwnProperty.call(obj, prop);
28822 /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()), __webpack_require__(30)))
28826 /***/ function(module, exports) {
28828 module.exports = function isBuffer(arg) {
28829 return arg && typeof arg === 'object'
28830 && typeof arg.copy === 'function'
28831 && typeof arg.fill === 'function'
28832 && typeof arg.readUInt8 === 'function';
28837 /***/ function(module, exports) {
28839 if (typeof Object.create === 'function') {
28840 // implementation from standard node.js 'util' module
28841 module.exports = function inherits(ctor, superCtor) {
28842 ctor.super_ = superCtor
28843 ctor.prototype = Object.create(superCtor.prototype, {
28853 // old school shim for old browsers
28854 module.exports = function inherits(ctor, superCtor) {
28855 ctor.super_ = superCtor
28856 var TempCtor = function () {}
28857 TempCtor.prototype = superCtor.prototype
28858 ctor.prototype = new TempCtor()
28859 ctor.prototype.constructor = ctor
28866 /***/ function(module, exports, __webpack_require__) {
28868 // http://wiki.commonjs.org/wiki/Unit_Testing/1.0
28870 // THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8!
28872 // Originally from narwhal.js (http://narwhaljs.org)
28873 // Copyright (c) 2009 Thomas Robinson <280north.com>
28875 // Permission is hereby granted, free of charge, to any person obtaining a copy
28876 // of this software and associated documentation files (the 'Software'), to
28877 // deal in the Software without restriction, including without limitation the
28878 // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
28879 // sell copies of the Software, and to permit persons to whom the Software is
28880 // furnished to do so, subject to the following conditions:
28882 // The above copyright notice and this permission notice shall be included in
28883 // all copies or substantial portions of the Software.
28885 // THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
28886 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
28887 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
28888 // AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
28889 // ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
28890 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
28892 // when used in node, this will actually load the util module we depend on
28893 // versus loading the builtin util module as happens otherwise
28894 // this is a bug in node module loading as far as I am concerned
28895 var util = __webpack_require__(60);
28897 var pSlice = Array.prototype.slice;
28898 var hasOwn = Object.prototype.hasOwnProperty;
28900 // 1. The assert module provides functions that throw
28901 // AssertionError's when particular conditions are not met. The
28902 // assert module must conform to the following interface.
28904 var assert = module.exports = ok;
28906 // 2. The AssertionError is defined in assert.
28907 // new assert.AssertionError({ message: message,
28909 // expected: expected })
28911 assert.AssertionError = function AssertionError(options) {
28912 this.name = 'AssertionError';
28913 this.actual = options.actual;
28914 this.expected = options.expected;
28915 this.operator = options.operator;
28916 if (options.message) {
28917 this.message = options.message;
28918 this.generatedMessage = false;
28920 this.message = getMessage(this);
28921 this.generatedMessage = true;
28923 var stackStartFunction = options.stackStartFunction || fail;
28925 if (Error.captureStackTrace) {
28926 Error.captureStackTrace(this, stackStartFunction);
28929 // non v8 browsers so we can have a stacktrace
28930 var err = new Error();
28932 var out = err.stack;
28934 // try to strip useless frames
28935 var fn_name = stackStartFunction.name;
28936 var idx = out.indexOf('\n' + fn_name);
28938 // once we have located the function frame
28939 // we need to strip out everything before it (and its line)
28940 var next_line = out.indexOf('\n', idx + 1);
28941 out = out.substring(next_line + 1);
28949 // assert.AssertionError instanceof Error
28950 util.inherits(assert.AssertionError, Error);
28952 function replacer(key, value) {
28953 if (util.isUndefined(value)) {
28956 if (util.isNumber(value) && !isFinite(value)) {
28957 return value.toString();
28959 if (util.isFunction(value) || util.isRegExp(value)) {
28960 return value.toString();
28965 function truncate(s, n) {
28966 if (util.isString(s)) {
28967 return s.length < n ? s : s.slice(0, n);
28973 function getMessage(self) {
28974 return truncate(JSON.stringify(self.actual, replacer), 128) + ' ' +
28975 self.operator + ' ' +
28976 truncate(JSON.stringify(self.expected, replacer), 128);
28979 // At present only the three keys mentioned above are used and
28980 // understood by the spec. Implementations or sub modules can pass
28981 // other keys to the AssertionError's constructor - they will be
28984 // 3. All of the following functions must throw an AssertionError
28985 // when a corresponding condition is not met, with a message that
28986 // may be undefined if not provided. All assertion methods provide
28987 // both the actual and expected values to the assertion error for
28988 // display purposes.
28990 function fail(actual, expected, message, operator, stackStartFunction) {
28991 throw new assert.AssertionError({
28994 expected: expected,
28995 operator: operator,
28996 stackStartFunction: stackStartFunction
29000 // EXTENSION! allows for well behaved errors defined elsewhere.
29001 assert.fail = fail;
29003 // 4. Pure assertion tests whether a value is truthy, as determined
29005 // assert.ok(guard, message_opt);
29006 // This statement is equivalent to assert.equal(true, !!guard,
29007 // message_opt);. To test strictly for the value true, use
29008 // assert.strictEqual(true, guard, message_opt);.
29010 function ok(value, message) {
29011 if (!value) fail(value, true, message, '==', assert.ok);
29015 // 5. The equality assertion tests shallow, coercive equality with
29017 // assert.equal(actual, expected, message_opt);
29019 assert.equal = function equal(actual, expected, message) {
29020 if (actual != expected) fail(actual, expected, message, '==', assert.equal);
29023 // 6. The non-equality assertion tests for whether two objects are not equal
29024 // with != assert.notEqual(actual, expected, message_opt);
29026 assert.notEqual = function notEqual(actual, expected, message) {
29027 if (actual == expected) {
29028 fail(actual, expected, message, '!=', assert.notEqual);
29032 // 7. The equivalence assertion tests a deep equality relation.
29033 // assert.deepEqual(actual, expected, message_opt);
29035 assert.deepEqual = function deepEqual(actual, expected, message) {
29036 if (!_deepEqual(actual, expected)) {
29037 fail(actual, expected, message, 'deepEqual', assert.deepEqual);
29041 function _deepEqual(actual, expected) {
29042 // 7.1. All identical values are equivalent, as determined by ===.
29043 if (actual === expected) {
29046 } else if (util.isBuffer(actual) && util.isBuffer(expected)) {
29047 if (actual.length != expected.length) return false;
29049 for (var i = 0; i < actual.length; i++) {
29050 if (actual[i] !== expected[i]) return false;
29055 // 7.2. If the expected value is a Date object, the actual value is
29056 // equivalent if it is also a Date object that refers to the same time.
29057 } else if (util.isDate(actual) && util.isDate(expected)) {
29058 return actual.getTime() === expected.getTime();
29060 // 7.3 If the expected value is a RegExp object, the actual value is
29061 // equivalent if it is also a RegExp object with the same source and
29062 // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`).
29063 } else if (util.isRegExp(actual) && util.isRegExp(expected)) {
29064 return actual.source === expected.source &&
29065 actual.global === expected.global &&
29066 actual.multiline === expected.multiline &&
29067 actual.lastIndex === expected.lastIndex &&
29068 actual.ignoreCase === expected.ignoreCase;
29070 // 7.4. Other pairs that do not both pass typeof value == 'object',
29071 // equivalence is determined by ==.
29072 } else if (!util.isObject(actual) && !util.isObject(expected)) {
29073 return actual == expected;
29075 // 7.5 For all other Object pairs, including Array objects, equivalence is
29076 // determined by having the same number of owned properties (as verified
29077 // with Object.prototype.hasOwnProperty.call), the same set of keys
29078 // (although not necessarily the same order), equivalent values for every
29079 // corresponding key, and an identical 'prototype' property. Note: this
29080 // accounts for both named and indexed properties on Arrays.
29082 return objEquiv(actual, expected);
29086 function isArguments(object) {
29087 return Object.prototype.toString.call(object) == '[object Arguments]';
29090 function objEquiv(a, b) {
29091 if (util.isNullOrUndefined(a) || util.isNullOrUndefined(b))
29093 // an identical 'prototype' property.
29094 if (a.prototype !== b.prototype) return false;
29095 // if one is a primitive, the other must be same
29096 if (util.isPrimitive(a) || util.isPrimitive(b)) {
29099 var aIsArgs = isArguments(a),
29100 bIsArgs = isArguments(b);
29101 if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs))
29104 a = pSlice.call(a);
29105 b = pSlice.call(b);
29106 return _deepEqual(a, b);
29108 var ka = objectKeys(a),
29109 kb = objectKeys(b),
29111 // having the same number of owned properties (keys incorporates
29113 if (ka.length != kb.length)
29115 //the same set of keys (although not necessarily the same order),
29118 //~~~cheap key test
29119 for (i = ka.length - 1; i >= 0; i--) {
29120 if (ka[i] != kb[i])
29123 //equivalent values for every corresponding key, and
29124 //~~~possibly expensive deep test
29125 for (i = ka.length - 1; i >= 0; i--) {
29127 if (!_deepEqual(a[key], b[key])) return false;
29132 // 8. The non-equivalence assertion tests for any deep inequality.
29133 // assert.notDeepEqual(actual, expected, message_opt);
29135 assert.notDeepEqual = function notDeepEqual(actual, expected, message) {
29136 if (_deepEqual(actual, expected)) {
29137 fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual);
29141 // 9. The strict equality assertion tests strict equality, as determined by ===.
29142 // assert.strictEqual(actual, expected, message_opt);
29144 assert.strictEqual = function strictEqual(actual, expected, message) {
29145 if (actual !== expected) {
29146 fail(actual, expected, message, '===', assert.strictEqual);
29150 // 10. The strict non-equality assertion tests for strict inequality, as
29151 // determined by !==. assert.notStrictEqual(actual, expected, message_opt);
29153 assert.notStrictEqual = function notStrictEqual(actual, expected, message) {
29154 if (actual === expected) {
29155 fail(actual, expected, message, '!==', assert.notStrictEqual);
29159 function expectedException(actual, expected) {
29160 if (!actual || !expected) {
29164 if (Object.prototype.toString.call(expected) == '[object RegExp]') {
29165 return expected.test(actual);
29166 } else if (actual instanceof expected) {
29168 } else if (expected.call({}, actual) === true) {
29175 function _throws(shouldThrow, block, expected, message) {
29178 if (util.isString(expected)) {
29179 message = expected;
29189 message = (expected && expected.name ? ' (' + expected.name + ').' : '.') +
29190 (message ? ' ' + message : '.');
29192 if (shouldThrow && !actual) {
29193 fail(actual, expected, 'Missing expected exception' + message);
29196 if (!shouldThrow && expectedException(actual, expected)) {
29197 fail(actual, expected, 'Got unwanted exception' + message);
29200 if ((shouldThrow && actual && expected &&
29201 !expectedException(actual, expected)) || (!shouldThrow && actual)) {
29206 // 11. Expected to throw an error:
29207 // assert.throws(block, Error_opt, message_opt);
29209 assert.throws = function(block, /*optional*/error, /*optional*/message) {
29210 _throws.apply(this, [true].concat(pSlice.call(arguments)));
29213 // EXTENSION! This is annoying to write outside this module.
29214 assert.doesNotThrow = function(block, /*optional*/message) {
29215 _throws.apply(this, [false].concat(pSlice.call(arguments)));
29218 assert.ifError = function(err) { if (err) {throw err;}};
29220 var objectKeys = Object.keys || function (obj) {
29222 for (var key in obj) {
29223 if (hasOwn.call(obj, key)) keys.push(key);
29231 /***/ function(module, exports) {
29233 // Generated by CoffeeScript 1.7.1
29236 PDFPage - represents a single page in the PDF document
29243 PDFPage = (function() {
29244 var DEFAULT_MARGINS, SIZES;
29246 function PDFPage(document, options) {
29248 this.document = document;
29249 if (options == null) {
29252 this.size = options.size || 'letter';
29253 this.layout = options.layout || 'portrait';
29254 if (typeof options.margin === 'number') {
29256 top: options.margin,
29257 left: options.margin,
29258 bottom: options.margin,
29259 right: options.margin
29262 this.margins = options.margins || DEFAULT_MARGINS;
29264 dimensions = Array.isArray(this.size) ? this.size : SIZES[this.size.toUpperCase()];
29265 this.width = dimensions[this.layout === 'portrait' ? 0 : 1];
29266 this.height = dimensions[this.layout === 'portrait' ? 1 : 0];
29267 this.content = this.document.ref();
29268 this.resources = this.document.ref({
29269 ProcSet: ['PDF', 'Text', 'ImageB', 'ImageC', 'ImageI']
29271 Object.defineProperties(this, {
29273 get: (function(_this) {
29274 return function() {
29276 return (_base = _this.resources.data).Font != null ? _base.Font : _base.Font = {};
29281 get: (function(_this) {
29282 return function() {
29284 return (_base = _this.resources.data).XObject != null ? _base.XObject : _base.XObject = {};
29289 get: (function(_this) {
29290 return function() {
29292 return (_base = _this.resources.data).ExtGState != null ? _base.ExtGState : _base.ExtGState = {};
29297 get: (function(_this) {
29298 return function() {
29300 return (_base = _this.resources.data).Pattern != null ? _base.Pattern : _base.Pattern = {};
29305 get: (function(_this) {
29306 return function() {
29308 return (_base = _this.dictionary.data).Annots != null ? _base.Annots : _base.Annots = [];
29313 this.dictionary = this.document.ref({
29315 Parent: this.document._root.data.Pages,
29316 MediaBox: [0, 0, this.width, this.height],
29317 Contents: this.content,
29318 Resources: this.resources
29322 PDFPage.prototype.maxY = function() {
29323 return this.height - this.margins.bottom;
29326 PDFPage.prototype.write = function(chunk) {
29327 return this.content.write(chunk);
29330 PDFPage.prototype.end = function() {
29331 this.dictionary.end();
29332 this.resources.end();
29333 return this.content.end();
29336 DEFAULT_MARGINS = {
29344 '4A0': [4767.87, 6740.79],
29345 '2A0': [3370.39, 4767.87],
29346 A0: [2383.94, 3370.39],
29347 A1: [1683.78, 2383.94],
29348 A2: [1190.55, 1683.78],
29349 A3: [841.89, 1190.55],
29350 A4: [595.28, 841.89],
29351 A5: [419.53, 595.28],
29352 A6: [297.64, 419.53],
29353 A7: [209.76, 297.64],
29354 A8: [147.40, 209.76],
29355 A9: [104.88, 147.40],
29356 A10: [73.70, 104.88],
29357 B0: [2834.65, 4008.19],
29358 B1: [2004.09, 2834.65],
29359 B2: [1417.32, 2004.09],
29360 B3: [1000.63, 1417.32],
29361 B4: [708.66, 1000.63],
29362 B5: [498.90, 708.66],
29363 B6: [354.33, 498.90],
29364 B7: [249.45, 354.33],
29365 B8: [175.75, 249.45],
29366 B9: [124.72, 175.75],
29367 B10: [87.87, 124.72],
29368 C0: [2599.37, 3676.54],
29369 C1: [1836.85, 2599.37],
29370 C2: [1298.27, 1836.85],
29371 C3: [918.43, 1298.27],
29372 C4: [649.13, 918.43],
29373 C5: [459.21, 649.13],
29374 C6: [323.15, 459.21],
29375 C7: [229.61, 323.15],
29376 C8: [161.57, 229.61],
29377 C9: [113.39, 161.57],
29378 C10: [79.37, 113.39],
29379 RA0: [2437.80, 3458.27],
29380 RA1: [1729.13, 2437.80],
29381 RA2: [1218.90, 1729.13],
29382 RA3: [864.57, 1218.90],
29383 RA4: [609.45, 864.57],
29384 SRA0: [2551.18, 3628.35],
29385 SRA1: [1814.17, 2551.18],
29386 SRA2: [1275.59, 1814.17],
29387 SRA3: [907.09, 1275.59],
29388 SRA4: [637.80, 907.09],
29389 EXECUTIVE: [521.86, 756.00],
29390 FOLIO: [612.00, 936.00],
29391 LEGAL: [612.00, 1008.00],
29392 LETTER: [612.00, 792.00],
29393 TABLOID: [792.00, 1224.00]
29400 module.exports = PDFPage;
29407 /***/ function(module, exports, __webpack_require__) {
29409 // Generated by CoffeeScript 1.7.1
29411 var PDFGradient, PDFLinearGradient, PDFRadialGradient, namedColors, _ref;
29413 _ref = __webpack_require__(66), PDFGradient = _ref.PDFGradient, PDFLinearGradient = _ref.PDFLinearGradient, PDFRadialGradient = _ref.PDFRadialGradient;
29416 initColor: function() {
29417 this._opacityRegistry = {};
29418 this._opacityCount = 0;
29419 return this._gradCount = 0;
29421 _normalizeColor: function(color) {
29423 if (color instanceof PDFGradient) {
29426 if (typeof color === 'string') {
29427 if (color.charAt(0) === '#') {
29428 if (color.length === 4) {
29429 color = color.replace(/#([0-9A-F])([0-9A-F])([0-9A-F])/i, "#$1$1$2$2$3$3");
29431 hex = parseInt(color.slice(1), 16);
29432 color = [hex >> 16, hex >> 8 & 0xff, hex & 0xff];
29433 } else if (namedColors[color]) {
29434 color = namedColors[color];
29437 if (Array.isArray(color)) {
29438 if (color.length === 3) {
29439 color = (function() {
29440 var _i, _len, _results;
29442 for (_i = 0, _len = color.length; _i < _len; _i++) {
29444 _results.push(part / 255);
29448 } else if (color.length === 4) {
29449 color = (function() {
29450 var _i, _len, _results;
29452 for (_i = 0, _len = color.length; _i < _len; _i++) {
29454 _results.push(part / 100);
29463 _setColor: function(color, stroke) {
29464 var gstate, name, op, space;
29465 color = this._normalizeColor(color);
29469 if (this._sMasked) {
29470 gstate = this.ref({
29475 name = "Gs" + (++this._opacityCount);
29476 this.page.ext_gstates[name] = gstate;
29477 this.addContent("/" + name + " gs");
29478 this._sMasked = false;
29480 op = stroke ? 'SCN' : 'scn';
29481 if (color instanceof PDFGradient) {
29482 this._setColorSpace('Pattern', stroke);
29485 space = color.length === 4 ? 'DeviceCMYK' : 'DeviceRGB';
29486 this._setColorSpace(space, stroke);
29487 color = color.join(' ');
29488 this.addContent("" + color + " " + op);
29492 _setColorSpace: function(space, stroke) {
29494 op = stroke ? 'CS' : 'cs';
29495 return this.addContent("/" + space + " " + op);
29497 fillColor: function(color, opacity) {
29499 if (opacity == null) {
29502 set = this._setColor(color, false);
29504 this.fillOpacity(opacity);
29506 this._fillColor = [color, opacity];
29509 strokeColor: function(color, opacity) {
29511 if (opacity == null) {
29514 set = this._setColor(color, true);
29516 this.strokeOpacity(opacity);
29520 opacity: function(opacity) {
29521 this._doOpacity(opacity, opacity);
29524 fillOpacity: function(opacity) {
29525 this._doOpacity(opacity, null);
29528 strokeOpacity: function(opacity) {
29529 this._doOpacity(null, opacity);
29532 _doOpacity: function(fillOpacity, strokeOpacity) {
29533 var dictionary, id, key, name, _ref1;
29534 if (!((fillOpacity != null) || (strokeOpacity != null))) {
29537 if (fillOpacity != null) {
29538 fillOpacity = Math.max(0, Math.min(1, fillOpacity));
29540 if (strokeOpacity != null) {
29541 strokeOpacity = Math.max(0, Math.min(1, strokeOpacity));
29543 key = "" + fillOpacity + "_" + strokeOpacity;
29544 if (this._opacityRegistry[key]) {
29545 _ref1 = this._opacityRegistry[key], dictionary = _ref1[0], name = _ref1[1];
29550 if (fillOpacity != null) {
29551 dictionary.ca = fillOpacity;
29553 if (strokeOpacity != null) {
29554 dictionary.CA = strokeOpacity;
29556 dictionary = this.ref(dictionary);
29558 id = ++this._opacityCount;
29560 this._opacityRegistry[key] = [dictionary, name];
29562 this.page.ext_gstates[name] = dictionary;
29563 return this.addContent("/" + name + " gs");
29565 linearGradient: function(x1, y1, x2, y2) {
29566 return new PDFLinearGradient(this, x1, y1, x2, y2);
29568 radialGradient: function(x1, y1, r1, x2, y2, r2) {
29569 return new PDFRadialGradient(this, x1, y1, r1, x2, y2, r2);
29574 aliceblue: [240, 248, 255],
29575 antiquewhite: [250, 235, 215],
29576 aqua: [0, 255, 255],
29577 aquamarine: [127, 255, 212],
29578 azure: [240, 255, 255],
29579 beige: [245, 245, 220],
29580 bisque: [255, 228, 196],
29582 blanchedalmond: [255, 235, 205],
29584 blueviolet: [138, 43, 226],
29585 brown: [165, 42, 42],
29586 burlywood: [222, 184, 135],
29587 cadetblue: [95, 158, 160],
29588 chartreuse: [127, 255, 0],
29589 chocolate: [210, 105, 30],
29590 coral: [255, 127, 80],
29591 cornflowerblue: [100, 149, 237],
29592 cornsilk: [255, 248, 220],
29593 crimson: [220, 20, 60],
29594 cyan: [0, 255, 255],
29595 darkblue: [0, 0, 139],
29596 darkcyan: [0, 139, 139],
29597 darkgoldenrod: [184, 134, 11],
29598 darkgray: [169, 169, 169],
29599 darkgreen: [0, 100, 0],
29600 darkgrey: [169, 169, 169],
29601 darkkhaki: [189, 183, 107],
29602 darkmagenta: [139, 0, 139],
29603 darkolivegreen: [85, 107, 47],
29604 darkorange: [255, 140, 0],
29605 darkorchid: [153, 50, 204],
29606 darkred: [139, 0, 0],
29607 darksalmon: [233, 150, 122],
29608 darkseagreen: [143, 188, 143],
29609 darkslateblue: [72, 61, 139],
29610 darkslategray: [47, 79, 79],
29611 darkslategrey: [47, 79, 79],
29612 darkturquoise: [0, 206, 209],
29613 darkviolet: [148, 0, 211],
29614 deeppink: [255, 20, 147],
29615 deepskyblue: [0, 191, 255],
29616 dimgray: [105, 105, 105],
29617 dimgrey: [105, 105, 105],
29618 dodgerblue: [30, 144, 255],
29619 firebrick: [178, 34, 34],
29620 floralwhite: [255, 250, 240],
29621 forestgreen: [34, 139, 34],
29622 fuchsia: [255, 0, 255],
29623 gainsboro: [220, 220, 220],
29624 ghostwhite: [248, 248, 255],
29625 gold: [255, 215, 0],
29626 goldenrod: [218, 165, 32],
29627 gray: [128, 128, 128],
29628 grey: [128, 128, 128],
29629 green: [0, 128, 0],
29630 greenyellow: [173, 255, 47],
29631 honeydew: [240, 255, 240],
29632 hotpink: [255, 105, 180],
29633 indianred: [205, 92, 92],
29634 indigo: [75, 0, 130],
29635 ivory: [255, 255, 240],
29636 khaki: [240, 230, 140],
29637 lavender: [230, 230, 250],
29638 lavenderblush: [255, 240, 245],
29639 lawngreen: [124, 252, 0],
29640 lemonchiffon: [255, 250, 205],
29641 lightblue: [173, 216, 230],
29642 lightcoral: [240, 128, 128],
29643 lightcyan: [224, 255, 255],
29644 lightgoldenrodyellow: [250, 250, 210],
29645 lightgray: [211, 211, 211],
29646 lightgreen: [144, 238, 144],
29647 lightgrey: [211, 211, 211],
29648 lightpink: [255, 182, 193],
29649 lightsalmon: [255, 160, 122],
29650 lightseagreen: [32, 178, 170],
29651 lightskyblue: [135, 206, 250],
29652 lightslategray: [119, 136, 153],
29653 lightslategrey: [119, 136, 153],
29654 lightsteelblue: [176, 196, 222],
29655 lightyellow: [255, 255, 224],
29657 limegreen: [50, 205, 50],
29658 linen: [250, 240, 230],
29659 magenta: [255, 0, 255],
29660 maroon: [128, 0, 0],
29661 mediumaquamarine: [102, 205, 170],
29662 mediumblue: [0, 0, 205],
29663 mediumorchid: [186, 85, 211],
29664 mediumpurple: [147, 112, 219],
29665 mediumseagreen: [60, 179, 113],
29666 mediumslateblue: [123, 104, 238],
29667 mediumspringgreen: [0, 250, 154],
29668 mediumturquoise: [72, 209, 204],
29669 mediumvioletred: [199, 21, 133],
29670 midnightblue: [25, 25, 112],
29671 mintcream: [245, 255, 250],
29672 mistyrose: [255, 228, 225],
29673 moccasin: [255, 228, 181],
29674 navajowhite: [255, 222, 173],
29676 oldlace: [253, 245, 230],
29677 olive: [128, 128, 0],
29678 olivedrab: [107, 142, 35],
29679 orange: [255, 165, 0],
29680 orangered: [255, 69, 0],
29681 orchid: [218, 112, 214],
29682 palegoldenrod: [238, 232, 170],
29683 palegreen: [152, 251, 152],
29684 paleturquoise: [175, 238, 238],
29685 palevioletred: [219, 112, 147],
29686 papayawhip: [255, 239, 213],
29687 peachpuff: [255, 218, 185],
29688 peru: [205, 133, 63],
29689 pink: [255, 192, 203],
29690 plum: [221, 160, 221],
29691 powderblue: [176, 224, 230],
29692 purple: [128, 0, 128],
29694 rosybrown: [188, 143, 143],
29695 royalblue: [65, 105, 225],
29696 saddlebrown: [139, 69, 19],
29697 salmon: [250, 128, 114],
29698 sandybrown: [244, 164, 96],
29699 seagreen: [46, 139, 87],
29700 seashell: [255, 245, 238],
29701 sienna: [160, 82, 45],
29702 silver: [192, 192, 192],
29703 skyblue: [135, 206, 235],
29704 slateblue: [106, 90, 205],
29705 slategray: [112, 128, 144],
29706 slategrey: [112, 128, 144],
29707 snow: [255, 250, 250],
29708 springgreen: [0, 255, 127],
29709 steelblue: [70, 130, 180],
29710 tan: [210, 180, 140],
29711 teal: [0, 128, 128],
29712 thistle: [216, 191, 216],
29713 tomato: [255, 99, 71],
29714 turquoise: [64, 224, 208],
29715 violet: [238, 130, 238],
29716 wheat: [245, 222, 179],
29717 white: [255, 255, 255],
29718 whitesmoke: [245, 245, 245],
29719 yellow: [255, 255, 0],
29720 yellowgreen: [154, 205, 50]
29728 /***/ function(module, exports) {
29730 // Generated by CoffeeScript 1.7.1
29732 var PDFGradient, PDFLinearGradient, PDFRadialGradient,
29733 __hasProp = {}.hasOwnProperty,
29734 __extends = 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; };
29736 PDFGradient = (function() {
29737 function PDFGradient(doc) {
29740 this.embedded = false;
29741 this.transform = [1, 0, 0, 1, 0, 0];
29742 this._colorSpace = 'DeviceRGB';
29745 PDFGradient.prototype.stop = function(pos, color, opacity) {
29746 if (opacity == null) {
29749 opacity = Math.max(0, Math.min(1, opacity));
29750 this.stops.push([pos, this.doc._normalizeColor(color), opacity]);
29754 PDFGradient.prototype.embed = function() {
29755 var bounds, dx, dy, encode, fn, form, grad, group, gstate, i, last, m, m0, m1, m11, m12, m2, m21, m22, m3, m4, m5, name, pattern, resources, sMask, shader, stop, stops, v, _i, _j, _len, _ref, _ref1, _ref2;
29756 if (this.embedded || this.stops.length === 0) {
29759 this.embedded = true;
29760 last = this.stops[this.stops.length - 1];
29762 this.stops.push([1, last[1], last[2]]);
29767 for (i = _i = 0, _ref = this.stops.length - 1; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) {
29769 if (i + 2 !== this.stops.length) {
29770 bounds.push(this.stops[i + 1][0]);
29772 fn = this.doc.ref({
29775 C0: this.stops[i + 0][1],
29776 C1: this.stops[i + 1][1],
29782 if (stops.length === 1) {
29785 fn = this.doc.ref({
29794 this.id = 'Sh' + (++this.doc._gradCount);
29795 m = this.doc._ctm.slice();
29796 m0 = m[0], m1 = m[1], m2 = m[2], m3 = m[3], m4 = m[4], m5 = m[5];
29797 _ref1 = this.transform, m11 = _ref1[0], m12 = _ref1[1], m21 = _ref1[2], m22 = _ref1[3], dx = _ref1[4], dy = _ref1[5];
29798 m[0] = m0 * m11 + m2 * m12;
29799 m[1] = m1 * m11 + m3 * m12;
29800 m[2] = m0 * m21 + m2 * m22;
29801 m[3] = m1 * m21 + m3 * m22;
29802 m[4] = m0 * dx + m2 * dy + m4;
29803 m[5] = m1 * dx + m3 * dy + m5;
29804 shader = this.shader(fn);
29806 pattern = this.doc.ref({
29810 Matrix: (function() {
29811 var _j, _len, _results;
29813 for (_j = 0, _len = m.length; _j < _len; _j++) {
29815 _results.push(+v.toFixed(5));
29820 this.doc.page.patterns[this.id] = pattern;
29822 if (this.stops.some(function(stop) {
29823 return stop[2] < 1;
29825 grad = this.opacityGradient();
29826 grad._colorSpace = 'DeviceGray';
29827 _ref2 = this.stops;
29828 for (_j = 0, _len = _ref2.length; _j < _len; _j++) {
29830 grad.stop(stop[0], [stop[2]]);
29832 grad = grad.embed();
29833 group = this.doc.ref({
29839 resources = this.doc.ref({
29840 ProcSet: ['PDF', 'Text', 'ImageB', 'ImageC', 'ImageI'],
29842 Sh1: grad.data.Shading
29846 form = this.doc.ref({
29850 BBox: [0, 0, this.doc.page.width, this.doc.page.height],
29852 Resources: resources
29854 form.end("/Sh1 sh");
29855 sMask = this.doc.ref({
29861 gstate = this.doc.ref({
29865 this.opacity_id = ++this.doc._opacityCount;
29866 name = "Gs" + this.opacity_id;
29867 this.doc.page.ext_gstates[name] = gstate;
29873 PDFGradient.prototype.apply = function(op) {
29874 if (!this.embedded) {
29877 this.doc.addContent("/" + this.id + " " + op);
29878 if (this.opacity_id) {
29879 this.doc.addContent("/Gs" + this.opacity_id + " gs");
29880 return this.doc._sMasked = true;
29884 return PDFGradient;
29888 PDFLinearGradient = (function(_super) {
29889 __extends(PDFLinearGradient, _super);
29891 function PDFLinearGradient(doc, x1, y1, x2, y2) {
29897 PDFLinearGradient.__super__.constructor.apply(this, arguments);
29900 PDFLinearGradient.prototype.shader = function(fn) {
29901 return this.doc.ref({
29903 ColorSpace: this._colorSpace,
29904 Coords: [this.x1, this.y1, this.x2, this.y2],
29906 Extend: [true, true]
29910 PDFLinearGradient.prototype.opacityGradient = function() {
29911 return new PDFLinearGradient(this.doc, this.x1, this.y1, this.x2, this.y2);
29914 return PDFLinearGradient;
29918 PDFRadialGradient = (function(_super) {
29919 __extends(PDFRadialGradient, _super);
29921 function PDFRadialGradient(doc, x1, y1, r1, x2, y2, r2) {
29929 PDFRadialGradient.__super__.constructor.apply(this, arguments);
29932 PDFRadialGradient.prototype.shader = function(fn) {
29933 return this.doc.ref({
29935 ColorSpace: this._colorSpace,
29936 Coords: [this.x1, this.y1, this.r1, this.x2, this.y2, this.r2],
29938 Extend: [true, true]
29942 PDFRadialGradient.prototype.opacityGradient = function() {
29943 return new PDFRadialGradient(this.doc, this.x1, this.y1, this.r1, this.x2, this.y2, this.r2);
29946 return PDFRadialGradient;
29951 PDFGradient: PDFGradient,
29952 PDFLinearGradient: PDFLinearGradient,
29953 PDFRadialGradient: PDFRadialGradient
29961 /***/ function(module, exports, __webpack_require__) {
29963 // Generated by CoffeeScript 1.7.1
29965 var KAPPA, SVGPath,
29966 __slice = [].slice;
29968 SVGPath = __webpack_require__(68);
29970 KAPPA = 4.0 * ((Math.sqrt(2) - 1.0) / 3.0);
29973 initVector: function() {
29974 this._ctm = [1, 0, 0, 1, 0, 0];
29975 return this._ctmStack = [];
29978 this._ctmStack.push(this._ctm.slice());
29979 return this.addContent('q');
29981 restore: function() {
29982 this._ctm = this._ctmStack.pop() || [1, 0, 0, 1, 0, 0];
29983 return this.addContent('Q');
29985 closePath: function() {
29986 return this.addContent('h');
29988 lineWidth: function(w) {
29989 return this.addContent("" + w + " w");
29996 lineCap: function(c) {
29997 if (typeof c === 'string') {
29998 c = this._CAP_STYLES[c.toUpperCase()];
30000 return this.addContent("" + c + " J");
30007 lineJoin: function(j) {
30008 if (typeof j === 'string') {
30009 j = this._JOIN_STYLES[j.toUpperCase()];
30011 return this.addContent("" + j + " j");
30013 miterLimit: function(m) {
30014 return this.addContent("" + m + " M");
30016 dash: function(length, options) {
30017 var phase, space, _ref;
30018 if (options == null) {
30021 if (length == null) {
30024 space = (_ref = options.space) != null ? _ref : length;
30025 phase = options.phase || 0;
30026 return this.addContent("[" + length + " " + space + "] " + phase + " d");
30028 undash: function() {
30029 return this.addContent("[] 0 d");
30031 moveTo: function(x, y) {
30032 return this.addContent("" + x + " " + y + " m");
30034 lineTo: function(x, y) {
30035 return this.addContent("" + x + " " + y + " l");
30037 bezierCurveTo: function(cp1x, cp1y, cp2x, cp2y, x, y) {
30038 return this.addContent("" + cp1x + " " + cp1y + " " + cp2x + " " + cp2y + " " + x + " " + y + " c");
30040 quadraticCurveTo: function(cpx, cpy, x, y) {
30041 return this.addContent("" + cpx + " " + cpy + " " + x + " " + y + " v");
30043 rect: function(x, y, w, h) {
30044 return this.addContent("" + x + " " + y + " " + w + " " + h + " re");
30046 roundedRect: function(x, y, w, h, r) {
30050 this.moveTo(x + r, y);
30051 this.lineTo(x + w - r, y);
30052 this.quadraticCurveTo(x + w, y, x + w, y + r);
30053 this.lineTo(x + w, y + h - r);
30054 this.quadraticCurveTo(x + w, y + h, x + w - r, y + h);
30055 this.lineTo(x + r, y + h);
30056 this.quadraticCurveTo(x, y + h, x, y + h - r);
30057 this.lineTo(x, y + r);
30058 return this.quadraticCurveTo(x, y, x + r, y);
30060 ellipse: function(x, y, r1, r2) {
30061 var ox, oy, xe, xm, ye, ym;
30073 this.moveTo(x, ym);
30074 this.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
30075 this.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
30076 this.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
30077 this.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
30078 return this.closePath();
30080 circle: function(x, y, radius) {
30081 return this.ellipse(x, y, radius);
30083 polygon: function() {
30084 var point, points, _i, _len;
30085 points = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
30086 this.moveTo.apply(this, points.shift());
30087 for (_i = 0, _len = points.length; _i < _len; _i++) {
30088 point = points[_i];
30089 this.lineTo.apply(this, point);
30091 return this.closePath();
30093 path: function(path) {
30094 SVGPath.apply(this, path);
30097 _windingRule: function(rule) {
30098 if (/even-?odd/.test(rule)) {
30103 fill: function(color, rule) {
30104 if (/(even-?odd)|(non-?zero)/.test(color)) {
30109 this.fillColor(color);
30111 return this.addContent('f' + this._windingRule(rule));
30113 stroke: function(color) {
30115 this.strokeColor(color);
30117 return this.addContent('S');
30119 fillAndStroke: function(fillColor, strokeColor, rule) {
30121 if (strokeColor == null) {
30122 strokeColor = fillColor;
30124 isFillRule = /(even-?odd)|(non-?zero)/;
30125 if (isFillRule.test(fillColor)) {
30129 if (isFillRule.test(strokeColor)) {
30130 rule = strokeColor;
30131 strokeColor = fillColor;
30134 this.fillColor(fillColor);
30135 this.strokeColor(strokeColor);
30137 return this.addContent('B' + this._windingRule(rule));
30139 clip: function(rule) {
30140 return this.addContent('W' + this._windingRule(rule) + ' n');
30142 transform: function(m11, m12, m21, m22, dx, dy) {
30143 var m, m0, m1, m2, m3, m4, m5, v, values;
30145 m0 = m[0], m1 = m[1], m2 = m[2], m3 = m[3], m4 = m[4], m5 = m[5];
30146 m[0] = m0 * m11 + m2 * m12;
30147 m[1] = m1 * m11 + m3 * m12;
30148 m[2] = m0 * m21 + m2 * m22;
30149 m[3] = m1 * m21 + m3 * m22;
30150 m[4] = m0 * dx + m2 * dy + m4;
30151 m[5] = m1 * dx + m3 * dy + m5;
30152 values = ((function() {
30153 var _i, _len, _ref, _results;
30154 _ref = [m11, m12, m21, m22, dx, dy];
30156 for (_i = 0, _len = _ref.length; _i < _len; _i++) {
30158 _results.push(+v.toFixed(5));
30162 return this.addContent("" + values + " cm");
30164 translate: function(x, y) {
30165 return this.transform(1, 0, 0, 1, x, y);
30167 rotate: function(angle, options) {
30168 var cos, rad, sin, x, x1, y, y1, _ref;
30169 if (options == null) {
30172 rad = angle * Math.PI / 180;
30173 cos = Math.cos(rad);
30174 sin = Math.sin(rad);
30176 if (options.origin != null) {
30177 _ref = options.origin, x = _ref[0], y = _ref[1];
30178 x1 = x * cos - y * sin;
30179 y1 = x * sin + y * cos;
30183 return this.transform(cos, sin, -sin, cos, x, y);
30185 scale: function(xFactor, yFactor, options) {
30187 if (yFactor == null) {
30190 if (options == null) {
30193 if (arguments.length === 2) {
30198 if (options.origin != null) {
30199 _ref = options.origin, x = _ref[0], y = _ref[1];
30203 return this.transform(xFactor, 0, 0, yFactor, x, y);
30212 /***/ function(module, exports) {
30214 // Generated by CoffeeScript 1.7.1
30218 SVGPath = (function() {
30219 var apply, arcToSegments, cx, cy, parameters, parse, px, py, runners, segmentToBezier, solveArc, sx, sy;
30221 function SVGPath() {}
30223 SVGPath.apply = function(doc, path) {
30225 commands = parse(path);
30226 return apply(commands, doc);
30252 parse = function(path) {
30253 var args, c, cmd, curArg, foundDecimal, params, ret, _i, _len;
30257 foundDecimal = false;
30259 for (_i = 0, _len = path.length; _i < _len; _i++) {
30261 if (parameters[c] != null) {
30262 params = parameters[c];
30264 if (curArg.length > 0) {
30265 args[args.length] = +curArg;
30267 ret[ret.length] = {
30273 foundDecimal = false;
30276 } else if ((c === " " || c === ",") || (c === "-" && curArg.length > 0 && curArg[curArg.length - 1] !== 'e') || (c === "." && foundDecimal)) {
30277 if (curArg.length === 0) {
30280 if (args.length === params) {
30281 ret[ret.length] = {
30293 args[args.length] = +curArg;
30295 foundDecimal = c === ".";
30296 curArg = c === '-' || c === '.' ? c : '';
30300 foundDecimal = true;
30304 if (curArg.length > 0) {
30305 if (args.length === params) {
30306 ret[ret.length] = {
30318 args[args.length] = +curArg;
30321 ret[ret.length] = {
30328 cx = cy = px = py = sx = sy = 0;
30330 apply = function(commands, doc) {
30331 var c, i, _i, _len, _name;
30332 cx = cy = px = py = sx = sy = 0;
30333 for (i = _i = 0, _len = commands.length; _i < _len; i = ++_i) {
30335 if (typeof runners[_name = c.cmd] === "function") {
30336 runners[_name](doc, c.args);
30339 return cx = cy = px = py = 0;
30343 M: function(doc, a) {
30349 return doc.moveTo(cx, cy);
30351 m: function(doc, a) {
30357 return doc.moveTo(cx, cy);
30359 C: function(doc, a) {
30364 return doc.bezierCurveTo.apply(doc, a);
30366 c: function(doc, a) {
30367 doc.bezierCurveTo(a[0] + cx, a[1] + cy, a[2] + cx, a[3] + cy, a[4] + cx, a[5] + cy);
30373 S: function(doc, a) {
30378 doc.bezierCurveTo(cx - (px - cx), cy - (py - cy), a[0], a[1], a[2], a[3]);
30384 s: function(doc, a) {
30389 doc.bezierCurveTo(cx - (px - cx), cy - (py - cy), cx + a[0], cy + a[1], cx + a[2], cy + a[3]);
30395 Q: function(doc, a) {
30400 return doc.quadraticCurveTo(a[0], a[1], cx, cy);
30402 q: function(doc, a) {
30403 doc.quadraticCurveTo(a[0] + cx, a[1] + cy, a[2] + cx, a[3] + cy);
30409 T: function(doc, a) {
30414 px = cx - (px - cx);
30415 py = cy - (py - cy);
30417 doc.quadraticCurveTo(px, py, a[0], a[1]);
30418 px = cx - (px - cx);
30419 py = cy - (py - cy);
30423 t: function(doc, a) {
30428 px = cx - (px - cx);
30429 py = cy - (py - cy);
30431 doc.quadraticCurveTo(px, py, cx + a[0], cy + a[1]);
30435 A: function(doc, a) {
30436 solveArc(doc, cx, cy, a);
30440 a: function(doc, a) {
30443 solveArc(doc, cx, cy, a);
30447 L: function(doc, a) {
30451 return doc.lineTo(cx, cy);
30453 l: function(doc, a) {
30457 return doc.lineTo(cx, cy);
30459 H: function(doc, a) {
30462 return doc.lineTo(cx, cy);
30464 h: function(doc, a) {
30467 return doc.lineTo(cx, cy);
30469 V: function(doc, a) {
30472 return doc.lineTo(cx, cy);
30474 v: function(doc, a) {
30477 return doc.lineTo(cx, cy);
30491 solveArc = function(doc, x, y, coords) {
30492 var bez, ex, ey, large, rot, rx, ry, seg, segs, sweep, _i, _len, _results;
30493 rx = coords[0], ry = coords[1], rot = coords[2], large = coords[3], sweep = coords[4], ex = coords[5], ey = coords[6];
30494 segs = arcToSegments(ex, ey, rx, ry, large, sweep, rot, x, y);
30496 for (_i = 0, _len = segs.length; _i < _len; _i++) {
30498 bez = segmentToBezier.apply(null, seg);
30499 _results.push(doc.bezierCurveTo.apply(doc, bez));
30504 arcToSegments = function(x, y, rx, ry, large, sweep, rotateX, ox, oy) {
30505 var a00, a01, a10, a11, cos_th, d, i, pl, result, segments, sfactor, sfactor_sq, sin_th, th, th0, th1, th2, th3, th_arc, x0, x1, xc, y0, y1, yc, _i;
30506 th = rotateX * (Math.PI / 180);
30507 sin_th = Math.sin(th);
30508 cos_th = Math.cos(th);
30511 px = cos_th * (ox - x) * 0.5 + sin_th * (oy - y) * 0.5;
30512 py = cos_th * (oy - y) * 0.5 - sin_th * (ox - x) * 0.5;
30513 pl = (px * px) / (rx * rx) + (py * py) / (ry * ry);
30515 pl = Math.sqrt(pl);
30521 a10 = (-sin_th) / ry;
30523 x0 = a00 * ox + a01 * oy;
30524 y0 = a10 * ox + a11 * oy;
30525 x1 = a00 * x + a01 * y;
30526 y1 = a10 * x + a11 * y;
30527 d = (x1 - x0) * (x1 - x0) + (y1 - y0) * (y1 - y0);
30528 sfactor_sq = 1 / d - 0.25;
30529 if (sfactor_sq < 0) {
30532 sfactor = Math.sqrt(sfactor_sq);
30533 if (sweep === large) {
30534 sfactor = -sfactor;
30536 xc = 0.5 * (x0 + x1) - sfactor * (y1 - y0);
30537 yc = 0.5 * (y0 + y1) + sfactor * (x1 - x0);
30538 th0 = Math.atan2(y0 - yc, x0 - xc);
30539 th1 = Math.atan2(y1 - yc, x1 - xc);
30540 th_arc = th1 - th0;
30541 if (th_arc < 0 && sweep === 1) {
30542 th_arc += 2 * Math.PI;
30543 } else if (th_arc > 0 && sweep === 0) {
30544 th_arc -= 2 * Math.PI;
30546 segments = Math.ceil(Math.abs(th_arc / (Math.PI * 0.5 + 0.001)));
30548 for (i = _i = 0; 0 <= segments ? _i < segments : _i > segments; i = 0 <= segments ? ++_i : --_i) {
30549 th2 = th0 + i * th_arc / segments;
30550 th3 = th0 + (i + 1) * th_arc / segments;
30551 result[i] = [xc, yc, th2, th3, rx, ry, sin_th, cos_th];
30556 segmentToBezier = function(cx, cy, th0, th1, rx, ry, sin_th, cos_th) {
30557 var a00, a01, a10, a11, t, th_half, x1, x2, x3, y1, y2, y3;
30559 a01 = -sin_th * ry;
30562 th_half = 0.5 * (th1 - th0);
30563 t = (8 / 3) * Math.sin(th_half * 0.5) * Math.sin(th_half * 0.5) / Math.sin(th_half);
30564 x1 = cx + Math.cos(th0) - t * Math.sin(th0);
30565 y1 = cy + Math.sin(th0) + t * Math.cos(th0);
30566 x3 = cx + Math.cos(th1);
30567 y3 = cy + Math.sin(th1);
30568 x2 = x3 + t * Math.sin(th1);
30569 y2 = y3 - t * Math.cos(th1);
30570 return [a00 * x1 + a01 * y1, a10 * x1 + a11 * y1, a00 * x2 + a01 * y2, a10 * x2 + a11 * y2, a00 * x3 + a01 * y3, a10 * x3 + a11 * y3];
30577 module.exports = SVGPath;
30584 /***/ function(module, exports, __webpack_require__) {
30586 // Generated by CoffeeScript 1.7.1
30590 PDFFont = __webpack_require__(70);
30593 initFonts: function() {
30594 this._fontFamilies = {};
30595 this._fontCount = 0;
30596 this._fontSize = 12;
30598 this._registeredFonts = {};
30601 font: function(src, family, size) {
30602 var cacheKey, font, id, _ref;
30603 if (typeof family === 'number') {
30607 if (typeof src === 'string' && this._registeredFonts[src]) {
30609 _ref = this._registeredFonts[src], src = _ref.src, family = _ref.family;
30611 cacheKey = family || src;
30612 if (typeof cacheKey !== 'string') {
30616 if (size != null) {
30617 this.fontSize(size);
30619 if (font = this._fontFamilies[cacheKey]) {
30623 id = 'F' + (++this._fontCount);
30624 this._font = new PDFFont(this, src, family, id);
30625 if (font = this._fontFamilies[this._font.name]) {
30630 this._fontFamilies[cacheKey] = this._font;
30632 this._fontFamilies[this._font.name] = this._font;
30635 fontSize: function(_fontSize) {
30636 this._fontSize = _fontSize;
30639 currentLineHeight: function(includeGap) {
30640 if (includeGap == null) {
30641 includeGap = false;
30643 return this._font.lineHeight(this._fontSize, includeGap);
30645 registerFont: function(name, src, family) {
30646 this._registeredFonts[name] = {
30659 /***/ function(module, exports, __webpack_require__) {
30661 /* WEBPACK VAR INJECTION */(function(Buffer, __dirname) {// Generated by CoffeeScript 1.7.1
30664 PDFFont - embeds fonts in PDF documents
30669 var AFMFont, PDFFont, Subset, TTFFont, fs;
30671 TTFFont = __webpack_require__(71);
30673 AFMFont = __webpack_require__(87);
30675 Subset = __webpack_require__(88);
30677 fs = __webpack_require__(44);
30679 PDFFont = (function() {
30680 var STANDARD_FONTS, toUnicodeCmap;
30682 function PDFFont(document, src, family, id) {
30683 this.document = document;
30685 if (typeof src === 'string') {
30686 if (src in STANDARD_FONTS) {
30688 this.font = new AFMFont(STANDARD_FONTS[src]());
30689 this.registerAFM(src);
30691 } else if (/\.(ttf|ttc)$/i.test(src)) {
30692 this.font = TTFFont.open(src, family);
30693 } else if (/\.dfont$/i.test(src)) {
30694 this.font = TTFFont.fromDFont(src, family);
30696 throw new Error('Not a supported font format or standard PDF font.');
30698 } else if (Buffer.isBuffer(src)) {
30699 this.font = TTFFont.fromBuffer(src, family);
30700 } else if (src instanceof Uint8Array) {
30701 this.font = TTFFont.fromBuffer(new Buffer(src), family);
30702 } else if (src instanceof ArrayBuffer) {
30703 this.font = TTFFont.fromBuffer(new Buffer(new Uint8Array(src)), family);
30705 throw new Error('Not a supported font format or standard PDF font.');
30707 this.subset = new Subset(this.font);
30708 this.registerTTF();
30712 "Courier": function() {
30713 return fs.readFileSync(__dirname + "/font/data/Courier.afm", 'utf8');
30715 "Courier-Bold": function() {
30716 return fs.readFileSync(__dirname + "/font/data/Courier-Bold.afm", 'utf8');
30718 "Courier-Oblique": function() {
30719 return fs.readFileSync(__dirname + "/font/data/Courier-Oblique.afm", 'utf8');
30721 "Courier-BoldOblique": function() {
30722 return fs.readFileSync(__dirname + "/font/data/Courier-BoldOblique.afm", 'utf8');
30724 "Helvetica": function() {
30725 return fs.readFileSync(__dirname + "/font/data/Helvetica.afm", 'utf8');
30727 "Helvetica-Bold": function() {
30728 return fs.readFileSync(__dirname + "/font/data/Helvetica-Bold.afm", 'utf8');
30730 "Helvetica-Oblique": function() {
30731 return fs.readFileSync(__dirname + "/font/data/Helvetica-Oblique.afm", 'utf8');
30733 "Helvetica-BoldOblique": function() {
30734 return fs.readFileSync(__dirname + "/font/data/Helvetica-BoldOblique.afm", 'utf8');
30736 "Times-Roman": function() {
30737 return fs.readFileSync(__dirname + "/font/data/Times-Roman.afm", 'utf8');
30739 "Times-Bold": function() {
30740 return fs.readFileSync(__dirname + "/font/data/Times-Bold.afm", 'utf8');
30742 "Times-Italic": function() {
30743 return fs.readFileSync(__dirname + "/font/data/Times-Italic.afm", 'utf8');
30745 "Times-BoldItalic": function() {
30746 return fs.readFileSync(__dirname + "/font/data/Times-BoldItalic.afm", 'utf8');
30748 "Symbol": function() {
30749 return fs.readFileSync(__dirname + "/font/data/Symbol.afm", 'utf8');
30751 "ZapfDingbats": function() {
30752 return fs.readFileSync(__dirname + "/font/data/ZapfDingbats.afm", 'utf8');
30756 PDFFont.prototype.use = function(characters) {
30758 return (_ref = this.subset) != null ? _ref.use(characters) : void 0;
30761 PDFFont.prototype.embed = function() {
30762 if (this.embedded || (this.dictionary == null)) {
30770 return this.embedded = true;
30773 PDFFont.prototype.encode = function(text) {
30776 return this.font.encodeText(text);
30778 return ((_ref = this.subset) != null ? _ref.encodeText(text) : void 0) || text;
30782 PDFFont.prototype.ref = function() {
30783 return this.dictionary != null ? this.dictionary : this.dictionary = this.document.ref();
30786 PDFFont.prototype.registerTTF = function() {
30787 var e, hi, low, raw, _ref;
30788 this.name = this.font.name.postscriptName;
30789 this.scaleFactor = 1000.0 / this.font.head.unitsPerEm;
30790 this.bbox = (function() {
30791 var _i, _len, _ref, _results;
30792 _ref = this.font.bbox;
30794 for (_i = 0, _len = _ref.length; _i < _len; _i++) {
30796 _results.push(Math.round(e * this.scaleFactor));
30801 if (this.font.post.exists) {
30802 raw = this.font.post.italic_angle;
30805 if (hi & 0x8000 !== 0) {
30806 hi = -((hi ^ 0xFFFF) + 1);
30808 this.italicAngle = +("" + hi + "." + low);
30810 this.italicAngle = 0;
30812 this.ascender = Math.round(this.font.ascender * this.scaleFactor);
30813 this.decender = Math.round(this.font.decender * this.scaleFactor);
30814 this.lineGap = Math.round(this.font.lineGap * this.scaleFactor);
30815 this.capHeight = (this.font.os2.exists && this.font.os2.capHeight) || this.ascender;
30816 this.xHeight = (this.font.os2.exists && this.font.os2.xHeight) || 0;
30817 this.familyClass = (this.font.os2.exists && this.font.os2.familyClass || 0) >> 8;
30818 this.isSerif = (_ref = this.familyClass) === 1 || _ref === 2 || _ref === 3 || _ref === 4 || _ref === 5 || _ref === 7;
30819 this.isScript = this.familyClass === 10;
30821 if (this.font.post.isFixedPitch) {
30822 this.flags |= 1 << 0;
30824 if (this.isSerif) {
30825 this.flags |= 1 << 1;
30827 if (this.isScript) {
30828 this.flags |= 1 << 3;
30830 if (this.italicAngle !== 0) {
30831 this.flags |= 1 << 6;
30833 this.flags |= 1 << 5;
30834 if (!this.font.cmap.unicode) {
30835 throw new Error('No unicode cmap for font');
30839 PDFFont.prototype.embedTTF = function() {
30840 var charWidths, cmap, code, data, descriptor, firstChar, fontfile, glyph;
30841 data = this.subset.encode();
30842 fontfile = this.document.ref();
30843 fontfile.write(data);
30844 fontfile.data.Length1 = fontfile.uncompressedLength;
30846 descriptor = this.document.ref({
30847 Type: 'FontDescriptor',
30848 FontName: this.subset.postscriptName,
30849 FontFile2: fontfile,
30850 FontBBox: this.bbox,
30853 ItalicAngle: this.italicAngle,
30854 Ascent: this.ascender,
30855 Descent: this.decender,
30856 CapHeight: this.capHeight,
30857 XHeight: this.xHeight
30860 firstChar = +Object.keys(this.subset.cmap)[0];
30861 charWidths = (function() {
30862 var _ref, _results;
30863 _ref = this.subset.cmap;
30865 for (code in _ref) {
30866 glyph = _ref[code];
30867 _results.push(Math.round(this.font.widthOfGlyph(glyph)));
30871 cmap = this.document.ref();
30872 cmap.end(toUnicodeCmap(this.subset.subset));
30873 this.dictionary.data = {
30875 BaseFont: this.subset.postscriptName,
30876 Subtype: 'TrueType',
30877 FontDescriptor: descriptor,
30878 FirstChar: firstChar,
30879 LastChar: firstChar + charWidths.length - 1,
30880 Widths: charWidths,
30881 Encoding: 'MacRomanEncoding',
30884 return this.dictionary.end();
30887 toUnicodeCmap = function(map) {
30888 var code, codes, range, unicode, unicodeMap, _i, _len;
30889 unicodeMap = '/CIDInit /ProcSet findresource begin\n12 dict begin\nbegincmap\n/CIDSystemInfo <<\n /Registry (Adobe)\n /Ordering (UCS)\n /Supplement 0\n>> def\n/CMapName /Adobe-Identity-UCS def\n/CMapType 2 def\n1 begincodespacerange\n<00><ff>\nendcodespacerange';
30890 codes = Object.keys(map).sort(function(a, b) {
30894 for (_i = 0, _len = codes.length; _i < _len; _i++) {
30896 if (range.length >= 100) {
30897 unicodeMap += "\n" + range.length + " beginbfchar\n" + (range.join('\n')) + "\nendbfchar";
30900 unicode = ('0000' + map[code].toString(16)).slice(-4);
30901 code = (+code).toString(16);
30902 range.push("<" + code + "><" + unicode + ">");
30904 if (range.length) {
30905 unicodeMap += "\n" + range.length + " beginbfchar\n" + (range.join('\n')) + "\nendbfchar\n";
30907 return unicodeMap += 'endcmap\nCMapName currentdict /CMap defineresource pop\nend\nend';
30910 PDFFont.prototype.registerAFM = function(name) {
30913 return _ref = this.font, this.ascender = _ref.ascender, this.decender = _ref.decender, this.bbox = _ref.bbox, this.lineGap = _ref.lineGap, _ref;
30916 PDFFont.prototype.embedAFM = function() {
30917 this.dictionary.data = {
30919 BaseFont: this.name,
30921 Encoding: 'WinAnsiEncoding'
30923 return this.dictionary.end();
30926 PDFFont.prototype.widthOfString = function(string, size) {
30927 var charCode, i, scale, width, _i, _ref;
30928 string = '' + string;
30930 for (i = _i = 0, _ref = string.length; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) {
30931 charCode = string.charCodeAt(i);
30932 width += this.font.widthOfGlyph(this.font.characterToGlyph(charCode)) || 0;
30934 scale = size / 1000;
30935 return width * scale;
30938 PDFFont.prototype.lineHeight = function(size, includeGap) {
30940 if (includeGap == null) {
30941 includeGap = false;
30943 gap = includeGap ? this.lineGap : 0;
30944 return (this.ascender + gap - this.decender) / 1000 * size;
30951 module.exports = PDFFont;
30955 /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2).Buffer, "/"))
30959 /***/ function(module, exports, __webpack_require__) {
30961 // Generated by CoffeeScript 1.7.1
30963 var CmapTable, DFont, Data, Directory, GlyfTable, HeadTable, HheaTable, HmtxTable, LocaTable, MaxpTable, NameTable, OS2Table, PostTable, TTFFont, fs;
30965 fs = __webpack_require__(44);
30967 Data = __webpack_require__(72);
30969 DFont = __webpack_require__(73);
30971 Directory = __webpack_require__(74);
30973 NameTable = __webpack_require__(75);
30975 HeadTable = __webpack_require__(78);
30977 CmapTable = __webpack_require__(79);
30979 HmtxTable = __webpack_require__(80);
30981 HheaTable = __webpack_require__(81);
30983 MaxpTable = __webpack_require__(82);
30985 PostTable = __webpack_require__(83);
30987 OS2Table = __webpack_require__(84);
30989 LocaTable = __webpack_require__(85);
30991 GlyfTable = __webpack_require__(86);
30993 TTFFont = (function() {
30994 TTFFont.open = function(filename, name) {
30996 contents = fs.readFileSync(filename);
30997 return new TTFFont(contents, name);
31000 TTFFont.fromDFont = function(filename, family) {
31002 dfont = DFont.open(filename);
31003 return new TTFFont(dfont.getNamedFont(family));
31006 TTFFont.fromBuffer = function(buffer, family) {
31009 ttf = new TTFFont(buffer, family);
31010 if (!(ttf.head.exists && ttf.name.exists && ttf.cmap.exists)) {
31011 dfont = new DFont(buffer);
31012 ttf = new TTFFont(dfont.getNamedFont(family));
31013 if (!(ttf.head.exists && ttf.name.exists && ttf.cmap.exists)) {
31014 throw new Error('Invalid TTF file in DFont');
31020 throw new Error('Unknown font format in buffer: ' + e.message);
31024 function TTFFont(rawData, name) {
31025 var data, i, numFonts, offset, offsets, version, _i, _j, _len;
31026 this.rawData = rawData;
31027 data = this.contents = new Data(this.rawData);
31028 if (data.readString(4) === 'ttcf') {
31030 throw new Error("Must specify a font name for TTC files.");
31032 version = data.readInt();
31033 numFonts = data.readInt();
31035 for (i = _i = 0; 0 <= numFonts ? _i < numFonts : _i > numFonts; i = 0 <= numFonts ? ++_i : --_i) {
31036 offsets[i] = data.readInt();
31038 for (i = _j = 0, _len = offsets.length; _j < _len; i = ++_j) {
31039 offset = offsets[i];
31042 if (this.name.postscriptName === name) {
31046 throw new Error("Font " + name + " not found in TTC file.");
31053 TTFFont.prototype.parse = function() {
31054 this.directory = new Directory(this.contents);
31055 this.head = new HeadTable(this);
31056 this.name = new NameTable(this);
31057 this.cmap = new CmapTable(this);
31058 this.hhea = new HheaTable(this);
31059 this.maxp = new MaxpTable(this);
31060 this.hmtx = new HmtxTable(this);
31061 this.post = new PostTable(this);
31062 this.os2 = new OS2Table(this);
31063 this.loca = new LocaTable(this);
31064 this.glyf = new GlyfTable(this);
31065 this.ascender = (this.os2.exists && this.os2.ascender) || this.hhea.ascender;
31066 this.decender = (this.os2.exists && this.os2.decender) || this.hhea.decender;
31067 this.lineGap = (this.os2.exists && this.os2.lineGap) || this.hhea.lineGap;
31068 return this.bbox = [this.head.xMin, this.head.yMin, this.head.xMax, this.head.yMax];
31071 TTFFont.prototype.characterToGlyph = function(character) {
31073 return ((_ref = this.cmap.unicode) != null ? _ref.codeMap[character] : void 0) || 0;
31076 TTFFont.prototype.widthOfGlyph = function(glyph) {
31078 scale = 1000.0 / this.head.unitsPerEm;
31079 return this.hmtx.forGlyph(glyph).advance * scale;
31086 module.exports = TTFFont;
31093 /***/ function(module, exports) {
31095 // Generated by CoffeeScript 1.7.1
31099 Data = (function() {
31100 function Data(data) {
31101 this.data = data != null ? data : [];
31103 this.length = this.data.length;
31106 Data.prototype.readByte = function() {
31107 return this.data[this.pos++];
31110 Data.prototype.writeByte = function(byte) {
31111 return this.data[this.pos++] = byte;
31114 Data.prototype.byteAt = function(index) {
31115 return this.data[index];
31118 Data.prototype.readBool = function() {
31119 return !!this.readByte();
31122 Data.prototype.writeBool = function(val) {
31123 return this.writeByte(val ? 1 : 0);
31126 Data.prototype.readUInt32 = function() {
31127 var b1, b2, b3, b4;
31128 b1 = this.readByte() * 0x1000000;
31129 b2 = this.readByte() << 16;
31130 b3 = this.readByte() << 8;
31131 b4 = this.readByte();
31132 return b1 + b2 + b3 + b4;
31135 Data.prototype.writeUInt32 = function(val) {
31136 this.writeByte((val >>> 24) & 0xff);
31137 this.writeByte((val >> 16) & 0xff);
31138 this.writeByte((val >> 8) & 0xff);
31139 return this.writeByte(val & 0xff);
31142 Data.prototype.readInt32 = function() {
31144 int = this.readUInt32();
31145 if (int >= 0x80000000) {
31146 return int - 0x100000000;
31152 Data.prototype.writeInt32 = function(val) {
31154 val += 0x100000000;
31156 return this.writeUInt32(val);
31159 Data.prototype.readUInt16 = function() {
31161 b1 = this.readByte() << 8;
31162 b2 = this.readByte();
31166 Data.prototype.writeUInt16 = function(val) {
31167 this.writeByte((val >> 8) & 0xff);
31168 return this.writeByte(val & 0xff);
31171 Data.prototype.readInt16 = function() {
31173 int = this.readUInt16();
31174 if (int >= 0x8000) {
31175 return int - 0x10000;
31181 Data.prototype.writeInt16 = function(val) {
31185 return this.writeUInt16(val);
31188 Data.prototype.readString = function(length) {
31191 for (i = _i = 0; 0 <= length ? _i < length : _i > length; i = 0 <= length ? ++_i : --_i) {
31192 ret[i] = String.fromCharCode(this.readByte());
31194 return ret.join('');
31197 Data.prototype.writeString = function(val) {
31198 var i, _i, _ref, _results;
31200 for (i = _i = 0, _ref = val.length; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) {
31201 _results.push(this.writeByte(val.charCodeAt(i)));
31206 Data.prototype.stringAt = function(pos, length) {
31208 return this.readString(length);
31211 Data.prototype.readShort = function() {
31212 return this.readInt16();
31215 Data.prototype.writeShort = function(val) {
31216 return this.writeInt16(val);
31219 Data.prototype.readLongLong = function() {
31220 var b1, b2, b3, b4, b5, b6, b7, b8;
31221 b1 = this.readByte();
31222 b2 = this.readByte();
31223 b3 = this.readByte();
31224 b4 = this.readByte();
31225 b5 = this.readByte();
31226 b6 = this.readByte();
31227 b7 = this.readByte();
31228 b8 = this.readByte();
31230 return ((b1 ^ 0xff) * 0x100000000000000 + (b2 ^ 0xff) * 0x1000000000000 + (b3 ^ 0xff) * 0x10000000000 + (b4 ^ 0xff) * 0x100000000 + (b5 ^ 0xff) * 0x1000000 + (b6 ^ 0xff) * 0x10000 + (b7 ^ 0xff) * 0x100 + (b8 ^ 0xff) + 1) * -1;
31232 return b1 * 0x100000000000000 + b2 * 0x1000000000000 + b3 * 0x10000000000 + b4 * 0x100000000 + b5 * 0x1000000 + b6 * 0x10000 + b7 * 0x100 + b8;
31235 Data.prototype.writeLongLong = function(val) {
31237 high = Math.floor(val / 0x100000000);
31238 low = val & 0xffffffff;
31239 this.writeByte((high >> 24) & 0xff);
31240 this.writeByte((high >> 16) & 0xff);
31241 this.writeByte((high >> 8) & 0xff);
31242 this.writeByte(high & 0xff);
31243 this.writeByte((low >> 24) & 0xff);
31244 this.writeByte((low >> 16) & 0xff);
31245 this.writeByte((low >> 8) & 0xff);
31246 return this.writeByte(low & 0xff);
31249 Data.prototype.readInt = function() {
31250 return this.readInt32();
31253 Data.prototype.writeInt = function(val) {
31254 return this.writeInt32(val);
31257 Data.prototype.slice = function(start, end) {
31258 return this.data.slice(start, end);
31261 Data.prototype.read = function(bytes) {
31264 for (i = _i = 0; 0 <= bytes ? _i < bytes : _i > bytes; i = 0 <= bytes ? ++_i : --_i) {
31265 buf.push(this.readByte());
31270 Data.prototype.write = function(bytes) {
31271 var byte, _i, _len, _results;
31273 for (_i = 0, _len = bytes.length; _i < _len; _i++) {
31275 _results.push(this.writeByte(byte));
31284 module.exports = Data;
31291 /***/ function(module, exports, __webpack_require__) {
31293 // Generated by CoffeeScript 1.7.1
31295 var DFont, Data, Directory, NameTable, fs;
31297 fs = __webpack_require__(44);
31299 Data = __webpack_require__(72);
31301 Directory = __webpack_require__(74);
31303 NameTable = __webpack_require__(75);
31305 DFont = (function() {
31306 DFont.open = function(filename) {
31308 contents = fs.readFileSync(filename);
31309 return new DFont(contents);
31312 function DFont(contents) {
31313 this.contents = new Data(contents);
31314 this.parse(this.contents);
31317 DFont.prototype.parse = function(data) {
31318 var attr, b2, b3, b4, dataLength, dataOffset, dataOfs, entry, font, handle, i, id, j, len, length, mapLength, mapOffset, maxIndex, maxTypeIndex, name, nameListOffset, nameOfs, p, pos, refListOffset, type, typeListOffset, _i, _j;
31319 dataOffset = data.readInt();
31320 mapOffset = data.readInt();
31321 dataLength = data.readInt();
31322 mapLength = data.readInt();
31324 data.pos = mapOffset + 24;
31325 typeListOffset = data.readShort() + mapOffset;
31326 nameListOffset = data.readShort() + mapOffset;
31327 data.pos = typeListOffset;
31328 maxIndex = data.readShort();
31329 for (i = _i = 0; _i <= maxIndex; i = _i += 1) {
31330 type = data.readString(4);
31331 maxTypeIndex = data.readShort();
31332 refListOffset = data.readShort();
31338 data.pos = typeListOffset + refListOffset;
31339 for (j = _j = 0; _j <= maxTypeIndex; j = _j += 1) {
31340 id = data.readShort();
31341 nameOfs = data.readShort();
31342 attr = data.readByte();
31343 b2 = data.readByte() << 16;
31344 b3 = data.readByte() << 8;
31345 b4 = data.readByte();
31346 dataOfs = dataOffset + (0 | b2 | b3 | b4);
31347 handle = data.readUInt32();
31355 if (nameOfs !== -1 && (nameListOffset + nameOfs < mapOffset + mapLength)) {
31356 data.pos = nameListOffset + nameOfs;
31357 len = data.readByte();
31358 entry.name = data.readString(len);
31359 } else if (type === 'sfnt') {
31360 data.pos = entry.offset;
31361 length = data.readUInt32();
31363 font.contents = new Data(data.slice(data.pos, data.pos + length));
31364 font.directory = new Directory(font.contents);
31365 name = new NameTable(font);
31366 entry.name = name.fontName[0].raw;
31369 this.map[type].list.push(entry);
31371 this.map[type].named[entry.name] = entry;
31378 DFont.prototype.getNamedFont = function(name) {
31379 var data, entry, length, pos, ret, _ref;
31380 data = this.contents;
31382 entry = (_ref = this.map.sfnt) != null ? _ref.named[name] : void 0;
31384 throw new Error("Font " + name + " not found in DFont file.");
31386 data.pos = entry.offset;
31387 length = data.readUInt32();
31388 ret = data.slice(data.pos, data.pos + length);
31397 module.exports = DFont;
31404 /***/ function(module, exports, __webpack_require__) {
31406 /* WEBPACK VAR INJECTION */(function(Buffer) {// Generated by CoffeeScript 1.7.1
31408 var Data, Directory,
31409 __slice = [].slice;
31411 Data = __webpack_require__(72);
31413 Directory = (function() {
31416 function Directory(data) {
31417 var entry, i, _i, _ref;
31418 this.scalarType = data.readInt();
31419 this.tableCount = data.readShort();
31420 this.searchRange = data.readShort();
31421 this.entrySelector = data.readShort();
31422 this.rangeShift = data.readShort();
31424 for (i = _i = 0, _ref = this.tableCount; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) {
31426 tag: data.readString(4),
31427 checksum: data.readInt(),
31428 offset: data.readInt(),
31429 length: data.readInt()
31431 this.tables[entry.tag] = entry;
31435 Directory.prototype.encode = function(tables) {
31436 var adjustment, directory, directoryLength, entrySelector, headOffset, log2, offset, rangeShift, searchRange, sum, table, tableCount, tableData, tag;
31437 tableCount = Object.keys(tables).length;
31438 log2 = Math.log(2);
31439 searchRange = Math.floor(Math.log(tableCount) / log2) * 16;
31440 entrySelector = Math.floor(searchRange / log2);
31441 rangeShift = tableCount * 16 - searchRange;
31442 directory = new Data;
31443 directory.writeInt(this.scalarType);
31444 directory.writeShort(tableCount);
31445 directory.writeShort(searchRange);
31446 directory.writeShort(entrySelector);
31447 directory.writeShort(rangeShift);
31448 directoryLength = tableCount * 16;
31449 offset = directory.pos + directoryLength;
31452 for (tag in tables) {
31453 table = tables[tag];
31454 directory.writeString(tag);
31455 directory.writeInt(checksum(table));
31456 directory.writeInt(offset);
31457 directory.writeInt(table.length);
31458 tableData = tableData.concat(table);
31459 if (tag === 'head') {
31460 headOffset = offset;
31462 offset += table.length;
31463 while (offset % 4) {
31468 directory.write(tableData);
31469 sum = checksum(directory.data);
31470 adjustment = 0xB1B0AFBA - sum;
31471 directory.pos = headOffset + 8;
31472 directory.writeUInt32(adjustment);
31473 return new Buffer(directory.data);
31476 checksum = function(data) {
31477 var i, sum, tmp, _i, _ref;
31478 data = __slice.call(data);
31479 while (data.length % 4) {
31482 tmp = new Data(data);
31484 for (i = _i = 0, _ref = data.length; _i < _ref; i = _i += 4) {
31485 sum += tmp.readUInt32();
31487 return sum & 0xFFFFFFFF;
31494 module.exports = Directory;
31498 /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2).Buffer))
31502 /***/ function(module, exports, __webpack_require__) {
31504 // Generated by CoffeeScript 1.7.1
31506 var Data, NameEntry, NameTable, Table, utils,
31507 __hasProp = {}.hasOwnProperty,
31508 __extends = 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; };
31510 Table = __webpack_require__(76);
31512 Data = __webpack_require__(72);
31514 utils = __webpack_require__(77);
31516 NameTable = (function(_super) {
31519 __extends(NameTable, _super);
31521 function NameTable() {
31522 return NameTable.__super__.constructor.apply(this, arguments);
31525 NameTable.prototype.tag = 'name';
31527 NameTable.prototype.parse = function(data) {
31528 var count, entries, entry, format, i, name, stringOffset, strings, text, _i, _j, _len, _name;
31529 data.pos = this.offset;
31530 format = data.readShort();
31531 count = data.readShort();
31532 stringOffset = data.readShort();
31534 for (i = _i = 0; 0 <= count ? _i < count : _i > count; i = 0 <= count ? ++_i : --_i) {
31536 platformID: data.readShort(),
31537 encodingID: data.readShort(),
31538 languageID: data.readShort(),
31539 nameID: data.readShort(),
31540 length: data.readShort(),
31541 offset: this.offset + stringOffset + data.readShort()
31545 for (i = _j = 0, _len = entries.length; _j < _len; i = ++_j) {
31546 entry = entries[i];
31547 data.pos = entry.offset;
31548 text = data.readString(entry.length);
31549 name = new NameEntry(text, entry);
31550 if (strings[_name = entry.nameID] == null) {
31551 strings[_name] = [];
31553 strings[entry.nameID].push(name);
31555 this.strings = strings;
31556 this.copyright = strings[0];
31557 this.fontFamily = strings[1];
31558 this.fontSubfamily = strings[2];
31559 this.uniqueSubfamily = strings[3];
31560 this.fontName = strings[4];
31561 this.version = strings[5];
31562 this.postscriptName = strings[6][0].raw.replace(/[\x00-\x19\x80-\xff]/g, "");
31563 this.trademark = strings[7];
31564 this.manufacturer = strings[8];
31565 this.designer = strings[9];
31566 this.description = strings[10];
31567 this.vendorUrl = strings[11];
31568 this.designerUrl = strings[12];
31569 this.license = strings[13];
31570 this.licenseUrl = strings[14];
31571 this.preferredFamily = strings[15];
31572 this.preferredSubfamily = strings[17];
31573 this.compatibleFull = strings[18];
31574 return this.sampleText = strings[19];
31577 subsetTag = "AAAAAA";
31579 NameTable.prototype.encode = function() {
31580 var id, list, nameID, nameTable, postscriptName, strCount, strTable, string, strings, table, val, _i, _len, _ref;
31582 _ref = this.strings;
31587 postscriptName = new NameEntry("" + subsetTag + "+" + this.postscriptName, {
31592 strings[6] = [postscriptName];
31593 subsetTag = utils.successorOf(subsetTag);
31595 for (id in strings) {
31596 list = strings[id];
31597 if (list != null) {
31598 strCount += list.length;
31602 strTable = new Data;
31603 table.writeShort(0);
31604 table.writeShort(strCount);
31605 table.writeShort(6 + 12 * strCount);
31606 for (nameID in strings) {
31607 list = strings[nameID];
31608 if (list != null) {
31609 for (_i = 0, _len = list.length; _i < _len; _i++) {
31611 table.writeShort(string.platformID);
31612 table.writeShort(string.encodingID);
31613 table.writeShort(string.languageID);
31614 table.writeShort(nameID);
31615 table.writeShort(string.length);
31616 table.writeShort(strTable.pos);
31617 strTable.writeString(string.raw);
31621 return nameTable = {
31622 postscriptName: postscriptName.raw,
31623 table: table.data.concat(strTable.data)
31631 module.exports = NameTable;
31633 NameEntry = (function() {
31634 function NameEntry(raw, entry) {
31636 this.length = this.raw.length;
31637 this.platformID = entry.platformID;
31638 this.encodingID = entry.encodingID;
31639 this.languageID = entry.languageID;
31651 /***/ function(module, exports) {
31653 // Generated by CoffeeScript 1.7.1
31657 Table = (function() {
31658 function Table(file) {
31661 info = this.file.directory.tables[this.tag];
31662 this.exists = !!info;
31664 this.offset = info.offset, this.length = info.length;
31665 this.parse(this.file.contents);
31669 Table.prototype.parse = function() {};
31671 Table.prototype.encode = function() {};
31673 Table.prototype.raw = function() {
31674 if (!this.exists) {
31677 this.file.contents.pos = this.offset;
31678 return this.file.contents.read(this.length);
31685 module.exports = Table;
31692 /***/ function(module, exports) {
31694 // Generated by CoffeeScript 1.7.1
31697 * An implementation of Ruby's string.succ method.
31700 * Returns the successor to str. The successor is calculated by incrementing characters starting
31701 * from the rightmost alphanumeric (or the rightmost character if there are no alphanumerics) in the
31702 * string. Incrementing a digit always results in another digit, and incrementing a letter results in
31703 * another letter of the same case.
31705 * If the increment generates a carry, the character to the left of it is incremented. This
31706 * process repeats until there is no carry, adding an additional character if necessary.
31708 * succ("abcd") == "abce"
31709 * succ("THX1138") == "THX1139"
31710 * succ("<<koala>>") == "<<koalb>>"
31711 * succ("1999zzz") == "2000aaa"
31712 * succ("ZZZ9999") == "AAAA0000"
31716 exports.successorOf = function(input) {
31717 var added, alphabet, carry, i, index, isUpperCase, last, length, next, result;
31718 alphabet = 'abcdefghijklmnopqrstuvwxyz';
31719 length = alphabet.length;
31723 last = input.charAt(--i);
31725 index = alphabet.indexOf(last.toLowerCase());
31726 if (index === -1) {
31730 next = alphabet.charAt((index + 1) % length);
31731 isUpperCase = last === last.toUpperCase();
31733 next = next.toUpperCase();
31735 carry = index + 1 >= length;
31736 if (carry && i === 0) {
31737 added = isUpperCase ? 'A' : 'a';
31738 result = added + next + result.slice(1);
31748 if (carry && i === 0) {
31749 result = '1' + next + result.slice(1);
31753 result = result.slice(0, i) + next + result.slice(i + 1);
31761 exports.invert = function(object) {
31764 for (key in object) {
31776 /***/ function(module, exports, __webpack_require__) {
31778 // Generated by CoffeeScript 1.7.1
31780 var Data, HeadTable, Table,
31781 __hasProp = {}.hasOwnProperty,
31782 __extends = 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; };
31784 Table = __webpack_require__(76);
31786 Data = __webpack_require__(72);
31788 HeadTable = (function(_super) {
31789 __extends(HeadTable, _super);
31791 function HeadTable() {
31792 return HeadTable.__super__.constructor.apply(this, arguments);
31795 HeadTable.prototype.tag = 'head';
31797 HeadTable.prototype.parse = function(data) {
31798 data.pos = this.offset;
31799 this.version = data.readInt();
31800 this.revision = data.readInt();
31801 this.checkSumAdjustment = data.readInt();
31802 this.magicNumber = data.readInt();
31803 this.flags = data.readShort();
31804 this.unitsPerEm = data.readShort();
31805 this.created = data.readLongLong();
31806 this.modified = data.readLongLong();
31807 this.xMin = data.readShort();
31808 this.yMin = data.readShort();
31809 this.xMax = data.readShort();
31810 this.yMax = data.readShort();
31811 this.macStyle = data.readShort();
31812 this.lowestRecPPEM = data.readShort();
31813 this.fontDirectionHint = data.readShort();
31814 this.indexToLocFormat = data.readShort();
31815 return this.glyphDataFormat = data.readShort();
31818 HeadTable.prototype.encode = function(loca) {
31821 table.writeInt(this.version);
31822 table.writeInt(this.revision);
31823 table.writeInt(this.checkSumAdjustment);
31824 table.writeInt(this.magicNumber);
31825 table.writeShort(this.flags);
31826 table.writeShort(this.unitsPerEm);
31827 table.writeLongLong(this.created);
31828 table.writeLongLong(this.modified);
31829 table.writeShort(this.xMin);
31830 table.writeShort(this.yMin);
31831 table.writeShort(this.xMax);
31832 table.writeShort(this.yMax);
31833 table.writeShort(this.macStyle);
31834 table.writeShort(this.lowestRecPPEM);
31835 table.writeShort(this.fontDirectionHint);
31836 table.writeShort(loca.type);
31837 table.writeShort(this.glyphDataFormat);
31845 module.exports = HeadTable;
31852 /***/ function(module, exports, __webpack_require__) {
31854 // Generated by CoffeeScript 1.7.1
31856 var CmapEntry, CmapTable, Data, Table,
31857 __hasProp = {}.hasOwnProperty,
31858 __extends = 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; };
31860 Table = __webpack_require__(76);
31862 Data = __webpack_require__(72);
31864 CmapTable = (function(_super) {
31865 __extends(CmapTable, _super);
31867 function CmapTable() {
31868 return CmapTable.__super__.constructor.apply(this, arguments);
31871 CmapTable.prototype.tag = 'cmap';
31873 CmapTable.prototype.parse = function(data) {
31874 var entry, i, tableCount, _i;
31875 data.pos = this.offset;
31876 this.version = data.readUInt16();
31877 tableCount = data.readUInt16();
31879 this.unicode = null;
31880 for (i = _i = 0; 0 <= tableCount ? _i < tableCount : _i > tableCount; i = 0 <= tableCount ? ++_i : --_i) {
31881 entry = new CmapEntry(data, this.offset);
31882 this.tables.push(entry);
31883 if (entry.isUnicode) {
31884 if (this.unicode == null) {
31885 this.unicode = entry;
31892 CmapTable.encode = function(charmap, encoding) {
31894 if (encoding == null) {
31895 encoding = 'macroman';
31897 result = CmapEntry.encode(charmap, encoding);
31899 table.writeUInt16(0);
31900 table.writeUInt16(1);
31901 result.table = table.data.concat(result.subtable);
31909 CmapEntry = (function() {
31910 function CmapEntry(data, offset) {
31911 var code, count, endCode, glyphId, glyphIds, i, idDelta, idRangeOffset, index, saveOffset, segCount, segCountX2, start, startCode, tail, _i, _j, _k, _len;
31912 this.platformID = data.readUInt16();
31913 this.encodingID = data.readShort();
31914 this.offset = offset + data.readInt();
31915 saveOffset = data.pos;
31916 data.pos = this.offset;
31917 this.format = data.readUInt16();
31918 this.length = data.readUInt16();
31919 this.language = data.readUInt16();
31920 this.isUnicode = (this.platformID === 3 && this.encodingID === 1 && this.format === 4) || this.platformID === 0 && this.format === 4;
31922 switch (this.format) {
31924 for (i = _i = 0; _i < 256; i = ++_i) {
31925 this.codeMap[i] = data.readByte();
31929 segCountX2 = data.readUInt16();
31930 segCount = segCountX2 / 2;
31932 endCode = (function() {
31935 for (i = _j = 0; 0 <= segCount ? _j < segCount : _j > segCount; i = 0 <= segCount ? ++_j : --_j) {
31936 _results.push(data.readUInt16());
31941 startCode = (function() {
31944 for (i = _j = 0; 0 <= segCount ? _j < segCount : _j > segCount; i = 0 <= segCount ? ++_j : --_j) {
31945 _results.push(data.readUInt16());
31949 idDelta = (function() {
31952 for (i = _j = 0; 0 <= segCount ? _j < segCount : _j > segCount; i = 0 <= segCount ? ++_j : --_j) {
31953 _results.push(data.readUInt16());
31957 idRangeOffset = (function() {
31960 for (i = _j = 0; 0 <= segCount ? _j < segCount : _j > segCount; i = 0 <= segCount ? ++_j : --_j) {
31961 _results.push(data.readUInt16());
31965 count = (this.length - data.pos + this.offset) / 2;
31966 glyphIds = (function() {
31969 for (i = _j = 0; 0 <= count ? _j < count : _j > count; i = 0 <= count ? ++_j : --_j) {
31970 _results.push(data.readUInt16());
31974 for (i = _j = 0, _len = endCode.length; _j < _len; i = ++_j) {
31976 start = startCode[i];
31977 for (code = _k = start; start <= tail ? _k <= tail : _k >= tail; code = start <= tail ? ++_k : --_k) {
31978 if (idRangeOffset[i] === 0) {
31979 glyphId = code + idDelta[i];
31981 index = idRangeOffset[i] / 2 + (code - start) - (segCount - i);
31982 glyphId = glyphIds[index] || 0;
31983 if (glyphId !== 0) {
31984 glyphId += idDelta[i];
31987 this.codeMap[code] = glyphId & 0xFFFF;
31991 data.pos = saveOffset;
31994 CmapEntry.encode = function(charmap, encoding) {
31995 var charMap, code, codeMap, codes, delta, deltas, diff, endCode, endCodes, entrySelector, glyphIDs, i, id, indexes, last, map, nextID, offset, old, rangeOffsets, rangeShift, result, searchRange, segCount, segCountX2, startCode, startCodes, startGlyph, subtable, _i, _j, _k, _l, _len, _len1, _len2, _len3, _len4, _len5, _len6, _len7, _m, _n, _name, _o, _p, _q;
31996 subtable = new Data;
31997 codes = Object.keys(charmap).sort(function(a, b) {
32000 switch (encoding) {
32003 indexes = (function() {
32006 for (i = _i = 0; _i < 256; i = ++_i) {
32015 for (_i = 0, _len = codes.length; _i < _len; _i++) {
32017 if (map[_name = charmap[code]] == null) {
32021 old: charmap[code],
32022 "new": map[charmap[code]]
32024 indexes[code] = map[charmap[code]];
32026 subtable.writeUInt16(1);
32027 subtable.writeUInt16(0);
32028 subtable.writeUInt32(12);
32029 subtable.writeUInt16(0);
32030 subtable.writeUInt16(262);
32031 subtable.writeUInt16(0);
32032 subtable.write(indexes);
32035 subtable: subtable.data,
32044 last = diff = null;
32045 for (_j = 0, _len1 = codes.length; _j < _len1; _j++) {
32047 old = charmap[code];
32048 if (map[old] == null) {
32049 map[old] = ++nextID;
32055 delta = map[old] - code;
32056 if ((last == null) || delta !== diff) {
32058 endCodes.push(last);
32060 startCodes.push(code);
32066 endCodes.push(last);
32068 endCodes.push(0xFFFF);
32069 startCodes.push(0xFFFF);
32070 segCount = startCodes.length;
32071 segCountX2 = segCount * 2;
32072 searchRange = 2 * Math.pow(Math.log(segCount) / Math.LN2, 2);
32073 entrySelector = Math.log(searchRange / 2) / Math.LN2;
32074 rangeShift = 2 * segCount - searchRange;
32078 for (i = _k = 0, _len2 = startCodes.length; _k < _len2; i = ++_k) {
32079 startCode = startCodes[i];
32080 endCode = endCodes[i];
32081 if (startCode === 0xFFFF) {
32083 rangeOffsets.push(0);
32086 startGlyph = charMap[startCode]["new"];
32087 if (startCode - startGlyph >= 0x8000) {
32089 rangeOffsets.push(2 * (glyphIDs.length + segCount - i));
32090 for (code = _l = startCode; startCode <= endCode ? _l <= endCode : _l >= endCode; code = startCode <= endCode ? ++_l : --_l) {
32091 glyphIDs.push(charMap[code]["new"]);
32094 deltas.push(startGlyph - startCode);
32095 rangeOffsets.push(0);
32098 subtable.writeUInt16(3);
32099 subtable.writeUInt16(1);
32100 subtable.writeUInt32(12);
32101 subtable.writeUInt16(4);
32102 subtable.writeUInt16(16 + segCount * 8 + glyphIDs.length * 2);
32103 subtable.writeUInt16(0);
32104 subtable.writeUInt16(segCountX2);
32105 subtable.writeUInt16(searchRange);
32106 subtable.writeUInt16(entrySelector);
32107 subtable.writeUInt16(rangeShift);
32108 for (_m = 0, _len3 = endCodes.length; _m < _len3; _m++) {
32109 code = endCodes[_m];
32110 subtable.writeUInt16(code);
32112 subtable.writeUInt16(0);
32113 for (_n = 0, _len4 = startCodes.length; _n < _len4; _n++) {
32114 code = startCodes[_n];
32115 subtable.writeUInt16(code);
32117 for (_o = 0, _len5 = deltas.length; _o < _len5; _o++) {
32118 delta = deltas[_o];
32119 subtable.writeUInt16(delta);
32121 for (_p = 0, _len6 = rangeOffsets.length; _p < _len6; _p++) {
32122 offset = rangeOffsets[_p];
32123 subtable.writeUInt16(offset);
32125 for (_q = 0, _len7 = glyphIDs.length; _q < _len7; _q++) {
32127 subtable.writeUInt16(id);
32131 subtable: subtable.data,
32132 maxGlyphID: nextID + 1
32141 module.exports = CmapTable;
32148 /***/ function(module, exports, __webpack_require__) {
32150 // Generated by CoffeeScript 1.7.1
32152 var Data, HmtxTable, Table,
32153 __hasProp = {}.hasOwnProperty,
32154 __extends = 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; };
32156 Table = __webpack_require__(76);
32158 Data = __webpack_require__(72);
32160 HmtxTable = (function(_super) {
32161 __extends(HmtxTable, _super);
32163 function HmtxTable() {
32164 return HmtxTable.__super__.constructor.apply(this, arguments);
32167 HmtxTable.prototype.tag = 'hmtx';
32169 HmtxTable.prototype.parse = function(data) {
32170 var i, last, lsbCount, m, _i, _j, _ref, _results;
32171 data.pos = this.offset;
32173 for (i = _i = 0, _ref = this.file.hhea.numberOfMetrics; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) {
32174 this.metrics.push({
32175 advance: data.readUInt16(),
32176 lsb: data.readInt16()
32179 lsbCount = this.file.maxp.numGlyphs - this.file.hhea.numberOfMetrics;
32180 this.leftSideBearings = (function() {
32183 for (i = _j = 0; 0 <= lsbCount ? _j < lsbCount : _j > lsbCount; i = 0 <= lsbCount ? ++_j : --_j) {
32184 _results.push(data.readInt16());
32188 this.widths = (function() {
32189 var _j, _len, _ref1, _results;
32190 _ref1 = this.metrics;
32192 for (_j = 0, _len = _ref1.length; _j < _len; _j++) {
32194 _results.push(m.advance);
32198 last = this.widths[this.widths.length - 1];
32200 for (i = _j = 0; 0 <= lsbCount ? _j < lsbCount : _j > lsbCount; i = 0 <= lsbCount ? ++_j : --_j) {
32201 _results.push(this.widths.push(last));
32206 HmtxTable.prototype.forGlyph = function(id) {
32208 if (id in this.metrics) {
32209 return this.metrics[id];
32212 advance: this.metrics[this.metrics.length - 1].advance,
32213 lsb: this.leftSideBearings[id - this.metrics.length]
32217 HmtxTable.prototype.encode = function(mapping) {
32218 var id, metric, table, _i, _len;
32220 for (_i = 0, _len = mapping.length; _i < _len; _i++) {
32222 metric = this.forGlyph(id);
32223 table.writeUInt16(metric.advance);
32224 table.writeUInt16(metric.lsb);
32233 module.exports = HmtxTable;
32240 /***/ function(module, exports, __webpack_require__) {
32242 // Generated by CoffeeScript 1.7.1
32244 var Data, HheaTable, Table,
32245 __hasProp = {}.hasOwnProperty,
32246 __extends = 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; };
32248 Table = __webpack_require__(76);
32250 Data = __webpack_require__(72);
32252 HheaTable = (function(_super) {
32253 __extends(HheaTable, _super);
32255 function HheaTable() {
32256 return HheaTable.__super__.constructor.apply(this, arguments);
32259 HheaTable.prototype.tag = 'hhea';
32261 HheaTable.prototype.parse = function(data) {
32262 data.pos = this.offset;
32263 this.version = data.readInt();
32264 this.ascender = data.readShort();
32265 this.decender = data.readShort();
32266 this.lineGap = data.readShort();
32267 this.advanceWidthMax = data.readShort();
32268 this.minLeftSideBearing = data.readShort();
32269 this.minRightSideBearing = data.readShort();
32270 this.xMaxExtent = data.readShort();
32271 this.caretSlopeRise = data.readShort();
32272 this.caretSlopeRun = data.readShort();
32273 this.caretOffset = data.readShort();
32275 this.metricDataFormat = data.readShort();
32276 return this.numberOfMetrics = data.readUInt16();
32279 HheaTable.prototype.encode = function(ids) {
32280 var i, table, _i, _ref;
32282 table.writeInt(this.version);
32283 table.writeShort(this.ascender);
32284 table.writeShort(this.decender);
32285 table.writeShort(this.lineGap);
32286 table.writeShort(this.advanceWidthMax);
32287 table.writeShort(this.minLeftSideBearing);
32288 table.writeShort(this.minRightSideBearing);
32289 table.writeShort(this.xMaxExtent);
32290 table.writeShort(this.caretSlopeRise);
32291 table.writeShort(this.caretSlopeRun);
32292 table.writeShort(this.caretOffset);
32293 for (i = _i = 0, _ref = 4 * 2; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) {
32294 table.writeByte(0);
32296 table.writeShort(this.metricDataFormat);
32297 table.writeUInt16(ids.length);
32305 module.exports = HheaTable;
32312 /***/ function(module, exports, __webpack_require__) {
32314 // Generated by CoffeeScript 1.7.1
32316 var Data, MaxpTable, Table,
32317 __hasProp = {}.hasOwnProperty,
32318 __extends = 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; };
32320 Table = __webpack_require__(76);
32322 Data = __webpack_require__(72);
32324 MaxpTable = (function(_super) {
32325 __extends(MaxpTable, _super);
32327 function MaxpTable() {
32328 return MaxpTable.__super__.constructor.apply(this, arguments);
32331 MaxpTable.prototype.tag = 'maxp';
32333 MaxpTable.prototype.parse = function(data) {
32334 data.pos = this.offset;
32335 this.version = data.readInt();
32336 this.numGlyphs = data.readUInt16();
32337 this.maxPoints = data.readUInt16();
32338 this.maxContours = data.readUInt16();
32339 this.maxCompositePoints = data.readUInt16();
32340 this.maxComponentContours = data.readUInt16();
32341 this.maxZones = data.readUInt16();
32342 this.maxTwilightPoints = data.readUInt16();
32343 this.maxStorage = data.readUInt16();
32344 this.maxFunctionDefs = data.readUInt16();
32345 this.maxInstructionDefs = data.readUInt16();
32346 this.maxStackElements = data.readUInt16();
32347 this.maxSizeOfInstructions = data.readUInt16();
32348 this.maxComponentElements = data.readUInt16();
32349 return this.maxComponentDepth = data.readUInt16();
32352 MaxpTable.prototype.encode = function(ids) {
32355 table.writeInt(this.version);
32356 table.writeUInt16(ids.length);
32357 table.writeUInt16(this.maxPoints);
32358 table.writeUInt16(this.maxContours);
32359 table.writeUInt16(this.maxCompositePoints);
32360 table.writeUInt16(this.maxComponentContours);
32361 table.writeUInt16(this.maxZones);
32362 table.writeUInt16(this.maxTwilightPoints);
32363 table.writeUInt16(this.maxStorage);
32364 table.writeUInt16(this.maxFunctionDefs);
32365 table.writeUInt16(this.maxInstructionDefs);
32366 table.writeUInt16(this.maxStackElements);
32367 table.writeUInt16(this.maxSizeOfInstructions);
32368 table.writeUInt16(this.maxComponentElements);
32369 table.writeUInt16(this.maxComponentDepth);
32377 module.exports = MaxpTable;
32384 /***/ function(module, exports, __webpack_require__) {
32386 // Generated by CoffeeScript 1.7.1
32388 var Data, PostTable, Table,
32389 __hasProp = {}.hasOwnProperty,
32390 __extends = 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; };
32392 Table = __webpack_require__(76);
32394 Data = __webpack_require__(72);
32396 PostTable = (function(_super) {
32397 var POSTSCRIPT_GLYPHS;
32399 __extends(PostTable, _super);
32401 function PostTable() {
32402 return PostTable.__super__.constructor.apply(this, arguments);
32405 PostTable.prototype.tag = 'post';
32407 PostTable.prototype.parse = function(data) {
32408 var i, length, numberOfGlyphs, _i, _results;
32409 data.pos = this.offset;
32410 this.format = data.readInt();
32411 this.italicAngle = data.readInt();
32412 this.underlinePosition = data.readShort();
32413 this.underlineThickness = data.readShort();
32414 this.isFixedPitch = data.readInt();
32415 this.minMemType42 = data.readInt();
32416 this.maxMemType42 = data.readInt();
32417 this.minMemType1 = data.readInt();
32418 this.maxMemType1 = data.readInt();
32419 switch (this.format) {
32423 numberOfGlyphs = data.readUInt16();
32424 this.glyphNameIndex = [];
32425 for (i = _i = 0; 0 <= numberOfGlyphs ? _i < numberOfGlyphs : _i > numberOfGlyphs; i = 0 <= numberOfGlyphs ? ++_i : --_i) {
32426 this.glyphNameIndex.push(data.readUInt16());
32430 while (data.pos < this.offset + this.length) {
32431 length = data.readByte();
32432 _results.push(this.names.push(data.readString(length)));
32437 numberOfGlyphs = data.readUInt16();
32438 return this.offsets = data.read(numberOfGlyphs);
32442 return this.map = (function() {
32443 var _j, _ref, _results1;
32445 for (i = _j = 0, _ref = this.file.maxp.numGlyphs; 0 <= _ref ? _j < _ref : _j > _ref; i = 0 <= _ref ? ++_j : --_j) {
32446 _results1.push(data.readUInt32());
32453 PostTable.prototype.glyphFor = function(code) {
32455 switch (this.format) {
32457 return POSTSCRIPT_GLYPHS[code] || '.notdef';
32459 index = this.glyphNameIndex[code];
32460 if (index <= 257) {
32461 return POSTSCRIPT_GLYPHS[index];
32463 return this.names[index - 258] || '.notdef';
32467 return POSTSCRIPT_GLYPHS[code + this.offsets[code]] || '.notdef';
32471 return this.map[code] || 0xFFFF;
32475 PostTable.prototype.encode = function(mapping) {
32476 var id, index, indexes, position, post, raw, string, strings, table, _i, _j, _k, _len, _len1, _len2;
32477 if (!this.exists) {
32481 if (this.format === 0x00030000) {
32484 table = new Data(raw.slice(0, 32));
32485 table.writeUInt32(0x00020000);
32489 for (_i = 0, _len = mapping.length; _i < _len; _i++) {
32491 post = this.glyphFor(id);
32492 position = POSTSCRIPT_GLYPHS.indexOf(post);
32493 if (position !== -1) {
32494 indexes.push(position);
32496 indexes.push(257 + strings.length);
32497 strings.push(post);
32500 table.writeUInt16(Object.keys(mapping).length);
32501 for (_j = 0, _len1 = indexes.length; _j < _len1; _j++) {
32502 index = indexes[_j];
32503 table.writeUInt16(index);
32505 for (_k = 0, _len2 = strings.length; _k < _len2; _k++) {
32506 string = strings[_k];
32507 table.writeByte(string.length);
32508 table.writeString(string);
32513 POSTSCRIPT_GLYPHS = '.notdef .null nonmarkingreturn space exclam quotedbl numbersign dollar percent\nampersand quotesingle parenleft parenright asterisk plus comma hyphen period slash\nzero one two three four five six seven eight nine colon semicolon less equal greater\nquestion at A B C D E F G H I J K L M N O P Q R S T U V W X Y Z\nbracketleft backslash bracketright asciicircum underscore grave\na b c d e f g h i j k l m n o p q r s t u v w x y z\nbraceleft bar braceright asciitilde Adieresis Aring Ccedilla Eacute Ntilde Odieresis\nUdieresis aacute agrave acircumflex adieresis atilde aring ccedilla eacute egrave\necircumflex edieresis iacute igrave icircumflex idieresis ntilde oacute ograve\nocircumflex odieresis otilde uacute ugrave ucircumflex udieresis dagger degree cent\nsterling section bullet paragraph germandbls registered copyright trademark acute\ndieresis notequal AE Oslash infinity plusminus lessequal greaterequal yen mu\npartialdiff summation product pi integral ordfeminine ordmasculine Omega ae oslash\nquestiondown exclamdown logicalnot radical florin approxequal Delta guillemotleft\nguillemotright ellipsis nonbreakingspace Agrave Atilde Otilde OE oe endash emdash\nquotedblleft quotedblright quoteleft quoteright divide lozenge ydieresis Ydieresis\nfraction currency guilsinglleft guilsinglright fi fl daggerdbl periodcentered\nquotesinglbase quotedblbase perthousand Acircumflex Ecircumflex Aacute Edieresis\nEgrave Iacute Icircumflex Idieresis Igrave Oacute Ocircumflex apple Ograve Uacute\nUcircumflex Ugrave dotlessi circumflex tilde macron breve dotaccent ring cedilla\nhungarumlaut ogonek caron Lslash lslash Scaron scaron Zcaron zcaron brokenbar Eth\neth Yacute yacute Thorn thorn minus multiply onesuperior twosuperior threesuperior\nonehalf onequarter threequarters franc Gbreve gbreve Idotaccent Scedilla scedilla\nCacute cacute Ccaron ccaron dcroat'.split(/\s+/g);
32519 module.exports = PostTable;
32526 /***/ function(module, exports, __webpack_require__) {
32528 // Generated by CoffeeScript 1.7.1
32530 var OS2Table, Table,
32531 __hasProp = {}.hasOwnProperty,
32532 __extends = 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; };
32534 Table = __webpack_require__(76);
32536 OS2Table = (function(_super) {
32537 __extends(OS2Table, _super);
32539 function OS2Table() {
32540 return OS2Table.__super__.constructor.apply(this, arguments);
32543 OS2Table.prototype.tag = 'OS/2';
32545 OS2Table.prototype.parse = function(data) {
32547 data.pos = this.offset;
32548 this.version = data.readUInt16();
32549 this.averageCharWidth = data.readShort();
32550 this.weightClass = data.readUInt16();
32551 this.widthClass = data.readUInt16();
32552 this.type = data.readShort();
32553 this.ySubscriptXSize = data.readShort();
32554 this.ySubscriptYSize = data.readShort();
32555 this.ySubscriptXOffset = data.readShort();
32556 this.ySubscriptYOffset = data.readShort();
32557 this.ySuperscriptXSize = data.readShort();
32558 this.ySuperscriptYSize = data.readShort();
32559 this.ySuperscriptXOffset = data.readShort();
32560 this.ySuperscriptYOffset = data.readShort();
32561 this.yStrikeoutSize = data.readShort();
32562 this.yStrikeoutPosition = data.readShort();
32563 this.familyClass = data.readShort();
32564 this.panose = (function() {
32567 for (i = _i = 0; _i < 10; i = ++_i) {
32568 _results.push(data.readByte());
32572 this.charRange = (function() {
32575 for (i = _i = 0; _i < 4; i = ++_i) {
32576 _results.push(data.readInt());
32580 this.vendorID = data.readString(4);
32581 this.selection = data.readShort();
32582 this.firstCharIndex = data.readShort();
32583 this.lastCharIndex = data.readShort();
32584 if (this.version > 0) {
32585 this.ascent = data.readShort();
32586 this.descent = data.readShort();
32587 this.lineGap = data.readShort();
32588 this.winAscent = data.readShort();
32589 this.winDescent = data.readShort();
32590 this.codePageRange = (function() {
32593 for (i = _i = 0; _i < 2; i = ++_i) {
32594 _results.push(data.readInt());
32598 if (this.version > 1) {
32599 this.xHeight = data.readShort();
32600 this.capHeight = data.readShort();
32601 this.defaultChar = data.readShort();
32602 this.breakChar = data.readShort();
32603 return this.maxContext = data.readShort();
32608 OS2Table.prototype.encode = function() {
32616 module.exports = OS2Table;
32623 /***/ function(module, exports, __webpack_require__) {
32625 // Generated by CoffeeScript 1.7.1
32627 var Data, LocaTable, Table,
32628 __hasProp = {}.hasOwnProperty,
32629 __extends = 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; };
32631 Table = __webpack_require__(76);
32633 Data = __webpack_require__(72);
32635 LocaTable = (function(_super) {
32636 __extends(LocaTable, _super);
32638 function LocaTable() {
32639 return LocaTable.__super__.constructor.apply(this, arguments);
32642 LocaTable.prototype.tag = 'loca';
32644 LocaTable.prototype.parse = function(data) {
32646 data.pos = this.offset;
32647 format = this.file.head.indexToLocFormat;
32648 if (format === 0) {
32649 return this.offsets = (function() {
32650 var _i, _ref, _results;
32652 for (i = _i = 0, _ref = this.length; _i < _ref; i = _i += 2) {
32653 _results.push(data.readUInt16() * 2);
32658 return this.offsets = (function() {
32659 var _i, _ref, _results;
32661 for (i = _i = 0, _ref = this.length; _i < _ref; i = _i += 4) {
32662 _results.push(data.readUInt32());
32669 LocaTable.prototype.indexOf = function(id) {
32670 return this.offsets[id];
32673 LocaTable.prototype.lengthOf = function(id) {
32674 return this.offsets[id + 1] - this.offsets[id];
32677 LocaTable.prototype.encode = function(offsets) {
32678 var o, offset, ret, table, _i, _j, _k, _len, _len1, _len2, _ref;
32680 for (_i = 0, _len = offsets.length; _i < _len; _i++) {
32681 offset = offsets[_i];
32682 if (!(offset > 0xFFFF)) {
32685 _ref = this.offsets;
32686 for (_j = 0, _len1 = _ref.length; _j < _len1; _j++) {
32688 table.writeUInt32(o);
32695 for (_k = 0, _len2 = offsets.length; _k < _len2; _k++) {
32697 table.writeUInt16(o / 2);
32709 module.exports = LocaTable;
32716 /***/ function(module, exports, __webpack_require__) {
32718 // Generated by CoffeeScript 1.7.1
32720 var CompoundGlyph, Data, GlyfTable, SimpleGlyph, Table,
32721 __hasProp = {}.hasOwnProperty,
32722 __extends = 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; },
32723 __slice = [].slice;
32725 Table = __webpack_require__(76);
32727 Data = __webpack_require__(72);
32729 GlyfTable = (function(_super) {
32730 __extends(GlyfTable, _super);
32732 function GlyfTable() {
32733 return GlyfTable.__super__.constructor.apply(this, arguments);
32736 GlyfTable.prototype.tag = 'glyf';
32738 GlyfTable.prototype.parse = function(data) {
32739 return this.cache = {};
32742 GlyfTable.prototype.glyphFor = function(id) {
32743 var data, index, length, loca, numberOfContours, raw, xMax, xMin, yMax, yMin;
32744 if (id in this.cache) {
32745 return this.cache[id];
32747 loca = this.file.loca;
32748 data = this.file.contents;
32749 index = loca.indexOf(id);
32750 length = loca.lengthOf(id);
32751 if (length === 0) {
32752 return this.cache[id] = null;
32754 data.pos = this.offset + index;
32755 raw = new Data(data.read(length));
32756 numberOfContours = raw.readShort();
32757 xMin = raw.readShort();
32758 yMin = raw.readShort();
32759 xMax = raw.readShort();
32760 yMax = raw.readShort();
32761 if (numberOfContours === -1) {
32762 this.cache[id] = new CompoundGlyph(raw, xMin, yMin, xMax, yMax);
32764 this.cache[id] = new SimpleGlyph(raw, numberOfContours, xMin, yMin, xMax, yMax);
32766 return this.cache[id];
32769 GlyfTable.prototype.encode = function(glyphs, mapping, old2new) {
32770 var glyph, id, offsets, table, _i, _len;
32773 for (_i = 0, _len = mapping.length; _i < _len; _i++) {
32775 glyph = glyphs[id];
32776 offsets.push(table.length);
32778 table = table.concat(glyph.encode(old2new));
32781 offsets.push(table.length);
32792 SimpleGlyph = (function() {
32793 function SimpleGlyph(raw, numberOfContours, xMin, yMin, xMax, yMax) {
32795 this.numberOfContours = numberOfContours;
32800 this.compound = false;
32803 SimpleGlyph.prototype.encode = function() {
32804 return this.raw.data;
32807 return SimpleGlyph;
32811 CompoundGlyph = (function() {
32812 var ARG_1_AND_2_ARE_WORDS, MORE_COMPONENTS, WE_HAVE_AN_X_AND_Y_SCALE, WE_HAVE_A_SCALE, WE_HAVE_A_TWO_BY_TWO, WE_HAVE_INSTRUCTIONS;
32814 ARG_1_AND_2_ARE_WORDS = 0x0001;
32816 WE_HAVE_A_SCALE = 0x0008;
32818 MORE_COMPONENTS = 0x0020;
32820 WE_HAVE_AN_X_AND_Y_SCALE = 0x0040;
32822 WE_HAVE_A_TWO_BY_TWO = 0x0080;
32824 WE_HAVE_INSTRUCTIONS = 0x0100;
32826 function CompoundGlyph(raw, xMin, yMin, xMax, yMax) {
32833 this.compound = true;
32834 this.glyphIDs = [];
32835 this.glyphOffsets = [];
32838 flags = data.readShort();
32839 this.glyphOffsets.push(data.pos);
32840 this.glyphIDs.push(data.readShort());
32841 if (!(flags & MORE_COMPONENTS)) {
32844 if (flags & ARG_1_AND_2_ARE_WORDS) {
32849 if (flags & WE_HAVE_A_TWO_BY_TWO) {
32851 } else if (flags & WE_HAVE_AN_X_AND_Y_SCALE) {
32853 } else if (flags & WE_HAVE_A_SCALE) {
32859 CompoundGlyph.prototype.encode = function(mapping) {
32860 var i, id, result, _i, _len, _ref;
32861 result = new Data(__slice.call(this.raw.data));
32862 _ref = this.glyphIDs;
32863 for (i = _i = 0, _len = _ref.length; _i < _len; i = ++_i) {
32865 result.pos = this.glyphOffsets[i];
32866 result.writeShort(mapping[id]);
32868 return result.data;
32871 return CompoundGlyph;
32875 module.exports = GlyfTable;
32882 /***/ function(module, exports, __webpack_require__) {
32884 // Generated by CoffeeScript 1.7.1
32888 fs = __webpack_require__(44);
32890 AFMFont = (function() {
32891 var WIN_ANSI_MAP, characters;
32893 AFMFont.open = function(filename) {
32894 return new AFMFont(fs.readFileSync(filename, 'utf8'));
32897 function AFMFont(contents) {
32899 this.contents = contents;
32900 this.attributes = {};
32901 this.glyphWidths = {};
32902 this.boundingBoxes = {};
32904 this.charWidths = (function() {
32907 for (i = _i = 0; _i <= 255; i = ++_i) {
32908 _results.push(this.glyphWidths[characters[i]]);
32912 this.bbox = (function() {
32913 var _i, _len, _ref, _results;
32914 _ref = this.attributes['FontBBox'].split(/\s+/);
32916 for (_i = 0, _len = _ref.length; _i < _len; _i++) {
32922 this.ascender = +(this.attributes['Ascender'] || 0);
32923 this.decender = +(this.attributes['Descender'] || 0);
32924 this.lineGap = (this.bbox[3] - this.bbox[1]) - (this.ascender - this.decender);
32927 AFMFont.prototype.parse = function() {
32928 var a, key, line, match, name, section, value, _i, _len, _ref;
32930 _ref = this.contents.split('\n');
32931 for (_i = 0, _len = _ref.length; _i < _len; _i++) {
32933 if (match = line.match(/^Start(\w+)/)) {
32934 section = match[1];
32936 } else if (match = line.match(/^End(\w+)/)) {
32941 case 'FontMetrics':
32942 match = line.match(/(^\w+)\s+(.*)/);
32945 if (a = this.attributes[key]) {
32946 if (!Array.isArray(a)) {
32947 a = this.attributes[key] = [a];
32951 this.attributes[key] = value;
32954 case 'CharMetrics':
32955 if (!/^CH?\s/.test(line)) {
32958 name = line.match(/\bN\s+(\.?\w+)\s*;/)[1];
32959 this.glyphWidths[name] = +line.match(/\bWX\s+(\d+)\s*;/)[1];
32994 AFMFont.prototype.encodeText = function(text) {
32995 var char, i, string, _i, _ref;
32997 for (i = _i = 0, _ref = text.length; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) {
32998 char = text.charCodeAt(i);
32999 char = WIN_ANSI_MAP[char] || char;
33000 string += String.fromCharCode(char);
33005 AFMFont.prototype.characterToGlyph = function(character) {
33006 return characters[WIN_ANSI_MAP[character] || character];
33009 AFMFont.prototype.widthOfGlyph = function(glyph) {
33010 return this.glyphWidths[glyph];
33013 characters = '.notdef .notdef .notdef .notdef\n.notdef .notdef .notdef .notdef\n.notdef .notdef .notdef .notdef\n.notdef .notdef .notdef .notdef\n.notdef .notdef .notdef .notdef\n.notdef .notdef .notdef .notdef\n.notdef .notdef .notdef .notdef\n.notdef .notdef .notdef .notdef\n\nspace exclam quotedbl numbersign\ndollar percent ampersand quotesingle\nparenleft parenright asterisk plus\ncomma hyphen period slash\nzero one two three\nfour five six seven\neight nine colon semicolon\nless equal greater question\n\nat A B C\nD E F G\nH I J K\nL M N O\nP Q R S\nT U V W\nX Y Z bracketleft\nbackslash bracketright asciicircum underscore\n\ngrave a b c\nd e f g\nh i j k\nl m n o\np q r s\nt u v w\nx y z braceleft\nbar braceright asciitilde .notdef\n\nEuro .notdef quotesinglbase florin\nquotedblbase ellipsis dagger daggerdbl\ncircumflex perthousand Scaron guilsinglleft\nOE .notdef Zcaron .notdef\n.notdef quoteleft quoteright quotedblleft\nquotedblright bullet endash emdash\ntilde trademark scaron guilsinglright\noe .notdef zcaron ydieresis\n\nspace exclamdown cent sterling\ncurrency yen brokenbar section\ndieresis copyright ordfeminine guillemotleft\nlogicalnot hyphen registered macron\ndegree plusminus twosuperior threesuperior\nacute mu paragraph periodcentered\ncedilla onesuperior ordmasculine guillemotright\nonequarter onehalf threequarters questiondown\n\nAgrave Aacute Acircumflex Atilde\nAdieresis Aring AE Ccedilla\nEgrave Eacute Ecircumflex Edieresis\nIgrave Iacute Icircumflex Idieresis\nEth Ntilde Ograve Oacute\nOcircumflex Otilde Odieresis multiply\nOslash Ugrave Uacute Ucircumflex\nUdieresis Yacute Thorn germandbls\n\nagrave aacute acircumflex atilde\nadieresis aring ae ccedilla\negrave eacute ecircumflex edieresis\nigrave iacute icircumflex idieresis\neth ntilde ograve oacute\nocircumflex otilde odieresis divide\noslash ugrave uacute ucircumflex\nudieresis yacute thorn ydieresis'.split(/\s+/);
33019 module.exports = AFMFont;
33026 /***/ function(module, exports, __webpack_require__) {
33028 // Generated by CoffeeScript 1.7.1
33030 var CmapTable, Subset, utils,
33031 __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; };
33033 CmapTable = __webpack_require__(79);
33035 utils = __webpack_require__(77);
33037 Subset = (function() {
33038 function Subset(font) {
33041 this.unicodes = {};
33045 Subset.prototype.use = function(character) {
33047 if (typeof character === 'string') {
33048 for (i = _i = 0, _ref = character.length; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) {
33049 this.use(character.charCodeAt(i));
33053 if (!this.unicodes[character]) {
33054 this.subset[this.next] = character;
33055 return this.unicodes[character] = this.next++;
33059 Subset.prototype.encodeText = function(text) {
33060 var char, i, string, _i, _ref;
33062 for (i = _i = 0, _ref = text.length; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) {
33063 char = this.unicodes[text.charCodeAt(i)];
33064 string += String.fromCharCode(char);
33069 Subset.prototype.generateCmap = function() {
33070 var mapping, roman, unicode, unicodeCmap, _ref;
33071 unicodeCmap = this.font.cmap.tables[0].codeMap;
33073 _ref = this.subset;
33074 for (roman in _ref) {
33075 unicode = _ref[roman];
33076 mapping[roman] = unicodeCmap[unicode];
33081 Subset.prototype.glyphIDs = function() {
33082 var ret, roman, unicode, unicodeCmap, val, _ref;
33083 unicodeCmap = this.font.cmap.tables[0].codeMap;
33085 _ref = this.subset;
33086 for (roman in _ref) {
33087 unicode = _ref[roman];
33088 val = unicodeCmap[unicode];
33089 if ((val != null) && __indexOf.call(ret, val) < 0) {
33096 Subset.prototype.glyphsFor = function(glyphIDs) {
33097 var additionalIDs, glyph, glyphs, id, _i, _len, _ref;
33099 for (_i = 0, _len = glyphIDs.length; _i < _len; _i++) {
33101 glyphs[id] = this.font.glyf.glyphFor(id);
33103 additionalIDs = [];
33104 for (id in glyphs) {
33105 glyph = glyphs[id];
33106 if (glyph != null ? glyph.compound : void 0) {
33107 additionalIDs.push.apply(additionalIDs, glyph.glyphIDs);
33110 if (additionalIDs.length > 0) {
33111 _ref = this.glyphsFor(additionalIDs);
33114 glyphs[id] = glyph;
33120 Subset.prototype.encode = function() {
33121 var cmap, code, glyf, glyphs, id, ids, loca, name, new2old, newIDs, nextGlyphID, old2new, oldID, oldIDs, tables, _ref, _ref1;
33122 cmap = CmapTable.encode(this.generateCmap(), 'unicode');
33123 glyphs = this.glyphsFor(this.glyphIDs());
33127 _ref = cmap.charMap;
33128 for (code in _ref) {
33130 old2new[ids.old] = ids["new"];
33132 nextGlyphID = cmap.maxGlyphID;
33133 for (oldID in glyphs) {
33134 if (!(oldID in old2new)) {
33135 old2new[oldID] = nextGlyphID++;
33138 new2old = utils.invert(old2new);
33139 newIDs = Object.keys(new2old).sort(function(a, b) {
33142 oldIDs = (function() {
33143 var _i, _len, _results;
33145 for (_i = 0, _len = newIDs.length; _i < _len; _i++) {
33147 _results.push(new2old[id]);
33151 glyf = this.font.glyf.encode(glyphs, oldIDs, old2new);
33152 loca = this.font.loca.encode(glyf.offsets);
33153 name = this.font.name.encode();
33154 this.postscriptName = name.postscriptName;
33156 _ref1 = cmap.charMap;
33157 for (code in _ref1) {
33159 this.cmap[code] = ids.old;
33165 hmtx: this.font.hmtx.encode(oldIDs),
33166 hhea: this.font.hhea.encode(oldIDs),
33167 maxp: this.font.maxp.encode(oldIDs),
33168 post: this.font.post.encode(oldIDs),
33170 head: this.font.head.encode(loca)
33172 if (this.font.os2.exists) {
33173 tables['OS/2'] = this.font.os2.raw();
33175 return this.font.directory.encode(tables);
33182 module.exports = Subset;
33189 /***/ function(module, exports, __webpack_require__) {
33191 // Generated by CoffeeScript 1.7.1
33195 LineWrapper = __webpack_require__(90);
33198 initText: function() {
33201 return this._lineGap = 0;
33203 lineGap: function(_lineGap) {
33204 this._lineGap = _lineGap;
33207 moveDown: function(lines) {
33208 if (lines == null) {
33211 this.y += this.currentLineHeight(true) * lines + this._lineGap;
33214 moveUp: function(lines) {
33215 if (lines == null) {
33218 this.y -= this.currentLineHeight(true) * lines + this._lineGap;
33221 _text: function(text, x, y, options, lineCallback) {
33222 var line, wrapper, _i, _len, _ref;
33223 options = this._initOptions(x, y, options);
33225 if (options.wordSpacing) {
33226 text = text.replace(/\s{2,}/g, ' ');
33228 if (options.width) {
33229 wrapper = this._wrapper;
33231 wrapper = new LineWrapper(this, options);
33232 wrapper.on('line', lineCallback);
33234 this._wrapper = options.continued ? wrapper : null;
33235 this._textOptions = options.continued ? options : null;
33236 wrapper.wrap(text, options);
33238 _ref = text.split('\n');
33239 for (_i = 0, _len = _ref.length; _i < _len; _i++) {
33241 lineCallback(line, options);
33246 text: function(text, x, y, options) {
33247 return this._text(text, x, y, options, this._line.bind(this));
33249 widthOfString: function(string, options) {
33250 if (options == null) {
33253 return this._font.widthOfString(string, this._fontSize) + (options.characterSpacing || 0) * (string.length - 1);
33255 heightOfString: function(text, options) {
33256 var height, lineGap, x, y;
33257 if (options == null) {
33260 x = this.x, y = this.y;
33261 options = this._initOptions(options);
33262 options.height = Infinity;
33263 lineGap = options.lineGap || this._lineGap || 0;
33264 this._text(text, this.x, this.y, options, (function(_this) {
33265 return function(line, options) {
33266 return _this.y += _this.currentLineHeight(true) + lineGap;
33269 height = this.y - y;
33274 list: function(list, x, y, options, wrapper) {
33275 var flatten, i, indent, itemIndent, items, level, levels, r;
33276 options = this._initOptions(x, y, options);
33277 r = Math.round((this._font.ascender / 1000 * this._fontSize) / 3);
33278 indent = options.textIndent || r * 5;
33279 itemIndent = options.bulletIndent || r * 8;
33283 flatten = function(list) {
33284 var i, item, _i, _len, _results;
33286 for (i = _i = 0, _len = list.length; _i < _len; i = ++_i) {
33288 if (Array.isArray(item)) {
33291 _results.push(level--);
33294 _results.push(levels.push(level));
33300 wrapper = new LineWrapper(this, options);
33301 wrapper.on('line', this._line.bind(this));
33304 wrapper.on('firstLine', (function(_this) {
33305 return function() {
33307 if ((l = levels[i++]) !== level) {
33308 diff = itemIndent * (l - level);
33310 wrapper.lineWidth -= diff;
33313 _this.circle(_this.x - indent + r, _this.y + r + (r / 2), r);
33314 return _this.fill();
33317 wrapper.on('sectionStart', (function(_this) {
33318 return function() {
33320 pos = indent + itemIndent * (level - 1);
33322 return wrapper.lineWidth -= pos;
33325 wrapper.on('sectionEnd', (function(_this) {
33326 return function() {
33328 pos = indent + itemIndent * (level - 1);
33330 return wrapper.lineWidth += pos;
33333 wrapper.wrap(items.join('\n'), options);
33336 _initOptions: function(x, y, options) {
33337 var key, margins, val, _ref;
33341 if (options == null) {
33344 if (typeof x === 'object') {
33348 options = (function() {
33351 for (k in options) {
33357 if (this._textOptions) {
33358 _ref = this._textOptions;
33359 for (key in _ref) {
33361 if (key !== 'continued') {
33362 if (options[key] == null) {
33363 options[key] = val;
33374 if (options.lineBreak !== false) {
33375 margins = this.page.margins;
33376 if (options.width == null) {
33377 options.width = this.page.width - this.x - margins.right;
33380 options.columns || (options.columns = 0);
33381 if (options.columnGap == null) {
33382 options.columnGap = 18;
33386 _line: function(text, options, wrapper) {
33388 if (options == null) {
33391 this._fragment(text, this.x, this.y, options);
33392 lineGap = options.lineGap || this._lineGap || 0;
33394 return this.x += this.widthOfString(text);
33396 return this.y += this.currentLineHeight(true) + lineGap;
33399 _fragment: function(text, x, y, options) {
33400 var align, characterSpacing, commands, d, encoded, i, lineWidth, lineY, mode, renderedWidth, spaceWidth, textWidth, word, wordSpacing, words, _base, _i, _len, _name;
33402 if (text.length === 0) {
33405 align = options.align || 'left';
33406 wordSpacing = options.wordSpacing || 0;
33407 characterSpacing = options.characterSpacing || 0;
33408 if (options.width) {
33411 textWidth = this.widthOfString(text.replace(/\s+$/, ''), options);
33412 x += options.lineWidth - textWidth;
33415 x += options.lineWidth / 2 - options.textWidth / 2;
33418 words = text.trim().split(/\s+/);
33419 textWidth = this.widthOfString(text.replace(/\s+/g, ''), options);
33420 spaceWidth = this.widthOfString(' ') + characterSpacing;
33421 wordSpacing = Math.max(0, (options.lineWidth - textWidth) / Math.max(1, words.length - 1) - spaceWidth);
33424 renderedWidth = options.textWidth + (wordSpacing * (options.wordCount - 1)) + (characterSpacing * (text.length - 1));
33425 if (options.link) {
33426 this.link(x, y, renderedWidth, this.currentLineHeight(), options.link);
33428 if (options.underline || options.strike) {
33430 if (!options.stroke) {
33431 this.strokeColor.apply(this, this._fillColor);
33433 lineWidth = this._fontSize < 10 ? 0.5 : Math.floor(this._fontSize / 10);
33434 this.lineWidth(lineWidth);
33435 d = options.underline ? 1 : 2;
33436 lineY = y + this.currentLineHeight() / d;
33437 if (options.underline) {
33438 lineY -= lineWidth;
33440 this.moveTo(x, lineY);
33441 this.lineTo(x + renderedWidth, lineY);
33446 this.transform(1, 0, 0, -1, 0, this.page.height);
33447 y = this.page.height - y - (this._font.ascender / 1000 * this._fontSize);
33448 if ((_base = this.page.fonts)[_name = this._font.id] == null) {
33449 _base[_name] = this._font.ref();
33451 this._font.use(text);
33452 this.addContent("BT");
33453 this.addContent("" + x + " " + y + " Td");
33454 this.addContent("/" + this._font.id + " " + this._fontSize + " Tf");
33455 mode = options.fill && options.stroke ? 2 : options.stroke ? 1 : 0;
33457 this.addContent("" + mode + " Tr");
33459 if (characterSpacing) {
33460 this.addContent("" + characterSpacing + " Tc");
33463 words = text.trim().split(/\s+/);
33464 wordSpacing += this.widthOfString(' ') + characterSpacing;
33465 wordSpacing *= 1000 / this._fontSize;
33467 for (_i = 0, _len = words.length; _i < _len; _i++) {
33469 encoded = this._font.encode(word);
33470 encoded = ((function() {
33471 var _j, _ref, _results;
33473 for (i = _j = 0, _ref = encoded.length; _j < _ref; i = _j += 1) {
33474 _results.push(encoded.charCodeAt(i).toString(16));
33478 commands.push("<" + encoded + "> " + (-wordSpacing));
33480 this.addContent("[" + (commands.join(' ')) + "] TJ");
33482 encoded = this._font.encode(text);
33483 encoded = ((function() {
33484 var _j, _ref, _results;
33486 for (i = _j = 0, _ref = encoded.length; _j < _ref; i = _j += 1) {
33487 _results.push(encoded.charCodeAt(i).toString(16));
33491 this.addContent("<" + encoded + "> Tj");
33493 this.addContent("ET");
33494 return this.restore();
33503 /***/ function(module, exports, __webpack_require__) {
33505 // Generated by CoffeeScript 1.7.1
33507 var EventEmitter, LineBreaker, LineWrapper,
33508 __hasProp = {}.hasOwnProperty,
33509 __extends = 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; };
33511 EventEmitter = __webpack_require__(26).EventEmitter;
33513 LineBreaker = __webpack_require__(91);
33515 LineWrapper = (function(_super) {
33516 __extends(LineWrapper, _super);
33518 function LineWrapper(document, options) {
33520 this.document = document;
33521 this.indent = options.indent || 0;
33522 this.characterSpacing = options.characterSpacing || 0;
33523 this.wordSpacing = options.wordSpacing === 0;
33524 this.columns = options.columns || 1;
33525 this.columnGap = (_ref = options.columnGap) != null ? _ref : 18;
33526 this.lineWidth = (options.width - (this.columnGap * (this.columns - 1))) / this.columns;
33527 this.spaceLeft = this.lineWidth;
33528 this.startX = this.document.x;
33529 this.startY = this.document.y;
33531 this.ellipsis = options.ellipsis;
33532 this.continuedX = 0;
33533 if (options.height != null) {
33534 this.height = options.height;
33535 this.maxY = this.startY + options.height;
33537 this.maxY = this.document.page.maxY();
33539 this.on('firstLine', (function(_this) {
33540 return function(options) {
33542 indent = _this.continuedX || _this.indent;
33543 _this.document.x += indent;
33544 _this.lineWidth -= indent;
33545 return _this.once('line', function() {
33546 _this.document.x -= indent;
33547 _this.lineWidth += indent;
33548 if (options.continued && !_this.continuedX) {
33549 _this.continuedX = _this.indent;
33551 if (!options.continued) {
33552 return _this.continuedX = 0;
33557 this.on('lastLine', (function(_this) {
33558 return function(options) {
33560 align = options.align;
33561 if (align === 'justify') {
33562 options.align = 'left';
33564 _this.lastLine = true;
33565 return _this.once('line', function() {
33566 _this.document.y += options.paragraphGap || 0;
33567 options.align = align;
33568 return _this.lastLine = false;
33574 LineWrapper.prototype.wordWidth = function(word) {
33575 return this.document.widthOfString(word, this) + this.characterSpacing + this.wordSpacing;
33578 LineWrapper.prototype.eachWord = function(text, fn) {
33579 var bk, breaker, fbk, l, last, lbk, shouldContinue, w, word, wordWidths;
33580 breaker = new LineBreaker(text);
33583 while (bk = breaker.nextBreak()) {
33584 word = text.slice((last != null ? last.position : void 0) || 0, bk.position);
33585 w = wordWidths[word] != null ? wordWidths[word] : wordWidths[word] = this.wordWidth(word);
33586 if (w > this.lineWidth + this.continuedX) {
33589 while (word.length) {
33591 while (w > this.spaceLeft) {
33592 w = this.wordWidth(word.slice(0, --l));
33594 fbk.required = l < word.length;
33595 shouldContinue = fn(word.slice(0, l), w, fbk, lbk);
33599 word = word.slice(l);
33600 w = this.wordWidth(word);
33601 if (shouldContinue === false) {
33606 shouldContinue = fn(word, w, bk, last);
33608 if (shouldContinue === false) {
33615 LineWrapper.prototype.wrap = function(text, options) {
33616 var buffer, emitLine, lc, nextY, textWidth, wc, y;
33617 if (options.indent != null) {
33618 this.indent = options.indent;
33620 if (options.characterSpacing != null) {
33621 this.characterSpacing = options.characterSpacing;
33623 if (options.wordSpacing != null) {
33624 this.wordSpacing = options.wordSpacing;
33626 if (options.ellipsis != null) {
33627 this.ellipsis = options.ellipsis;
33629 nextY = this.document.y + this.document.currentLineHeight(true);
33630 if (this.document.y > this.maxY || nextY > this.maxY) {
33631 this.nextSection();
33637 y = this.document.y;
33638 emitLine = (function(_this) {
33639 return function() {
33640 options.textWidth = textWidth + _this.wordSpacing * (wc - 1);
33641 options.wordCount = wc;
33642 options.lineWidth = _this.lineWidth;
33643 y = _this.document.y;
33644 _this.emit('line', buffer, options, _this);
33648 this.emit('sectionStart', options, this);
33649 this.eachWord(text, (function(_this) {
33650 return function(word, w, bk, last) {
33651 var lh, shouldContinue;
33652 if ((last == null) || last.required) {
33653 _this.emit('firstLine', options, _this);
33654 _this.spaceLeft = _this.lineWidth;
33656 if (w <= _this.spaceLeft) {
33661 if (bk.required || w > _this.spaceLeft) {
33663 _this.emit('lastLine', options, _this);
33665 lh = _this.document.currentLineHeight(true);
33666 if ((_this.height != null) && _this.ellipsis && _this.document.y + lh * 2 > _this.maxY && _this.column >= _this.columns) {
33667 if (_this.ellipsis === true) {
33668 _this.ellipsis = '…';
33670 buffer = buffer.replace(/\s+$/, '');
33671 textWidth = _this.wordWidth(buffer + _this.ellipsis);
33672 while (textWidth > _this.lineWidth) {
33673 buffer = buffer.slice(0, -1).replace(/\s+$/, '');
33674 textWidth = _this.wordWidth(buffer + _this.ellipsis);
33676 buffer = buffer + _this.ellipsis;
33679 if (_this.document.y + lh > _this.maxY) {
33680 shouldContinue = _this.nextSection();
33681 if (!shouldContinue) {
33688 if (w > _this.spaceLeft) {
33694 _this.spaceLeft = _this.lineWidth;
33699 _this.spaceLeft = _this.lineWidth - w;
33705 return _this.spaceLeft -= w;
33710 this.emit('lastLine', options, this);
33713 this.emit('sectionEnd', options, this);
33714 if (options.continued === true) {
33716 this.continuedX = 0;
33718 this.continuedX += options.textWidth;
33719 return this.document.y = y;
33721 return this.document.x = this.startX;
33725 LineWrapper.prototype.nextSection = function(options) {
33727 this.emit('sectionEnd', options, this);
33728 if (++this.column > this.columns) {
33729 if (this.height != null) {
33732 this.document.addPage();
33734 this.startY = this.document.page.margins.top;
33735 this.maxY = this.document.page.maxY();
33736 this.document.x = this.startX;
33737 if (this.document._fillColor) {
33738 (_ref = this.document).fillColor.apply(_ref, this.document._fillColor);
33740 this.emit('pageBreak', options, this);
33742 this.document.x += this.lineWidth + this.columnGap;
33743 this.document.y = this.startY;
33744 this.emit('columnBreak', options, this);
33746 this.emit('sectionStart', options, this);
33750 return LineWrapper;
33754 module.exports = LineWrapper;
33761 /***/ function(module, exports, __webpack_require__) {
33763 // Generated by CoffeeScript 1.7.1
33765 var AI, AL, BA, BK, CB, CI_BRK, CJ, CP_BRK, CR, DI_BRK, ID, IN_BRK, LF, LineBreaker, NL, NS, PR_BRK, SA, SG, SP, UnicodeTrie, WJ, XX, characterClasses, classTrie, pairTable, _ref, _ref1;
33767 UnicodeTrie = __webpack_require__(92);
33769 classTrie = new UnicodeTrie(__webpack_require__(93));
33771 _ref = __webpack_require__(94), BK = _ref.BK, CR = _ref.CR, LF = _ref.LF, NL = _ref.NL, CB = _ref.CB, BA = _ref.BA, SP = _ref.SP, WJ = _ref.WJ, SP = _ref.SP, BK = _ref.BK, LF = _ref.LF, NL = _ref.NL, AI = _ref.AI, AL = _ref.AL, SA = _ref.SA, SG = _ref.SG, XX = _ref.XX, CJ = _ref.CJ, ID = _ref.ID, NS = _ref.NS, characterClasses = _ref.characterClasses;
33773 _ref1 = __webpack_require__(95), DI_BRK = _ref1.DI_BRK, IN_BRK = _ref1.IN_BRK, CI_BRK = _ref1.CI_BRK, CP_BRK = _ref1.CP_BRK, PR_BRK = _ref1.PR_BRK, pairTable = _ref1.pairTable;
33775 LineBreaker = (function() {
33776 var Break, mapClass, mapFirst;
33778 function LineBreaker(string) {
33779 this.string = string;
33782 this.curClass = null;
33783 this.nextClass = null;
33786 LineBreaker.prototype.nextCodePoint = function() {
33788 code = this.string.charCodeAt(this.pos++);
33789 next = this.string.charCodeAt(this.pos);
33790 if ((0xd800 <= code && code <= 0xdbff) && (0xdc00 <= next && next <= 0xdfff)) {
33792 return ((code - 0xd800) * 0x400) + (next - 0xdc00) + 0x10000;
33797 mapClass = function(c) {
33812 mapFirst = function(c) {
33826 LineBreaker.prototype.nextCharClass = function(first) {
33827 if (first == null) {
33830 return mapClass(classTrie.get(this.nextCodePoint()));
33833 Break = (function() {
33834 function Break(position, required) {
33835 this.position = position;
33836 this.required = required != null ? required : false;
33843 LineBreaker.prototype.nextBreak = function() {
33844 var cur, lastClass, shouldBreak;
33845 if (this.curClass == null) {
33846 this.curClass = mapFirst(this.nextCharClass());
33848 while (this.pos < this.string.length) {
33849 this.lastPos = this.pos;
33850 lastClass = this.nextClass;
33851 this.nextClass = this.nextCharClass();
33852 if (this.curClass === BK || (this.curClass === CR && this.nextClass !== LF)) {
33853 this.curClass = mapFirst(mapClass(this.nextClass));
33854 return new Break(this.lastPos, true);
33856 cur = (function() {
33857 switch (this.nextClass) {
33859 return this.curClass;
33871 this.curClass = cur;
33872 if (this.nextClass === CB) {
33873 return new Break(this.lastPos);
33877 shouldBreak = false;
33878 switch (pairTable[this.curClass][this.nextClass]) {
33880 shouldBreak = true;
33883 shouldBreak = lastClass === SP;
33886 shouldBreak = lastClass === SP;
33887 if (!shouldBreak) {
33892 if (lastClass !== SP) {
33896 this.curClass = this.nextClass;
33898 return new Break(this.lastPos);
33901 if (this.pos >= this.string.length) {
33902 if (this.lastPos < this.string.length) {
33903 this.lastPos = this.string.length;
33904 return new Break(this.string.length);
33911 return LineBreaker;
33915 module.exports = LineBreaker;
33922 /***/ function(module, exports) {
33924 // Generated by CoffeeScript 1.7.1
33926 __slice = [].slice;
33928 UnicodeTrie = (function() {
33929 var DATA_BLOCK_LENGTH, DATA_GRANULARITY, DATA_MASK, INDEX_1_OFFSET, INDEX_2_BLOCK_LENGTH, INDEX_2_BMP_LENGTH, INDEX_2_MASK, INDEX_SHIFT, LSCP_INDEX_2_LENGTH, LSCP_INDEX_2_OFFSET, OMITTED_BMP_INDEX_1_LENGTH, SHIFT_1, SHIFT_1_2, SHIFT_2, UTF8_2B_INDEX_2_LENGTH, UTF8_2B_INDEX_2_OFFSET;
33935 SHIFT_1_2 = SHIFT_1 - SHIFT_2;
33937 OMITTED_BMP_INDEX_1_LENGTH = 0x10000 >> SHIFT_1;
33939 INDEX_2_BLOCK_LENGTH = 1 << SHIFT_1_2;
33941 INDEX_2_MASK = INDEX_2_BLOCK_LENGTH - 1;
33945 DATA_BLOCK_LENGTH = 1 << SHIFT_2;
33947 DATA_MASK = DATA_BLOCK_LENGTH - 1;
33949 LSCP_INDEX_2_OFFSET = 0x10000 >> SHIFT_2;
33951 LSCP_INDEX_2_LENGTH = 0x400 >> SHIFT_2;
33953 INDEX_2_BMP_LENGTH = LSCP_INDEX_2_OFFSET + LSCP_INDEX_2_LENGTH;
33955 UTF8_2B_INDEX_2_OFFSET = INDEX_2_BMP_LENGTH;
33957 UTF8_2B_INDEX_2_LENGTH = 0x800 >> 6;
33959 INDEX_1_OFFSET = UTF8_2B_INDEX_2_OFFSET + UTF8_2B_INDEX_2_LENGTH;
33961 DATA_GRANULARITY = 1 << INDEX_SHIFT;
33963 function UnicodeTrie(json) {
33965 if (json == null) {
33968 this.data = json.data || [];
33969 this.highStart = (_ref = json.highStart) != null ? _ref : 0;
33970 this.errorValue = (_ref1 = json.errorValue) != null ? _ref1 : -1;
33973 UnicodeTrie.prototype.get = function(codePoint) {
33975 if (codePoint < 0 || codePoint > 0x10ffff) {
33976 return this.errorValue;
33978 if (codePoint < 0xd800 || (codePoint > 0xdbff && codePoint <= 0xffff)) {
33979 index = (this.data[codePoint >> SHIFT_2] << INDEX_SHIFT) + (codePoint & DATA_MASK);
33980 return this.data[index];
33982 if (codePoint <= 0xffff) {
33983 index = (this.data[LSCP_INDEX_2_OFFSET + ((codePoint - 0xd800) >> SHIFT_2)] << INDEX_SHIFT) + (codePoint & DATA_MASK);
33984 return this.data[index];
33986 if (codePoint < this.highStart) {
33987 index = this.data[(INDEX_1_OFFSET - OMITTED_BMP_INDEX_1_LENGTH) + (codePoint >> SHIFT_1)];
33988 index = this.data[index + ((codePoint >> SHIFT_2) & INDEX_2_MASK)];
33989 index = (index << INDEX_SHIFT) + (codePoint & DATA_MASK);
33990 return this.data[index];
33992 return this.data[this.data.length - DATA_GRANULARITY];
33995 UnicodeTrie.prototype.toJSON = function() {
33998 data: __slice.call(this.data),
33999 highStart: this.highStart,
34000 errorValue: this.errorValue
34005 return UnicodeTrie;
34009 module.exports = UnicodeTrie;
34014 /***/ function(module, exports) {
66635 "highStart": 919552,
66641 /***/ function(module, exports) {
66643 // Generated by CoffeeScript 1.7.1
66645 var AI, AL, B2, BA, BB, BK, CB, CJ, CL, CM, CP, CR, EX, GL, H2, H3, HL, HY, ID, IN, IS, JL, JT, JV, LF, NL, NS, NU, OP, PO, PR, QU, RI, SA, SG, SP, SY, WJ, XX, ZW;
66647 exports.OP = OP = 0;
66649 exports.CL = CL = 1;
66651 exports.CP = CP = 2;
66653 exports.QU = QU = 3;
66655 exports.GL = GL = 4;
66657 exports.NS = NS = 5;
66659 exports.EX = EX = 6;
66661 exports.SY = SY = 7;
66663 exports.IS = IS = 8;
66665 exports.PR = PR = 9;
66667 exports.PO = PO = 10;
66669 exports.NU = NU = 11;
66671 exports.AL = AL = 12;
66673 exports.HL = HL = 13;
66675 exports.ID = ID = 14;
66677 exports.IN = IN = 15;
66679 exports.HY = HY = 16;
66681 exports.BA = BA = 17;
66683 exports.BB = BB = 18;
66685 exports.B2 = B2 = 19;
66687 exports.ZW = ZW = 20;
66689 exports.CM = CM = 21;
66691 exports.WJ = WJ = 22;
66693 exports.H2 = H2 = 23;
66695 exports.H3 = H3 = 24;
66697 exports.JL = JL = 25;
66699 exports.JV = JV = 26;
66701 exports.JT = JT = 27;
66703 exports.RI = RI = 28;
66705 exports.AI = AI = 29;
66707 exports.BK = BK = 30;
66709 exports.CB = CB = 31;
66711 exports.CJ = CJ = 32;
66713 exports.CR = CR = 33;
66715 exports.LF = LF = 34;
66717 exports.NL = NL = 35;
66719 exports.SA = SA = 36;
66721 exports.SG = SG = 37;
66723 exports.SP = SP = 38;
66725 exports.XX = XX = 39;
66732 /***/ function(module, exports) {
66734 // Generated by CoffeeScript 1.7.1
66736 var CI_BRK, CP_BRK, DI_BRK, IN_BRK, PR_BRK;
66738 exports.DI_BRK = DI_BRK = 0;
66740 exports.IN_BRK = IN_BRK = 1;
66742 exports.CI_BRK = CI_BRK = 2;
66744 exports.CP_BRK = CP_BRK = 3;
66746 exports.PR_BRK = PR_BRK = 4;
66748 exports.pairTable = [[PR_BRK, PR_BRK, PR_BRK, PR_BRK, PR_BRK, PR_BRK, PR_BRK, PR_BRK, PR_BRK, PR_BRK, PR_BRK, PR_BRK, PR_BRK, PR_BRK, PR_BRK, PR_BRK, PR_BRK, PR_BRK, PR_BRK, PR_BRK, PR_BRK, CP_BRK, PR_BRK, PR_BRK, PR_BRK, PR_BRK, PR_BRK, PR_BRK, PR_BRK], [DI_BRK, PR_BRK, PR_BRK, IN_BRK, IN_BRK, PR_BRK, PR_BRK, PR_BRK, PR_BRK, IN_BRK, IN_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, IN_BRK, IN_BRK, DI_BRK, DI_BRK, PR_BRK, CI_BRK, PR_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK], [DI_BRK, PR_BRK, PR_BRK, IN_BRK, IN_BRK, PR_BRK, PR_BRK, PR_BRK, PR_BRK, IN_BRK, IN_BRK, IN_BRK, IN_BRK, IN_BRK, DI_BRK, DI_BRK, IN_BRK, IN_BRK, DI_BRK, DI_BRK, PR_BRK, CI_BRK, PR_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK], [PR_BRK, PR_BRK, PR_BRK, IN_BRK, IN_BRK, IN_BRK, PR_BRK, PR_BRK, PR_BRK, IN_BRK, IN_BRK, IN_BRK, IN_BRK, IN_BRK, IN_BRK, IN_BRK, IN_BRK, IN_BRK, IN_BRK, IN_BRK, PR_BRK, CI_BRK, PR_BRK, IN_BRK, IN_BRK, IN_BRK, IN_BRK, IN_BRK, IN_BRK], [IN_BRK, PR_BRK, PR_BRK, IN_BRK, IN_BRK, IN_BRK, PR_BRK, PR_BRK, PR_BRK, IN_BRK, IN_BRK, IN_BRK, IN_BRK, IN_BRK, IN_BRK, IN_BRK, IN_BRK, IN_BRK, IN_BRK, IN_BRK, PR_BRK, CI_BRK, PR_BRK, IN_BRK, IN_BRK, IN_BRK, IN_BRK, IN_BRK, IN_BRK], [DI_BRK, PR_BRK, PR_BRK, IN_BRK, IN_BRK, IN_BRK, PR_BRK, PR_BRK, PR_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, IN_BRK, IN_BRK, DI_BRK, DI_BRK, PR_BRK, CI_BRK, PR_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK], [DI_BRK, PR_BRK, PR_BRK, IN_BRK, IN_BRK, IN_BRK, PR_BRK, PR_BRK, PR_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, IN_BRK, IN_BRK, DI_BRK, DI_BRK, PR_BRK, CI_BRK, PR_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK], [DI_BRK, PR_BRK, PR_BRK, IN_BRK, IN_BRK, IN_BRK, PR_BRK, PR_BRK, PR_BRK, DI_BRK, DI_BRK, IN_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, IN_BRK, IN_BRK, DI_BRK, DI_BRK, PR_BRK, CI_BRK, PR_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK], [DI_BRK, PR_BRK, PR_BRK, IN_BRK, IN_BRK, IN_BRK, PR_BRK, PR_BRK, PR_BRK, DI_BRK, DI_BRK, IN_BRK, IN_BRK, IN_BRK, DI_BRK, DI_BRK, IN_BRK, IN_BRK, DI_BRK, DI_BRK, PR_BRK, CI_BRK, PR_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK], [IN_BRK, PR_BRK, PR_BRK, IN_BRK, IN_BRK, IN_BRK, PR_BRK, PR_BRK, PR_BRK, DI_BRK, DI_BRK, IN_BRK, IN_BRK, IN_BRK, IN_BRK, DI_BRK, IN_BRK, IN_BRK, DI_BRK, DI_BRK, PR_BRK, CI_BRK, PR_BRK, IN_BRK, IN_BRK, IN_BRK, IN_BRK, IN_BRK, DI_BRK], [IN_BRK, PR_BRK, PR_BRK, IN_BRK, IN_BRK, IN_BRK, PR_BRK, PR_BRK, PR_BRK, DI_BRK, DI_BRK, IN_BRK, IN_BRK, IN_BRK, DI_BRK, DI_BRK, IN_BRK, IN_BRK, DI_BRK, DI_BRK, PR_BRK, CI_BRK, PR_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK], [IN_BRK, PR_BRK, PR_BRK, IN_BRK, IN_BRK, IN_BRK, PR_BRK, PR_BRK, PR_BRK, IN_BRK, IN_BRK, IN_BRK, IN_BRK, IN_BRK, DI_BRK, IN_BRK, IN_BRK, IN_BRK, DI_BRK, DI_BRK, PR_BRK, CI_BRK, PR_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK], [IN_BRK, PR_BRK, PR_BRK, IN_BRK, IN_BRK, IN_BRK, PR_BRK, PR_BRK, PR_BRK, DI_BRK, DI_BRK, IN_BRK, IN_BRK, IN_BRK, DI_BRK, IN_BRK, IN_BRK, IN_BRK, DI_BRK, DI_BRK, PR_BRK, CI_BRK, PR_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK], [IN_BRK, PR_BRK, PR_BRK, IN_BRK, IN_BRK, IN_BRK, PR_BRK, PR_BRK, PR_BRK, DI_BRK, DI_BRK, IN_BRK, IN_BRK, IN_BRK, DI_BRK, IN_BRK, IN_BRK, IN_BRK, DI_BRK, DI_BRK, PR_BRK, CI_BRK, PR_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK], [DI_BRK, PR_BRK, PR_BRK, IN_BRK, IN_BRK, IN_BRK, PR_BRK, PR_BRK, PR_BRK, DI_BRK, IN_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, IN_BRK, IN_BRK, IN_BRK, DI_BRK, DI_BRK, PR_BRK, CI_BRK, PR_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK], [DI_BRK, PR_BRK, PR_BRK, IN_BRK, IN_BRK, IN_BRK, PR_BRK, PR_BRK, PR_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, IN_BRK, IN_BRK, IN_BRK, DI_BRK, DI_BRK, PR_BRK, CI_BRK, PR_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK], [DI_BRK, PR_BRK, PR_BRK, IN_BRK, DI_BRK, IN_BRK, PR_BRK, PR_BRK, PR_BRK, DI_BRK, DI_BRK, IN_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, IN_BRK, IN_BRK, DI_BRK, DI_BRK, PR_BRK, CI_BRK, PR_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK], [DI_BRK, PR_BRK, PR_BRK, IN_BRK, DI_BRK, IN_BRK, PR_BRK, PR_BRK, PR_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, IN_BRK, IN_BRK, DI_BRK, DI_BRK, PR_BRK, CI_BRK, PR_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK], [IN_BRK, PR_BRK, PR_BRK, IN_BRK, IN_BRK, IN_BRK, PR_BRK, PR_BRK, PR_BRK, IN_BRK, IN_BRK, IN_BRK, IN_BRK, IN_BRK, IN_BRK, IN_BRK, IN_BRK, IN_BRK, IN_BRK, IN_BRK, PR_BRK, CI_BRK, PR_BRK, IN_BRK, IN_BRK, IN_BRK, IN_BRK, IN_BRK, IN_BRK], [DI_BRK, PR_BRK, PR_BRK, IN_BRK, IN_BRK, IN_BRK, PR_BRK, PR_BRK, PR_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, IN_BRK, IN_BRK, DI_BRK, PR_BRK, PR_BRK, CI_BRK, PR_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK], [DI_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, PR_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK], [IN_BRK, PR_BRK, PR_BRK, IN_BRK, IN_BRK, IN_BRK, PR_BRK, PR_BRK, PR_BRK, DI_BRK, DI_BRK, IN_BRK, IN_BRK, IN_BRK, DI_BRK, IN_BRK, IN_BRK, IN_BRK, DI_BRK, DI_BRK, PR_BRK, CI_BRK, PR_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK], [IN_BRK, PR_BRK, PR_BRK, IN_BRK, IN_BRK, IN_BRK, PR_BRK, PR_BRK, PR_BRK, IN_BRK, IN_BRK, IN_BRK, IN_BRK, IN_BRK, IN_BRK, IN_BRK, IN_BRK, IN_BRK, IN_BRK, IN_BRK, PR_BRK, CI_BRK, PR_BRK, IN_BRK, IN_BRK, IN_BRK, IN_BRK, IN_BRK, IN_BRK], [DI_BRK, PR_BRK, PR_BRK, IN_BRK, IN_BRK, IN_BRK, PR_BRK, PR_BRK, PR_BRK, DI_BRK, IN_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, IN_BRK, IN_BRK, IN_BRK, DI_BRK, DI_BRK, PR_BRK, CI_BRK, PR_BRK, DI_BRK, DI_BRK, DI_BRK, IN_BRK, IN_BRK, DI_BRK], [DI_BRK, PR_BRK, PR_BRK, IN_BRK, IN_BRK, IN_BRK, PR_BRK, PR_BRK, PR_BRK, DI_BRK, IN_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, IN_BRK, IN_BRK, IN_BRK, DI_BRK, DI_BRK, PR_BRK, CI_BRK, PR_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, IN_BRK, DI_BRK], [DI_BRK, PR_BRK, PR_BRK, IN_BRK, IN_BRK, IN_BRK, PR_BRK, PR_BRK, PR_BRK, DI_BRK, IN_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, IN_BRK, IN_BRK, IN_BRK, DI_BRK, DI_BRK, PR_BRK, CI_BRK, PR_BRK, IN_BRK, IN_BRK, IN_BRK, IN_BRK, DI_BRK, DI_BRK], [DI_BRK, PR_BRK, PR_BRK, IN_BRK, IN_BRK, IN_BRK, PR_BRK, PR_BRK, PR_BRK, DI_BRK, IN_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, IN_BRK, IN_BRK, IN_BRK, DI_BRK, DI_BRK, PR_BRK, CI_BRK, PR_BRK, DI_BRK, DI_BRK, DI_BRK, IN_BRK, IN_BRK, DI_BRK], [DI_BRK, PR_BRK, PR_BRK, IN_BRK, IN_BRK, IN_BRK, PR_BRK, PR_BRK, PR_BRK, DI_BRK, IN_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, IN_BRK, IN_BRK, IN_BRK, DI_BRK, DI_BRK, PR_BRK, CI_BRK, PR_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, IN_BRK, DI_BRK], [DI_BRK, PR_BRK, PR_BRK, IN_BRK, IN_BRK, IN_BRK, PR_BRK, PR_BRK, PR_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, IN_BRK, IN_BRK, DI_BRK, DI_BRK, PR_BRK, CI_BRK, PR_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, IN_BRK]];
66755 /***/ function(module, exports, __webpack_require__) {
66757 /* WEBPACK VAR INJECTION */(function(Buffer) {// Generated by CoffeeScript 1.7.1
66761 PDFImage = __webpack_require__(97);
66764 initImages: function() {
66765 this._imageRegistry = {};
66766 return this._imageCount = 0;
66768 image: function(src, x, y, options) {
66769 var bh, bp, bw, h, hp, image, ip, w, wp, _base, _name, _ref, _ref1, _ref2;
66770 if (options == null) {
66773 if (typeof x === 'object') {
66777 x = (_ref = x != null ? x : options.x) != null ? _ref : this.x;
66778 y = (_ref1 = y != null ? y : options.y) != null ? _ref1 : this.y;
66779 if (!Buffer.isBuffer(src)) {
66780 image = this._imageRegistry[src];
66783 image = PDFImage.open(src, 'I' + (++this._imageCount));
66785 if (!Buffer.isBuffer(src)) {
66786 this._imageRegistry[src] = image;
66789 if ((_base = this.page.xobjects)[_name = image.label] == null) {
66790 _base[_name] = image.obj;
66792 w = options.width || image.width;
66793 h = options.height || image.height;
66794 if (options.width && !options.height) {
66795 wp = w / image.width;
66796 w = image.width * wp;
66797 h = image.height * wp;
66798 } else if (options.height && !options.width) {
66799 hp = h / image.height;
66800 w = image.width * hp;
66801 h = image.height * hp;
66802 } else if (options.scale) {
66803 w = image.width * options.scale;
66804 h = image.height * options.scale;
66805 } else if (options.fit) {
66806 _ref2 = options.fit, bw = _ref2[0], bh = _ref2[1];
66808 ip = image.width / image.height;
66816 if (options.align === 'center') {
66817 x = x + bw / 2 - w / 2;
66818 } else if (options.align === 'right') {
66821 if (options.valign === 'center') {
66822 y = y + bh / 2 - h / 2;
66823 } else if (options.valign === 'bottom') {
66827 if (this.y === y) {
66831 this.transform(w, 0, 0, -h, x, y + h);
66832 this.addContent("/" + image.label + " Do");
66840 /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2).Buffer))
66844 /***/ function(module, exports, __webpack_require__) {
66846 /* WEBPACK VAR INJECTION */(function(Buffer) {// Generated by CoffeeScript 1.7.1
66849 PDFImage - embeds images in PDF documents
66854 var Data, JPEG, PDFImage, PNG, fs;
66856 fs = __webpack_require__(44);
66858 Data = __webpack_require__(72);
66860 JPEG = __webpack_require__(98);
66862 PNG = __webpack_require__(99);
66864 PDFImage = (function() {
66865 function PDFImage() {}
66867 PDFImage.open = function(src, label) {
66869 if (Buffer.isBuffer(src)) {
66872 if (match = /^data:.+;base64,(.*)$/.exec(src)) {
66873 data = new Buffer(match[1], 'base64');
66875 data = fs.readFileSync(src);
66881 if (data[0] === 0xff && data[1] === 0xd8) {
66882 return new JPEG(data, label);
66883 } else if (data[0] === 0x89 && data.toString('ascii', 1, 4) === 'PNG') {
66884 return new PNG(data, label);
66886 throw new Error('Unknown image format.');
66894 module.exports = PDFImage;
66898 /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2).Buffer))
66902 /***/ function(module, exports, __webpack_require__) {
66904 // Generated by CoffeeScript 1.7.1
66907 __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; };
66909 fs = __webpack_require__(44);
66911 JPEG = (function() {
66914 MARKERS = [0xFFC0, 0xFFC1, 0xFFC2, 0xFFC3, 0xFFC5, 0xFFC6, 0xFFC7, 0xFFC8, 0xFFC9, 0xFFCA, 0xFFCB, 0xFFCC, 0xFFCD, 0xFFCE, 0xFFCF];
66916 function JPEG(data, label) {
66917 var channels, marker, pos;
66919 this.label = label;
66920 if (this.data.readUInt16BE(0) !== 0xFFD8) {
66921 throw "SOI not found in JPEG";
66924 while (pos < this.data.length) {
66925 marker = this.data.readUInt16BE(pos);
66927 if (__indexOf.call(MARKERS, marker) >= 0) {
66930 pos += this.data.readUInt16BE(pos);
66932 if (__indexOf.call(MARKERS, marker) < 0) {
66933 throw "Invalid JPEG.";
66936 this.bits = this.data[pos++];
66937 this.height = this.data.readUInt16BE(pos);
66939 this.width = this.data.readUInt16BE(pos);
66941 channels = this.data[pos++];
66942 this.colorSpace = (function() {
66943 switch (channels) {
66945 return 'DeviceGray';
66947 return 'DeviceRGB';
66949 return 'DeviceCMYK';
66955 JPEG.prototype.embed = function(document) {
66959 this.obj = document.ref({
66962 BitsPerComponent: this.bits,
66964 Height: this.height,
66965 ColorSpace: this.colorSpace,
66966 Filter: 'DCTDecode'
66968 if (this.colorSpace === 'DeviceCMYK') {
66969 this.obj.data['Decode'] = [1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0];
66971 this.obj.end(this.data);
66972 return this.data = null;
66979 module.exports = JPEG;
66986 /***/ function(module, exports, __webpack_require__) {
66988 /* WEBPACK VAR INJECTION */(function(Buffer) {// Generated by CoffeeScript 1.7.1
66990 var PNG, PNGImage, zlib;
66992 zlib = __webpack_require__(47);
66994 PNG = __webpack_require__(100);
66996 PNGImage = (function() {
66997 function PNGImage(data, label) {
66998 this.label = label;
66999 this.image = new PNG(data);
67000 this.width = this.image.width;
67001 this.height = this.image.height;
67002 this.imgData = this.image.imgData;
67006 PNGImage.prototype.embed = function(document) {
67007 var mask, palette, params, rgb, val, x, _i, _len;
67008 this.document = document;
67012 this.obj = document.ref({
67015 BitsPerComponent: this.image.bits,
67017 Height: this.height,
67018 Filter: 'FlateDecode'
67020 if (!this.image.hasAlphaChannel) {
67021 params = document.ref({
67023 Colors: this.image.colors,
67024 BitsPerComponent: this.image.bits,
67025 Columns: this.width
67027 this.obj.data['DecodeParms'] = params;
67030 if (this.image.palette.length === 0) {
67031 this.obj.data['ColorSpace'] = this.image.colorSpace;
67033 palette = document.ref();
67034 palette.end(new Buffer(this.image.palette));
67035 this.obj.data['ColorSpace'] = ['Indexed', 'DeviceRGB', (this.image.palette.length / 3) - 1, palette];
67037 if (this.image.transparency.grayscale) {
67038 val = this.image.transparency.greyscale;
67039 return this.obj.data['Mask'] = [val, val];
67040 } else if (this.image.transparency.rgb) {
67041 rgb = this.image.transparency.rgb;
67043 for (_i = 0, _len = rgb.length; _i < _len; _i++) {
67047 return this.obj.data['Mask'] = mask;
67048 } else if (this.image.transparency.indexed) {
67049 return this.loadIndexedAlphaChannel();
67050 } else if (this.image.hasAlphaChannel) {
67051 return this.splitAlphaChannel();
67053 return this.finalize();
67057 PNGImage.prototype.finalize = function() {
67059 if (this.alphaChannel) {
67060 sMask = this.document.ref({
67063 Height: this.height,
67065 BitsPerComponent: 8,
67066 Filter: 'FlateDecode',
67067 ColorSpace: 'DeviceGray',
67070 sMask.end(this.alphaChannel);
67071 this.obj.data['SMask'] = sMask;
67073 this.obj.end(this.imgData);
67075 return this.imgData = null;
67078 PNGImage.prototype.splitAlphaChannel = function() {
67079 return this.image.decodePixels((function(_this) {
67080 return function(pixels) {
67081 var a, alphaChannel, colorByteSize, done, i, imgData, len, p, pixelCount;
67082 colorByteSize = _this.image.colors * _this.image.bits / 8;
67083 pixelCount = _this.width * _this.height;
67084 imgData = new Buffer(pixelCount * colorByteSize);
67085 alphaChannel = new Buffer(pixelCount);
67087 len = pixels.length;
67089 imgData[p++] = pixels[i++];
67090 imgData[p++] = pixels[i++];
67091 imgData[p++] = pixels[i++];
67092 alphaChannel[a++] = pixels[i++];
67095 zlib.deflate(imgData, function(err, imgData) {
67096 _this.imgData = imgData;
67100 if (++done === 2) {
67101 return _this.finalize();
67104 return zlib.deflate(alphaChannel, function(err, alphaChannel) {
67105 _this.alphaChannel = alphaChannel;
67109 if (++done === 2) {
67110 return _this.finalize();
67117 PNGImage.prototype.loadIndexedAlphaChannel = function(fn) {
67119 transparency = this.image.transparency.indexed;
67120 return this.image.decodePixels((function(_this) {
67121 return function(pixels) {
67122 var alphaChannel, i, j, _i, _ref;
67123 alphaChannel = new Buffer(_this.width * _this.height);
67125 for (j = _i = 0, _ref = pixels.length; _i < _ref; j = _i += 1) {
67126 alphaChannel[i++] = transparency[pixels[j]];
67128 return zlib.deflate(alphaChannel, function(err, alphaChannel) {
67129 _this.alphaChannel = alphaChannel;
67133 return _this.finalize();
67143 module.exports = PNGImage;
67147 /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2).Buffer))
67151 /***/ function(module, exports, __webpack_require__) {
67153 /* WEBPACK VAR INJECTION */(function(Buffer) {// Generated by CoffeeScript 1.4.0
67157 # Copyright (c) 2011 Devon Govett
67159 # Permission is hereby granted, free of charge, to any person obtaining a copy of this
67160 # software and associated documentation files (the "Software"), to deal in the Software
67161 # without restriction, including without limitation the rights to use, copy, modify, merge,
67162 # publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
67163 # to whom the Software is furnished to do so, subject to the following conditions:
67165 # The above copyright notice and this permission notice shall be included in all copies or
67166 # substantial portions of the Software.
67168 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
67169 # BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
67170 # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
67171 # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
67172 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
67179 fs = __webpack_require__(44);
67181 zlib = __webpack_require__(47);
67183 module.exports = PNG = (function() {
67185 PNG.decode = function(path, fn) {
67186 return fs.readFile(path, function(err, file) {
67188 png = new PNG(file);
67189 return png.decode(function(pixels) {
67195 PNG.load = function(path) {
67197 file = fs.readFileSync(path);
67198 return new PNG(file);
67201 function PNG(data) {
67202 var chunkSize, colors, i, index, key, section, short, text, _i, _j, _ref;
67207 this.transparency = {};
67210 chunkSize = this.readUInt32();
67211 section = ((function() {
67214 for (i = _i = 0; _i < 4; i = ++_i) {
67215 _results.push(String.fromCharCode(this.data[this.pos++]));
67218 }).call(this)).join('');
67221 this.width = this.readUInt32();
67222 this.height = this.readUInt32();
67223 this.bits = this.data[this.pos++];
67224 this.colorType = this.data[this.pos++];
67225 this.compressionMethod = this.data[this.pos++];
67226 this.filterMethod = this.data[this.pos++];
67227 this.interlaceMethod = this.data[this.pos++];
67230 this.palette = this.read(chunkSize);
67233 for (i = _i = 0; _i < chunkSize; i = _i += 1) {
67234 this.imgData.push(this.data[this.pos++]);
67238 this.transparency = {};
67239 switch (this.colorType) {
67241 this.transparency.indexed = this.read(chunkSize);
67242 short = 255 - this.transparency.indexed.length;
67244 for (i = _j = 0; 0 <= short ? _j < short : _j > short; i = 0 <= short ? ++_j : --_j) {
67245 this.transparency.indexed.push(255);
67250 this.transparency.grayscale = this.read(chunkSize)[0];
67253 this.transparency.rgb = this.read(chunkSize);
67257 text = this.read(chunkSize);
67258 index = text.indexOf(0);
67259 key = String.fromCharCode.apply(String, text.slice(0, index));
67260 this.text[key] = String.fromCharCode.apply(String, text.slice(index + 1));
67263 this.colors = (function() {
67264 switch (this.colorType) {
67274 this.hasAlphaChannel = (_ref = this.colorType) === 4 || _ref === 6;
67275 colors = this.colors + (this.hasAlphaChannel ? 1 : 0);
67276 this.pixelBitlength = this.bits * colors;
67277 this.colorSpace = (function() {
67278 switch (this.colors) {
67280 return 'DeviceGray';
67282 return 'DeviceRGB';
67285 this.imgData = new Buffer(this.imgData);
67288 this.pos += chunkSize;
67291 if (this.pos > this.data.length) {
67292 throw new Error("Incomplete or corrupt PNG file");
67298 PNG.prototype.read = function(bytes) {
67299 var i, _i, _results;
67301 for (i = _i = 0; 0 <= bytes ? _i < bytes : _i > bytes; i = 0 <= bytes ? ++_i : --_i) {
67302 _results.push(this.data[this.pos++]);
67307 PNG.prototype.readUInt32 = function() {
67308 var b1, b2, b3, b4;
67309 b1 = this.data[this.pos++] << 24;
67310 b2 = this.data[this.pos++] << 16;
67311 b3 = this.data[this.pos++] << 8;
67312 b4 = this.data[this.pos++];
67313 return b1 | b2 | b3 | b4;
67316 PNG.prototype.readUInt16 = function() {
67318 b1 = this.data[this.pos++] << 8;
67319 b2 = this.data[this.pos++];
67323 PNG.prototype.decodePixels = function(fn) {
67325 return zlib.inflate(this.imgData, function(err, data) {
67326 var byte, c, col, i, left, length, p, pa, paeth, pb, pc, pixelBytes, pixels, pos, row, scanlineLength, upper, upperLeft, _i, _j, _k, _l, _m;
67330 pixelBytes = _this.pixelBitlength / 8;
67331 scanlineLength = pixelBytes * _this.width;
67332 pixels = new Buffer(scanlineLength * _this.height);
67333 length = data.length;
67337 while (pos < length) {
67338 switch (data[pos++]) {
67340 for (i = _i = 0; _i < scanlineLength; i = _i += 1) {
67341 pixels[c++] = data[pos++];
67345 for (i = _j = 0; _j < scanlineLength; i = _j += 1) {
67346 byte = data[pos++];
67347 left = i < pixelBytes ? 0 : pixels[c - pixelBytes];
67348 pixels[c++] = (byte + left) % 256;
67352 for (i = _k = 0; _k < scanlineLength; i = _k += 1) {
67353 byte = data[pos++];
67354 col = (i - (i % pixelBytes)) / pixelBytes;
67355 upper = row && pixels[(row - 1) * scanlineLength + col * pixelBytes + (i % pixelBytes)];
67356 pixels[c++] = (upper + byte) % 256;
67360 for (i = _l = 0; _l < scanlineLength; i = _l += 1) {
67361 byte = data[pos++];
67362 col = (i - (i % pixelBytes)) / pixelBytes;
67363 left = i < pixelBytes ? 0 : pixels[c - pixelBytes];
67364 upper = row && pixels[(row - 1) * scanlineLength + col * pixelBytes + (i % pixelBytes)];
67365 pixels[c++] = (byte + Math.floor((left + upper) / 2)) % 256;
67369 for (i = _m = 0; _m < scanlineLength; i = _m += 1) {
67370 byte = data[pos++];
67371 col = (i - (i % pixelBytes)) / pixelBytes;
67372 left = i < pixelBytes ? 0 : pixels[c - pixelBytes];
67374 upper = upperLeft = 0;
67376 upper = pixels[(row - 1) * scanlineLength + col * pixelBytes + (i % pixelBytes)];
67377 upperLeft = col && pixels[(row - 1) * scanlineLength + (col - 1) * pixelBytes + (i % pixelBytes)];
67379 p = left + upper - upperLeft;
67380 pa = Math.abs(p - left);
67381 pb = Math.abs(p - upper);
67382 pc = Math.abs(p - upperLeft);
67383 if (pa <= pb && pa <= pc) {
67385 } else if (pb <= pc) {
67390 pixels[c++] = (byte + paeth) % 256;
67394 throw new Error("Invalid filter algorithm: " + data[pos - 1]);
67402 PNG.prototype.decodePalette = function() {
67403 var c, i, length, palette, pos, ret, transparency, _i, _ref, _ref1;
67404 palette = this.palette;
67405 transparency = this.transparency.indexed || [];
67406 ret = new Buffer(transparency.length + palette.length);
67408 length = palette.length;
67410 for (i = _i = 0, _ref = palette.length; _i < _ref; i = _i += 3) {
67411 ret[pos++] = palette[i];
67412 ret[pos++] = palette[i + 1];
67413 ret[pos++] = palette[i + 2];
67414 ret[pos++] = (_ref1 = transparency[c++]) != null ? _ref1 : 255;
67419 PNG.prototype.copyToImageData = function(imageData, pixels) {
67420 var alpha, colors, data, i, input, j, k, length, palette, v, _ref;
67421 colors = this.colors;
67423 alpha = this.hasAlphaChannel;
67424 if (this.palette.length) {
67425 palette = (_ref = this._decodedPalette) != null ? _ref : this._decodedPalette = this.decodePalette();
67429 data = (imageData != null ? imageData.data : void 0) || imageData;
67430 length = data.length;
67431 input = palette || pixels;
67433 if (colors === 1) {
67434 while (i < length) {
67435 k = palette ? pixels[i / 4] * 4 : j;
67440 data[i++] = alpha ? input[k++] : 255;
67444 while (i < length) {
67445 k = palette ? pixels[i / 4] * 4 : j;
67446 data[i++] = input[k++];
67447 data[i++] = input[k++];
67448 data[i++] = input[k++];
67449 data[i++] = alpha ? input[k++] : 255;
67455 PNG.prototype.decode = function(fn) {
67458 ret = new Buffer(this.width * this.height * 4);
67459 return this.decodePixels(function(pixels) {
67460 _this.copyToImageData(ret, pixels);
67471 /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2).Buffer))
67475 /***/ function(module, exports) {
67477 // Generated by CoffeeScript 1.7.1
67480 annotate: function(x, y, w, h, options) {
67482 options.Type = 'Annot';
67483 options.Rect = this._convertRect(x, y, w, h);
67484 options.Border = [0, 0, 0];
67485 if (options.Subtype !== 'Link') {
67486 if (options.C == null) {
67487 options.C = this._normalizeColor(options.color || [0, 0, 0]);
67490 delete options.color;
67491 if (typeof options.Dest === 'string') {
67492 options.Dest = new String(options.Dest);
67494 for (key in options) {
67495 val = options[key];
67496 options[key[0].toUpperCase() + key.slice(1)] = val;
67498 ref = this.ref(options);
67499 this.page.annotations.push(ref);
67503 note: function(x, y, w, h, contents, options) {
67504 if (options == null) {
67507 options.Subtype = 'Text';
67508 options.Contents = new String(contents);
67509 options.Name = 'Comment';
67510 if (options.color == null) {
67511 options.color = [243, 223, 92];
67513 return this.annotate(x, y, w, h, options);
67515 link: function(x, y, w, h, url, options) {
67516 if (options == null) {
67519 options.Subtype = 'Link';
67520 options.A = this.ref({
67522 URI: new String(url)
67525 return this.annotate(x, y, w, h, options);
67527 _markup: function(x, y, w, h, options) {
67528 var x1, x2, y1, y2, _ref;
67529 if (options == null) {
67532 _ref = this._convertRect(x, y, w, h), x1 = _ref[0], y1 = _ref[1], x2 = _ref[2], y2 = _ref[3];
67533 options.QuadPoints = [x1, y2, x2, y2, x1, y1, x2, y1];
67534 options.Contents = new String;
67535 return this.annotate(x, y, w, h, options);
67537 highlight: function(x, y, w, h, options) {
67538 if (options == null) {
67541 options.Subtype = 'Highlight';
67542 if (options.color == null) {
67543 options.color = [241, 238, 148];
67545 return this._markup(x, y, w, h, options);
67547 underline: function(x, y, w, h, options) {
67548 if (options == null) {
67551 options.Subtype = 'Underline';
67552 return this._markup(x, y, w, h, options);
67554 strike: function(x, y, w, h, options) {
67555 if (options == null) {
67558 options.Subtype = 'StrikeOut';
67559 return this._markup(x, y, w, h, options);
67561 lineAnnotation: function(x1, y1, x2, y2, options) {
67562 if (options == null) {
67565 options.Subtype = 'Line';
67566 options.Contents = new String;
67567 options.L = [x1, this.page.height - y1, x2, this.page.height - y2];
67568 return this.annotate(x1, y1, x2, y2, options);
67570 rectAnnotation: function(x, y, w, h, options) {
67571 if (options == null) {
67574 options.Subtype = 'Square';
67575 options.Contents = new String;
67576 return this.annotate(x, y, w, h, options);
67578 ellipseAnnotation: function(x, y, w, h, options) {
67579 if (options == null) {
67582 options.Subtype = 'Circle';
67583 options.Contents = new String;
67584 return this.annotate(x, y, w, h, options);
67586 textAnnotation: function(x, y, w, h, text, options) {
67587 if (options == null) {
67590 options.Subtype = 'FreeText';
67591 options.Contents = new String(text);
67592 options.DA = new String;
67593 return this.annotate(x, y, w, h, options);
67595 _convertRect: function(x1, y1, w, h) {
67596 var m0, m1, m2, m3, m4, m5, x2, y2, _ref;
67600 _ref = this._ctm, m0 = _ref[0], m1 = _ref[1], m2 = _ref[2], m3 = _ref[3], m4 = _ref[4], m5 = _ref[5];
67601 x1 = m0 * x1 + m2 * y1 + m4;
67602 y1 = m1 * x1 + m3 * y1 + m5;
67603 x2 = m0 * x2 + m2 * y2 + m4;
67604 y2 = m1 * x2 + m3 * y2 + m5;
67605 return [x1, y1, x2, y2];
67614 /***/ function(module, exports) {
67617 '4A0': [4767.87, 6740.79],
67618 '2A0': [3370.39, 4767.87],
67619 A0: [2383.94, 3370.39],
67620 A1: [1683.78, 2383.94],
67621 A2: [1190.55, 1683.78],
67622 A3: [841.89, 1190.55],
67623 A4: [595.28, 841.89],
67624 A5: [419.53, 595.28],
67625 A6: [297.64, 419.53],
67626 A7: [209.76, 297.64],
67627 A8: [147.40, 209.76],
67628 A9: [104.88, 147.40],
67629 A10: [73.70, 104.88],
67630 B0: [2834.65, 4008.19],
67631 B1: [2004.09, 2834.65],
67632 B2: [1417.32, 2004.09],
67633 B3: [1000.63, 1417.32],
67634 B4: [708.66, 1000.63],
67635 B5: [498.90, 708.66],
67636 B6: [354.33, 498.90],
67637 B7: [249.45, 354.33],
67638 B8: [175.75, 249.45],
67639 B9: [124.72, 175.75],
67640 B10: [87.87, 124.72],
67641 C0: [2599.37, 3676.54],
67642 C1: [1836.85, 2599.37],
67643 C2: [1298.27, 1836.85],
67644 C3: [918.43, 1298.27],
67645 C4: [649.13, 918.43],
67646 C5: [459.21, 649.13],
67647 C6: [323.15, 459.21],
67648 C7: [229.61, 323.15],
67649 C8: [161.57, 229.61],
67650 C9: [113.39, 161.57],
67651 C10: [79.37, 113.39],
67652 RA0: [2437.80, 3458.27],
67653 RA1: [1729.13, 2437.80],
67654 RA2: [1218.90, 1729.13],
67655 RA3: [864.57, 1218.90],
67656 RA4: [609.45, 864.57],
67657 SRA0: [2551.18, 3628.35],
67658 SRA1: [1814.17, 2551.18],
67659 SRA2: [1275.59, 1814.17],
67660 SRA3: [907.09, 1275.59],
67661 SRA4: [637.80, 907.09],
67662 EXECUTIVE: [521.86, 756.00],
67663 FOLIO: [612.00, 936.00],
67664 LEGAL: [612.00, 1008.00],
67665 LETTER: [612.00, 792.00],
67666 TABLOID: [792.00, 1224.00]
67672 /***/ function(module, exports, __webpack_require__) {
67674 /* WEBPACK VAR INJECTION */(function(Buffer) {/* jslint node: true */
67677 var pdfKit = __webpack_require__(24);
67678 var PDFImage = __webpack_require__(97);
67680 function ImageMeasure(pdfDoc, imageDictionary) {
67681 this.pdfDoc = pdfDoc;
67682 this.imageDictionary = imageDictionary || {};
67685 ImageMeasure.prototype.measureImage = function(src) {
67689 if (!this.pdfDoc._imageRegistry[src]) {
67690 label = 'I' + (++this.pdfDoc._imageCount);
67691 image = PDFImage.open(realImageSrc(src), label);
67692 image.embed(this.pdfDoc);
67693 this.pdfDoc._imageRegistry[src] = image;
67695 image = this.pdfDoc._imageRegistry[src];
67698 return { width: image.width, height: image.height };
67700 function realImageSrc(src) {
67701 var img = that.imageDictionary[src];
67703 if (!img) return src;
67705 var index = img.indexOf('base64,');
67707 throw 'invalid image format, images dictionary should contain dataURL entries';
67710 return new Buffer(img.substring(index + 7), 'base64');
67714 module.exports = ImageMeasure;
67716 /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2).Buffer))
67720 /***/ function(module, exports) {
67722 /* jslint node: true */
67726 function groupDecorations(line) {
67727 var groups = [], curGroup = null;
67728 for(var i = 0, l = line.inlines.length; i < l; i++) {
67729 var inline = line.inlines[i];
67730 var decoration = inline.decoration;
67735 var color = inline.decorationColor || inline.color || 'black';
67736 var style = inline.decorationStyle || 'solid';
67737 decoration = Array.isArray(decoration) ? decoration : [ decoration ];
67738 for(var ii = 0, ll = decoration.length; ii < ll; ii++) {
67739 var deco = decoration[ii];
67740 if(!curGroup || deco !== curGroup.decoration ||
67741 style !== curGroup.decorationStyle || color !== curGroup.decorationColor ||
67742 deco === 'lineThrough') {
67747 decorationColor: color,
67748 decorationStyle: style,
67749 inlines: [ inline ]
67751 groups.push(curGroup);
67753 curGroup.inlines.push(inline);
67761 function drawDecoration(group, x, y, pdfKitDoc) {
67762 function maxInline() {
67764 for (var i = 0, l = group.inlines.length; i < l; i++) {
67765 var inl = group.inlines[i];
67766 max = inl.fontSize > max ? i : max;
67768 return group.inlines[max];
67772 for (var i = 0, l = group.inlines.length; i < l; i++) {
67773 sum += group.inlines[i].width;
67777 var firstInline = group.inlines[0],
67778 biggerInline = maxInline(),
67779 totalWidth = width(),
67780 lineAscent = group.line.getAscenderHeight(),
67781 ascent = biggerInline.font.ascender / 1000 * biggerInline.fontSize,
67782 height = biggerInline.height,
67783 descent = height - ascent;
67785 var lw = 0.5 + Math.floor(Math.max(biggerInline.fontSize - 8, 0) / 2) * 0.12;
67787 switch (group.decoration) {
67789 y += lineAscent + descent * 0.45;
67792 y += lineAscent - (ascent * 0.85);
67794 case 'lineThrough':
67795 y += lineAscent - (ascent * 0.25);
67798 throw 'Unkown decoration : ' + group.decoration;
67802 if(group.decorationStyle === 'double') {
67803 var gap = Math.max(0.5, lw*2);
67804 pdfKitDoc .fillColor(group.decorationColor)
67805 .rect(x + firstInline.x, y-lw/2, totalWidth, lw/2).fill()
67806 .rect(x + firstInline.x, y+gap-lw/2, totalWidth, lw/2).fill();
67807 } else if(group.decorationStyle === 'dashed') {
67808 var nbDashes = Math.ceil(totalWidth / (3.96+2.84));
67809 var rdx = x + firstInline.x;
67810 pdfKitDoc.rect(rdx, y, totalWidth, lw).clip();
67811 pdfKitDoc.fillColor(group.decorationColor);
67812 for (var i = 0; i < nbDashes; i++) {
67813 pdfKitDoc.rect(rdx, y-lw/2, 3.96, lw).fill();
67814 rdx += 3.96 + 2.84;
67816 } else if(group.decorationStyle === 'dotted') {
67817 var nbDots = Math.ceil(totalWidth / (lw*3));
67818 var rx = x + firstInline.x;
67819 pdfKitDoc.rect(rx, y, totalWidth, lw).clip();
67820 pdfKitDoc.fillColor(group.decorationColor);
67821 for (var ii = 0; ii < nbDots; ii++) {
67822 pdfKitDoc.rect(rx, y-lw/2, lw, lw).fill();
67825 } else if(group.decorationStyle === 'wavy') {
67826 var sh = 0.7, sv = 1;
67827 var nbWaves = Math.ceil(totalWidth / (sh*2))+1;
67828 var rwx = x + firstInline.x - 1;
67829 pdfKitDoc.rect(x + firstInline.x, y-sv, totalWidth, y+sv).clip();
67830 pdfKitDoc.lineWidth(0.24);
67831 pdfKitDoc.moveTo(rwx, y);
67832 for(var iii = 0; iii < nbWaves; iii++) {
67833 pdfKitDoc .bezierCurveTo(rwx+sh, y-sv, rwx+sh*2, y-sv, rwx+sh*3, y)
67834 .bezierCurveTo(rwx+sh*4, y+sv, rwx+sh*5, y+sv, rwx+sh*6, y);
67837 pdfKitDoc.stroke(group.decorationColor);
67840 pdfKitDoc .fillColor(group.decorationColor)
67841 .rect(x + firstInline.x, y-lw/2, totalWidth, lw)
67844 pdfKitDoc.restore();
67847 function drawDecorations(line, x, y, pdfKitDoc) {
67848 var groups = groupDecorations(line);
67849 for (var i = 0, l = groups.length; i < l; i++) {
67850 drawDecoration(groups[i], x, y, pdfKitDoc);
67854 function drawBackground(line, x, y, pdfKitDoc) {
67855 var height = line.getHeight();
67856 for(var i = 0, l = line.inlines.length; i < l; i++) {
67857 var inline = line.inlines[i];
67858 if(inline.background) {
67859 pdfKitDoc .fillColor(inline.background)
67860 .rect(x + inline.x, y, inline.width, height)
67867 drawBackground: drawBackground,
67868 drawDecorations: drawDecorations
67873 /***/ function(module, exports, __webpack_require__) {
67875 var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* FileSaver.js
67876 * A saveAs() FileSaver implementation.
67879 * By Eli Grey, http://eligrey.com
67881 * See https://github.com/eligrey/FileSaver.js/blob/master/LICENSE.md
67885 /*jslint bitwise: true, indent: 4, laxbreak: true, laxcomma: true, smarttabs: true, plusplus: true */
67887 /*! @source http://purl.eligrey.com/github/FileSaver.js/blob/master/FileSaver.js */
67889 var saveAs = saveAs || (function(view) {
67891 // IE <10 is explicitly unsupported
67892 if (typeof navigator !== "undefined" && /MSIE [1-9]\./.test(navigator.userAgent)) {
67896 doc = view.document
67897 // only get URL when necessary in case Blob.js hasn't overridden it yet
67898 , get_URL = function() {
67899 return view.URL || view.webkitURL || view;
67901 , save_link = doc.createElementNS("http://www.w3.org/1999/xhtml", "a")
67902 , can_use_save_link = "download" in save_link
67903 , click = function(node) {
67904 var event = new MouseEvent("click");
67905 node.dispatchEvent(event);
67907 , webkit_req_fs = view.webkitRequestFileSystem
67908 , req_fs = view.requestFileSystem || webkit_req_fs || view.mozRequestFileSystem
67909 , throw_outside = function(ex) {
67910 (view.setImmediate || view.setTimeout)(function() {
67914 , force_saveable_type = "application/octet-stream"
67916 // See https://code.google.com/p/chromium/issues/detail?id=375297#c7 and
67917 // https://github.com/eligrey/FileSaver.js/commit/485930a#commitcomment-8768047
67918 // for the reasoning behind the timeout and revocation flow
67919 , arbitrary_revoke_timeout = 500 // in ms
67920 , revoke = function(file) {
67921 var revoker = function() {
67922 if (typeof file === "string") { // file is an object URL
67923 get_URL().revokeObjectURL(file);
67924 } else { // file is a File
67931 setTimeout(revoker, arbitrary_revoke_timeout);
67934 , dispatch = function(filesaver, event_types, event) {
67935 event_types = [].concat(event_types);
67936 var i = event_types.length;
67938 var listener = filesaver["on" + event_types[i]];
67939 if (typeof listener === "function") {
67941 listener.call(filesaver, event || filesaver);
67948 , auto_bom = function(blob) {
67949 // prepend BOM for UTF-8 XML and text/* types (including HTML)
67950 if (/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(blob.type)) {
67951 return new Blob(["\ufeff", blob], {type: blob.type});
67955 , FileSaver = function(blob, name, no_auto_bom) {
67956 if (!no_auto_bom) {
67957 blob = auto_bom(blob);
67959 // First try a.download, then web filesystem, then object URLs
67963 , blob_changed = false
67966 , dispatch_all = function() {
67967 dispatch(filesaver, "writestart progress write writeend".split(" "));
67969 // on any filesys errors revert to saving with object URLs
67970 , fs_error = function() {
67971 // don't create more object URLs than needed
67972 if (blob_changed || !object_url) {
67973 object_url = get_URL().createObjectURL(blob);
67976 target_view.location.href = object_url;
67978 var new_tab = view.open(object_url, "_blank");
67979 if (new_tab == undefined && typeof safari !== "undefined") {
67980 //Apple do not allow window.open, see http://bit.ly/1kZffRI
67981 view.location.href = object_url
67984 filesaver.readyState = filesaver.DONE;
67986 revoke(object_url);
67988 , abortable = function(func) {
67989 return function() {
67990 if (filesaver.readyState !== filesaver.DONE) {
67991 return func.apply(this, arguments);
67995 , create_if_not_found = {create: true, exclusive: false}
67998 filesaver.readyState = filesaver.INIT;
68002 if (can_use_save_link) {
68003 object_url = get_URL().createObjectURL(blob);
68004 save_link.href = object_url;
68005 save_link.download = name;
68006 setTimeout(function() {
68009 revoke(object_url);
68010 filesaver.readyState = filesaver.DONE;
68014 // Object and web filesystem URLs have a problem saving in Google Chrome when
68015 // viewed in a tab, so I force save with application/octet-stream
68016 // http://code.google.com/p/chromium/issues/detail?id=91158
68017 // Update: Google errantly closed 91158, I submitted it again:
68018 // https://code.google.com/p/chromium/issues/detail?id=389642
68019 if (view.chrome && type && type !== force_saveable_type) {
68020 slice = blob.slice || blob.webkitSlice;
68021 blob = slice.call(blob, 0, blob.size, force_saveable_type);
68022 blob_changed = true;
68024 // Since I can't be sure that the guessed media type will trigger a download
68025 // in WebKit, I append .download to the filename.
68026 // https://bugs.webkit.org/show_bug.cgi?id=65440
68027 if (webkit_req_fs && name !== "download") {
68028 name += ".download";
68030 if (type === force_saveable_type || webkit_req_fs) {
68031 target_view = view;
68037 fs_min_size += blob.size;
68038 req_fs(view.TEMPORARY, fs_min_size, abortable(function(fs) {
68039 fs.root.getDirectory("saved", create_if_not_found, abortable(function(dir) {
68040 var save = function() {
68041 dir.getFile(name, create_if_not_found, abortable(function(file) {
68042 file.createWriter(abortable(function(writer) {
68043 writer.onwriteend = function(event) {
68044 target_view.location.href = file.toURL();
68045 filesaver.readyState = filesaver.DONE;
68046 dispatch(filesaver, "writeend", event);
68049 writer.onerror = function() {
68050 var error = writer.error;
68051 if (error.code !== error.ABORT_ERR) {
68055 "writestart progress write abort".split(" ").forEach(function(event) {
68056 writer["on" + event] = filesaver["on" + event];
68058 writer.write(blob);
68059 filesaver.abort = function() {
68061 filesaver.readyState = filesaver.DONE;
68063 filesaver.readyState = filesaver.WRITING;
68067 dir.getFile(name, {create: false}, abortable(function(file) {
68068 // delete file if it already exists
68071 }), abortable(function(ex) {
68072 if (ex.code === ex.NOT_FOUND_ERR) {
68081 , FS_proto = FileSaver.prototype
68082 , saveAs = function(blob, name, no_auto_bom) {
68083 return new FileSaver(blob, name, no_auto_bom);
68086 // IE 10+ (native saveAs)
68087 if (typeof navigator !== "undefined" && navigator.msSaveOrOpenBlob) {
68088 return function(blob, name, no_auto_bom) {
68089 if (!no_auto_bom) {
68090 blob = auto_bom(blob);
68092 return navigator.msSaveOrOpenBlob(blob, name || "download");
68096 FS_proto.abort = function() {
68097 var filesaver = this;
68098 filesaver.readyState = filesaver.DONE;
68099 dispatch(filesaver, "abort");
68101 FS_proto.readyState = FS_proto.INIT = 0;
68102 FS_proto.WRITING = 1;
68106 FS_proto.onwritestart =
68107 FS_proto.onprogress =
68111 FS_proto.onwriteend =
68116 typeof self !== "undefined" && self
68117 || typeof window !== "undefined" && window
68120 // `self` is undefined in Firefox for Android content script context
68121 // while `this` is nsIContentFrameMessageManager
68122 // with an attribute `content` that corresponds to the window
68124 if (typeof module !== "undefined" && module.exports) {
68125 module.exports.saveAs = saveAs;
68126 } else if (("function" !== "undefined" && __webpack_require__(106) !== null) && (__webpack_require__(107) != null)) {
68127 !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = function() {
68129 }.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
68135 /***/ function(module, exports) {
68137 module.exports = function() { throw new Error("define cannot be used indirect"); };
68142 /***/ function(module, exports) {
68144 (function(__webpack_amd_options__) {module.exports = __webpack_amd_options__;
68146 }.call(exports, {}))