2 * HTMLMinifier v3.5.20 (https://kangax.github.io/html-minifier/)
3 * Copyright 2010-2018 Juriy "kangax" Zaytsev
4 * Licensed under the MIT license
7 require=(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
10 exports.byteLength = byteLength
11 exports.toByteArray = toByteArray
12 exports.fromByteArray = fromByteArray
16 var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
18 var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
19 for (var i = 0, len = code.length; i < len; ++i) {
21 revLookup[code.charCodeAt(i)] = i
24 // Support decoding URL-safe base64 strings, as Node.js does.
25 // See: https://en.wikipedia.org/wiki/Base64#URL_applications
26 revLookup['-'.charCodeAt(0)] = 62
27 revLookup['_'.charCodeAt(0)] = 63
29 function getLens (b64) {
33 throw new Error('Invalid string. Length must be a multiple of 4')
36 // Trim off extra bytes after placeholder bytes are found
37 // See: https://github.com/beatgammit/base64-js/issues/42
38 var validLen = b64.indexOf('=')
39 if (validLen === -1) validLen = len
41 var placeHoldersLen = validLen === len
45 return [validLen, placeHoldersLen]
48 // base64 is 4/3 + up to two characters of the original data
49 function byteLength (b64) {
50 var lens = getLens(b64)
51 var validLen = lens[0]
52 var placeHoldersLen = lens[1]
53 return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
56 function _byteLength (b64, validLen, placeHoldersLen) {
57 return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
60 function toByteArray (b64) {
62 var lens = getLens(b64)
63 var validLen = lens[0]
64 var placeHoldersLen = lens[1]
66 var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))
70 // if there are placeholders, only get up to the last complete 4 chars
71 var len = placeHoldersLen > 0
75 for (var i = 0; i < len; i += 4) {
77 (revLookup[b64.charCodeAt(i)] << 18) |
78 (revLookup[b64.charCodeAt(i + 1)] << 12) |
79 (revLookup[b64.charCodeAt(i + 2)] << 6) |
80 revLookup[b64.charCodeAt(i + 3)]
81 arr[curByte++] = (tmp >> 16) & 0xFF
82 arr[curByte++] = (tmp >> 8) & 0xFF
83 arr[curByte++] = tmp & 0xFF
86 if (placeHoldersLen === 2) {
88 (revLookup[b64.charCodeAt(i)] << 2) |
89 (revLookup[b64.charCodeAt(i + 1)] >> 4)
90 arr[curByte++] = tmp & 0xFF
93 if (placeHoldersLen === 1) {
95 (revLookup[b64.charCodeAt(i)] << 10) |
96 (revLookup[b64.charCodeAt(i + 1)] << 4) |
97 (revLookup[b64.charCodeAt(i + 2)] >> 2)
98 arr[curByte++] = (tmp >> 8) & 0xFF
99 arr[curByte++] = tmp & 0xFF
105 function tripletToBase64 (num) {
106 return lookup[num >> 18 & 0x3F] +
107 lookup[num >> 12 & 0x3F] +
108 lookup[num >> 6 & 0x3F] +
112 function encodeChunk (uint8, start, end) {
115 for (var i = start; i < end; i += 3) {
117 ((uint8[i] << 16) & 0xFF0000) +
118 ((uint8[i + 1] << 8) & 0xFF00) +
119 (uint8[i + 2] & 0xFF)
120 output.push(tripletToBase64(tmp))
122 return output.join('')
125 function fromByteArray (uint8) {
127 var len = uint8.length
128 var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
130 var maxChunkLength = 16383 // must be multiple of 3
132 // go through the array every three bytes, we'll deal with trailing stuff later
133 for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
134 parts.push(encodeChunk(
135 uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)
139 // pad the end with zeros, but make sure to not forget the extra bytes
140 if (extraBytes === 1) {
144 lookup[(tmp << 4) & 0x3F] +
147 } else if (extraBytes === 2) {
148 tmp = (uint8[len - 2] << 8) + uint8[len - 1]
151 lookup[(tmp >> 4) & 0x3F] +
152 lookup[(tmp << 2) & 0x3F] +
157 return parts.join('')
160 },{}],2:[function(require,module,exports){
162 },{}],3:[function(require,module,exports){
163 arguments[4][2][0].apply(exports,arguments)
164 },{"dup":2}],4:[function(require,module,exports){
166 * The buffer module from node.js, for the browser.
168 * @author Feross Aboukhadijeh <https://feross.org>
171 /* eslint-disable no-proto */
175 var base64 = require('base64-js')
176 var ieee754 = require('ieee754')
178 exports.Buffer = Buffer
179 exports.SlowBuffer = SlowBuffer
180 exports.INSPECT_MAX_BYTES = 50
182 var K_MAX_LENGTH = 0x7fffffff
183 exports.kMaxLength = K_MAX_LENGTH
186 * If `Buffer.TYPED_ARRAY_SUPPORT`:
187 * === true Use Uint8Array implementation (fastest)
188 * === false Print warning and recommend using `buffer` v4.x which has an Object
189 * implementation (most compatible, even IE6)
191 * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
192 * Opera 11.6+, iOS 4.2+.
194 * We report that the browser does not support typed arrays if the are not subclassable
195 * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
196 * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
197 * for __proto__ and has a buggy typed array implementation.
199 Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport()
201 if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&
202 typeof console.error === 'function') {
204 'This browser lacks typed array (Uint8Array) support which is required by ' +
205 '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'
209 function typedArraySupport () {
210 // Can typed array instances can be augmented?
212 var arr = new Uint8Array(1)
213 arr.__proto__ = { __proto__: Uint8Array.prototype, foo: function () { return 42 } }
214 return arr.foo() === 42
220 Object.defineProperty(Buffer.prototype, 'parent', {
223 if (!Buffer.isBuffer(this)) return undefined
228 Object.defineProperty(Buffer.prototype, 'offset', {
231 if (!Buffer.isBuffer(this)) return undefined
232 return this.byteOffset
236 function createBuffer (length) {
237 if (length > K_MAX_LENGTH) {
238 throw new RangeError('The value "' + length + '" is invalid for option "size"')
240 // Return an augmented `Uint8Array` instance
241 var buf = new Uint8Array(length)
242 buf.__proto__ = Buffer.prototype
247 * The Buffer constructor returns instances of `Uint8Array` that have their
248 * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
249 * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
250 * and the `Uint8Array` methods. Square bracket notation works as expected -- it
251 * returns a single octet.
253 * The `Uint8Array` prototype remains unmodified.
256 function Buffer (arg, encodingOrOffset, length) {
258 if (typeof arg === 'number') {
259 if (typeof encodingOrOffset === 'string') {
261 'The "string" argument must be of type string. Received type number'
264 return allocUnsafe(arg)
266 return from(arg, encodingOrOffset, length)
269 // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
270 if (typeof Symbol !== 'undefined' && Symbol.species != null &&
271 Buffer[Symbol.species] === Buffer) {
272 Object.defineProperty(Buffer, Symbol.species, {
280 Buffer.poolSize = 8192 // not used by this implementation
282 function from (value, encodingOrOffset, length) {
283 if (typeof value === 'string') {
284 return fromString(value, encodingOrOffset)
287 if (ArrayBuffer.isView(value)) {
288 return fromArrayLike(value)
293 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
294 'or Array-like Object. Received type ' + (typeof value)
298 if (isInstance(value, ArrayBuffer) ||
299 (value && isInstance(value.buffer, ArrayBuffer))) {
300 return fromArrayBuffer(value, encodingOrOffset, length)
303 if (typeof value === 'number') {
305 'The "value" argument must not be of type number. Received type number'
309 var valueOf = value.valueOf && value.valueOf()
310 if (valueOf != null && valueOf !== value) {
311 return Buffer.from(valueOf, encodingOrOffset, length)
314 var b = fromObject(value)
317 if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null &&
318 typeof value[Symbol.toPrimitive] === 'function') {
320 value[Symbol.toPrimitive]('string'), encodingOrOffset, length
325 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
326 'or Array-like Object. Received type ' + (typeof value)
331 * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
332 * if value is a number.
333 * Buffer.from(str[, encoding])
335 * Buffer.from(buffer)
336 * Buffer.from(arrayBuffer[, byteOffset[, length]])
338 Buffer.from = function (value, encodingOrOffset, length) {
339 return from(value, encodingOrOffset, length)
342 // Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
343 // https://github.com/feross/buffer/pull/148
344 Buffer.prototype.__proto__ = Uint8Array.prototype
345 Buffer.__proto__ = Uint8Array
347 function assertSize (size) {
348 if (typeof size !== 'number') {
349 throw new TypeError('"size" argument must be of type number')
350 } else if (size < 0) {
351 throw new RangeError('The value "' + size + '" is invalid for option "size"')
355 function alloc (size, fill, encoding) {
358 return createBuffer(size)
360 if (fill !== undefined) {
361 // Only pay attention to encoding if it's a string. This
362 // prevents accidentally sending in a number that would
363 // be interpretted as a start offset.
364 return typeof encoding === 'string'
365 ? createBuffer(size).fill(fill, encoding)
366 : createBuffer(size).fill(fill)
368 return createBuffer(size)
372 * Creates a new filled Buffer instance.
373 * alloc(size[, fill[, encoding]])
375 Buffer.alloc = function (size, fill, encoding) {
376 return alloc(size, fill, encoding)
379 function allocUnsafe (size) {
381 return createBuffer(size < 0 ? 0 : checked(size) | 0)
385 * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
387 Buffer.allocUnsafe = function (size) {
388 return allocUnsafe(size)
391 * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
393 Buffer.allocUnsafeSlow = function (size) {
394 return allocUnsafe(size)
397 function fromString (string, encoding) {
398 if (typeof encoding !== 'string' || encoding === '') {
402 if (!Buffer.isEncoding(encoding)) {
403 throw new TypeError('Unknown encoding: ' + encoding)
406 var length = byteLength(string, encoding) | 0
407 var buf = createBuffer(length)
409 var actual = buf.write(string, encoding)
411 if (actual !== length) {
412 // Writing a hex string, for example, that contains invalid characters will
413 // cause everything after the first invalid character to be ignored. (e.g.
414 // 'abxxcd' will be treated as 'ab')
415 buf = buf.slice(0, actual)
421 function fromArrayLike (array) {
422 var length = array.length < 0 ? 0 : checked(array.length) | 0
423 var buf = createBuffer(length)
424 for (var i = 0; i < length; i += 1) {
425 buf[i] = array[i] & 255
430 function fromArrayBuffer (array, byteOffset, length) {
431 if (byteOffset < 0 || array.byteLength < byteOffset) {
432 throw new RangeError('"offset" is outside of buffer bounds')
435 if (array.byteLength < byteOffset + (length || 0)) {
436 throw new RangeError('"length" is outside of buffer bounds')
440 if (byteOffset === undefined && length === undefined) {
441 buf = new Uint8Array(array)
442 } else if (length === undefined) {
443 buf = new Uint8Array(array, byteOffset)
445 buf = new Uint8Array(array, byteOffset, length)
448 // Return an augmented `Uint8Array` instance
449 buf.__proto__ = Buffer.prototype
453 function fromObject (obj) {
454 if (Buffer.isBuffer(obj)) {
455 var len = checked(obj.length) | 0
456 var buf = createBuffer(len)
458 if (buf.length === 0) {
462 obj.copy(buf, 0, 0, len)
466 if (obj.length !== undefined) {
467 if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
468 return createBuffer(0)
470 return fromArrayLike(obj)
473 if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
474 return fromArrayLike(obj.data)
478 function checked (length) {
479 // Note: cannot use `length < K_MAX_LENGTH` here because that fails when
480 // length is NaN (which is otherwise coerced to zero.)
481 if (length >= K_MAX_LENGTH) {
482 throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
483 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')
488 function SlowBuffer (length) {
489 if (+length != length) { // eslint-disable-line eqeqeq
492 return Buffer.alloc(+length)
495 Buffer.isBuffer = function isBuffer (b) {
496 return b != null && b._isBuffer === true &&
497 b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false
500 Buffer.compare = function compare (a, b) {
501 if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength)
502 if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength)
503 if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
505 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array'
509 if (a === b) return 0
514 for (var i = 0, len = Math.min(x, y); i < len; ++i) {
527 Buffer.isEncoding = function isEncoding (encoding) {
528 switch (String(encoding).toLowerCase()) {
546 Buffer.concat = function concat (list, length) {
547 if (!Array.isArray(list)) {
548 throw new TypeError('"list" argument must be an Array of Buffers')
551 if (list.length === 0) {
552 return Buffer.alloc(0)
556 if (length === undefined) {
558 for (i = 0; i < list.length; ++i) {
559 length += list[i].length
563 var buffer = Buffer.allocUnsafe(length)
565 for (i = 0; i < list.length; ++i) {
567 if (isInstance(buf, Uint8Array)) {
568 buf = Buffer.from(buf)
570 if (!Buffer.isBuffer(buf)) {
571 throw new TypeError('"list" argument must be an Array of Buffers')
573 buf.copy(buffer, pos)
579 function byteLength (string, encoding) {
580 if (Buffer.isBuffer(string)) {
583 if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {
584 return string.byteLength
586 if (typeof string !== 'string') {
588 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' +
589 'Received type ' + typeof string
593 var len = string.length
594 var mustMatch = (arguments.length > 2 && arguments[2] === true)
595 if (!mustMatch && len === 0) return 0
597 // Use a for loop to avoid recursion
598 var loweredCase = false
607 return utf8ToBytes(string).length
616 return base64ToBytes(string).length
619 return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8
621 encoding = ('' + encoding).toLowerCase()
626 Buffer.byteLength = byteLength
628 function slowToString (encoding, start, end) {
629 var loweredCase = false
631 // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
632 // property of a typed array.
634 // This behaves neither like String nor Uint8Array in that we set start/end
635 // to their upper/lower bounds if the value passed is out of range.
636 // undefined is handled specially as per ECMA-262 6th Edition,
637 // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
638 if (start === undefined || start < 0) {
641 // Return early if start > this.length. Done here to prevent potential uint32
642 // coercion fail below.
643 if (start > this.length) {
647 if (end === undefined || end > this.length) {
655 // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
663 if (!encoding) encoding = 'utf8'
668 return hexSlice(this, start, end)
672 return utf8Slice(this, start, end)
675 return asciiSlice(this, start, end)
679 return latin1Slice(this, start, end)
682 return base64Slice(this, start, end)
688 return utf16leSlice(this, start, end)
691 if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
692 encoding = (encoding + '').toLowerCase()
698 // This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
699 // to detect a Buffer instance. It's not possible to use `instanceof Buffer`
700 // reliably in a browserify context because there could be multiple different
701 // copies of the 'buffer' package in use. This method works even for Buffer
702 // instances that were created from another copy of the `buffer` package.
703 // See: https://github.com/feross/buffer/issues/154
704 Buffer.prototype._isBuffer = true
706 function swap (b, n, m) {
712 Buffer.prototype.swap16 = function swap16 () {
713 var len = this.length
715 throw new RangeError('Buffer size must be a multiple of 16-bits')
717 for (var i = 0; i < len; i += 2) {
723 Buffer.prototype.swap32 = function swap32 () {
724 var len = this.length
726 throw new RangeError('Buffer size must be a multiple of 32-bits')
728 for (var i = 0; i < len; i += 4) {
730 swap(this, i + 1, i + 2)
735 Buffer.prototype.swap64 = function swap64 () {
736 var len = this.length
738 throw new RangeError('Buffer size must be a multiple of 64-bits')
740 for (var i = 0; i < len; i += 8) {
742 swap(this, i + 1, i + 6)
743 swap(this, i + 2, i + 5)
744 swap(this, i + 3, i + 4)
749 Buffer.prototype.toString = function toString () {
750 var length = this.length
751 if (length === 0) return ''
752 if (arguments.length === 0) return utf8Slice(this, 0, length)
753 return slowToString.apply(this, arguments)
756 Buffer.prototype.toLocaleString = Buffer.prototype.toString
758 Buffer.prototype.equals = function equals (b) {
759 if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
760 if (this === b) return true
761 return Buffer.compare(this, b) === 0
764 Buffer.prototype.inspect = function inspect () {
766 var max = exports.INSPECT_MAX_BYTES
767 str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim()
768 if (this.length > max) str += ' ... '
769 return '<Buffer ' + str + '>'
772 Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
773 if (isInstance(target, Uint8Array)) {
774 target = Buffer.from(target, target.offset, target.byteLength)
776 if (!Buffer.isBuffer(target)) {
778 'The "target" argument must be one of type Buffer or Uint8Array. ' +
779 'Received type ' + (typeof target)
783 if (start === undefined) {
786 if (end === undefined) {
787 end = target ? target.length : 0
789 if (thisStart === undefined) {
792 if (thisEnd === undefined) {
793 thisEnd = this.length
796 if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
797 throw new RangeError('out of range index')
800 if (thisStart >= thisEnd && start >= end) {
803 if (thisStart >= thisEnd) {
815 if (this === target) return 0
817 var x = thisEnd - thisStart
819 var len = Math.min(x, y)
821 var thisCopy = this.slice(thisStart, thisEnd)
822 var targetCopy = target.slice(start, end)
824 for (var i = 0; i < len; ++i) {
825 if (thisCopy[i] !== targetCopy[i]) {
837 // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
838 // OR the last index of `val` in `buffer` at offset <= `byteOffset`.
841 // - buffer - a Buffer to search
842 // - val - a string, Buffer, or number
843 // - byteOffset - an index into `buffer`; will be clamped to an int32
844 // - encoding - an optional encoding, relevant is val is a string
845 // - dir - true for indexOf, false for lastIndexOf
846 function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
847 // Empty buffer means no match
848 if (buffer.length === 0) return -1
850 // Normalize byteOffset
851 if (typeof byteOffset === 'string') {
852 encoding = byteOffset
854 } else if (byteOffset > 0x7fffffff) {
855 byteOffset = 0x7fffffff
856 } else if (byteOffset < -0x80000000) {
857 byteOffset = -0x80000000
859 byteOffset = +byteOffset // Coerce to Number.
860 if (numberIsNaN(byteOffset)) {
861 // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
862 byteOffset = dir ? 0 : (buffer.length - 1)
865 // Normalize byteOffset: negative offsets start from the end of the buffer
866 if (byteOffset < 0) byteOffset = buffer.length + byteOffset
867 if (byteOffset >= buffer.length) {
869 else byteOffset = buffer.length - 1
870 } else if (byteOffset < 0) {
871 if (dir) byteOffset = 0
876 if (typeof val === 'string') {
877 val = Buffer.from(val, encoding)
880 // Finally, search either indexOf (if dir is true) or lastIndexOf
881 if (Buffer.isBuffer(val)) {
882 // Special case: looking for empty string/buffer always fails
883 if (val.length === 0) {
886 return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
887 } else if (typeof val === 'number') {
888 val = val & 0xFF // Search for a byte value [0-255]
889 if (typeof Uint8Array.prototype.indexOf === 'function') {
891 return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
893 return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
896 return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
899 throw new TypeError('val must be string, number or Buffer')
902 function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
904 var arrLength = arr.length
905 var valLength = val.length
907 if (encoding !== undefined) {
908 encoding = String(encoding).toLowerCase()
909 if (encoding === 'ucs2' || encoding === 'ucs-2' ||
910 encoding === 'utf16le' || encoding === 'utf-16le') {
911 if (arr.length < 2 || val.length < 2) {
921 function read (buf, i) {
922 if (indexSize === 1) {
925 return buf.readUInt16BE(i * indexSize)
932 for (i = byteOffset; i < arrLength; i++) {
933 if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
934 if (foundIndex === -1) foundIndex = i
935 if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
937 if (foundIndex !== -1) i -= i - foundIndex
942 if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
943 for (i = byteOffset; i >= 0; i--) {
945 for (var j = 0; j < valLength; j++) {
946 if (read(arr, i + j) !== read(val, j)) {
958 Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
959 return this.indexOf(val, byteOffset, encoding) !== -1
962 Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
963 return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
966 Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
967 return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
970 function hexWrite (buf, string, offset, length) {
971 offset = Number(offset) || 0
972 var remaining = buf.length - offset
976 length = Number(length)
977 if (length > remaining) {
982 var strLen = string.length
984 if (length > strLen / 2) {
987 for (var i = 0; i < length; ++i) {
988 var parsed = parseInt(string.substr(i * 2, 2), 16)
989 if (numberIsNaN(parsed)) return i
990 buf[offset + i] = parsed
995 function utf8Write (buf, string, offset, length) {
996 return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
999 function asciiWrite (buf, string, offset, length) {
1000 return blitBuffer(asciiToBytes(string), buf, offset, length)
1003 function latin1Write (buf, string, offset, length) {
1004 return asciiWrite(buf, string, offset, length)
1007 function base64Write (buf, string, offset, length) {
1008 return blitBuffer(base64ToBytes(string), buf, offset, length)
1011 function ucs2Write (buf, string, offset, length) {
1012 return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
1015 Buffer.prototype.write = function write (string, offset, length, encoding) {
1016 // Buffer#write(string)
1017 if (offset === undefined) {
1019 length = this.length
1021 // Buffer#write(string, encoding)
1022 } else if (length === undefined && typeof offset === 'string') {
1024 length = this.length
1026 // Buffer#write(string, offset[, length][, encoding])
1027 } else if (isFinite(offset)) {
1028 offset = offset >>> 0
1029 if (isFinite(length)) {
1030 length = length >>> 0
1031 if (encoding === undefined) encoding = 'utf8'
1038 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
1042 var remaining = this.length - offset
1043 if (length === undefined || length > remaining) length = remaining
1045 if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
1046 throw new RangeError('Attempt to write outside buffer bounds')
1049 if (!encoding) encoding = 'utf8'
1051 var loweredCase = false
1055 return hexWrite(this, string, offset, length)
1059 return utf8Write(this, string, offset, length)
1062 return asciiWrite(this, string, offset, length)
1066 return latin1Write(this, string, offset, length)
1069 // Warning: maxLength not taken into account in base64Write
1070 return base64Write(this, string, offset, length)
1076 return ucs2Write(this, string, offset, length)
1079 if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
1080 encoding = ('' + encoding).toLowerCase()
1086 Buffer.prototype.toJSON = function toJSON () {
1089 data: Array.prototype.slice.call(this._arr || this, 0)
1093 function base64Slice (buf, start, end) {
1094 if (start === 0 && end === buf.length) {
1095 return base64.fromByteArray(buf)
1097 return base64.fromByteArray(buf.slice(start, end))
1101 function utf8Slice (buf, start, end) {
1102 end = Math.min(buf.length, end)
1107 var firstByte = buf[i]
1108 var codePoint = null
1109 var bytesPerSequence = (firstByte > 0xEF) ? 4
1110 : (firstByte > 0xDF) ? 3
1111 : (firstByte > 0xBF) ? 2
1114 if (i + bytesPerSequence <= end) {
1115 var secondByte, thirdByte, fourthByte, tempCodePoint
1117 switch (bytesPerSequence) {
1119 if (firstByte < 0x80) {
1120 codePoint = firstByte
1124 secondByte = buf[i + 1]
1125 if ((secondByte & 0xC0) === 0x80) {
1126 tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
1127 if (tempCodePoint > 0x7F) {
1128 codePoint = tempCodePoint
1133 secondByte = buf[i + 1]
1134 thirdByte = buf[i + 2]
1135 if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
1136 tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
1137 if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
1138 codePoint = tempCodePoint
1143 secondByte = buf[i + 1]
1144 thirdByte = buf[i + 2]
1145 fourthByte = buf[i + 3]
1146 if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
1147 tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
1148 if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
1149 codePoint = tempCodePoint
1155 if (codePoint === null) {
1156 // we did not generate a valid codePoint so insert a
1157 // replacement char (U+FFFD) and advance only 1 byte
1159 bytesPerSequence = 1
1160 } else if (codePoint > 0xFFFF) {
1161 // encode to utf16 (surrogate pair dance)
1162 codePoint -= 0x10000
1163 res.push(codePoint >>> 10 & 0x3FF | 0xD800)
1164 codePoint = 0xDC00 | codePoint & 0x3FF
1168 i += bytesPerSequence
1171 return decodeCodePointsArray(res)
1174 // Based on http://stackoverflow.com/a/22747272/680742, the browser with
1175 // the lowest limit is Chrome, with 0x10000 args.
1176 // We go 1 magnitude less, for safety
1177 var MAX_ARGUMENTS_LENGTH = 0x1000
1179 function decodeCodePointsArray (codePoints) {
1180 var len = codePoints.length
1181 if (len <= MAX_ARGUMENTS_LENGTH) {
1182 return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
1185 // Decode in chunks to avoid "call stack size exceeded".
1189 res += String.fromCharCode.apply(
1191 codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
1197 function asciiSlice (buf, start, end) {
1199 end = Math.min(buf.length, end)
1201 for (var i = start; i < end; ++i) {
1202 ret += String.fromCharCode(buf[i] & 0x7F)
1207 function latin1Slice (buf, start, end) {
1209 end = Math.min(buf.length, end)
1211 for (var i = start; i < end; ++i) {
1212 ret += String.fromCharCode(buf[i])
1217 function hexSlice (buf, start, end) {
1218 var len = buf.length
1220 if (!start || start < 0) start = 0
1221 if (!end || end < 0 || end > len) end = len
1224 for (var i = start; i < end; ++i) {
1225 out += toHex(buf[i])
1230 function utf16leSlice (buf, start, end) {
1231 var bytes = buf.slice(start, end)
1233 for (var i = 0; i < bytes.length; i += 2) {
1234 res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))
1239 Buffer.prototype.slice = function slice (start, end) {
1240 var len = this.length
1242 end = end === undefined ? len : ~~end
1246 if (start < 0) start = 0
1247 } else if (start > len) {
1253 if (end < 0) end = 0
1254 } else if (end > len) {
1258 if (end < start) end = start
1260 var newBuf = this.subarray(start, end)
1261 // Return an augmented `Uint8Array` instance
1262 newBuf.__proto__ = Buffer.prototype
1267 * Need to make sure that buffer isn't trying to write out of bounds.
1269 function checkOffset (offset, ext, length) {
1270 if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
1271 if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
1274 Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
1275 offset = offset >>> 0
1276 byteLength = byteLength >>> 0
1277 if (!noAssert) checkOffset(offset, byteLength, this.length)
1279 var val = this[offset]
1282 while (++i < byteLength && (mul *= 0x100)) {
1283 val += this[offset + i] * mul
1289 Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
1290 offset = offset >>> 0
1291 byteLength = byteLength >>> 0
1293 checkOffset(offset, byteLength, this.length)
1296 var val = this[offset + --byteLength]
1298 while (byteLength > 0 && (mul *= 0x100)) {
1299 val += this[offset + --byteLength] * mul
1305 Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
1306 offset = offset >>> 0
1307 if (!noAssert) checkOffset(offset, 1, this.length)
1311 Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
1312 offset = offset >>> 0
1313 if (!noAssert) checkOffset(offset, 2, this.length)
1314 return this[offset] | (this[offset + 1] << 8)
1317 Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
1318 offset = offset >>> 0
1319 if (!noAssert) checkOffset(offset, 2, this.length)
1320 return (this[offset] << 8) | this[offset + 1]
1323 Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
1324 offset = offset >>> 0
1325 if (!noAssert) checkOffset(offset, 4, this.length)
1327 return ((this[offset]) |
1328 (this[offset + 1] << 8) |
1329 (this[offset + 2] << 16)) +
1330 (this[offset + 3] * 0x1000000)
1333 Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
1334 offset = offset >>> 0
1335 if (!noAssert) checkOffset(offset, 4, this.length)
1337 return (this[offset] * 0x1000000) +
1338 ((this[offset + 1] << 16) |
1339 (this[offset + 2] << 8) |
1343 Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
1344 offset = offset >>> 0
1345 byteLength = byteLength >>> 0
1346 if (!noAssert) checkOffset(offset, byteLength, this.length)
1348 var val = this[offset]
1351 while (++i < byteLength && (mul *= 0x100)) {
1352 val += this[offset + i] * mul
1356 if (val >= mul) val -= Math.pow(2, 8 * byteLength)
1361 Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
1362 offset = offset >>> 0
1363 byteLength = byteLength >>> 0
1364 if (!noAssert) checkOffset(offset, byteLength, this.length)
1368 var val = this[offset + --i]
1369 while (i > 0 && (mul *= 0x100)) {
1370 val += this[offset + --i] * mul
1374 if (val >= mul) val -= Math.pow(2, 8 * byteLength)
1379 Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
1380 offset = offset >>> 0
1381 if (!noAssert) checkOffset(offset, 1, this.length)
1382 if (!(this[offset] & 0x80)) return (this[offset])
1383 return ((0xff - this[offset] + 1) * -1)
1386 Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
1387 offset = offset >>> 0
1388 if (!noAssert) checkOffset(offset, 2, this.length)
1389 var val = this[offset] | (this[offset + 1] << 8)
1390 return (val & 0x8000) ? val | 0xFFFF0000 : val
1393 Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
1394 offset = offset >>> 0
1395 if (!noAssert) checkOffset(offset, 2, this.length)
1396 var val = this[offset + 1] | (this[offset] << 8)
1397 return (val & 0x8000) ? val | 0xFFFF0000 : val
1400 Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
1401 offset = offset >>> 0
1402 if (!noAssert) checkOffset(offset, 4, this.length)
1404 return (this[offset]) |
1405 (this[offset + 1] << 8) |
1406 (this[offset + 2] << 16) |
1407 (this[offset + 3] << 24)
1410 Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
1411 offset = offset >>> 0
1412 if (!noAssert) checkOffset(offset, 4, this.length)
1414 return (this[offset] << 24) |
1415 (this[offset + 1] << 16) |
1416 (this[offset + 2] << 8) |
1420 Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
1421 offset = offset >>> 0
1422 if (!noAssert) checkOffset(offset, 4, this.length)
1423 return ieee754.read(this, offset, true, 23, 4)
1426 Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
1427 offset = offset >>> 0
1428 if (!noAssert) checkOffset(offset, 4, this.length)
1429 return ieee754.read(this, offset, false, 23, 4)
1432 Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
1433 offset = offset >>> 0
1434 if (!noAssert) checkOffset(offset, 8, this.length)
1435 return ieee754.read(this, offset, true, 52, 8)
1438 Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
1439 offset = offset >>> 0
1440 if (!noAssert) checkOffset(offset, 8, this.length)
1441 return ieee754.read(this, offset, false, 52, 8)
1444 function checkInt (buf, value, offset, ext, max, min) {
1445 if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
1446 if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
1447 if (offset + ext > buf.length) throw new RangeError('Index out of range')
1450 Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
1452 offset = offset >>> 0
1453 byteLength = byteLength >>> 0
1455 var maxBytes = Math.pow(2, 8 * byteLength) - 1
1456 checkInt(this, value, offset, byteLength, maxBytes, 0)
1461 this[offset] = value & 0xFF
1462 while (++i < byteLength && (mul *= 0x100)) {
1463 this[offset + i] = (value / mul) & 0xFF
1466 return offset + byteLength
1469 Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
1471 offset = offset >>> 0
1472 byteLength = byteLength >>> 0
1474 var maxBytes = Math.pow(2, 8 * byteLength) - 1
1475 checkInt(this, value, offset, byteLength, maxBytes, 0)
1478 var i = byteLength - 1
1480 this[offset + i] = value & 0xFF
1481 while (--i >= 0 && (mul *= 0x100)) {
1482 this[offset + i] = (value / mul) & 0xFF
1485 return offset + byteLength
1488 Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
1490 offset = offset >>> 0
1491 if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
1492 this[offset] = (value & 0xff)
1496 Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
1498 offset = offset >>> 0
1499 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
1500 this[offset] = (value & 0xff)
1501 this[offset + 1] = (value >>> 8)
1505 Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
1507 offset = offset >>> 0
1508 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
1509 this[offset] = (value >>> 8)
1510 this[offset + 1] = (value & 0xff)
1514 Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
1516 offset = offset >>> 0
1517 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
1518 this[offset + 3] = (value >>> 24)
1519 this[offset + 2] = (value >>> 16)
1520 this[offset + 1] = (value >>> 8)
1521 this[offset] = (value & 0xff)
1525 Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
1527 offset = offset >>> 0
1528 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
1529 this[offset] = (value >>> 24)
1530 this[offset + 1] = (value >>> 16)
1531 this[offset + 2] = (value >>> 8)
1532 this[offset + 3] = (value & 0xff)
1536 Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
1538 offset = offset >>> 0
1540 var limit = Math.pow(2, (8 * byteLength) - 1)
1542 checkInt(this, value, offset, byteLength, limit - 1, -limit)
1548 this[offset] = value & 0xFF
1549 while (++i < byteLength && (mul *= 0x100)) {
1550 if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
1553 this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
1556 return offset + byteLength
1559 Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
1561 offset = offset >>> 0
1563 var limit = Math.pow(2, (8 * byteLength) - 1)
1565 checkInt(this, value, offset, byteLength, limit - 1, -limit)
1568 var i = byteLength - 1
1571 this[offset + i] = value & 0xFF
1572 while (--i >= 0 && (mul *= 0x100)) {
1573 if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
1576 this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
1579 return offset + byteLength
1582 Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
1584 offset = offset >>> 0
1585 if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
1586 if (value < 0) value = 0xff + value + 1
1587 this[offset] = (value & 0xff)
1591 Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
1593 offset = offset >>> 0
1594 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
1595 this[offset] = (value & 0xff)
1596 this[offset + 1] = (value >>> 8)
1600 Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
1602 offset = offset >>> 0
1603 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
1604 this[offset] = (value >>> 8)
1605 this[offset + 1] = (value & 0xff)
1609 Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
1611 offset = offset >>> 0
1612 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
1613 this[offset] = (value & 0xff)
1614 this[offset + 1] = (value >>> 8)
1615 this[offset + 2] = (value >>> 16)
1616 this[offset + 3] = (value >>> 24)
1620 Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
1622 offset = offset >>> 0
1623 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
1624 if (value < 0) value = 0xffffffff + value + 1
1625 this[offset] = (value >>> 24)
1626 this[offset + 1] = (value >>> 16)
1627 this[offset + 2] = (value >>> 8)
1628 this[offset + 3] = (value & 0xff)
1632 function checkIEEE754 (buf, value, offset, ext, max, min) {
1633 if (offset + ext > buf.length) throw new RangeError('Index out of range')
1634 if (offset < 0) throw new RangeError('Index out of range')
1637 function writeFloat (buf, value, offset, littleEndian, noAssert) {
1639 offset = offset >>> 0
1641 checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
1643 ieee754.write(buf, value, offset, littleEndian, 23, 4)
1647 Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
1648 return writeFloat(this, value, offset, true, noAssert)
1651 Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
1652 return writeFloat(this, value, offset, false, noAssert)
1655 function writeDouble (buf, value, offset, littleEndian, noAssert) {
1657 offset = offset >>> 0
1659 checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
1661 ieee754.write(buf, value, offset, littleEndian, 52, 8)
1665 Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
1666 return writeDouble(this, value, offset, true, noAssert)
1669 Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
1670 return writeDouble(this, value, offset, false, noAssert)
1673 // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
1674 Buffer.prototype.copy = function copy (target, targetStart, start, end) {
1675 if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer')
1676 if (!start) start = 0
1677 if (!end && end !== 0) end = this.length
1678 if (targetStart >= target.length) targetStart = target.length
1679 if (!targetStart) targetStart = 0
1680 if (end > 0 && end < start) end = start
1682 // Copy 0 bytes; we're done
1683 if (end === start) return 0
1684 if (target.length === 0 || this.length === 0) return 0
1686 // Fatal error conditions
1687 if (targetStart < 0) {
1688 throw new RangeError('targetStart out of bounds')
1690 if (start < 0 || start >= this.length) throw new RangeError('Index out of range')
1691 if (end < 0) throw new RangeError('sourceEnd out of bounds')
1694 if (end > this.length) end = this.length
1695 if (target.length - targetStart < end - start) {
1696 end = target.length - targetStart + start
1699 var len = end - start
1701 if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {
1702 // Use built-in when available, missing from IE11
1703 this.copyWithin(targetStart, start, end)
1704 } else if (this === target && start < targetStart && targetStart < end) {
1705 // descending copy from end
1706 for (var i = len - 1; i >= 0; --i) {
1707 target[i + targetStart] = this[i + start]
1710 Uint8Array.prototype.set.call(
1712 this.subarray(start, end),
1721 // buffer.fill(number[, offset[, end]])
1722 // buffer.fill(buffer[, offset[, end]])
1723 // buffer.fill(string[, offset[, end]][, encoding])
1724 Buffer.prototype.fill = function fill (val, start, end, encoding) {
1725 // Handle string cases:
1726 if (typeof val === 'string') {
1727 if (typeof start === 'string') {
1731 } else if (typeof end === 'string') {
1735 if (encoding !== undefined && typeof encoding !== 'string') {
1736 throw new TypeError('encoding must be a string')
1738 if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
1739 throw new TypeError('Unknown encoding: ' + encoding)
1741 if (val.length === 1) {
1742 var code = val.charCodeAt(0)
1743 if ((encoding === 'utf8' && code < 128) ||
1744 encoding === 'latin1') {
1745 // Fast path: If `val` fits into a single byte, use that numeric value.
1749 } else if (typeof val === 'number') {
1753 // Invalid ranges are not set to a default, so can range check early.
1754 if (start < 0 || this.length < start || this.length < end) {
1755 throw new RangeError('Out of range index')
1763 end = end === undefined ? this.length : end >>> 0
1768 if (typeof val === 'number') {
1769 for (i = start; i < end; ++i) {
1773 var bytes = Buffer.isBuffer(val)
1775 : Buffer.from(val, encoding)
1776 var len = bytes.length
1778 throw new TypeError('The value "' + val +
1779 '" is invalid for argument "value"')
1781 for (i = 0; i < end - start; ++i) {
1782 this[i + start] = bytes[i % len]
1792 var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g
1794 function base64clean (str) {
1795 // Node takes equal signs as end of the Base64 encoding
1796 str = str.split('=')[0]
1797 // Node strips out invalid characters like \n and \t from the string, base64-js does not
1798 str = str.trim().replace(INVALID_BASE64_RE, '')
1799 // Node converts strings with length < 2 to ''
1800 if (str.length < 2) return ''
1801 // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
1802 while (str.length % 4 !== 0) {
1808 function toHex (n) {
1809 if (n < 16) return '0' + n.toString(16)
1810 return n.toString(16)
1813 function utf8ToBytes (string, units) {
1814 units = units || Infinity
1816 var length = string.length
1817 var leadSurrogate = null
1820 for (var i = 0; i < length; ++i) {
1821 codePoint = string.charCodeAt(i)
1823 // is surrogate component
1824 if (codePoint > 0xD7FF && codePoint < 0xE000) {
1825 // last char was a lead
1826 if (!leadSurrogate) {
1828 if (codePoint > 0xDBFF) {
1830 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
1832 } else if (i + 1 === length) {
1834 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
1839 leadSurrogate = codePoint
1845 if (codePoint < 0xDC00) {
1846 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
1847 leadSurrogate = codePoint
1851 // valid surrogate pair
1852 codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
1853 } else if (leadSurrogate) {
1854 // valid bmp char, but last char was a lead
1855 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
1858 leadSurrogate = null
1861 if (codePoint < 0x80) {
1862 if ((units -= 1) < 0) break
1863 bytes.push(codePoint)
1864 } else if (codePoint < 0x800) {
1865 if ((units -= 2) < 0) break
1867 codePoint >> 0x6 | 0xC0,
1868 codePoint & 0x3F | 0x80
1870 } else if (codePoint < 0x10000) {
1871 if ((units -= 3) < 0) break
1873 codePoint >> 0xC | 0xE0,
1874 codePoint >> 0x6 & 0x3F | 0x80,
1875 codePoint & 0x3F | 0x80
1877 } else if (codePoint < 0x110000) {
1878 if ((units -= 4) < 0) break
1880 codePoint >> 0x12 | 0xF0,
1881 codePoint >> 0xC & 0x3F | 0x80,
1882 codePoint >> 0x6 & 0x3F | 0x80,
1883 codePoint & 0x3F | 0x80
1886 throw new Error('Invalid code point')
1893 function asciiToBytes (str) {
1895 for (var i = 0; i < str.length; ++i) {
1896 // Node's code seems to be doing this and not & 0x7F..
1897 byteArray.push(str.charCodeAt(i) & 0xFF)
1902 function utf16leToBytes (str, units) {
1905 for (var i = 0; i < str.length; ++i) {
1906 if ((units -= 2) < 0) break
1908 c = str.charCodeAt(i)
1918 function base64ToBytes (str) {
1919 return base64.toByteArray(base64clean(str))
1922 function blitBuffer (src, dst, offset, length) {
1923 for (var i = 0; i < length; ++i) {
1924 if ((i + offset >= dst.length) || (i >= src.length)) break
1925 dst[i + offset] = src[i]
1930 // ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass
1931 // the `instanceof` check but they should be treated as of that type.
1932 // See: https://github.com/feross/buffer/issues/166
1933 function isInstance (obj, type) {
1934 return obj instanceof type ||
1935 (obj != null && obj.constructor != null && obj.constructor.name != null &&
1936 obj.constructor.name === type.name)
1938 function numberIsNaN (obj) {
1940 return obj !== obj // eslint-disable-line no-self-compare
1943 },{"base64-js":1,"ieee754":105}],5:[function(require,module,exports){
1946 "101": "Switching Protocols",
1947 "102": "Processing",
1951 "203": "Non-Authoritative Information",
1952 "204": "No Content",
1953 "205": "Reset Content",
1954 "206": "Partial Content",
1955 "207": "Multi-Status",
1956 "208": "Already Reported",
1958 "300": "Multiple Choices",
1959 "301": "Moved Permanently",
1962 "304": "Not Modified",
1964 "307": "Temporary Redirect",
1965 "308": "Permanent Redirect",
1966 "400": "Bad Request",
1967 "401": "Unauthorized",
1968 "402": "Payment Required",
1971 "405": "Method Not Allowed",
1972 "406": "Not Acceptable",
1973 "407": "Proxy Authentication Required",
1974 "408": "Request Timeout",
1977 "411": "Length Required",
1978 "412": "Precondition Failed",
1979 "413": "Payload Too Large",
1980 "414": "URI Too Long",
1981 "415": "Unsupported Media Type",
1982 "416": "Range Not Satisfiable",
1983 "417": "Expectation Failed",
1984 "418": "I'm a teapot",
1985 "421": "Misdirected Request",
1986 "422": "Unprocessable Entity",
1988 "424": "Failed Dependency",
1989 "425": "Unordered Collection",
1990 "426": "Upgrade Required",
1991 "428": "Precondition Required",
1992 "429": "Too Many Requests",
1993 "431": "Request Header Fields Too Large",
1994 "451": "Unavailable For Legal Reasons",
1995 "500": "Internal Server Error",
1996 "501": "Not Implemented",
1997 "502": "Bad Gateway",
1998 "503": "Service Unavailable",
1999 "504": "Gateway Timeout",
2000 "505": "HTTP Version Not Supported",
2001 "506": "Variant Also Negotiates",
2002 "507": "Insufficient Storage",
2003 "508": "Loop Detected",
2004 "509": "Bandwidth Limit Exceeded",
2005 "510": "Not Extended",
2006 "511": "Network Authentication Required"
2009 },{}],6:[function(require,module,exports){
2010 module.exports = require('./lib/clean');
2012 },{"./lib/clean":7}],7:[function(require,module,exports){
2013 (function (process){
2015 * Clean-css - https://github.com/jakubpawlowicz/clean-css
2016 * Released under the terms of MIT license
2018 * Copyright (C) 2017 JakubPawlowicz.com
2021 var level0Optimize = require('./optimizer/level-0/optimize');
2022 var level1Optimize = require('./optimizer/level-1/optimize');
2023 var level2Optimize = require('./optimizer/level-2/optimize');
2024 var validator = require('./optimizer/validator');
2026 var compatibilityFrom = require('./options/compatibility');
2027 var fetchFrom = require('./options/fetch');
2028 var formatFrom = require('./options/format').formatFrom;
2029 var inlineFrom = require('./options/inline');
2030 var inlineRequestFrom = require('./options/inline-request');
2031 var inlineTimeoutFrom = require('./options/inline-timeout');
2032 var OptimizationLevel = require('./options/optimization-level').OptimizationLevel;
2033 var optimizationLevelFrom = require('./options/optimization-level').optimizationLevelFrom;
2034 var rebaseFrom = require('./options/rebase');
2035 var rebaseToFrom = require('./options/rebase-to');
2037 var inputSourceMapTracker = require('./reader/input-source-map-tracker');
2038 var readSources = require('./reader/read-sources');
2040 var serializeStyles = require('./writer/simple');
2041 var serializeStylesAndSourceMap = require('./writer/source-maps');
2043 var CleanCSS = module.exports = function CleanCSS(options) {
2044 options = options || {};
2047 compatibility: compatibilityFrom(options.compatibility),
2048 fetch: fetchFrom(options.fetch),
2049 format: formatFrom(options.format),
2050 inline: inlineFrom(options.inline),
2051 inlineRequest: inlineRequestFrom(options.inlineRequest),
2052 inlineTimeout: inlineTimeoutFrom(options.inlineTimeout),
2053 level: optimizationLevelFrom(options.level),
2054 rebase: rebaseFrom(options.rebase),
2055 rebaseTo: rebaseToFrom(options.rebaseTo),
2056 returnPromise: !!options.returnPromise,
2057 sourceMap: !!options.sourceMap,
2058 sourceMapInlineSources: !!options.sourceMapInlineSources
2063 // for compatibility with optimize-css-assets-webpack-plugin
2064 CleanCSS.process = function (input, opts) {
2066 var optsTo = opts.to;
2069 cleanCss = new CleanCSS(Object.assign({ returnPromise: true, rebaseTo: optsTo }, opts));
2071 return cleanCss.minify(input)
2072 .then(function(output) {
2073 return { css: output.styles };
2078 CleanCSS.prototype.minify = function (input, maybeSourceMap, maybeCallback) {
2079 var options = this.options;
2081 if (options.returnPromise) {
2082 return new Promise(function (resolve, reject) {
2083 minify(input, options, maybeSourceMap, function (errors, output) {
2090 return minify(input, options, maybeSourceMap, maybeCallback);
2094 function minify(input, options, maybeSourceMap, maybeCallback) {
2095 var sourceMap = typeof maybeSourceMap != 'function' ?
2098 var callback = typeof maybeCallback == 'function' ?
2100 (typeof maybeSourceMap == 'function' ? maybeSourceMap : null);
2106 startedAt: Date.now(),
2113 inlinedStylesheets: [],
2114 inputSourceMapTracker: inputSourceMapTracker(),
2115 localOnly: !callback,
2119 validator: validator(options.compatibility),
2124 context.inputSourceMapTracker.track(undefined, sourceMap);
2127 return runner(context.localOnly)(function () {
2128 return readSources(input, context, function (tokens) {
2129 var serialize = context.options.sourceMap ?
2130 serializeStylesAndSourceMap :
2133 var optimizedTokens = optimize(tokens, context);
2134 var optimizedStyles = serialize(optimizedTokens, context);
2135 var output = withMetadata(optimizedStyles, context);
2138 callback(context.errors.length > 0 ? context.errors : null, output) :
2144 function runner(localOnly) {
2145 // to always execute code asynchronously when a callback is given
2146 // more at blog.izs.me/post/59142742143/designing-apis-for-asynchrony
2148 function (callback) { return callback(); } :
2152 function optimize(tokens, context) {
2155 optimized = level0Optimize(tokens, context);
2156 optimized = OptimizationLevel.One in context.options.level ?
2157 level1Optimize(tokens, context) :
2159 optimized = OptimizationLevel.Two in context.options.level ?
2160 level2Optimize(tokens, context, true) :
2166 function withMetadata(output, context) {
2167 output.stats = calculateStatsFrom(output.styles, context);
2168 output.errors = context.errors;
2169 output.inlinedStylesheets = context.inlinedStylesheets;
2170 output.warnings = context.warnings;
2175 function calculateStatsFrom(styles, context) {
2176 var finishedAt = Date.now();
2177 var timeSpent = finishedAt - context.stats.startedAt;
2179 delete context.stats.startedAt;
2180 context.stats.timeSpent = timeSpent;
2181 context.stats.efficiency = 1 - styles.length / context.stats.originalSize;
2182 context.stats.minifiedSize = styles.length;
2184 return context.stats;
2187 }).call(this,require('_process'))
2188 },{"./optimizer/level-0/optimize":9,"./optimizer/level-1/optimize":10,"./optimizer/level-2/optimize":29,"./optimizer/validator":57,"./options/compatibility":59,"./options/fetch":60,"./options/format":61,"./options/inline":64,"./options/inline-request":62,"./options/inline-timeout":63,"./options/optimization-level":65,"./options/rebase":67,"./options/rebase-to":66,"./reader/input-source-map-tracker":71,"./reader/read-sources":77,"./writer/simple":99,"./writer/source-maps":100,"_process":112}],8:[function(require,module,exports){
2190 ASTERISK: 'asterisk',
2192 BACKSLASH: 'backslash',
2193 UNDERSCORE: 'underscore'
2196 module.exports = Hack;
2198 },{}],9:[function(require,module,exports){
2199 function level0Optimize(tokens) {
2200 // noop as level 0 means no optimizations!
2204 module.exports = level0Optimize;
2206 },{}],10:[function(require,module,exports){
2207 var shortenHex = require('./shorten-hex');
2208 var shortenHsl = require('./shorten-hsl');
2209 var shortenRgb = require('./shorten-rgb');
2210 var sortSelectors = require('./sort-selectors');
2211 var tidyRules = require('./tidy-rules');
2212 var tidyBlock = require('./tidy-block');
2213 var tidyAtRule = require('./tidy-at-rule');
2215 var Hack = require('../hack');
2216 var removeUnused = require('../remove-unused');
2217 var restoreFromOptimizing = require('../restore-from-optimizing');
2218 var wrapForOptimizing = require('../wrap-for-optimizing').all;
2220 var OptimizationLevel = require('../../options/optimization-level').OptimizationLevel;
2222 var Token = require('../../tokenizer/token');
2223 var Marker = require('../../tokenizer/marker');
2225 var formatPosition = require('../../utils/format-position');
2226 var split = require('../../utils/split');
2228 var serializeRules = require('../../writer/one-time').rules;
2230 var IgnoreProperty = 'ignore-property';
2232 var CHARSET_TOKEN = '@charset';
2233 var CHARSET_REGEXP = new RegExp('^' + CHARSET_TOKEN, 'i');
2235 var DEFAULT_ROUNDING_PRECISION = require('../../options/rounding-precision').DEFAULT;
2237 var WHOLE_PIXEL_VALUE = /(?:^|\s|\()(-?\d+)px/;
2238 var TIME_VALUE = /^(\-?[\d\.]+)(m?s)$/;
2240 var HEX_VALUE_PATTERN = /[0-9a-f]/i;
2241 var PROPERTY_NAME_PATTERN = /^(?:\-chrome\-|\-[\w\-]+\w|\w[\w\-]+\w|\-\-\S+)$/;
2242 var IMPORT_PREFIX_PATTERN = /^@import/i;
2243 var QUOTED_PATTERN = /^('.*'|".*")$/;
2244 var QUOTED_BUT_SAFE_PATTERN = /^['"][a-zA-Z][a-zA-Z\d\-_]+['"]$/;
2245 var URL_PREFIX_PATTERN = /^url\(/i;
2246 var VARIABLE_NAME_PATTERN = /^--\S+$/;
2248 function isNegative(value) {
2249 return value && value[1][0] == '-' && parseFloat(value[1]) < 0;
2252 function isQuoted(value) {
2253 return QUOTED_PATTERN.test(value);
2256 function isUrl(value) {
2257 return URL_PREFIX_PATTERN.test(value);
2260 function normalizeUrl(value) {
2262 .replace(URL_PREFIX_PATTERN, 'url(')
2263 .replace(/\\?\n|\\?\r\n/g, '');
2266 function optimizeBackground(property) {
2267 var values = property.value;
2269 if (values.length == 1 && values[0][1] == 'none') {
2270 values[0][1] = '0 0';
2273 if (values.length == 1 && values[0][1] == 'transparent') {
2274 values[0][1] = '0 0';
2278 function optimizeBorderRadius(property) {
2279 var values = property.value;
2282 if (values.length == 3 && values[1][1] == '/' && values[0][1] == values[2][1]) {
2284 } else if (values.length == 5 && values[2][1] == '/' && values[0][1] == values[3][1] && values[1][1] == values[4][1]) {
2286 } else if (values.length == 7 && values[3][1] == '/' && values[0][1] == values[4][1] && values[1][1] == values[5][1] && values[2][1] == values[6][1]) {
2288 } else if (values.length == 9 && values[4][1] == '/' && values[0][1] == values[5][1] && values[1][1] == values[6][1] && values[2][1] == values[7][1] && values[3][1] == values[8][1]) {
2293 property.value.splice(spliceAt);
2294 property.dirty = true;
2298 function optimizeColors(name, value, compatibility) {
2299 if (value.indexOf('#') === -1 && value.indexOf('rgb') == -1 && value.indexOf('hsl') == -1) {
2300 return shortenHex(value);
2304 .replace(/rgb\((\-?\d+),(\-?\d+),(\-?\d+)\)/g, function (match, red, green, blue) {
2305 return shortenRgb(red, green, blue);
2307 .replace(/hsl\((-?\d+),(-?\d+)%?,(-?\d+)%?\)/g, function (match, hue, saturation, lightness) {
2308 return shortenHsl(hue, saturation, lightness);
2310 .replace(/(^|[^='"])#([0-9a-f]{6})/gi, function (match, prefix, color, at, inputValue) {
2311 var suffix = inputValue[at + match.length];
2313 if (suffix && HEX_VALUE_PATTERN.test(suffix)) {
2315 } else if (color[0] == color[1] && color[2] == color[3] && color[4] == color[5]) {
2316 return (prefix + '#' + color[0] + color[2] + color[4]).toLowerCase();
2318 return (prefix + '#' + color).toLowerCase();
2321 .replace(/(^|[^='"])#([0-9a-f]{3})/gi, function (match, prefix, color) {
2322 return prefix + '#' + color.toLowerCase();
2324 .replace(/(rgb|rgba|hsl|hsla)\(([^\)]+)\)/g, function (match, colorFunction, colorDef) {
2325 var tokens = colorDef.split(',');
2326 var applies = (colorFunction == 'hsl' && tokens.length == 3) ||
2327 (colorFunction == 'hsla' && tokens.length == 4) ||
2328 (colorFunction == 'rgb' && tokens.length == 3 && colorDef.indexOf('%') > 0) ||
2329 (colorFunction == 'rgba' && tokens.length == 4 && colorDef.indexOf('%') > 0);
2335 if (tokens[1].indexOf('%') == -1) {
2339 if (tokens[2].indexOf('%') == -1) {
2343 return colorFunction + '(' + tokens.join(',') + ')';
2346 if (compatibility.colors.opacity && name.indexOf('background') == -1) {
2347 value = value.replace(/(?:rgba|hsla)\(0,0%?,0%?,0\)/g, function (match) {
2348 if (split(value, ',').pop().indexOf('gradient(') > -1) {
2352 return 'transparent';
2356 return shortenHex(value);
2359 function optimizeFilter(property) {
2360 if (property.value.length == 1) {
2361 property.value[0][1] = property.value[0][1].replace(/progid:DXImageTransform\.Microsoft\.(Alpha|Chroma)(\W)/, function (match, filter, suffix) {
2362 return filter.toLowerCase() + suffix;
2366 property.value[0][1] = property.value[0][1]
2367 .replace(/,(\S)/g, ', $1')
2368 .replace(/ ?= ?/g, '=');
2371 function optimizeFontWeight(property, atIndex) {
2372 var value = property.value[atIndex][1];
2374 if (value == 'normal') {
2376 } else if (value == 'bold') {
2380 property.value[atIndex][1] = value;
2383 function optimizeMultipleZeros(property) {
2384 var values = property.value;
2387 if (values.length == 4 && values[0][1] === '0' && values[1][1] === '0' && values[2][1] === '0' && values[3][1] === '0') {
2388 if (property.name.indexOf('box-shadow') > -1) {
2396 property.value.splice(spliceAt);
2397 property.dirty = true;
2401 function optimizeOutline(property) {
2402 var values = property.value;
2404 if (values.length == 1 && values[0][1] == 'none') {
2409 function optimizePixelLengths(_, value, compatibility) {
2410 if (!WHOLE_PIXEL_VALUE.test(value)) {
2414 return value.replace(WHOLE_PIXEL_VALUE, function (match, val) {
2416 var intVal = parseInt(val);
2422 if (compatibility.properties.shorterLengthUnits && compatibility.units.pt && intVal * 3 % 4 === 0) {
2423 newValue = intVal * 3 / 4 + 'pt';
2426 if (compatibility.properties.shorterLengthUnits && compatibility.units.pc && intVal % 16 === 0) {
2427 newValue = intVal / 16 + 'pc';
2430 if (compatibility.properties.shorterLengthUnits && compatibility.units.in && intVal % 96 === 0) {
2431 newValue = intVal / 96 + 'in';
2435 newValue = match.substring(0, match.indexOf(val)) + newValue;
2438 return newValue && newValue.length < match.length ? newValue : match;
2442 function optimizePrecision(_, value, precisionOptions) {
2443 if (!precisionOptions.enabled || value.indexOf('.') === -1) {
2448 .replace(precisionOptions.decimalPointMatcher, '$1$2$3')
2449 .replace(precisionOptions.zeroMatcher, function (match, integerPart, fractionPart, unit) {
2450 var multiplier = precisionOptions.units[unit].multiplier;
2451 var parsedInteger = parseInt(integerPart);
2452 var integer = isNaN(parsedInteger) ? 0 : parsedInteger;
2453 var fraction = parseFloat(fractionPart);
2455 return Math.round((integer + fraction) * multiplier) / multiplier + unit;
2459 function optimizeTimeUnits(_, value) {
2460 if (!TIME_VALUE.test(value))
2463 return value.replace(TIME_VALUE, function (match, val, unit) {
2467 newValue = parseInt(val) / 1000 + 's';
2468 } else if (unit == 's') {
2469 newValue = parseFloat(val) * 1000 + 'ms';
2472 return newValue.length < match.length ? newValue : match;
2476 function optimizeUnits(name, value, unitsRegexp) {
2477 if (/^(?:\-moz\-calc|\-webkit\-calc|calc|rgb|hsl|rgba|hsla)\(/.test(value)) {
2481 if (name == 'flex' || name == '-ms-flex' || name == '-webkit-flex' || name == 'flex-basis' || name == '-webkit-flex-basis') {
2485 if (value.indexOf('%') > 0 && (name == 'height' || name == 'max-height' || name == 'width' || name == 'max-width')) {
2490 .replace(unitsRegexp, '$1' + '0' + '$2')
2491 .replace(unitsRegexp, '$1' + '0' + '$2');
2494 function optimizeWhitespace(name, value) {
2495 if (name.indexOf('filter') > -1 || value.indexOf(' ') == -1 || value.indexOf('expression') === 0) {
2499 if (value.indexOf(Marker.SINGLE_QUOTE) > -1 || value.indexOf(Marker.DOUBLE_QUOTE) > -1) {
2503 value = value.replace(/\s+/g, ' ');
2505 if (value.indexOf('calc') > -1) {
2506 value = value.replace(/\) ?\/ ?/g, ')/ ');
2510 .replace(/(\(;?)\s+/g, '$1')
2511 .replace(/\s+(;?\))/g, '$1')
2512 .replace(/, /g, ',');
2515 function optimizeZeroDegUnit(_, value) {
2516 if (value.indexOf('0deg') == -1) {
2520 return value.replace(/\(0deg\)/g, '(0)');
2523 function optimizeZeroUnits(name, value) {
2524 if (value.indexOf('0') == -1) {
2528 if (value.indexOf('-') > -1) {
2530 .replace(/([^\w\d\-]|^)\-0([^\.]|$)/g, '$10$2')
2531 .replace(/([^\w\d\-]|^)\-0([^\.]|$)/g, '$10$2');
2535 .replace(/(^|\s)0+([1-9])/g, '$1$2')
2536 .replace(/(^|\D)\.0+(\D|$)/g, '$10$2')
2537 .replace(/(^|\D)\.0+(\D|$)/g, '$10$2')
2538 .replace(/\.([1-9]*)0+(\D|$)/g, function (match, nonZeroPart, suffix) {
2539 return (nonZeroPart.length > 0 ? '.' : '') + nonZeroPart + suffix;
2541 .replace(/(^|\D)0\.(\d)/g, '$1.$2');
2544 function removeQuotes(name, value) {
2545 if (name == 'content' || name.indexOf('font-variation-settings') > -1 || name.indexOf('font-feature-settings') > -1 || name.indexOf('grid-') > -1) {
2549 return QUOTED_BUT_SAFE_PATTERN.test(value) ?
2550 value.substring(1, value.length - 1) :
2554 function removeUrlQuotes(value) {
2555 return /^url\(['"].+['"]\)$/.test(value) && !/^url\(['"].*[\*\s\(\)'"].*['"]\)$/.test(value) && !/^url\(['"]data:[^;]+;charset/.test(value) ?
2556 value.replace(/["']/g, '') :
2560 function transformValue(propertyName, propertyValue, rule, transformCallback) {
2561 var selector = serializeRules(rule);
2562 var transformedValue = transformCallback(propertyName, propertyValue, selector);
2564 if (transformedValue === undefined) {
2565 return propertyValue;
2566 } else if (transformedValue === false) {
2567 return IgnoreProperty;
2569 return transformedValue;
2575 function optimizeBody(rule, properties, context) {
2576 var options = context.options;
2577 var levelOptions = options.level[OptimizationLevel.One];
2578 var property, name, type, value;
2581 var _properties = wrapForOptimizing(properties, true);
2584 for (var i = 0, l = _properties.length; i < l; i++) {
2585 property = _properties[i];
2586 name = property.name;
2588 if (!PROPERTY_NAME_PATTERN.test(name)) {
2589 propertyToken = property.all[property.position];
2590 context.warnings.push('Invalid property name \'' + name + '\' at ' + formatPosition(propertyToken[1][2][0]) + '. Ignoring.');
2591 property.unused = true;
2594 if (property.value.length === 0) {
2595 propertyToken = property.all[property.position];
2596 context.warnings.push('Empty property \'' + name + '\' at ' + formatPosition(propertyToken[1][2][0]) + '. Ignoring.');
2597 property.unused = true;
2600 if (property.hack && (
2601 (property.hack[0] == Hack.ASTERISK || property.hack[0] == Hack.UNDERSCORE) && !options.compatibility.properties.iePrefixHack ||
2602 property.hack[0] == Hack.BACKSLASH && !options.compatibility.properties.ieSuffixHack ||
2603 property.hack[0] == Hack.BANG && !options.compatibility.properties.ieBangHack)) {
2604 property.unused = true;
2607 if (levelOptions.removeNegativePaddings && name.indexOf('padding') === 0 && (isNegative(property.value[0]) || isNegative(property.value[1]) || isNegative(property.value[2]) || isNegative(property.value[3]))) {
2608 property.unused = true;
2611 if (!options.compatibility.properties.ieFilters && isLegacyFilter(property)) {
2612 property.unused = true;
2615 if (property.unused) {
2619 if (property.block) {
2620 optimizeBody(rule, property.value[0][1], context);
2624 if (VARIABLE_NAME_PATTERN.test(name)) {
2628 for (var j = 0, m = property.value.length; j < m; j++) {
2629 type = property.value[j][0];
2630 value = property.value[j][1];
2631 valueIsUrl = isUrl(value);
2633 if (type == Token.PROPERTY_BLOCK) {
2634 property.unused = true;
2635 context.warnings.push('Invalid value token at ' + formatPosition(value[0][1][2][0]) + '. Ignoring.');
2639 if (valueIsUrl && !context.validator.isUrl(value)) {
2640 property.unused = true;
2641 context.warnings.push('Broken URL \'' + value + '\' at ' + formatPosition(property.value[j][2][0]) + '. Ignoring.');
2646 value = levelOptions.normalizeUrls ?
2647 normalizeUrl(value) :
2649 value = !options.compatibility.properties.urlQuotes ?
2650 removeUrlQuotes(value) :
2652 } else if (isQuoted(value)) {
2653 value = levelOptions.removeQuotes ?
2654 removeQuotes(name, value) :
2657 value = levelOptions.removeWhitespace ?
2658 optimizeWhitespace(name, value) :
2660 value = optimizePrecision(name, value, options.precision);
2661 value = optimizePixelLengths(name, value, options.compatibility);
2662 value = levelOptions.replaceTimeUnits ?
2663 optimizeTimeUnits(name, value) :
2665 value = levelOptions.replaceZeroUnits ?
2666 optimizeZeroUnits(name, value) :
2669 if (options.compatibility.properties.zeroUnits) {
2670 value = optimizeZeroDegUnit(name, value);
2671 value = optimizeUnits(name, value, options.unitsRegexp);
2674 if (options.compatibility.properties.colors) {
2675 value = optimizeColors(name, value, options.compatibility);
2679 value = transformValue(name, value, rule, levelOptions.transform);
2681 if (value === IgnoreProperty) {
2682 property.unused = true;
2683 continue propertyLoop;
2686 property.value[j][1] = value;
2689 if (levelOptions.replaceMultipleZeros) {
2690 optimizeMultipleZeros(property);
2693 if (name == 'background' && levelOptions.optimizeBackground) {
2694 optimizeBackground(property);
2695 } else if (name.indexOf('border') === 0 && name.indexOf('radius') > 0 && levelOptions.optimizeBorderRadius) {
2696 optimizeBorderRadius(property);
2697 } else if (name == 'filter'&& levelOptions.optimizeFilter && options.compatibility.properties.ieFilters) {
2698 optimizeFilter(property);
2699 } else if (name == 'font-weight' && levelOptions.optimizeFontWeight) {
2700 optimizeFontWeight(property, 0);
2701 } else if (name == 'outline' && levelOptions.optimizeOutline) {
2702 optimizeOutline(property);
2706 restoreFromOptimizing(_properties);
2707 removeUnused(_properties);
2708 removeComments(properties, options);
2711 function removeComments(tokens, options) {
2715 for (i = 0; i < tokens.length; i++) {
2718 if (token[0] != Token.COMMENT) {
2722 optimizeComment(token, options);
2724 if (token[1].length === 0) {
2725 tokens.splice(i, 1);
2731 function optimizeComment(token, options) {
2732 if (token[1][2] == Marker.EXCLAMATION && (options.level[OptimizationLevel.One].specialComments == 'all' || options.commentsKept < options.level[OptimizationLevel.One].specialComments)) {
2733 options.commentsKept++;
2740 function cleanupCharsets(tokens) {
2741 var hasCharset = false;
2743 for (var i = 0, l = tokens.length; i < l; i++) {
2744 var token = tokens[i];
2746 if (token[0] != Token.AT_RULE)
2749 if (!CHARSET_REGEXP.test(token[1]))
2752 if (hasCharset || token[1].indexOf(CHARSET_TOKEN) == -1) {
2753 tokens.splice(i, 1);
2758 tokens.splice(i, 1);
2759 tokens.unshift([Token.AT_RULE, token[1].replace(CHARSET_REGEXP, CHARSET_TOKEN)]);
2764 function buildUnitRegexp(options) {
2765 var units = ['px', 'em', 'ex', 'cm', 'mm', 'in', 'pt', 'pc', '%'];
2766 var otherUnits = ['ch', 'rem', 'vh', 'vm', 'vmax', 'vmin', 'vw'];
2768 otherUnits.forEach(function (unit) {
2769 if (options.compatibility.units[unit]) {
2774 return new RegExp('(^|\\s|\\(|,)0(?:' + units.join('|') + ')(\\W|$)', 'g');
2777 function buildPrecisionOptions(roundingPrecision) {
2778 var precisionOptions = {
2782 var optimizable = [];
2786 for (unit in roundingPrecision) {
2787 value = roundingPrecision[unit];
2789 if (value != DEFAULT_ROUNDING_PRECISION) {
2790 precisionOptions.units[unit] = {};
2791 precisionOptions.units[unit].value = value;
2792 precisionOptions.units[unit].multiplier = Math.pow(10, value);
2794 optimizable.push(unit);
2798 if (optimizable.length > 0) {
2799 precisionOptions.enabled = true;
2800 precisionOptions.decimalPointMatcher = new RegExp('(\\d)\\.($|' + optimizable.join('|') + ')($|\W)', 'g');
2801 precisionOptions.zeroMatcher = new RegExp('(\\d*)(\\.\\d+)(' + optimizable.join('|') + ')', 'g');
2804 return precisionOptions;
2807 function isImport(token) {
2808 return IMPORT_PREFIX_PATTERN.test(token[1]);
2811 function isLegacyFilter(property) {
2814 if (property.name == 'filter' || property.name == '-ms-filter') {
2815 value = property.value[0][1];
2817 return value.indexOf('progid') > -1 ||
2818 value.indexOf('alpha') === 0 ||
2819 value.indexOf('chroma') === 0;
2825 function level1Optimize(tokens, context) {
2826 var options = context.options;
2827 var levelOptions = options.level[OptimizationLevel.One];
2828 var ie7Hack = options.compatibility.selectors.ie7Hack;
2829 var adjacentSpace = options.compatibility.selectors.adjacentSpace;
2830 var spaceAfterClosingBrace = options.compatibility.properties.spaceAfterClosingBrace;
2831 var format = options.format;
2832 var mayHaveCharset = false;
2833 var afterRules = false;
2835 options.unitsRegexp = options.unitsRegexp || buildUnitRegexp(options);
2836 options.precision = options.precision || buildPrecisionOptions(levelOptions.roundingPrecision);
2837 options.commentsKept = options.commentsKept || 0;
2839 for (var i = 0, l = tokens.length; i < l; i++) {
2840 var token = tokens[i];
2844 token[1] = isImport(token) && afterRules ? '' : token[1];
2845 token[1] = levelOptions.tidyAtRules ? tidyAtRule(token[1]) : token[1];
2846 mayHaveCharset = true;
2848 case Token.AT_RULE_BLOCK:
2849 optimizeBody(token[1], token[2], context);
2852 case Token.NESTED_BLOCK:
2853 token[1] = levelOptions.tidyBlockScopes ? tidyBlock(token[1], spaceAfterClosingBrace) : token[1];
2854 level1Optimize(token[2], context);
2858 optimizeComment(token, options);
2861 token[1] = levelOptions.tidySelectors ? tidyRules(token[1], !ie7Hack, adjacentSpace, format, context.warnings) : token[1];
2862 token[1] = token[1].length > 1 ? sortSelectors(token[1], levelOptions.selectorsSortingMethod) : token[1];
2863 optimizeBody(token[1], token[2], context);
2868 if (token[0] == Token.COMMENT && token[1].length === 0 || levelOptions.removeEmpty && (token[1].length === 0 || (token[2] && token[2].length === 0))) {
2869 tokens.splice(i, 1);
2875 if (levelOptions.cleanupCharsets && mayHaveCharset) {
2876 cleanupCharsets(tokens);
2882 module.exports = level1Optimize;
2884 },{"../../options/optimization-level":65,"../../options/rounding-precision":68,"../../tokenizer/marker":83,"../../tokenizer/token":84,"../../utils/format-position":87,"../../utils/split":96,"../../writer/one-time":98,"../hack":8,"../remove-unused":55,"../restore-from-optimizing":56,"../wrap-for-optimizing":58,"./shorten-hex":11,"./shorten-hsl":12,"./shorten-rgb":13,"./sort-selectors":14,"./tidy-at-rule":15,"./tidy-block":16,"./tidy-rules":17}],11:[function(require,module,exports){
2886 aliceblue: '#f0f8ff',
2887 antiquewhite: '#faebd7',
2889 aquamarine: '#7fffd4',
2894 blanchedalmond: '#ffebcd',
2896 blueviolet: '#8a2be2',
2898 burlywood: '#deb887',
2899 cadetblue: '#5f9ea0',
2900 chartreuse: '#7fff00',
2901 chocolate: '#d2691e',
2903 cornflowerblue: '#6495ed',
2904 cornsilk: '#fff8dc',
2907 darkblue: '#00008b',
2908 darkcyan: '#008b8b',
2909 darkgoldenrod: '#b8860b',
2910 darkgray: '#a9a9a9',
2911 darkgreen: '#006400',
2912 darkgrey: '#a9a9a9',
2913 darkkhaki: '#bdb76b',
2914 darkmagenta: '#8b008b',
2915 darkolivegreen: '#556b2f',
2916 darkorange: '#ff8c00',
2917 darkorchid: '#9932cc',
2919 darksalmon: '#e9967a',
2920 darkseagreen: '#8fbc8f',
2921 darkslateblue: '#483d8b',
2922 darkslategray: '#2f4f4f',
2923 darkslategrey: '#2f4f4f',
2924 darkturquoise: '#00ced1',
2925 darkviolet: '#9400d3',
2926 deeppink: '#ff1493',
2927 deepskyblue: '#00bfff',
2930 dodgerblue: '#1e90ff',
2931 firebrick: '#b22222',
2932 floralwhite: '#fffaf0',
2933 forestgreen: '#228b22',
2935 gainsboro: '#dcdcdc',
2936 ghostwhite: '#f8f8ff',
2938 goldenrod: '#daa520',
2941 greenyellow: '#adff2f',
2943 honeydew: '#f0fff0',
2945 indianred: '#cd5c5c',
2949 lavender: '#e6e6fa',
2950 lavenderblush: '#fff0f5',
2951 lawngreen: '#7cfc00',
2952 lemonchiffon: '#fffacd',
2953 lightblue: '#add8e6',
2954 lightcoral: '#f08080',
2955 lightcyan: '#e0ffff',
2956 lightgoldenrodyellow: '#fafad2',
2957 lightgray: '#d3d3d3',
2958 lightgreen: '#90ee90',
2959 lightgrey: '#d3d3d3',
2960 lightpink: '#ffb6c1',
2961 lightsalmon: '#ffa07a',
2962 lightseagreen: '#20b2aa',
2963 lightskyblue: '#87cefa',
2964 lightslategray: '#778899',
2965 lightslategrey: '#778899',
2966 lightsteelblue: '#b0c4de',
2967 lightyellow: '#ffffe0',
2969 limegreen: '#32cd32',
2973 mediumaquamarine: '#66cdaa',
2974 mediumblue: '#0000cd',
2975 mediumorchid: '#ba55d3',
2976 mediumpurple: '#9370db',
2977 mediumseagreen: '#3cb371',
2978 mediumslateblue: '#7b68ee',
2979 mediumspringgreen: '#00fa9a',
2980 mediumturquoise: '#48d1cc',
2981 mediumvioletred: '#c71585',
2982 midnightblue: '#191970',
2983 mintcream: '#f5fffa',
2984 mistyrose: '#ffe4e1',
2985 moccasin: '#ffe4b5',
2986 navajowhite: '#ffdead',
2990 olivedrab: '#6b8e23',
2992 orangered: '#ff4500',
2994 palegoldenrod: '#eee8aa',
2995 palegreen: '#98fb98',
2996 paleturquoise: '#afeeee',
2997 palevioletred: '#db7093',
2998 papayawhip: '#ffefd5',
2999 peachpuff: '#ffdab9',
3003 powderblue: '#b0e0e6',
3005 rebeccapurple: '#663399',
3007 rosybrown: '#bc8f8f',
3008 royalblue: '#4169e1',
3009 saddlebrown: '#8b4513',
3011 sandybrown: '#f4a460',
3012 seagreen: '#2e8b57',
3013 seashell: '#fff5ee',
3017 slateblue: '#6a5acd',
3018 slategray: '#708090',
3019 slategrey: '#708090',
3021 springgreen: '#00ff7f',
3022 steelblue: '#4682b4',
3027 turquoise: '#40e0d0',
3031 whitesmoke: '#f5f5f5',
3033 yellowgreen: '#9acd32'
3039 for (var name in COLORS) {
3040 var hex = COLORS[name];
3042 if (name.length < hex.length) {
3049 var toHexPattern = new RegExp('(^| |,|\\))(' + Object.keys(toHex).join('|') + ')( |,|\\)|$)', 'ig');
3050 var toNamePattern = new RegExp('(' + Object.keys(toName).join('|') + ')([^a-f0-9]|$)', 'ig');
3052 function hexConverter(match, prefix, colorValue, suffix) {
3053 return prefix + toHex[colorValue.toLowerCase()] + suffix;
3056 function nameConverter(match, colorValue, suffix) {
3057 return toName[colorValue.toLowerCase()] + suffix;
3060 function shortenHex(value) {
3061 var hasHex = value.indexOf('#') > -1;
3062 var shortened = value.replace(toHexPattern, hexConverter);
3064 if (shortened != value) {
3065 shortened = shortened.replace(toHexPattern, hexConverter);
3069 shortened.replace(toNamePattern, nameConverter) :
3073 module.exports = shortenHex;
3075 },{}],12:[function(require,module,exports){
3076 // HSL to RGB converter. Both methods adapted from:
3077 // http://mjijackson.com/2008/02/rgb-to-hsl-and-rgb-to-hsv-color-model-conversion-algorithms-in-javascript
3079 function hslToRgb(h, s, l) {
3082 // normalize hue orientation b/w 0 and 360 degrees
3101 r = g = b = l; // achromatic
3107 r = hueToRgb(p, q, h + 1/3);
3108 g = hueToRgb(p, q, h);
3109 b = hueToRgb(p, q, h - 1/3);
3112 return [~~(r * 255), ~~(g * 255), ~~(b * 255)];
3115 function hueToRgb(p, q, t) {
3118 if (t < 1/6) return p + (q - p) * 6 * t;
3119 if (t < 1/2) return q;
3120 if (t < 2/3) return p + (q - p) * (2/3 - t) * 6;
3124 function shortenHsl(hue, saturation, lightness) {
3125 var asRgb = hslToRgb(hue, saturation, lightness);
3126 var redAsHex = asRgb[0].toString(16);
3127 var greenAsHex = asRgb[1].toString(16);
3128 var blueAsHex = asRgb[2].toString(16);
3131 ((redAsHex.length == 1 ? '0' : '') + redAsHex) +
3132 ((greenAsHex.length == 1 ? '0' : '') + greenAsHex) +
3133 ((blueAsHex.length == 1 ? '0' : '') + blueAsHex);
3136 module.exports = shortenHsl;
3138 },{}],13:[function(require,module,exports){
3139 function shortenRgb(red, green, blue) {
3140 var normalizedRed = Math.max(0, Math.min(parseInt(red), 255));
3141 var normalizedGreen = Math.max(0, Math.min(parseInt(green), 255));
3142 var normalizedBlue = Math.max(0, Math.min(parseInt(blue), 255));
3144 // Credit: Asen http://jsbin.com/UPUmaGOc/2/edit?js,console
3145 return '#' + ('00000' + (normalizedRed << 16 | normalizedGreen << 8 | normalizedBlue).toString(16)).slice(-6);
3148 module.exports = shortenRgb;
3150 },{}],14:[function(require,module,exports){
3151 var naturalCompare = require('../../utils/natural-compare');
3153 function naturalSorter(scope1, scope2) {
3154 return naturalCompare(scope1[1], scope2[1]);
3157 function standardSorter(scope1, scope2) {
3158 return scope1[1] > scope2[1] ? 1 : -1;
3161 function sortSelectors(selectors, method) {
3164 return selectors.sort(naturalSorter);
3166 return selectors.sort(standardSorter);
3173 module.exports = sortSelectors;
3175 },{"../../utils/natural-compare":94}],15:[function(require,module,exports){
3176 function tidyAtRule(value) {
3178 .replace(/\s+/g, ' ')
3179 .replace(/url\(\s+/g, 'url(')
3180 .replace(/\s+\)/g, ')')
3184 module.exports = tidyAtRule;
3186 },{}],16:[function(require,module,exports){
3187 var SUPPORTED_COMPACT_BLOCK_MATCHER = /^@media\W/;
3189 function tidyBlock(values, spaceAfterClosingBrace) {
3190 var withoutSpaceAfterClosingBrace;
3193 for (i = values.length - 1; i >= 0; i--) {
3194 withoutSpaceAfterClosingBrace = !spaceAfterClosingBrace && SUPPORTED_COMPACT_BLOCK_MATCHER.test(values[i][1]);
3196 values[i][1] = values[i][1]
3197 .replace(/\n|\r\n/g, ' ')
3198 .replace(/\s+/g, ' ')
3199 .replace(/(,|:|\() /g, '$1')
3200 .replace(/ \)/g, ')')
3201 .replace(/'([a-zA-Z][a-zA-Z\d\-_]+)'/, '$1')
3202 .replace(/"([a-zA-Z][a-zA-Z\d\-_]+)"/, '$1')
3203 .replace(withoutSpaceAfterClosingBrace ? /\) /g : null, ')');
3209 module.exports = tidyBlock;
3211 },{}],17:[function(require,module,exports){
3212 var Spaces = require('../../options/format').Spaces;
3213 var Marker = require('../../tokenizer/marker');
3214 var formatPosition = require('../../utils/format-position');
3216 var CASE_ATTRIBUTE_PATTERN = /[\s"'][iI]\s*\]/;
3217 var CASE_RESTORE_PATTERN = /([\d\w])([iI])\]/g;
3218 var DOUBLE_QUOTE_CASE_PATTERN = /="([a-zA-Z][a-zA-Z\d\-_]+)"([iI])/g;
3219 var DOUBLE_QUOTE_PATTERN = /="([a-zA-Z][a-zA-Z\d\-_]+)"(\s|\])/g;
3220 var HTML_COMMENT_PATTERN = /^(?:(?:<!--|-->)\s*)+/;
3221 var SINGLE_QUOTE_CASE_PATTERN = /='([a-zA-Z][a-zA-Z\d\-_]+)'([iI])/g;
3222 var SINGLE_QUOTE_PATTERN = /='([a-zA-Z][a-zA-Z\d\-_]+)'(\s|\])/g;
3223 var RELATION_PATTERN = /[>\+~]/;
3224 var WHITESPACE_PATTERN = /\s/;
3226 var ASTERISK_PLUS_HTML_HACK = '*+html ';
3227 var ASTERISK_FIRST_CHILD_PLUS_HTML_HACK = '*:first-child+html ';
3228 var LESS_THAN = '<';
3230 function hasInvalidCharacters(value) {
3232 var isInvalid = false;
3234 var isQuote = false;
3237 for (i = 0, l = value.length; i < l; i++) {
3238 character = value[i];
3241 // continue as always
3242 } else if (character == Marker.SINGLE_QUOTE || character == Marker.DOUBLE_QUOTE) {
3244 } else if (!isQuote && (character == Marker.CLOSE_CURLY_BRACKET || character == Marker.EXCLAMATION || character == LESS_THAN || character == Marker.SEMICOLON)) {
3247 } else if (!isQuote && i === 0 && RELATION_PATTERN.test(character)) {
3252 isEscaped = character == Marker.BACK_SLASH;
3258 function removeWhitespace(value, format) {
3271 var roundBracketLevel = 0;
3272 var wasRelation = false;
3273 var wasWhitespace = false;
3274 var withCaseAttribute = CASE_ATTRIBUTE_PATTERN.test(value);
3275 var spaceAroundRelation = format && format.spaces[Spaces.AroundSelectorRelation];
3278 for (i = 0, l = value.length; i < l; i++) {
3279 character = value[i];
3281 isNewLineNix = character == Marker.NEW_LINE_NIX;
3282 isNewLineWin = character == Marker.NEW_LINE_NIX && value[i - 1] == Marker.CARRIAGE_RETURN;
3283 isQuoted = isSingleQuoted || isDoubleQuoted;
3284 isRelation = !isAttribute && !isEscaped && roundBracketLevel === 0 && RELATION_PATTERN.test(character);
3285 isWhitespace = WHITESPACE_PATTERN.test(character);
3287 if (wasEscaped && isQuoted && isNewLineWin) {
3288 // swallow escaped new windows lines in comments
3291 } else if (isEscaped && isQuoted && isNewLineNix) {
3292 // swallow escaped new *nix lines in comments
3294 } else if (isEscaped) {
3295 stripped.push(character);
3296 } else if (character == Marker.OPEN_SQUARE_BRACKET && !isQuoted) {
3297 stripped.push(character);
3299 } else if (character == Marker.CLOSE_SQUARE_BRACKET && !isQuoted) {
3300 stripped.push(character);
3301 isAttribute = false;
3302 } else if (character == Marker.OPEN_ROUND_BRACKET && !isQuoted) {
3303 stripped.push(character);
3304 roundBracketLevel++;
3305 } else if (character == Marker.CLOSE_ROUND_BRACKET && !isQuoted) {
3306 stripped.push(character);
3307 roundBracketLevel--;
3308 } else if (character == Marker.SINGLE_QUOTE && !isQuoted) {
3309 stripped.push(character);
3310 isSingleQuoted = true;
3311 } else if (character == Marker.DOUBLE_QUOTE && !isQuoted) {
3312 stripped.push(character);
3313 isDoubleQuoted = true;
3314 } else if (character == Marker.SINGLE_QUOTE && isQuoted) {
3315 stripped.push(character);
3316 isSingleQuoted = false;
3317 } else if (character == Marker.DOUBLE_QUOTE && isQuoted) {
3318 stripped.push(character);
3319 isDoubleQuoted = false;
3320 } else if (isWhitespace && wasRelation && !spaceAroundRelation) {
3322 } else if (!isWhitespace && wasRelation && spaceAroundRelation) {
3323 stripped.push(Marker.SPACE);
3324 stripped.push(character);
3325 } else if (isWhitespace && (isAttribute || roundBracketLevel > 0) && !isQuoted) {
3327 } else if (isWhitespace && wasWhitespace && !isQuoted) {
3329 } else if ((isNewLineWin || isNewLineNix) && (isAttribute || roundBracketLevel > 0) && isQuoted) {
3331 } else if (isRelation && wasWhitespace && !spaceAroundRelation) {
3333 stripped.push(character);
3334 } else if (isRelation && !wasWhitespace && spaceAroundRelation) {
3335 stripped.push(Marker.SPACE);
3336 stripped.push(character);
3337 } else if (isWhitespace) {
3338 stripped.push(Marker.SPACE);
3340 stripped.push(character);
3343 wasEscaped = isEscaped;
3344 isEscaped = character == Marker.BACK_SLASH;
3345 wasRelation = isRelation;
3346 wasWhitespace = isWhitespace;
3349 return withCaseAttribute ?
3350 stripped.join('').replace(CASE_RESTORE_PATTERN, '$1 $2]') :
3354 function removeQuotes(value) {
3355 if (value.indexOf('\'') == -1 && value.indexOf('"') == -1) {
3360 .replace(SINGLE_QUOTE_CASE_PATTERN, '=$1 $2')
3361 .replace(SINGLE_QUOTE_PATTERN, '=$1$2')
3362 .replace(DOUBLE_QUOTE_CASE_PATTERN, '=$1 $2')
3363 .replace(DOUBLE_QUOTE_PATTERN, '=$1$2');
3366 function tidyRules(rules, removeUnsupported, adjacentSpace, format, warnings) {
3370 function removeHTMLComment(rule, match) {
3371 warnings.push('HTML comment \'' + match + '\' at ' + formatPosition(rule[2][0]) + '. Removing.');
3375 for (var i = 0, l = rules.length; i < l; i++) {
3376 var rule = rules[i];
3377 var reduced = rule[1];
3379 reduced = reduced.replace(HTML_COMMENT_PATTERN, removeHTMLComment.bind(null, rule));
3381 if (hasInvalidCharacters(reduced)) {
3382 warnings.push('Invalid selector \'' + rule[1] + '\' at ' + formatPosition(rule[2][0]) + '. Ignoring.');
3386 reduced = removeWhitespace(reduced, format);
3387 reduced = removeQuotes(reduced);
3389 if (adjacentSpace && reduced.indexOf('nav') > 0) {
3390 reduced = reduced.replace(/\+nav(\S|$)/, '+ nav$1');
3393 if (removeUnsupported && reduced.indexOf(ASTERISK_PLUS_HTML_HACK) > -1) {
3397 if (removeUnsupported && reduced.indexOf(ASTERISK_FIRST_CHILD_PLUS_HTML_HACK) > -1) {
3401 if (reduced.indexOf('*') > -1) {
3403 .replace(/\*([:#\.\[])/g, '$1')
3404 .replace(/^(\:first\-child)?\+html/, '*$1+html');
3407 if (repeated.indexOf(reduced) > -1) {
3412 repeated.push(reduced);
3416 if (list.length == 1 && list[0][1].length === 0) {
3417 warnings.push('Empty selector \'' + list[0][1] + '\' at ' + formatPosition(list[0][2][0]) + '. Ignoring.');
3424 module.exports = tidyRules;
3426 },{"../../options/format":61,"../../tokenizer/marker":83,"../../utils/format-position":87}],18:[function(require,module,exports){
3427 var InvalidPropertyError = require('./invalid-property-error');
3429 var wrapSingle = require('../wrap-for-optimizing').single;
3431 var Token = require('../../tokenizer/token');
3432 var Marker = require('../../tokenizer/marker');
3434 var formatPosition = require('../../utils/format-position');
3436 function _anyIsInherit(values) {
3439 for (i = 0, l = values.length; i < l; i++) {
3440 if (values[i][1] == 'inherit') {
3448 function _colorFilter(validator) {
3449 return function (value) {
3450 return value[1] == 'invert' || validator.isColor(value[1]) || validator.isPrefixed(value[1]);
3454 function _styleFilter(validator) {
3455 return function (value) {
3456 return value[1] != 'inherit' && validator.isStyleKeyword(value[1]) && !validator.isColorFunction(value[1]);
3460 function _wrapDefault(name, property, compactable) {
3461 var descriptor = compactable[name];
3462 if (descriptor.doubleValues && descriptor.defaultValue.length == 2) {
3465 [Token.PROPERTY_NAME, name],
3466 [Token.PROPERTY_VALUE, descriptor.defaultValue[0]],
3467 [Token.PROPERTY_VALUE, descriptor.defaultValue[1]]
3469 } else if (descriptor.doubleValues && descriptor.defaultValue.length == 1) {
3472 [Token.PROPERTY_NAME, name],
3473 [Token.PROPERTY_VALUE, descriptor.defaultValue[0]]
3478 [Token.PROPERTY_NAME, name],
3479 [Token.PROPERTY_VALUE, descriptor.defaultValue]
3484 function _widthFilter(validator) {
3485 return function (value) {
3486 return value[1] != 'inherit' &&
3487 (validator.isWidth(value[1]) || validator.isUnit(value[1]) && !validator.isDynamicUnit(value[1])) &&
3488 !validator.isStyleKeyword(value[1]) &&
3489 !validator.isColorFunction(value[1]);
3493 function animation(property, compactable, validator) {
3494 var duration = _wrapDefault(property.name + '-duration', property, compactable);
3495 var timing = _wrapDefault(property.name + '-timing-function', property, compactable);
3496 var delay = _wrapDefault(property.name + '-delay', property, compactable);
3497 var iteration = _wrapDefault(property.name + '-iteration-count', property, compactable);
3498 var direction = _wrapDefault(property.name + '-direction', property, compactable);
3499 var fill = _wrapDefault(property.name + '-fill-mode', property, compactable);
3500 var play = _wrapDefault(property.name + '-play-state', property, compactable);
3501 var name = _wrapDefault(property.name + '-name', property, compactable);
3502 var components = [duration, timing, delay, iteration, direction, fill, play, name];
3503 var values = property.value;
3505 var durationSet = false;
3506 var timingSet = false;
3507 var delaySet = false;
3508 var iterationSet = false;
3509 var directionSet = false;
3510 var fillSet = false;
3511 var playSet = false;
3512 var nameSet = false;
3516 if (property.value.length == 1 && property.value[0][1] == 'inherit') {
3517 duration.value = timing.value = delay.value = iteration.value = direction.value = fill.value = play.value = name.value = property.value;
3521 if (values.length > 1 && _anyIsInherit(values)) {
3522 throw new InvalidPropertyError('Invalid animation values at ' + formatPosition(values[0][2][0]) + '. Ignoring.');
3525 for (i = 0, l = values.length; i < l; i++) {
3528 if (validator.isTime(value[1]) && !durationSet) {
3529 duration.value = [value];
3531 } else if (validator.isTime(value[1]) && !delaySet) {
3532 delay.value = [value];
3534 } else if ((validator.isGlobal(value[1]) || validator.isTimingFunction(value[1])) && !timingSet) {
3535 timing.value = [value];
3537 } else if ((validator.isAnimationIterationCountKeyword(value[1]) || validator.isPositiveNumber(value[1])) && !iterationSet) {
3538 iteration.value = [value];
3539 iterationSet = true;
3540 } else if (validator.isAnimationDirectionKeyword(value[1]) && !directionSet) {
3541 direction.value = [value];
3542 directionSet = true;
3543 } else if (validator.isAnimationFillModeKeyword(value[1]) && !fillSet) {
3544 fill.value = [value];
3546 } else if (validator.isAnimationPlayStateKeyword(value[1]) && !playSet) {
3547 play.value = [value];
3549 } else if ((validator.isAnimationNameKeyword(value[1]) || validator.isIdentifier(value[1])) && !nameSet) {
3550 name.value = [value];
3553 throw new InvalidPropertyError('Invalid animation value at ' + formatPosition(value[2][0]) + '. Ignoring.');
3560 function background(property, compactable, validator) {
3561 var image = _wrapDefault('background-image', property, compactable);
3562 var position = _wrapDefault('background-position', property, compactable);
3563 var size = _wrapDefault('background-size', property, compactable);
3564 var repeat = _wrapDefault('background-repeat', property, compactable);
3565 var attachment = _wrapDefault('background-attachment', property, compactable);
3566 var origin = _wrapDefault('background-origin', property, compactable);
3567 var clip = _wrapDefault('background-clip', property, compactable);
3568 var color = _wrapDefault('background-color', property, compactable);
3569 var components = [image, position, size, repeat, attachment, origin, clip, color];
3570 var values = property.value;
3572 var positionSet = false;
3573 var clipSet = false;
3574 var originSet = false;
3575 var repeatSet = false;
3577 var anyValueSet = false;
3579 if (property.value.length == 1 && property.value[0][1] == 'inherit') {
3580 // NOTE: 'inherit' is not a valid value for background-attachment
3581 color.value = image.value = repeat.value = position.value = size.value = origin.value = clip.value = property.value;
3585 if (property.value.length == 1 && property.value[0][1] == '0 0') {
3589 for (var i = values.length - 1; i >= 0; i--) {
3590 var value = values[i];
3592 if (validator.isBackgroundAttachmentKeyword(value[1])) {
3593 attachment.value = [value];
3595 } else if (validator.isBackgroundClipKeyword(value[1]) || validator.isBackgroundOriginKeyword(value[1])) {
3597 origin.value = [value];
3600 clip.value = [value];
3604 } else if (validator.isBackgroundRepeatKeyword(value[1])) {
3606 repeat.value.unshift(value);
3608 repeat.value = [value];
3612 } else if (validator.isBackgroundPositionKeyword(value[1]) || validator.isBackgroundSizeKeyword(value[1]) || validator.isUnit(value[1]) || validator.isDynamicUnit(value[1])) {
3614 var previousValue = values[i - 1];
3616 if (previousValue[1] == Marker.FORWARD_SLASH) {
3617 size.value = [value];
3618 } else if (i > 1 && values[i - 2][1] == Marker.FORWARD_SLASH) {
3619 size.value = [previousValue, value];
3623 position.value = [];
3625 position.value.unshift(value);
3630 position.value = [];
3632 position.value.unshift(value);
3636 } else if ((color.value[0][1] == compactable[color.name].defaultValue || color.value[0][1] == 'none') && (validator.isColor(value[1]) || validator.isPrefixed(value[1]))) {
3637 color.value = [value];
3639 } else if (validator.isUrl(value[1]) || validator.isFunction(value[1])) {
3640 image.value = [value];
3645 if (clipSet && !originSet)
3646 origin.value = clip.value.slice(0);
3649 throw new InvalidPropertyError('Invalid background value at ' + formatPosition(values[0][2][0]) + '. Ignoring.');
3655 function borderRadius(property, compactable) {
3656 var values = property.value;
3659 for (var i = 0, l = values.length; i < l; i++) {
3660 if (values[i][1] == Marker.FORWARD_SLASH) {
3666 if (splitAt === 0 || splitAt === values.length - 1) {
3667 throw new InvalidPropertyError('Invalid border-radius value at ' + formatPosition(values[0][2][0]) + '. Ignoring.');
3670 var target = _wrapDefault(property.name, property, compactable);
3671 target.value = splitAt > -1 ?
3672 values.slice(0, splitAt) :
3674 target.components = fourValues(target, compactable);
3676 var remainder = _wrapDefault(property.name, property, compactable);
3677 remainder.value = splitAt > -1 ?
3678 values.slice(splitAt + 1) :
3680 remainder.components = fourValues(remainder, compactable);
3682 for (var j = 0; j < 4; j++) {
3683 target.components[j].multiplex = true;
3684 target.components[j].value = target.components[j].value.concat(remainder.components[j].value);
3687 return target.components;
3690 function font(property, compactable, validator) {
3691 var style = _wrapDefault('font-style', property, compactable);
3692 var variant = _wrapDefault('font-variant', property, compactable);
3693 var weight = _wrapDefault('font-weight', property, compactable);
3694 var stretch = _wrapDefault('font-stretch', property, compactable);
3695 var size = _wrapDefault('font-size', property, compactable);
3696 var height = _wrapDefault('line-height', property, compactable);
3697 var family = _wrapDefault('font-family', property, compactable);
3698 var components = [style, variant, weight, stretch, size, height, family];
3699 var values = property.value;
3700 var fuzzyMatched = 4; // style, variant, weight, and stretch
3702 var isStretchSet = false;
3704 var isStyleSet = false;
3706 var isVariantSet = false;
3708 var isWeightSet = false;
3710 var isSizeSet = false;
3711 var appendableFamilyName = false;
3713 if (!values[index]) {
3714 throw new InvalidPropertyError('Missing font values at ' + formatPosition(property.all[property.position][1][2][0]) + '. Ignoring.');
3717 if (values.length == 1 && values[0][1] == 'inherit') {
3718 style.value = variant.value = weight.value = stretch.value = size.value = height.value = family.value = values;
3722 if (values.length == 1 && (validator.isFontKeyword(values[0][1]) || validator.isGlobal(values[0][1]) || validator.isPrefixed(values[0][1]))) {
3723 values[0][1] = Marker.INTERNAL + values[0][1];
3724 style.value = variant.value = weight.value = stretch.value = size.value = height.value = family.value = values;
3728 if (values.length < 2 || !_anyIsFontSize(values, validator) || !_anyIsFontFamily(values, validator)) {
3729 throw new InvalidPropertyError('Invalid font values at ' + formatPosition(property.all[property.position][1][2][0]) + '. Ignoring.');
3732 if (values.length > 1 && _anyIsInherit(values)) {
3733 throw new InvalidPropertyError('Invalid font values at ' + formatPosition(values[0][2][0]) + '. Ignoring.');
3736 // fuzzy match style, variant, weight, and stretch on first elements
3737 while (index < fuzzyMatched) {
3738 isStretchValid = validator.isFontStretchKeyword(values[index][1]) || validator.isGlobal(values[index][1]);
3739 isStyleValid = validator.isFontStyleKeyword(values[index][1]) || validator.isGlobal(values[index][1]);
3740 isVariantValid = validator.isFontVariantKeyword(values[index][1]) || validator.isGlobal(values[index][1]);
3741 isWeightValid = validator.isFontWeightKeyword(values[index][1]) || validator.isGlobal(values[index][1]);
3743 if (isStyleValid && !isStyleSet) {
3744 style.value = [values[index]];
3746 } else if (isVariantValid && !isVariantSet) {
3747 variant.value = [values[index]];
3748 isVariantSet = true;
3749 } else if (isWeightValid && !isWeightSet) {
3750 weight.value = [values[index]];
3752 } else if (isStretchValid && !isStretchSet) {
3753 stretch.value = [values[index]];
3754 isStretchSet = true;
3755 } else if (isStyleValid && isStyleSet || isVariantValid && isVariantSet || isWeightValid && isWeightSet || isStretchValid && isStretchSet) {
3756 throw new InvalidPropertyError('Invalid font style / variant / weight / stretch value at ' + formatPosition(values[0][2][0]) + '. Ignoring.');
3764 // now comes font-size ...
3765 if (validator.isFontSizeKeyword(values[index][1]) || validator.isUnit(values[index][1]) && !validator.isDynamicUnit(values[index][1])) {
3766 size.value = [values[index]];
3770 throw new InvalidPropertyError('Missing font size at ' + formatPosition(values[0][2][0]) + '. Ignoring.');
3773 if (!values[index]) {
3774 throw new InvalidPropertyError('Missing font family at ' + formatPosition(values[0][2][0]) + '. Ignoring.');
3777 // ... and perhaps line-height
3778 if (isSizeSet && values[index] && values[index][1] == Marker.FORWARD_SLASH && values[index + 1] && (validator.isLineHeightKeyword(values[index + 1][1]) || validator.isUnit(values[index + 1][1]) || validator.isNumber(values[index + 1][1]))) {
3779 height.value = [values[index + 1]];
3784 // ... and whatever comes next is font-family
3787 while (values[index]) {
3788 if (values[index][1] == Marker.COMMA) {
3789 appendableFamilyName = false;
3791 if (appendableFamilyName) {
3792 family.value[family.value.length - 1][1] += Marker.SPACE + values[index][1];
3794 family.value.push(values[index]);
3797 appendableFamilyName = true;
3803 if (family.value.length === 0) {
3804 throw new InvalidPropertyError('Missing font family at ' + formatPosition(values[0][2][0]) + '. Ignoring.');
3810 function _anyIsFontSize(values, validator) {
3814 for (i = 0, l = values.length; i < l; i++) {
3817 if (validator.isFontSizeKeyword(value[1]) || validator.isUnit(value[1]) && !validator.isDynamicUnit(value[1]) || validator.isFunction(value[1])) {
3825 function _anyIsFontFamily(values, validator) {
3829 for (i = 0, l = values.length; i < l; i++) {
3832 if (validator.isIdentifier(value[1])) {
3840 function fourValues(property, compactable) {
3841 var componentNames = compactable[property.name].components;
3842 var components = [];
3843 var value = property.value;
3845 if (value.length < 1)
3848 if (value.length < 2)
3849 value[1] = value[0].slice(0);
3850 if (value.length < 3)
3851 value[2] = value[0].slice(0);
3852 if (value.length < 4)
3853 value[3] = value[1].slice(0);
3855 for (var i = componentNames.length - 1; i >= 0; i--) {
3856 var component = wrapSingle([
3858 [Token.PROPERTY_NAME, componentNames[i]]
3860 component.value = [value[i]];
3861 components.unshift(component);
3867 function multiplex(splitWith) {
3868 return function (property, compactable, validator) {
3870 var values = property.value;
3873 // find split commas
3874 for (i = 0, l = values.length; i < l; i++) {
3875 if (values[i][1] == ',')
3879 if (splitsAt.length === 0)
3880 return splitWith(property, compactable, validator);
3882 var splitComponents = [];
3884 // split over commas, and into components
3885 for (i = 0, l = splitsAt.length; i <= l; i++) {
3886 var from = i === 0 ? 0 : splitsAt[i - 1] + 1;
3887 var to = i < l ? splitsAt[i] : values.length;
3889 var _property = _wrapDefault(property.name, property, compactable);
3890 _property.value = values.slice(from, to);
3892 splitComponents.push(splitWith(_property, compactable, validator));
3895 var components = splitComponents[0];
3897 // group component values from each split
3898 for (i = 0, l = components.length; i < l; i++) {
3899 components[i].multiplex = true;
3901 for (j = 1, m = splitComponents.length; j < m; j++) {
3902 components[i].value.push([Token.PROPERTY_VALUE, Marker.COMMA]);
3903 Array.prototype.push.apply(components[i].value, splitComponents[j][i].value);
3911 function listStyle(property, compactable, validator) {
3912 var type = _wrapDefault('list-style-type', property, compactable);
3913 var position = _wrapDefault('list-style-position', property, compactable);
3914 var image = _wrapDefault('list-style-image', property, compactable);
3915 var components = [type, position, image];
3917 if (property.value.length == 1 && property.value[0][1] == 'inherit') {
3918 type.value = position.value = image.value = [property.value[0]];
3922 var values = property.value.slice(0);
3923 var total = values.length;
3927 for (index = 0, total = values.length; index < total; index++) {
3928 if (validator.isUrl(values[index][1]) || values[index][1] == '0') {
3929 image.value = [values[index]];
3930 values.splice(index, 1);
3935 // ... then `position`
3936 for (index = 0, total = values.length; index < total; index++) {
3937 if (validator.isListStylePositionKeyword(values[index][1])) {
3938 position.value = [values[index]];
3939 values.splice(index, 1);
3944 // ... and what's left is a `type`
3945 if (values.length > 0 && (validator.isListStyleTypeKeyword(values[0][1]) || validator.isIdentifier(values[0][1]))) {
3946 type.value = [values[0]];
3952 function transition(property, compactable, validator) {
3953 var prop = _wrapDefault(property.name + '-property', property, compactable);
3954 var duration = _wrapDefault(property.name + '-duration', property, compactable);
3955 var timing = _wrapDefault(property.name + '-timing-function', property, compactable);
3956 var delay = _wrapDefault(property.name + '-delay', property, compactable);
3957 var components = [prop, duration, timing, delay];
3958 var values = property.value;
3960 var durationSet = false;
3961 var delaySet = false;
3962 var propSet = false;
3963 var timingSet = false;
3967 if (property.value.length == 1 && property.value[0][1] == 'inherit') {
3968 prop.value = duration.value = timing.value = delay.value = property.value;
3972 if (values.length > 1 && _anyIsInherit(values)) {
3973 throw new InvalidPropertyError('Invalid animation values at ' + formatPosition(values[0][2][0]) + '. Ignoring.');
3976 for (i = 0, l = values.length; i < l; i++) {
3979 if (validator.isTime(value[1]) && !durationSet) {
3980 duration.value = [value];
3982 } else if (validator.isTime(value[1]) && !delaySet) {
3983 delay.value = [value];
3985 } else if ((validator.isGlobal(value[1]) || validator.isTimingFunction(value[1])) && !timingSet) {
3986 timing.value = [value];
3988 } else if (validator.isIdentifier(value[1]) && !propSet) {
3989 prop.value = [value];
3992 throw new InvalidPropertyError('Invalid animation value at ' + formatPosition(value[2][0]) + '. Ignoring.');
3999 function widthStyleColor(property, compactable, validator) {
4000 var descriptor = compactable[property.name];
4002 _wrapDefault(descriptor.components[0], property, compactable),
4003 _wrapDefault(descriptor.components[1], property, compactable),
4004 _wrapDefault(descriptor.components[2], property, compactable)
4006 var color, style, width;
4008 for (var i = 0; i < 3; i++) {
4009 var component = components[i];
4011 if (component.name.indexOf('color') > 0)
4013 else if (component.name.indexOf('style') > 0)
4019 if ((property.value.length == 1 && property.value[0][1] == 'inherit') ||
4020 (property.value.length == 3 && property.value[0][1] == 'inherit' && property.value[1][1] == 'inherit' && property.value[2][1] == 'inherit')) {
4021 color.value = style.value = width.value = [property.value[0]];
4025 var values = property.value.slice(0);
4028 // NOTE: usually users don't follow the required order of parts in this shorthand,
4029 // so we'll try to parse it caring as little about order as possible
4031 if (values.length > 0) {
4032 matches = values.filter(_widthFilter(validator));
4033 match = matches.length > 1 && (matches[0][1] == 'none' || matches[0][1] == 'auto') ? matches[1] : matches[0];
4035 width.value = [match];
4036 values.splice(values.indexOf(match), 1);
4040 if (values.length > 0) {
4041 match = values.filter(_styleFilter(validator))[0];
4043 style.value = [match];
4044 values.splice(values.indexOf(match), 1);
4048 if (values.length > 0) {
4049 match = values.filter(_colorFilter(validator))[0];
4051 color.value = [match];
4052 values.splice(values.indexOf(match), 1);
4060 animation: animation,
4061 background: background,
4062 border: widthStyleColor,
4063 borderRadius: borderRadius,
4065 fourValues: fourValues,
4066 listStyle: listStyle,
4067 multiplex: multiplex,
4068 outline: widthStyleColor,
4069 transition: transition
4072 },{"../../tokenizer/marker":83,"../../tokenizer/token":84,"../../utils/format-position":87,"../wrap-for-optimizing":58,"./invalid-property-error":23}],19:[function(require,module,exports){
4073 var understandable = require('./properties/understandable');
4075 function animationIterationCount(validator, value1, value2) {
4076 if (!understandable(validator, value1, value2, 0, true) && !(validator.isAnimationIterationCountKeyword(value2) || validator.isPositiveNumber(value2))) {
4078 } else if (validator.isVariable(value1) && validator.isVariable(value2)) {
4082 return validator.isAnimationIterationCountKeyword(value2) || validator.isPositiveNumber(value2);
4085 function animationName(validator, value1, value2) {
4086 if (!understandable(validator, value1, value2, 0, true) && !(validator.isAnimationNameKeyword(value2) || validator.isIdentifier(value2))) {
4088 } else if (validator.isVariable(value1) && validator.isVariable(value2)) {
4092 return validator.isAnimationNameKeyword(value2) || validator.isIdentifier(value2);
4095 function areSameFunction(validator, value1, value2) {
4096 if (!validator.isFunction(value1) || !validator.isFunction(value2)) {
4100 var function1Name = value1.substring(0, value1.indexOf('('));
4101 var function2Name = value2.substring(0, value2.indexOf('('));
4103 return function1Name === function2Name;
4106 function backgroundPosition(validator, value1, value2) {
4107 if (!understandable(validator, value1, value2, 0, true) && !(validator.isBackgroundPositionKeyword(value2) || validator.isGlobal(value2))) {
4109 } else if (validator.isVariable(value1) && validator.isVariable(value2)) {
4111 } else if (validator.isBackgroundPositionKeyword(value2) || validator.isGlobal(value2)) {
4115 return unit(validator, value1, value2);
4118 function backgroundSize(validator, value1, value2) {
4119 if (!understandable(validator, value1, value2, 0, true) && !(validator.isBackgroundSizeKeyword(value2) || validator.isGlobal(value2))) {
4121 } else if (validator.isVariable(value1) && validator.isVariable(value2)) {
4123 } else if (validator.isBackgroundSizeKeyword(value2) || validator.isGlobal(value2)) {
4127 return unit(validator, value1, value2);
4130 function color(validator, value1, value2) {
4131 if (!understandable(validator, value1, value2, 0, true) && !validator.isColor(value2)) {
4133 } else if (validator.isVariable(value1) && validator.isVariable(value2)) {
4135 } else if (!validator.colorOpacity && (validator.isRgbColor(value1) || validator.isHslColor(value1))) {
4137 } else if (!validator.colorOpacity && (validator.isRgbColor(value2) || validator.isHslColor(value2))) {
4139 } else if (validator.isColor(value1) && validator.isColor(value2)) {
4143 return sameFunctionOrValue(validator, value1, value2);
4146 function components(overrideCheckers) {
4147 return function (validator, value1, value2, position) {
4148 return overrideCheckers[position](validator, value1, value2);
4152 function fontFamily(validator, value1, value2) {
4153 return understandable(validator, value1, value2, 0, true);
4156 function image(validator, value1, value2) {
4157 if (!understandable(validator, value1, value2, 0, true) && !validator.isImage(value2)) {
4159 } else if (validator.isVariable(value1) && validator.isVariable(value2)) {
4161 } else if (validator.isImage(value2)) {
4163 } else if (validator.isImage(value1)) {
4167 return sameFunctionOrValue(validator, value1, value2);
4170 function keyword(propertyName) {
4171 return function(validator, value1, value2) {
4172 if (!understandable(validator, value1, value2, 0, true) && !validator.isKeyword(propertyName)(value2)) {
4174 } else if (validator.isVariable(value1) && validator.isVariable(value2)) {
4178 return validator.isKeyword(propertyName)(value2);
4182 function keywordWithGlobal(propertyName) {
4183 return function(validator, value1, value2) {
4184 if (!understandable(validator, value1, value2, 0, true) && !(validator.isKeyword(propertyName)(value2) || validator.isGlobal(value2))) {
4186 } else if (validator.isVariable(value1) && validator.isVariable(value2)) {
4190 return validator.isKeyword(propertyName)(value2) || validator.isGlobal(value2);
4194 function propertyName(validator, value1, value2) {
4195 if (!understandable(validator, value1, value2, 0, true) && !validator.isIdentifier(value2)) {
4197 } else if (validator.isVariable(value1) && validator.isVariable(value2)) {
4201 return validator.isIdentifier(value2);
4204 function sameFunctionOrValue(validator, value1, value2) {
4205 return areSameFunction(validator, value1, value2) ?
4210 function textShadow(validator, value1, value2) {
4211 if (!understandable(validator, value1, value2, 0, true) && !(validator.isUnit(value2) || validator.isColor(value2) || validator.isGlobal(value2))) {
4213 } else if (validator.isVariable(value1) && validator.isVariable(value2)) {
4217 return validator.isUnit(value2) || validator.isColor(value2) || validator.isGlobal(value2);
4220 function time(validator, value1, value2) {
4221 if (!understandable(validator, value1, value2, 0, true) && !validator.isTime(value2)) {
4223 } else if (validator.isVariable(value1) && validator.isVariable(value2)) {
4225 } else if (validator.isTime(value1) && !validator.isTime(value2)) {
4227 } else if (validator.isTime(value2)) {
4229 } else if (validator.isTime(value1)) {
4231 } else if (validator.isFunction(value1) && !validator.isPrefixed(value1) && validator.isFunction(value2) && !validator.isPrefixed(value2)) {
4235 return sameFunctionOrValue(validator, value1, value2);
4238 function timingFunction(validator, value1, value2) {
4239 if (!understandable(validator, value1, value2, 0, true) && !(validator.isTimingFunction(value2) || validator.isGlobal(value2))) {
4241 } else if (validator.isVariable(value1) && validator.isVariable(value2)) {
4245 return validator.isTimingFunction(value2) || validator.isGlobal(value2);
4248 function unit(validator, value1, value2) {
4249 if (!understandable(validator, value1, value2, 0, true) && !validator.isUnit(value2)) {
4251 } else if (validator.isVariable(value1) && validator.isVariable(value2)) {
4253 } else if (validator.isUnit(value1) && !validator.isUnit(value2)) {
4255 } else if (validator.isUnit(value2)) {
4257 } else if (validator.isUnit(value1)) {
4259 } else if (validator.isFunction(value1) && !validator.isPrefixed(value1) && validator.isFunction(value2) && !validator.isPrefixed(value2)) {
4263 return sameFunctionOrValue(validator, value1, value2);
4266 function unitOrKeywordWithGlobal(propertyName) {
4267 var byKeyword = keywordWithGlobal(propertyName);
4269 return function(validator, value1, value2) {
4270 return unit(validator, value1, value2) || byKeyword(validator, value1, value2);
4274 function unitOrNumber(validator, value1, value2) {
4275 if (!understandable(validator, value1, value2, 0, true) && !(validator.isUnit(value2) || validator.isNumber(value2))) {
4277 } else if (validator.isVariable(value1) && validator.isVariable(value2)) {
4279 } else if ((validator.isUnit(value1) || validator.isNumber(value1)) && !(validator.isUnit(value2) || validator.isNumber(value2))) {
4281 } else if (validator.isUnit(value2) || validator.isNumber(value2)) {
4283 } else if (validator.isUnit(value1) || validator.isNumber(value1)) {
4285 } else if (validator.isFunction(value1) && !validator.isPrefixed(value1) && validator.isFunction(value2) && !validator.isPrefixed(value2)) {
4289 return sameFunctionOrValue(validator, value1, value2);
4292 function zIndex(validator, value1, value2) {
4293 if (!understandable(validator, value1, value2, 0, true) && !validator.isZIndex(value2)) {
4295 } else if (validator.isVariable(value1) && validator.isVariable(value2)) {
4299 return validator.isZIndex(value2);
4305 components: components,
4307 propertyName: propertyName,
4309 timingFunction: timingFunction,
4311 unitOrNumber: unitOrNumber
4314 animationDirection: keywordWithGlobal('animation-direction'),
4315 animationFillMode: keyword('animation-fill-mode'),
4316 animationIterationCount: animationIterationCount,
4317 animationName: animationName,
4318 animationPlayState: keywordWithGlobal('animation-play-state'),
4319 backgroundAttachment: keyword('background-attachment'),
4320 backgroundClip: keywordWithGlobal('background-clip'),
4321 backgroundOrigin: keyword('background-origin'),
4322 backgroundPosition: backgroundPosition,
4323 backgroundRepeat: keyword('background-repeat'),
4324 backgroundSize: backgroundSize,
4325 bottom: unitOrKeywordWithGlobal('bottom'),
4326 borderCollapse: keyword('border-collapse'),
4327 borderStyle: keywordWithGlobal('*-style'),
4328 clear: keywordWithGlobal('clear'),
4329 cursor: keywordWithGlobal('cursor'),
4330 display: keywordWithGlobal('display'),
4331 float: keywordWithGlobal('float'),
4332 left: unitOrKeywordWithGlobal('left'),
4333 fontFamily: fontFamily,
4334 fontStretch: keywordWithGlobal('font-stretch'),
4335 fontStyle: keywordWithGlobal('font-style'),
4336 fontVariant: keywordWithGlobal('font-variant'),
4337 fontWeight: keywordWithGlobal('font-weight'),
4338 listStyleType: keywordWithGlobal('list-style-type'),
4339 listStylePosition: keywordWithGlobal('list-style-position'),
4340 outlineStyle: keywordWithGlobal('*-style'),
4341 overflow: keywordWithGlobal('overflow'),
4342 position: keywordWithGlobal('position'),
4343 right: unitOrKeywordWithGlobal('right'),
4344 textAlign: keywordWithGlobal('text-align'),
4345 textDecoration: keywordWithGlobal('text-decoration'),
4346 textOverflow: keywordWithGlobal('text-overflow'),
4347 textShadow: textShadow,
4348 top: unitOrKeywordWithGlobal('top'),
4349 transform: sameFunctionOrValue,
4350 verticalAlign: unitOrKeywordWithGlobal('vertical-align'),
4351 visibility: keywordWithGlobal('visibility'),
4352 whiteSpace: keywordWithGlobal('white-space'),
4357 },{"./properties/understandable":40}],20:[function(require,module,exports){
4358 var wrapSingle = require('../wrap-for-optimizing').single;
4360 var Token = require('../../tokenizer/token');
4362 function deep(property) {
4363 var cloned = shallow(property);
4364 for (var i = property.components.length - 1; i >= 0; i--) {
4365 var component = shallow(property.components[i]);
4366 component.value = property.components[i].value.slice(0);
4367 cloned.components.unshift(component);
4370 cloned.dirty = true;
4371 cloned.value = property.value.slice(0);
4376 function shallow(property) {
4377 var cloned = wrapSingle([
4379 [Token.PROPERTY_NAME, property.name]
4381 cloned.important = property.important;
4382 cloned.hack = property.hack;
4383 cloned.unused = false;
4392 },{"../../tokenizer/token":84,"../wrap-for-optimizing":58}],21:[function(require,module,exports){
4393 // Contains the interpretation of CSS properties, as used by the property optimizer
4395 var breakUp = require('./break-up');
4396 var canOverride = require('./can-override');
4397 var restore = require('./restore');
4399 var override = require('../../utils/override');
4401 // Properties to process
4402 // Extend this object in order to add support for more properties in the optimizer.
4404 // Each key in this object represents a CSS property and should be an object.
4405 // Such an object contains properties that describe how the represented CSS property should be handled.
4406 // Possible options:
4408 // * components: array (Only specify for shorthand properties.)
4409 // Contains the names of the granular properties this shorthand compacts.
4411 // * canOverride: function
4412 // Returns whether two tokens of this property can be merged with each other.
4413 // This property has no meaning for shorthands.
4415 // * defaultValue: string
4416 // Specifies the default value of the property according to the CSS standard.
4417 // For shorthand, this is used when every component is set to its default value, therefore it should be the shortest possible default value of all the components.
4419 // * shortestValue: string
4420 // Specifies the shortest possible value the property can possibly have.
4421 // (Falls back to defaultValue if unspecified.)
4423 // * breakUp: function (Only specify for shorthand properties.)
4424 // Breaks the shorthand up to its components.
4426 // * restore: function (Only specify for shorthand properties.)
4427 // Puts the shorthand together from its components.
4431 canOverride: canOverride.generic.components([
4432 canOverride.generic.time,
4433 canOverride.generic.timingFunction,
4434 canOverride.generic.time,
4435 canOverride.property.animationIterationCount,
4436 canOverride.property.animationDirection,
4437 canOverride.property.animationFillMode,
4438 canOverride.property.animationPlayState,
4439 canOverride.property.animationName
4442 'animation-duration',
4443 'animation-timing-function',
4445 'animation-iteration-count',
4446 'animation-direction',
4447 'animation-fill-mode',
4448 'animation-play-state',
4451 breakUp: breakUp.multiplex(breakUp.animation),
4452 defaultValue: 'none',
4453 restore: restore.multiplex(restore.withoutDefaults),
4461 'animation-delay': {
4462 canOverride: canOverride.generic.time,
4467 intoMultiplexMode: 'real',
4474 'animation-direction': {
4475 canOverride: canOverride.property.animationDirection,
4479 defaultValue: 'normal',
4480 intoMultiplexMode: 'real',
4487 'animation-duration': {
4488 canOverride: canOverride.generic.time,
4493 intoMultiplexMode: 'real',
4494 keepUnlessDefault: 'animation-delay',
4501 'animation-fill-mode': {
4502 canOverride: canOverride.property.animationFillMode,
4506 defaultValue: 'none',
4507 intoMultiplexMode: 'real',
4514 'animation-iteration-count': {
4515 canOverride: canOverride.property.animationIterationCount,
4520 intoMultiplexMode: 'real',
4528 canOverride: canOverride.property.animationName,
4532 defaultValue: 'none',
4533 intoMultiplexMode: 'real',
4540 'animation-play-state': {
4541 canOverride: canOverride.property.animationPlayState,
4545 defaultValue: 'running',
4546 intoMultiplexMode: 'real',
4553 'animation-timing-function': {
4554 canOverride: canOverride.generic.timingFunction,
4558 defaultValue: 'ease',
4559 intoMultiplexMode: 'real',
4567 canOverride: canOverride.generic.components([
4568 canOverride.generic.image,
4569 canOverride.property.backgroundPosition,
4570 canOverride.property.backgroundSize,
4571 canOverride.property.backgroundRepeat,
4572 canOverride.property.backgroundAttachment,
4573 canOverride.property.backgroundOrigin,
4574 canOverride.property.backgroundClip,
4575 canOverride.generic.color
4579 'background-position',
4581 'background-repeat',
4582 'background-attachment',
4583 'background-origin',
4587 breakUp: breakUp.multiplex(breakUp.background),
4588 defaultValue: '0 0',
4589 restore: restore.multiplex(restore.background),
4593 'background-attachment': {
4594 canOverride: canOverride.property.backgroundAttachment,
4598 defaultValue: 'scroll',
4599 intoMultiplexMode: 'real'
4601 'background-clip': {
4602 canOverride: canOverride.property.backgroundClip,
4606 defaultValue: 'border-box',
4607 intoMultiplexMode: 'real',
4608 shortestValue: 'border-box'
4610 'background-color': {
4611 canOverride: canOverride.generic.color,
4615 defaultValue: 'transparent',
4616 intoMultiplexMode: 'real', // otherwise real color will turn into default since color appears in last multiplex only
4617 multiplexLastOnly: true,
4618 nonMergeableValue: 'none',
4619 shortestValue: 'red'
4621 'background-image': {
4622 canOverride: canOverride.generic.image,
4626 defaultValue: 'none',
4627 intoMultiplexMode: 'default'
4629 'background-origin': {
4630 canOverride: canOverride.property.backgroundOrigin,
4634 defaultValue: 'padding-box',
4635 intoMultiplexMode: 'real',
4636 shortestValue: 'border-box'
4638 'background-position': {
4639 canOverride: canOverride.property.backgroundPosition,
4643 defaultValue: ['0', '0'],
4645 intoMultiplexMode: 'real',
4648 'background-repeat': {
4649 canOverride: canOverride.property.backgroundRepeat,
4653 defaultValue: ['repeat'],
4655 intoMultiplexMode: 'real'
4657 'background-size': {
4658 canOverride: canOverride.property.backgroundSize,
4662 defaultValue: ['auto'],
4664 intoMultiplexMode: 'real',
4665 shortestValue: '0 0'
4668 canOverride: canOverride.property.bottom,
4669 defaultValue: 'auto'
4672 breakUp: breakUp.border,
4673 canOverride: canOverride.generic.components([
4674 canOverride.generic.unit,
4675 canOverride.property.borderStyle,
4676 canOverride.generic.color
4683 defaultValue: 'none',
4684 overridesShorthands: [
4690 restore: restore.withoutDefaults,
4692 shorthandComponents: true
4695 breakUp: breakUp.border,
4696 canOverride: canOverride.generic.components([
4697 canOverride.generic.unit,
4698 canOverride.property.borderStyle,
4699 canOverride.generic.color
4702 'border-bottom-width',
4703 'border-bottom-style',
4704 'border-bottom-color'
4706 defaultValue: 'none',
4707 restore: restore.withoutDefaults,
4710 'border-bottom-color': {
4711 canOverride: canOverride.generic.color,
4716 defaultValue: 'none'
4718 'border-bottom-left-radius': {
4719 canOverride: canOverride.generic.unit,
4729 'border-bottom-right-radius': {
4730 canOverride: canOverride.generic.unit,
4740 'border-bottom-style': {
4741 canOverride: canOverride.property.borderStyle,
4746 defaultValue: 'none'
4748 'border-bottom-width': {
4749 canOverride: canOverride.generic.unit,
4754 defaultValue: 'medium',
4755 oppositeTo: 'border-top-width',
4758 'border-collapse': {
4759 canOverride: canOverride.property.borderCollapse,
4760 defaultValue: 'separate'
4763 breakUp: breakUp.fourValues,
4764 canOverride: canOverride.generic.components([
4765 canOverride.generic.color,
4766 canOverride.generic.color,
4767 canOverride.generic.color,
4768 canOverride.generic.color
4775 'border-right-color',
4776 'border-bottom-color',
4779 defaultValue: 'none',
4780 restore: restore.fourValues,
4781 shortestValue: 'red',
4785 breakUp: breakUp.border,
4786 canOverride: canOverride.generic.components([
4787 canOverride.generic.unit,
4788 canOverride.property.borderStyle,
4789 canOverride.generic.color
4792 'border-left-width',
4793 'border-left-style',
4796 defaultValue: 'none',
4797 restore: restore.withoutDefaults,
4800 'border-left-color': {
4801 canOverride: canOverride.generic.color,
4806 defaultValue: 'none'
4808 'border-left-style': {
4809 canOverride: canOverride.property.borderStyle,
4814 defaultValue: 'none'
4816 'border-left-width': {
4817 canOverride: canOverride.generic.unit,
4822 defaultValue: 'medium',
4823 oppositeTo: 'border-right-width',
4827 breakUp: breakUp.borderRadius,
4828 canOverride: canOverride.generic.components([
4829 canOverride.generic.unit,
4830 canOverride.generic.unit,
4831 canOverride.generic.unit,
4832 canOverride.generic.unit
4835 'border-top-left-radius',
4836 'border-top-right-radius',
4837 'border-bottom-right-radius',
4838 'border-bottom-left-radius'
4841 restore: restore.borderRadius,
4849 breakUp: breakUp.border,
4850 canOverride: canOverride.generic.components([
4851 canOverride.generic.unit,
4852 canOverride.property.borderStyle,
4853 canOverride.generic.color
4856 'border-right-width',
4857 'border-right-style',
4858 'border-right-color'
4860 defaultValue: 'none',
4861 restore: restore.withoutDefaults,
4864 'border-right-color': {
4865 canOverride: canOverride.generic.color,
4870 defaultValue: 'none'
4872 'border-right-style': {
4873 canOverride: canOverride.property.borderStyle,
4878 defaultValue: 'none'
4880 'border-right-width': {
4881 canOverride: canOverride.generic.unit,
4886 defaultValue: 'medium',
4887 oppositeTo: 'border-left-width',
4891 breakUp: breakUp.fourValues,
4892 canOverride: canOverride.generic.components([
4893 canOverride.property.borderStyle,
4894 canOverride.property.borderStyle,
4895 canOverride.property.borderStyle,
4896 canOverride.property.borderStyle
4903 'border-right-style',
4904 'border-bottom-style',
4907 defaultValue: 'none',
4908 restore: restore.fourValues,
4912 breakUp: breakUp.border,
4913 canOverride: canOverride.generic.components([
4914 canOverride.generic.unit,
4915 canOverride.property.borderStyle,
4916 canOverride.generic.color
4923 defaultValue: 'none',
4924 restore: restore.withoutDefaults,
4927 'border-top-color': {
4928 canOverride: canOverride.generic.color,
4933 defaultValue: 'none'
4935 'border-top-left-radius': {
4936 canOverride: canOverride.generic.unit,
4946 'border-top-right-radius': {
4947 canOverride: canOverride.generic.unit,
4957 'border-top-style': {
4958 canOverride: canOverride.property.borderStyle,
4963 defaultValue: 'none'
4965 'border-top-width': {
4966 canOverride: canOverride.generic.unit,
4971 defaultValue: 'medium',
4972 oppositeTo: 'border-bottom-width',
4976 breakUp: breakUp.fourValues,
4977 canOverride: canOverride.generic.components([
4978 canOverride.generic.unit,
4979 canOverride.generic.unit,
4980 canOverride.generic.unit,
4981 canOverride.generic.unit
4988 'border-right-width',
4989 'border-bottom-width',
4992 defaultValue: 'medium',
4993 restore: restore.fourValues,
4998 canOverride: canOverride.property.clear,
4999 defaultValue: 'none'
5002 canOverride: canOverride.generic.color,
5003 defaultValue: 'transparent',
5004 shortestValue: 'red'
5007 canOverride: canOverride.property.cursor,
5008 defaultValue: 'auto'
5011 canOverride: canOverride.property.display,
5014 canOverride: canOverride.property.float,
5015 defaultValue: 'none'
5018 breakUp: breakUp.font,
5019 canOverride: canOverride.generic.components([
5020 canOverride.property.fontStyle,
5021 canOverride.property.fontVariant,
5022 canOverride.property.fontWeight,
5023 canOverride.property.fontStretch,
5024 canOverride.generic.unit,
5025 canOverride.generic.unit,
5026 canOverride.property.fontFamily
5037 restore: restore.font,
5041 canOverride: canOverride.property.fontFamily,
5042 defaultValue: 'user|agent|specific'
5045 canOverride: canOverride.generic.unit,
5046 defaultValue: 'medium',
5050 canOverride: canOverride.property.fontStretch,
5051 defaultValue: 'normal'
5054 canOverride: canOverride.property.fontStyle,
5055 defaultValue: 'normal'
5058 canOverride: canOverride.property.fontVariant,
5059 defaultValue: 'normal'
5062 canOverride: canOverride.property.fontWeight,
5063 defaultValue: 'normal',
5064 shortestValue: '400'
5067 canOverride: canOverride.generic.unit,
5068 defaultValue: 'auto',
5072 canOverride: canOverride.property.left,
5073 defaultValue: 'auto'
5076 canOverride: canOverride.generic.unitOrNumber,
5077 defaultValue: 'normal',
5081 canOverride: canOverride.generic.components([
5082 canOverride.property.listStyleType,
5083 canOverride.property.listStylePosition,
5084 canOverride.property.listStyleImage
5088 'list-style-position',
5091 breakUp: breakUp.listStyle,
5092 restore: restore.withoutDefaults,
5093 defaultValue: 'outside', // can't use 'disc' because that'd override default 'decimal' for <ol>
5094 shortestValue: 'none',
5097 'list-style-image' : {
5098 canOverride: canOverride.generic.image,
5102 defaultValue: 'none'
5104 'list-style-position' : {
5105 canOverride: canOverride.property.listStylePosition,
5109 defaultValue: 'outside',
5110 shortestValue: 'inside'
5112 'list-style-type' : {
5113 canOverride: canOverride.property.listStyleType,
5117 // NOTE: we can't tell the real default value here, it's 'disc' for <ul> and 'decimal' for <ol>
5118 // this is a hack, but it doesn't matter because this value will be either overridden or
5119 // it will disappear at the final step anyway
5120 defaultValue: 'decimal|disc',
5121 shortestValue: 'none'
5124 breakUp: breakUp.fourValues,
5125 canOverride: canOverride.generic.components([
5126 canOverride.generic.unit,
5127 canOverride.generic.unit,
5128 canOverride.generic.unit,
5129 canOverride.generic.unit
5138 restore: restore.fourValues,
5142 canOverride: canOverride.generic.unit,
5147 oppositeTo: 'margin-top'
5150 canOverride: canOverride.generic.unit,
5155 oppositeTo: 'margin-right'
5158 canOverride: canOverride.generic.unit,
5163 oppositeTo: 'margin-left'
5166 canOverride: canOverride.generic.unit,
5171 oppositeTo: 'margin-bottom'
5174 canOverride: canOverride.generic.components([
5175 canOverride.generic.color,
5176 canOverride.property.outlineStyle,
5177 canOverride.generic.unit
5184 breakUp: breakUp.outline,
5185 restore: restore.withoutDefaults,
5190 canOverride: canOverride.generic.color,
5194 defaultValue: 'invert',
5195 shortestValue: 'red'
5198 canOverride: canOverride.property.outlineStyle,
5202 defaultValue: 'none'
5205 canOverride: canOverride.generic.unit,
5209 defaultValue: 'medium',
5213 canOverride: canOverride.property.overflow,
5214 defaultValue: 'visible'
5217 canOverride: canOverride.property.overflow,
5218 defaultValue: 'visible'
5221 canOverride: canOverride.property.overflow,
5222 defaultValue: 'visible'
5225 breakUp: breakUp.fourValues,
5226 canOverride: canOverride.generic.components([
5227 canOverride.generic.unit,
5228 canOverride.generic.unit,
5229 canOverride.generic.unit,
5230 canOverride.generic.unit
5239 restore: restore.fourValues,
5243 canOverride: canOverride.generic.unit,
5248 oppositeTo: 'padding-top'
5251 canOverride: canOverride.generic.unit,
5256 oppositeTo: 'padding-right'
5259 canOverride: canOverride.generic.unit,
5264 oppositeTo: 'padding-left'
5267 canOverride: canOverride.generic.unit,
5272 oppositeTo: 'padding-bottom'
5275 canOverride: canOverride.property.position,
5276 defaultValue: 'static'
5279 canOverride: canOverride.property.right,
5280 defaultValue: 'auto'
5283 canOverride: canOverride.property.textAlign,
5284 // NOTE: we can't tell the real default value here, as it depends on default text direction
5285 // this is a hack, but it doesn't matter because this value will be either overridden or
5286 // it will disappear anyway
5287 defaultValue: 'left|right'
5289 'text-decoration': {
5290 canOverride: canOverride.property.textDecoration,
5291 defaultValue: 'none'
5294 canOverride: canOverride.property.textOverflow,
5295 defaultValue: 'none'
5298 canOverride: canOverride.property.textShadow,
5299 defaultValue: 'none'
5302 canOverride: canOverride.property.top,
5303 defaultValue: 'auto'
5306 canOverride: canOverride.property.transform,
5314 breakUp: breakUp.multiplex(breakUp.transition),
5315 canOverride: canOverride.generic.components([
5316 canOverride.property.transitionProperty,
5317 canOverride.generic.time,
5318 canOverride.generic.timingFunction,
5319 canOverride.generic.time
5322 'transition-property',
5323 'transition-duration',
5324 'transition-timing-function',
5327 defaultValue: 'none',
5328 restore: restore.multiplex(restore.withoutDefaults),
5336 'transition-delay': {
5337 canOverride: canOverride.generic.time,
5342 intoMultiplexMode: 'real',
5349 'transition-duration': {
5350 canOverride: canOverride.generic.time,
5355 intoMultiplexMode: 'real',
5362 'transition-property': {
5363 canOverride: canOverride.generic.propertyName,
5367 defaultValue: 'all',
5368 intoMultiplexMode: 'placeholder',
5369 placeholderValue: '_', // it's a short value that won't match any property and still be a valid `transition-property`
5376 'transition-timing-function': {
5377 canOverride: canOverride.generic.timingFunction,
5381 defaultValue: 'ease',
5382 intoMultiplexMode: 'real',
5390 canOverride: canOverride.property.verticalAlign,
5391 defaultValue: 'baseline'
5394 canOverride: canOverride.property.visibility,
5395 defaultValue: 'visible'
5398 canOverride: canOverride.property.whiteSpace,
5399 defaultValue: 'normal'
5402 canOverride: canOverride.generic.unit,
5403 defaultValue: 'auto',
5407 canOverride: canOverride.property.zIndex,
5408 defaultValue: 'auto'
5412 function cloneDescriptor(propertyName, prefix) {
5413 var clonedDescriptor = override(compactable[propertyName], {});
5415 if ('componentOf' in clonedDescriptor) {
5416 clonedDescriptor.componentOf = clonedDescriptor.componentOf.map(function (shorthandName) {
5417 return prefix + shorthandName;
5421 if ('components' in clonedDescriptor) {
5422 clonedDescriptor.components = clonedDescriptor.components.map(function (longhandName) {
5423 return prefix + longhandName;
5427 if ('keepUnlessDefault' in clonedDescriptor) {
5428 clonedDescriptor.keepUnlessDefault = prefix + clonedDescriptor.keepUnlessDefault;
5431 return clonedDescriptor;
5434 // generate vendor-prefixed properties
5435 var vendorPrefixedCompactable = {};
5437 for (var propertyName in compactable) {
5438 var descriptor = compactable[propertyName];
5440 if (!('vendorPrefixes' in descriptor)) {
5444 for (var i = 0; i < descriptor.vendorPrefixes.length; i++) {
5445 var prefix = descriptor.vendorPrefixes[i];
5446 var clonedDescriptor = cloneDescriptor(propertyName, prefix);
5447 delete clonedDescriptor.vendorPrefixes;
5449 vendorPrefixedCompactable[prefix + propertyName] = clonedDescriptor;
5452 delete descriptor.vendorPrefixes;
5455 module.exports = override(compactable, vendorPrefixedCompactable);
5457 },{"../../utils/override":95,"./break-up":18,"./can-override":19,"./restore":49}],22:[function(require,module,exports){
5458 // This extractor is used in level 2 optimizations
5459 // IMPORTANT: Mind Token class and this code is not related!
5460 // Properties will be tokenized in one step, see #429
5462 var Token = require('../../tokenizer/token');
5463 var serializeRules = require('../../writer/one-time').rules;
5464 var serializeValue = require('../../writer/one-time').value;
5466 function extractProperties(token) {
5467 var properties = [];
5468 var inSpecificSelector;
5474 if (token[0] == Token.RULE) {
5475 inSpecificSelector = !/[\.\+>~]/.test(serializeRules(token[1]));
5477 for (i = 0, l = token[2].length; i < l; i++) {
5478 property = token[2][i];
5480 if (property[0] != Token.PROPERTY)
5483 name = property[1][1];
5484 if (name.length === 0)
5487 if (name.indexOf('--') === 0)
5490 value = serializeValue(property, i);
5502 } else if (token[0] == Token.NESTED_BLOCK) {
5503 for (i = 0, l = token[2].length; i < l; i++) {
5504 properties = properties.concat(extractProperties(token[2][i]));
5511 function findNameRoot(name) {
5512 if (name == 'list-style')
5514 if (name.indexOf('-radius') > 0)
5515 return 'border-radius';
5516 if (name == 'border-collapse' || name == 'border-spacing' || name == 'border-image')
5518 if (name.indexOf('border-') === 0 && /^border\-\w+\-\w+$/.test(name))
5519 return name.match(/border\-\w+/)[0];
5520 if (name.indexOf('border-') === 0 && /^border\-\w+$/.test(name))
5522 if (name.indexOf('text-') === 0)
5524 if (name == '-chrome-')
5527 return name.replace(/^\-\w+\-/, '').match(/([a-zA-Z]+)/)[0].toLowerCase();
5530 module.exports = extractProperties;
5532 },{"../../tokenizer/token":84,"../../writer/one-time":98}],23:[function(require,module,exports){
5533 function InvalidPropertyError(message) {
5534 this.name = 'InvalidPropertyError';
5535 this.message = message;
5536 this.stack = (new Error()).stack;
5539 InvalidPropertyError.prototype = Object.create(Error.prototype);
5540 InvalidPropertyError.prototype.constructor = InvalidPropertyError;
5542 module.exports = InvalidPropertyError;
5544 },{}],24:[function(require,module,exports){
5545 var Marker = require('../../tokenizer/marker');
5546 var split = require('../../utils/split');
5548 var DEEP_SELECTOR_PATTERN = /\/deep\//;
5549 var DOUBLE_COLON_PATTERN = /^::/;
5550 var NOT_PSEUDO = ':not';
5551 var PSEUDO_CLASSES_WITH_ARGUMENTS = [
5557 ':nth-last-of-type',
5560 var RELATION_PATTERN = /[>\+~]/;
5561 var UNMIXABLE_PSEUDO_CLASSES = [
5568 var UNMIXABLE_PSEUDO_ELEMENTS = [
5576 DOUBLE_QUOTE: 'double-quote',
5577 SINGLE_QUOTE: 'single-quote',
5581 function isMergeable(selector, mergeablePseudoClasses, mergeablePseudoElements, multiplePseudoMerging) {
5582 var singleSelectors = split(selector, Marker.COMMA);
5586 for (i = 0, l = singleSelectors.length; i < l; i++) {
5587 singleSelector = singleSelectors[i];
5589 if (singleSelector.length === 0 ||
5590 isDeepSelector(singleSelector) ||
5591 (singleSelector.indexOf(Marker.COLON) > -1 && !areMergeable(singleSelector, extractPseudoFrom(singleSelector), mergeablePseudoClasses, mergeablePseudoElements, multiplePseudoMerging))) {
5599 function isDeepSelector(selector) {
5600 return DEEP_SELECTOR_PATTERN.test(selector);
5603 function extractPseudoFrom(selector) {
5607 var level = Level.ROOT;
5608 var roundBracketLevel = 0;
5611 var isPseudo = false;
5613 var wasColon = false;
5617 for (index = 0, len = selector.length; index < len; index++) {
5618 character = selector[index];
5620 isRelation = !isEscaped && RELATION_PATTERN.test(character);
5621 isQuoted = level == Level.DOUBLE_QUOTE || level == Level.SINGLE_QUOTE;
5624 buffer.push(character);
5625 } else if (character == Marker.DOUBLE_QUOTE && level == Level.ROOT) {
5626 buffer.push(character);
5627 level = Level.DOUBLE_QUOTE;
5628 } else if (character == Marker.DOUBLE_QUOTE && level == Level.DOUBLE_QUOTE) {
5629 buffer.push(character);
5631 } else if (character == Marker.SINGLE_QUOTE && level == Level.ROOT) {
5632 buffer.push(character);
5633 level = Level.SINGLE_QUOTE;
5634 } else if (character == Marker.SINGLE_QUOTE && level == Level.SINGLE_QUOTE) {
5635 buffer.push(character);
5637 } else if (isQuoted) {
5638 buffer.push(character);
5639 } else if (character == Marker.OPEN_ROUND_BRACKET) {
5640 buffer.push(character);
5641 roundBracketLevel++;
5642 } else if (character == Marker.CLOSE_ROUND_BRACKET && roundBracketLevel == 1 && isPseudo) {
5643 buffer.push(character);
5644 list.push(buffer.join(''));
5645 roundBracketLevel--;
5648 } else if (character == Marker.CLOSE_ROUND_BRACKET) {
5649 buffer.push(character);
5650 roundBracketLevel--;
5651 } else if (character == Marker.COLON && roundBracketLevel === 0 && isPseudo && !wasColon) {
5652 list.push(buffer.join(''));
5654 buffer.push(character);
5655 } else if (character == Marker.COLON && roundBracketLevel === 0 && !wasColon) {
5657 buffer.push(character);
5659 } else if (character == Marker.SPACE && roundBracketLevel === 0 && isPseudo) {
5660 list.push(buffer.join(''));
5663 } else if (isRelation && roundBracketLevel === 0 && isPseudo) {
5664 list.push(buffer.join(''));
5668 buffer.push(character);
5671 isEscaped = character == Marker.BACK_SLASH;
5672 wasColon = character == Marker.COLON;
5675 if (buffer.length > 0 && isPseudo) {
5676 list.push(buffer.join(''));
5682 function areMergeable(selector, matches, mergeablePseudoClasses, mergeablePseudoElements, multiplePseudoMerging) {
5683 return areAllowed(matches, mergeablePseudoClasses, mergeablePseudoElements) &&
5684 needArguments(matches) &&
5685 (matches.length < 2 || !someIncorrectlyChained(selector, matches)) &&
5686 (matches.length < 2 || multiplePseudoMerging && allMixable(matches));
5689 function areAllowed(matches, mergeablePseudoClasses, mergeablePseudoElements) {
5694 for (i = 0, l = matches.length; i < l; i++) {
5696 name = match.indexOf(Marker.OPEN_ROUND_BRACKET) > -1 ?
5697 match.substring(0, match.indexOf(Marker.OPEN_ROUND_BRACKET)) :
5700 if (mergeablePseudoClasses.indexOf(name) === -1 && mergeablePseudoElements.indexOf(name) === -1) {
5708 function needArguments(matches) {
5715 for (i = 0, l = matches.length; i < l; i++) {
5718 bracketOpensAt = match.indexOf(Marker.OPEN_ROUND_BRACKET);
5719 hasArguments = bracketOpensAt > -1;
5720 name = hasArguments ?
5721 match.substring(0, bracketOpensAt) :
5724 if (hasArguments && PSEUDO_CLASSES_WITH_ARGUMENTS.indexOf(name) == -1) {
5728 if (!hasArguments && PSEUDO_CLASSES_WITH_ARGUMENTS.indexOf(name) > -1) {
5736 function someIncorrectlyChained(selector, matches) {
5737 var positionInSelector = 0;
5747 for (i = 0, l = matches.length; i < l; i++) {
5749 nextMatch = matches[i + 1];
5755 matchAt = selector.indexOf(match, positionInSelector);
5756 nextMatchAt = selector.indexOf(match, matchAt + 1);
5757 positionInSelector = nextMatchAt;
5758 areChained = matchAt + match.length == nextMatchAt;
5761 name = match.indexOf(Marker.OPEN_ROUND_BRACKET) > -1 ?
5762 match.substring(0, match.indexOf(Marker.OPEN_ROUND_BRACKET)) :
5764 nextName = nextMatch.indexOf(Marker.OPEN_ROUND_BRACKET) > -1 ?
5765 nextMatch.substring(0, nextMatch.indexOf(Marker.OPEN_ROUND_BRACKET)) :
5768 if (name != NOT_PSEUDO || nextName != NOT_PSEUDO) {
5777 function allMixable(matches) {
5778 var unmixableMatches = 0;
5782 for (i = 0, l = matches.length; i < l; i++) {
5785 if (isPseudoElement(match)) {
5786 unmixableMatches += UNMIXABLE_PSEUDO_ELEMENTS.indexOf(match) > -1 ? 1 : 0;
5788 unmixableMatches += UNMIXABLE_PSEUDO_CLASSES.indexOf(match) > -1 ? 1 : 0;
5791 if (unmixableMatches > 1) {
5799 function isPseudoElement(pseudo) {
5800 return DOUBLE_COLON_PATTERN.test(pseudo);
5803 module.exports = isMergeable;
5805 },{"../../tokenizer/marker":83,"../../utils/split":96}],25:[function(require,module,exports){
5806 var isMergeable = require('./is-mergeable');
5808 var optimizeProperties = require('./properties/optimize');
5810 var sortSelectors = require('../level-1/sort-selectors');
5811 var tidyRules = require('../level-1/tidy-rules');
5813 var OptimizationLevel = require('../../options/optimization-level').OptimizationLevel;
5815 var serializeBody = require('../../writer/one-time').body;
5816 var serializeRules = require('../../writer/one-time').rules;
5818 var Token = require('../../tokenizer/token');
5820 function mergeAdjacent(tokens, context) {
5821 var lastToken = [null, [], []];
5822 var options = context.options;
5823 var adjacentSpace = options.compatibility.selectors.adjacentSpace;
5824 var selectorsSortingMethod = options.level[OptimizationLevel.One].selectorsSortingMethod;
5825 var mergeablePseudoClasses = options.compatibility.selectors.mergeablePseudoClasses;
5826 var mergeablePseudoElements = options.compatibility.selectors.mergeablePseudoElements;
5827 var mergeLimit = options.compatibility.selectors.mergeLimit;
5828 var multiplePseudoMerging = options.compatibility.selectors.multiplePseudoMerging;
5830 for (var i = 0, l = tokens.length; i < l; i++) {
5831 var token = tokens[i];
5833 if (token[0] != Token.RULE) {
5834 lastToken = [null, [], []];
5838 if (lastToken[0] == Token.RULE && serializeRules(token[1]) == serializeRules(lastToken[1])) {
5839 Array.prototype.push.apply(lastToken[2], token[2]);
5840 optimizeProperties(lastToken[2], true, true, context);
5842 } else if (lastToken[0] == Token.RULE && serializeBody(token[2]) == serializeBody(lastToken[2]) &&
5843 isMergeable(serializeRules(token[1]), mergeablePseudoClasses, mergeablePseudoElements, multiplePseudoMerging) &&
5844 isMergeable(serializeRules(lastToken[1]), mergeablePseudoClasses, mergeablePseudoElements, multiplePseudoMerging) &&
5845 lastToken[1].length < mergeLimit) {
5846 lastToken[1] = tidyRules(lastToken[1].concat(token[1]), false, adjacentSpace, false, context.warnings);
5847 lastToken[1] = lastToken.length > 1 ? sortSelectors(lastToken[1], selectorsSortingMethod) : lastToken[1];
5855 module.exports = mergeAdjacent;
5857 },{"../../options/optimization-level":65,"../../tokenizer/token":84,"../../writer/one-time":98,"../level-1/sort-selectors":14,"../level-1/tidy-rules":17,"./is-mergeable":24,"./properties/optimize":36}],26:[function(require,module,exports){
5858 var canReorder = require('./reorderable').canReorder;
5859 var canReorderSingle = require('./reorderable').canReorderSingle;
5860 var extractProperties = require('./extract-properties');
5861 var rulesOverlap = require('./rules-overlap');
5863 var serializeRules = require('../../writer/one-time').rules;
5864 var OptimizationLevel = require('../../options/optimization-level').OptimizationLevel;
5865 var Token = require('../../tokenizer/token');
5867 function mergeMediaQueries(tokens, context) {
5868 var mergeSemantically = context.options.level[OptimizationLevel.Two].mergeSemantically;
5869 var specificityCache = context.cache.specificity;
5870 var candidates = {};
5873 for (var i = tokens.length - 1; i >= 0; i--) {
5874 var token = tokens[i];
5875 if (token[0] != Token.NESTED_BLOCK) {
5879 var key = serializeRules(token[1]);
5880 var candidate = candidates[key];
5883 candidates[key] = candidate;
5889 for (var name in candidates) {
5890 var positions = candidates[name];
5893 for (var j = positions.length - 1; j > 0; j--) {
5894 var positionOne = positions[j];
5895 var tokenOne = tokens[positionOne];
5896 var positionTwo = positions[j - 1];
5897 var tokenTwo = tokens[positionTwo];
5900 for (var direction = 1; direction >= -1; direction -= 2) {
5901 var topToBottom = direction == 1;
5902 var from = topToBottom ? positionOne + 1 : positionTwo - 1;
5903 var to = topToBottom ? positionTwo : positionOne;
5904 var delta = topToBottom ? 1 : -1;
5905 var source = topToBottom ? tokenOne : tokenTwo;
5906 var target = topToBottom ? tokenTwo : tokenOne;
5907 var movedProperties = extractProperties(source);
5909 while (from != to) {
5910 var traversedProperties = extractProperties(tokens[from]);
5913 if (mergeSemantically && allSameRulePropertiesCanBeReordered(movedProperties, traversedProperties, specificityCache)) {
5917 if (!canReorder(movedProperties, traversedProperties, specificityCache))
5918 continue directionLoop;
5921 target[2] = topToBottom ?
5922 source[2].concat(target[2]) :
5923 target[2].concat(source[2]);
5926 reduced.push(target);
5927 continue positionLoop;
5935 function allSameRulePropertiesCanBeReordered(movedProperties, traversedProperties, specificityCache) {
5938 var traversedProperty;
5943 for (i = 0, l = movedProperties.length; i < l; i++) {
5944 movedProperty = movedProperties[i];
5945 movedRule = movedProperty[5];
5947 for (j = 0, m = traversedProperties.length; j < m; j++) {
5948 traversedProperty = traversedProperties[j];
5949 traversedRule = traversedProperty[5];
5951 if (rulesOverlap(movedRule, traversedRule, true) && !canReorderSingle(movedProperty, traversedProperty, specificityCache)) {
5960 module.exports = mergeMediaQueries;
5962 },{"../../options/optimization-level":65,"../../tokenizer/token":84,"../../writer/one-time":98,"./extract-properties":22,"./reorderable":47,"./rules-overlap":51}],27:[function(require,module,exports){
5963 var isMergeable = require('./is-mergeable');
5965 var sortSelectors = require('../level-1/sort-selectors');
5966 var tidyRules = require('../level-1/tidy-rules');
5968 var OptimizationLevel = require('../../options/optimization-level').OptimizationLevel;
5970 var serializeBody = require('../../writer/one-time').body;
5971 var serializeRules = require('../../writer/one-time').rules;
5973 var Token = require('../../tokenizer/token');
5975 function unsafeSelector(value) {
5976 return /\.|\*| :/.test(value);
5979 function isBemElement(token) {
5980 var asString = serializeRules(token[1]);
5981 return asString.indexOf('__') > -1 || asString.indexOf('--') > -1;
5984 function withoutModifier(selector) {
5985 return selector.replace(/--[^ ,>\+~:]+/g, '');
5988 function removeAnyUnsafeElements(left, candidates) {
5989 var leftSelector = withoutModifier(serializeRules(left[1]));
5991 for (var body in candidates) {
5992 var right = candidates[body];
5993 var rightSelector = withoutModifier(serializeRules(right[1]));
5995 if (rightSelector.indexOf(leftSelector) > -1 || leftSelector.indexOf(rightSelector) > -1)
5996 delete candidates[body];
6000 function mergeNonAdjacentByBody(tokens, context) {
6001 var options = context.options;
6002 var mergeSemantically = options.level[OptimizationLevel.Two].mergeSemantically;
6003 var adjacentSpace = options.compatibility.selectors.adjacentSpace;
6004 var selectorsSortingMethod = options.level[OptimizationLevel.One].selectorsSortingMethod;
6005 var mergeablePseudoClasses = options.compatibility.selectors.mergeablePseudoClasses;
6006 var mergeablePseudoElements = options.compatibility.selectors.mergeablePseudoElements;
6007 var multiplePseudoMerging = options.compatibility.selectors.multiplePseudoMerging;
6008 var candidates = {};
6010 for (var i = tokens.length - 1; i >= 0; i--) {
6011 var token = tokens[i];
6012 if (token[0] != Token.RULE)
6015 if (token[2].length > 0 && (!mergeSemantically && unsafeSelector(serializeRules(token[1]))))
6018 if (token[2].length > 0 && mergeSemantically && isBemElement(token))
6019 removeAnyUnsafeElements(token, candidates);
6021 var candidateBody = serializeBody(token[2]);
6022 var oldToken = candidates[candidateBody];
6024 isMergeable(serializeRules(token[1]), mergeablePseudoClasses, mergeablePseudoElements, multiplePseudoMerging) &&
6025 isMergeable(serializeRules(oldToken[1]), mergeablePseudoClasses, mergeablePseudoElements, multiplePseudoMerging)) {
6027 if (token[2].length > 0) {
6028 token[1] = tidyRules(oldToken[1].concat(token[1]), false, adjacentSpace, false, context.warnings);
6029 token[1] = token[1].length > 1 ? sortSelectors(token[1], selectorsSortingMethod) : token[1];
6031 token[1] = oldToken[1].concat(token[1]);
6035 candidates[candidateBody] = null;
6038 candidates[serializeBody(token[2])] = token;
6042 module.exports = mergeNonAdjacentByBody;
6044 },{"../../options/optimization-level":65,"../../tokenizer/token":84,"../../writer/one-time":98,"../level-1/sort-selectors":14,"../level-1/tidy-rules":17,"./is-mergeable":24}],28:[function(require,module,exports){
6045 var canReorder = require('./reorderable').canReorder;
6046 var extractProperties = require('./extract-properties');
6048 var optimizeProperties = require('./properties/optimize');
6050 var serializeRules = require('../../writer/one-time').rules;
6052 var Token = require('../../tokenizer/token');
6054 function mergeNonAdjacentBySelector(tokens, context) {
6055 var specificityCache = context.cache.specificity;
6056 var allSelectors = {};
6057 var repeatedSelectors = [];
6060 for (i = tokens.length - 1; i >= 0; i--) {
6061 if (tokens[i][0] != Token.RULE)
6063 if (tokens[i][2].length === 0)
6066 var selector = serializeRules(tokens[i][1]);
6067 allSelectors[selector] = [i].concat(allSelectors[selector] || []);
6069 if (allSelectors[selector].length == 2)
6070 repeatedSelectors.push(selector);
6073 for (i = repeatedSelectors.length - 1; i >= 0; i--) {
6074 var positions = allSelectors[repeatedSelectors[i]];
6077 for (var j = positions.length - 1; j > 0; j--) {
6078 var positionOne = positions[j - 1];
6079 var tokenOne = tokens[positionOne];
6080 var positionTwo = positions[j];
6081 var tokenTwo = tokens[positionTwo];
6084 for (var direction = 1; direction >= -1; direction -= 2) {
6085 var topToBottom = direction == 1;
6086 var from = topToBottom ? positionOne + 1 : positionTwo - 1;
6087 var to = topToBottom ? positionTwo : positionOne;
6088 var delta = topToBottom ? 1 : -1;
6089 var moved = topToBottom ? tokenOne : tokenTwo;
6090 var target = topToBottom ? tokenTwo : tokenOne;
6091 var movedProperties = extractProperties(moved);
6093 while (from != to) {
6094 var traversedProperties = extractProperties(tokens[from]);
6097 // traversed then moved as we move selectors towards the start
6098 var reorderable = topToBottom ?
6099 canReorder(movedProperties, traversedProperties, specificityCache) :
6100 canReorder(traversedProperties, movedProperties, specificityCache);
6102 if (!reorderable && !topToBottom)
6103 continue selectorIterator;
6104 if (!reorderable && topToBottom)
6105 continue directionIterator;
6109 Array.prototype.push.apply(moved[2], target[2]);
6110 target[2] = moved[2];
6112 Array.prototype.push.apply(target[2], moved[2]);
6115 optimizeProperties(target[2], true, true, context);
6122 module.exports = mergeNonAdjacentBySelector;
6124 },{"../../tokenizer/token":84,"../../writer/one-time":98,"./extract-properties":22,"./properties/optimize":36,"./reorderable":47}],29:[function(require,module,exports){
6125 var mergeAdjacent = require('./merge-adjacent');
6126 var mergeMediaQueries = require('./merge-media-queries');
6127 var mergeNonAdjacentByBody = require('./merge-non-adjacent-by-body');
6128 var mergeNonAdjacentBySelector = require('./merge-non-adjacent-by-selector');
6129 var reduceNonAdjacent = require('./reduce-non-adjacent');
6130 var removeDuplicateFontAtRules = require('./remove-duplicate-font-at-rules');
6131 var removeDuplicateMediaQueries = require('./remove-duplicate-media-queries');
6132 var removeDuplicates = require('./remove-duplicates');
6133 var removeUnusedAtRules = require('./remove-unused-at-rules');
6134 var restructure = require('./restructure');
6136 var optimizeProperties = require('./properties/optimize');
6138 var OptimizationLevel = require('../../options/optimization-level').OptimizationLevel;
6140 var Token = require('../../tokenizer/token');
6142 function removeEmpty(tokens) {
6143 for (var i = 0, l = tokens.length; i < l; i++) {
6144 var token = tokens[i];
6145 var isEmpty = false;
6149 isEmpty = token[1].length === 0 || token[2].length === 0;
6151 case Token.NESTED_BLOCK:
6152 removeEmpty(token[2]);
6153 isEmpty = token[2].length === 0;
6156 isEmpty = token[1].length === 0;
6158 case Token.AT_RULE_BLOCK:
6159 isEmpty = token[2].length === 0;
6163 tokens.splice(i, 1);
6170 function recursivelyOptimizeBlocks(tokens, context) {
6171 for (var i = 0, l = tokens.length; i < l; i++) {
6172 var token = tokens[i];
6174 if (token[0] == Token.NESTED_BLOCK) {
6175 var isKeyframes = /@(-moz-|-o-|-webkit-)?keyframes/.test(token[1][0][1]);
6176 level2Optimize(token[2], context, !isKeyframes);
6181 function recursivelyOptimizeProperties(tokens, context) {
6182 for (var i = 0, l = tokens.length; i < l; i++) {
6183 var token = tokens[i];
6187 optimizeProperties(token[2], true, true, context);
6189 case Token.NESTED_BLOCK:
6190 recursivelyOptimizeProperties(token[2], context);
6195 function level2Optimize(tokens, context, withRestructuring) {
6196 var levelOptions = context.options.level[OptimizationLevel.Two];
6200 recursivelyOptimizeBlocks(tokens, context);
6201 recursivelyOptimizeProperties(tokens, context);
6203 if (levelOptions.removeDuplicateRules) {
6204 removeDuplicates(tokens, context);
6207 if (levelOptions.mergeAdjacentRules) {
6208 mergeAdjacent(tokens, context);
6211 if (levelOptions.reduceNonAdjacentRules) {
6212 reduceNonAdjacent(tokens, context);
6215 if (levelOptions.mergeNonAdjacentRules && levelOptions.mergeNonAdjacentRules != 'body') {
6216 mergeNonAdjacentBySelector(tokens, context);
6219 if (levelOptions.mergeNonAdjacentRules && levelOptions.mergeNonAdjacentRules != 'selector') {
6220 mergeNonAdjacentByBody(tokens, context);
6223 if (levelOptions.restructureRules && levelOptions.mergeAdjacentRules && withRestructuring) {
6224 restructure(tokens, context);
6225 mergeAdjacent(tokens, context);
6228 if (levelOptions.restructureRules && !levelOptions.mergeAdjacentRules && withRestructuring) {
6229 restructure(tokens, context);
6232 if (levelOptions.removeDuplicateFontRules) {
6233 removeDuplicateFontAtRules(tokens, context);
6236 if (levelOptions.removeDuplicateMediaBlocks) {
6237 removeDuplicateMediaQueries(tokens, context);
6240 if (levelOptions.removeUnusedAtRules) {
6241 removeUnusedAtRules(tokens, context);
6244 if (levelOptions.mergeMedia) {
6245 reduced = mergeMediaQueries(tokens, context);
6246 for (i = reduced.length - 1; i >= 0; i--) {
6247 level2Optimize(reduced[i][2], context, false);
6251 if (levelOptions.removeEmpty) {
6252 removeEmpty(tokens);
6258 module.exports = level2Optimize;
6260 },{"../../options/optimization-level":65,"../../tokenizer/token":84,"./merge-adjacent":25,"./merge-media-queries":26,"./merge-non-adjacent-by-body":27,"./merge-non-adjacent-by-selector":28,"./properties/optimize":36,"./reduce-non-adjacent":42,"./remove-duplicate-font-at-rules":43,"./remove-duplicate-media-queries":44,"./remove-duplicates":45,"./remove-unused-at-rules":46,"./restructure":50}],30:[function(require,module,exports){
6261 var Marker = require('../../../tokenizer/marker');
6263 function everyValuesPair(fn, left, right) {
6264 var leftSize = left.value.length;
6265 var rightSize = right.value.length;
6266 var total = Math.max(leftSize, rightSize);
6267 var lowerBound = Math.min(leftSize, rightSize) - 1;
6272 for (position = 0; position < total; position++) {
6273 leftValue = left.value[position] && left.value[position][1] || leftValue;
6274 rightValue = right.value[position] && right.value[position][1] || rightValue;
6276 if (leftValue == Marker.COMMA || rightValue == Marker.COMMA) {
6280 if (!fn(leftValue, rightValue, position, position <= lowerBound)) {
6288 module.exports = everyValuesPair;
6290 },{"../../../tokenizer/marker":83}],31:[function(require,module,exports){
6291 var compactable = require('../compactable');
6293 function findComponentIn(shorthand, longhand) {
6294 var comparator = nameComparator(longhand);
6296 return findInDirectComponents(shorthand, comparator) || findInSubComponents(shorthand, comparator);
6299 function nameComparator(to) {
6300 return function (property) {
6301 return to.name === property.name;
6305 function findInDirectComponents(shorthand, comparator) {
6306 return shorthand.components.filter(comparator)[0];
6309 function findInSubComponents(shorthand, comparator) {
6310 var shorthandComponent;
6314 if (!compactable[shorthand.name].shorthandComponents) {
6318 for (i = 0, l = shorthand.components.length; i < l; i++) {
6319 shorthandComponent = shorthand.components[i];
6320 longhandMatch = findInDirectComponents(shorthandComponent, comparator);
6322 if (longhandMatch) {
6323 return longhandMatch;
6330 module.exports = findComponentIn;
6332 },{"../compactable":21}],32:[function(require,module,exports){
6333 function hasInherit(property) {
6334 for (var i = property.value.length - 1; i >= 0; i--) {
6335 if (property.value[i][1] == 'inherit')
6342 module.exports = hasInherit;
6344 },{}],33:[function(require,module,exports){
6345 var compactable = require('../compactable');
6347 function isComponentOf(property1, property2, shallow) {
6348 return isDirectComponentOf(property1, property2) ||
6349 !shallow && !!compactable[property1.name].shorthandComponents && isSubComponentOf(property1, property2);
6352 function isDirectComponentOf(property1, property2) {
6353 var descriptor = compactable[property1.name];
6355 return 'components' in descriptor && descriptor.components.indexOf(property2.name) > -1;
6358 function isSubComponentOf(property1, property2) {
6361 .some(function (component) {
6362 return isDirectComponentOf(component, property2);
6366 module.exports = isComponentOf;
6368 },{"../compactable":21}],34:[function(require,module,exports){
6369 var Marker = require('../../../tokenizer/marker');
6371 function isMergeableShorthand(shorthand) {
6372 if (shorthand.name != 'font') {
6376 return shorthand.value[0][1].indexOf(Marker.INTERNAL) == -1;
6379 module.exports = isMergeableShorthand;
6381 },{"../../../tokenizer/marker":83}],35:[function(require,module,exports){
6382 var everyValuesPair = require('./every-values-pair');
6383 var hasInherit = require('./has-inherit');
6384 var populateComponents = require('./populate-components');
6386 var compactable = require('../compactable');
6387 var deepClone = require('../clone').deep;
6388 var restoreWithComponents = require('../restore-with-components');
6390 var restoreFromOptimizing = require('../../restore-from-optimizing');
6391 var wrapSingle = require('../../wrap-for-optimizing').single;
6393 var serializeBody = require('../../../writer/one-time').body;
6394 var Token = require('../../../tokenizer/token');
6396 function mergeIntoShorthands(properties, validator) {
6397 var candidates = {};
6404 // there is no shorthand property made up of less than 3 longhands
6405 if (properties.length < 3) {
6409 for (i = 0, l = properties.length; i < l; i++) {
6410 property = properties[i];
6411 descriptor = compactable[property.name];
6413 if (property.unused) {
6417 if (property.hack) {
6421 if (property.block) {
6425 invalidateOrCompact(properties, i, candidates, validator);
6427 if (descriptor && descriptor.componentOf) {
6428 for (j = 0, m = descriptor.componentOf.length; j < m; j++) {
6429 componentOf = descriptor.componentOf[j];
6431 candidates[componentOf] = candidates[componentOf] || {};
6432 candidates[componentOf][property.name] = property;
6437 invalidateOrCompact(properties, i, candidates, validator);
6440 function invalidateOrCompact(properties, position, candidates, validator) {
6441 var invalidatedBy = properties[position];
6443 var shorthandDescriptor;
6444 var candidateComponents;
6446 for (shorthandName in candidates) {
6447 if (undefined !== invalidatedBy && shorthandName == invalidatedBy.name) {
6451 shorthandDescriptor = compactable[shorthandName];
6452 candidateComponents = candidates[shorthandName];
6453 if (invalidatedBy && invalidates(candidates, shorthandName, invalidatedBy)) {
6454 delete candidates[shorthandName];
6458 if (shorthandDescriptor.components.length > Object.keys(candidateComponents).length) {
6462 if (mixedImportance(candidateComponents)) {
6466 if (!overridable(candidateComponents, shorthandName, validator)) {
6470 if (!mergeable(candidateComponents)) {
6474 if (mixedInherit(candidateComponents)) {
6475 replaceWithInheritBestFit(properties, candidateComponents, shorthandName, validator);
6477 replaceWithShorthand(properties, candidateComponents, shorthandName, validator);
6482 function invalidates(candidates, shorthandName, invalidatedBy) {
6483 var shorthandDescriptor = compactable[shorthandName];
6484 var invalidatedByDescriptor = compactable[invalidatedBy.name];
6487 if ('overridesShorthands' in shorthandDescriptor && shorthandDescriptor.overridesShorthands.indexOf(invalidatedBy.name) > -1) {
6491 if (invalidatedByDescriptor && 'componentOf' in invalidatedByDescriptor) {
6492 for (componentName in candidates[shorthandName]) {
6493 if (invalidatedByDescriptor.componentOf.indexOf(componentName) > -1) {
6502 function mixedImportance(components) {
6506 for (componentName in components) {
6507 if (undefined !== important && components[componentName].important != important) {
6511 important = components[componentName].important;
6517 function overridable(components, shorthandName, validator) {
6518 var descriptor = compactable[shorthandName];
6519 var newValuePlaceholder = [
6521 [Token.PROPERTY_NAME, shorthandName],
6522 [Token.PROPERTY_VALUE, descriptor.defaultValue]
6524 var newProperty = wrapSingle(newValuePlaceholder);
6529 populateComponents([newProperty], validator, []);
6531 for (i = 0, l = descriptor.components.length; i < l; i++) {
6532 component = components[descriptor.components[i]];
6533 mayOverride = compactable[component.name].canOverride;
6535 if (!everyValuesPair(mayOverride.bind(null, validator), newProperty.components[i], component)) {
6543 function mergeable(components) {
6544 var lastCount = null;
6551 for (componentName in components) {
6552 component = components[componentName];
6553 descriptor = compactable[componentName];
6555 if (!('restore' in descriptor)) {
6559 restoreFromOptimizing([component.all[component.position]], restoreWithComponents);
6560 values = descriptor.restore(component, compactable);
6562 currentCount = values.length;
6564 if (lastCount !== null && currentCount !== lastCount) {
6568 lastCount = currentCount;
6574 function mixedInherit(components) {
6576 var lastValue = null;
6579 for (componentName in components) {
6580 currentValue = hasInherit(components[componentName]);
6582 if (lastValue !== null && lastValue !== currentValue) {
6586 lastValue = currentValue;
6592 function replaceWithInheritBestFit(properties, candidateComponents, shorthandName, validator) {
6593 var viaLonghands = buildSequenceWithInheritLonghands(candidateComponents, shorthandName, validator);
6594 var viaShorthand = buildSequenceWithInheritShorthand(candidateComponents, shorthandName, validator);
6595 var longhandTokensSequence = viaLonghands[0];
6596 var shorthandTokensSequence = viaShorthand[0];
6597 var isLonghandsShorter = serializeBody(longhandTokensSequence).length < serializeBody(shorthandTokensSequence).length;
6598 var newTokensSequence = isLonghandsShorter ? longhandTokensSequence : shorthandTokensSequence;
6599 var newProperty = isLonghandsShorter ? viaLonghands[1] : viaShorthand[1];
6600 var newComponents = isLonghandsShorter ? viaLonghands[2] : viaShorthand[2];
6601 var all = candidateComponents[Object.keys(candidateComponents)[0]].all;
6607 newProperty.position = all.length;
6608 newProperty.shorthand = true;
6609 newProperty.dirty = true;
6610 newProperty.all = all;
6611 newProperty.all.push(newTokensSequence[0]);
6613 properties.push(newProperty);
6615 for (componentName in candidateComponents) {
6616 oldComponent = candidateComponents[componentName];
6617 oldComponent.unused = true;
6619 if (oldComponent.name in newComponents) {
6620 newComponent = newComponents[oldComponent.name];
6621 newToken = findTokenIn(newTokensSequence, componentName);
6623 newComponent.position = all.length;
6624 newComponent.all = all;
6625 newComponent.all.push(newToken);
6627 properties.push(newComponent);
6632 function buildSequenceWithInheritLonghands(components, shorthandName, validator) {
6633 var tokensSequence = [];
6634 var inheritComponents = {};
6635 var nonInheritComponents = {};
6636 var descriptor = compactable[shorthandName];
6637 var shorthandToken = [
6639 [Token.PROPERTY_NAME, shorthandName],
6640 [Token.PROPERTY_VALUE, descriptor.defaultValue]
6642 var newProperty = wrapSingle(shorthandToken);
6649 populateComponents([newProperty], validator, []);
6651 for (i = 0, l = descriptor.components.length; i < l; i++) {
6652 component = components[descriptor.components[i]];
6654 if (hasInherit(component)) {
6655 longhandToken = component.all[component.position].slice(0, 2);
6656 Array.prototype.push.apply(longhandToken, component.value);
6657 tokensSequence.push(longhandToken);
6659 newComponent = deepClone(component);
6660 newComponent.value = inferComponentValue(components, newComponent.name);
6662 newProperty.components[i] = newComponent;
6663 inheritComponents[component.name] = deepClone(component);
6665 newComponent = deepClone(component);
6666 newComponent.all = component.all;
6667 newProperty.components[i] = newComponent;
6669 nonInheritComponents[component.name] = component;
6673 nameMetadata = joinMetadata(nonInheritComponents, 1);
6674 shorthandToken[1].push(nameMetadata);
6676 restoreFromOptimizing([newProperty], restoreWithComponents);
6678 shorthandToken = shorthandToken.slice(0, 2);
6679 Array.prototype.push.apply(shorthandToken, newProperty.value);
6681 tokensSequence.unshift(shorthandToken);
6683 return [tokensSequence, newProperty, inheritComponents];
6686 function inferComponentValue(components, propertyName) {
6687 var descriptor = compactable[propertyName];
6689 if ('oppositeTo' in descriptor) {
6690 return components[descriptor.oppositeTo].value;
6692 return [[Token.PROPERTY_VALUE, descriptor.defaultValue]];
6696 function joinMetadata(components, at) {
6700 var componentMetadata;
6703 for (componentName in components) {
6704 component = components[componentName];
6705 originalValue = component.all[component.position];
6706 componentMetadata = originalValue[at][originalValue[at].length - 1];
6708 Array.prototype.push.apply(metadata, componentMetadata);
6711 return metadata.sort(metadataSorter);
6714 function metadataSorter(metadata1, metadata2) {
6715 var line1 = metadata1[0];
6716 var line2 = metadata2[0];
6717 var column1 = metadata1[1];
6718 var column2 = metadata2[1];
6720 if (line1 < line2) {
6722 } else if (line1 === line2) {
6723 return column1 < column2 ? -1 : 1;
6729 function buildSequenceWithInheritShorthand(components, shorthandName, validator) {
6730 var tokensSequence = [];
6731 var inheritComponents = {};
6732 var nonInheritComponents = {};
6733 var descriptor = compactable[shorthandName];
6734 var shorthandToken = [
6736 [Token.PROPERTY_NAME, shorthandName],
6737 [Token.PROPERTY_VALUE, 'inherit']
6739 var newProperty = wrapSingle(shorthandToken);
6746 populateComponents([newProperty], validator, []);
6748 for (i = 0, l = descriptor.components.length; i < l; i++) {
6749 component = components[descriptor.components[i]];
6751 if (hasInherit(component)) {
6752 inheritComponents[component.name] = component;
6754 longhandToken = component.all[component.position].slice(0, 2);
6755 Array.prototype.push.apply(longhandToken, component.value);
6756 tokensSequence.push(longhandToken);
6758 nonInheritComponents[component.name] = deepClone(component);
6762 nameMetadata = joinMetadata(inheritComponents, 1);
6763 shorthandToken[1].push(nameMetadata);
6765 valueMetadata = joinMetadata(inheritComponents, 2);
6766 shorthandToken[2].push(valueMetadata);
6768 tokensSequence.unshift(shorthandToken);
6770 return [tokensSequence, newProperty, nonInheritComponents];
6773 function findTokenIn(tokens, componentName) {
6776 for (i = 0, l = tokens.length; i < l; i++) {
6777 if (tokens[i][1][1] == componentName) {
6783 function replaceWithShorthand(properties, candidateComponents, shorthandName, validator) {
6784 var descriptor = compactable[shorthandName];
6787 var newValuePlaceholder = [
6789 [Token.PROPERTY_NAME, shorthandName],
6790 [Token.PROPERTY_VALUE, descriptor.defaultValue]
6794 var newProperty = wrapSingle(newValuePlaceholder);
6795 newProperty.shorthand = true;
6796 newProperty.dirty = true;
6798 populateComponents([newProperty], validator, []);
6800 for (var i = 0, l = descriptor.components.length; i < l; i++) {
6801 var component = candidateComponents[descriptor.components[i]];
6803 newProperty.components[i] = deepClone(component);
6804 newProperty.important = component.important;
6806 all = component.all;
6809 for (var componentName in candidateComponents) {
6810 candidateComponents[componentName].unused = true;
6813 nameMetadata = joinMetadata(candidateComponents, 1);
6814 newValuePlaceholder[1].push(nameMetadata);
6816 valueMetadata = joinMetadata(candidateComponents, 2);
6817 newValuePlaceholder[2].push(valueMetadata);
6819 newProperty.position = all.length;
6820 newProperty.all = all;
6821 newProperty.all.push(newValuePlaceholder);
6823 properties.push(newProperty);
6826 module.exports = mergeIntoShorthands;
6828 },{"../../../tokenizer/token":84,"../../../writer/one-time":98,"../../restore-from-optimizing":56,"../../wrap-for-optimizing":58,"../clone":20,"../compactable":21,"../restore-with-components":48,"./every-values-pair":30,"./has-inherit":32,"./populate-components":39}],36:[function(require,module,exports){
6829 var mergeIntoShorthands = require('./merge-into-shorthands');
6830 var overrideProperties = require('./override-properties');
6831 var populateComponents = require('./populate-components');
6833 var restoreWithComponents = require('../restore-with-components');
6835 var wrapForOptimizing = require('../../wrap-for-optimizing').all;
6836 var removeUnused = require('../../remove-unused');
6837 var restoreFromOptimizing = require('../../restore-from-optimizing');
6839 var OptimizationLevel = require('../../../options/optimization-level').OptimizationLevel;
6841 function optimizeProperties(properties, withOverriding, withMerging, context) {
6842 var levelOptions = context.options.level[OptimizationLevel.Two];
6843 var _properties = wrapForOptimizing(properties, false, levelOptions.skipProperties);
6847 populateComponents(_properties, context.validator, context.warnings);
6849 for (i = 0, l = _properties.length; i < l; i++) {
6850 _property = _properties[i];
6851 if (_property.block) {
6852 optimizeProperties(_property.value[0][1], withOverriding, withMerging, context);
6856 if (withMerging && levelOptions.mergeIntoShorthands) {
6857 mergeIntoShorthands(_properties, context.validator);
6860 if (withOverriding && levelOptions.overrideProperties) {
6861 overrideProperties(_properties, withMerging, context.options.compatibility, context.validator);
6864 restoreFromOptimizing(_properties, restoreWithComponents);
6865 removeUnused(_properties);
6868 module.exports = optimizeProperties;
6870 },{"../../../options/optimization-level":65,"../../remove-unused":55,"../../restore-from-optimizing":56,"../../wrap-for-optimizing":58,"../restore-with-components":48,"./merge-into-shorthands":35,"./override-properties":37,"./populate-components":39}],37:[function(require,module,exports){
6871 var hasInherit = require('./has-inherit');
6872 var everyValuesPair = require('./every-values-pair');
6873 var findComponentIn = require('./find-component-in');
6874 var isComponentOf = require('./is-component-of');
6875 var isMergeableShorthand = require('./is-mergeable-shorthand');
6876 var overridesNonComponentShorthand = require('./overrides-non-component-shorthand');
6877 var sameVendorPrefixesIn = require('./vendor-prefixes').same;
6879 var compactable = require('../compactable');
6880 var deepClone = require('../clone').deep;
6881 var restoreWithComponents = require('../restore-with-components');
6882 var shallowClone = require('../clone').shallow;
6884 var restoreFromOptimizing = require('../../restore-from-optimizing');
6886 var Token = require('../../../tokenizer/token');
6887 var Marker = require('../../../tokenizer/marker');
6889 var serializeProperty = require('../../../writer/one-time').property;
6891 function wouldBreakCompatibility(property, validator) {
6892 for (var i = 0; i < property.components.length; i++) {
6893 var component = property.components[i];
6894 var descriptor = compactable[component.name];
6895 var canOverride = descriptor && descriptor.canOverride || canOverride.sameValue;
6897 var _component = shallowClone(component);
6898 _component.value = [[Token.PROPERTY_VALUE, descriptor.defaultValue]];
6900 if (!everyValuesPair(canOverride.bind(null, validator), _component, component)) {
6908 function overrideIntoMultiplex(property, by) {
6911 turnIntoMultiplex(by, multiplexSize(property));
6912 property.value = by.value;
6915 function overrideByMultiplex(property, by) {
6917 property.multiplex = true;
6918 property.value = by.value;
6921 function overrideSimple(property, by) {
6923 property.value = by.value;
6926 function override(property, by) {
6928 overrideByMultiplex(property, by);
6929 else if (property.multiplex)
6930 overrideIntoMultiplex(property, by);
6932 overrideSimple(property, by);
6935 function overrideShorthand(property, by) {
6938 for (var i = 0, l = property.components.length; i < l; i++) {
6939 override(property.components[i], by.components[i], property.multiplex);
6943 function turnIntoMultiplex(property, size) {
6944 property.multiplex = true;
6946 if (compactable[property.name].shorthand) {
6947 turnShorthandValueIntoMultiplex(property, size);
6949 turnLonghandValueIntoMultiplex(property, size);
6953 function turnShorthandValueIntoMultiplex(property, size) {
6957 for (i = 0, l = property.components.length; i < l; i++) {
6958 component = property.components[i];
6960 if (!component.multiplex) {
6961 turnLonghandValueIntoMultiplex(component, size);
6966 function turnLonghandValueIntoMultiplex(property, size) {
6967 var descriptor = compactable[property.name];
6968 var withRealValue = descriptor.intoMultiplexMode == 'real';
6969 var withValue = descriptor.intoMultiplexMode == 'real' ?
6970 property.value.slice(0) :
6971 (descriptor.intoMultiplexMode == 'placeholder' ? descriptor.placeholderValue : descriptor.defaultValue);
6972 var i = multiplexSize(property);
6974 var m = withValue.length;
6976 for (; i < size; i++) {
6977 property.value.push([Token.PROPERTY_VALUE, Marker.COMMA]);
6979 if (Array.isArray(withValue)) {
6980 for (j = 0; j < m; j++) {
6981 property.value.push(withRealValue ? withValue[j] : [Token.PROPERTY_VALUE, withValue[j]]);
6984 property.value.push(withRealValue ? withValue : [Token.PROPERTY_VALUE, withValue]);
6989 function multiplexSize(component) {
6992 for (var i = 0, l = component.value.length; i < l; i++) {
6993 if (component.value[i][1] == Marker.COMMA)
7000 function lengthOf(property) {
7003 [Token.PROPERTY_NAME, property.name]
7004 ].concat(property.value);
7005 return serializeProperty([fakeAsArray], 0).length;
7008 function moreSameShorthands(properties, startAt, name) {
7009 // Since we run the main loop in `compactOverrides` backwards, at this point some
7010 // properties may not be marked as unused.
7011 // We should consider reverting the order if possible
7014 for (var i = startAt; i >= 0; i--) {
7015 if (properties[i].name == name && !properties[i].unused)
7024 function overridingFunction(shorthand, validator) {
7025 for (var i = 0, l = shorthand.components.length; i < l; i++) {
7026 if (!anyValue(validator.isUrl, shorthand.components[i]) && anyValue(validator.isFunction, shorthand.components[i])) {
7034 function anyValue(fn, property) {
7035 for (var i = 0, l = property.value.length; i < l; i++) {
7036 if (property.value[i][1] == Marker.COMMA)
7039 if (fn(property.value[i][1]))
7046 function wouldResultInLongerValue(left, right) {
7047 if (!left.multiplex && !right.multiplex || left.multiplex && right.multiplex)
7050 var multiplex = left.multiplex ? left : right;
7051 var simple = left.multiplex ? right : left;
7054 var multiplexClone = deepClone(multiplex);
7055 restoreFromOptimizing([multiplexClone], restoreWithComponents);
7057 var simpleClone = deepClone(simple);
7058 restoreFromOptimizing([simpleClone], restoreWithComponents);
7060 var lengthBefore = lengthOf(multiplexClone) + 1 + lengthOf(simpleClone);
7062 if (left.multiplex) {
7063 component = findComponentIn(multiplexClone, simpleClone);
7064 overrideIntoMultiplex(component, simpleClone);
7066 component = findComponentIn(simpleClone, multiplexClone);
7067 turnIntoMultiplex(simpleClone, multiplexSize(multiplexClone));
7068 overrideByMultiplex(component, multiplexClone);
7071 restoreFromOptimizing([simpleClone], restoreWithComponents);
7073 var lengthAfter = lengthOf(simpleClone);
7075 return lengthBefore <= lengthAfter;
7078 function isCompactable(property) {
7079 return property.name in compactable;
7082 function noneOverrideHack(left, right) {
7083 return !left.multiplex &&
7084 (left.name == 'background' || left.name == 'background-image') &&
7086 (right.name == 'background' || right.name == 'background-image') &&
7087 anyLayerIsNone(right.value);
7090 function anyLayerIsNone(values) {
7091 var layers = intoLayers(values);
7093 for (var i = 0, l = layers.length; i < l; i++) {
7094 if (layers[i].length == 1 && layers[i][0][1] == 'none')
7101 function intoLayers(values) {
7104 for (var i = 0, layer = [], l = values.length; i < l; i++) {
7105 var value = values[i];
7106 if (value[1] == Marker.COMMA) {
7118 function overrideProperties(properties, withMerging, compatibility, validator) {
7119 var mayOverride, right, left, component;
7120 var overriddenComponents;
7121 var overriddenComponent;
7122 var overridingComponent;
7127 for (i = properties.length - 1; i >= 0; i--) {
7128 right = properties[i];
7130 if (!isCompactable(right))
7136 mayOverride = compactable[right.name].canOverride;
7139 for (j = i - 1; j >= 0; j--) {
7140 left = properties[j];
7142 if (!isCompactable(left))
7148 if (left.unused || right.unused)
7151 if (left.hack && !right.hack && !right.important || !left.hack && !left.important && right.hack)
7154 if (left.important == right.important && left.hack[0] != right.hack[0])
7157 if (left.important == right.important && (left.hack[0] != right.hack[0] || (left.hack[1] && left.hack[1] != right.hack[1])))
7160 if (hasInherit(right))
7163 if (noneOverrideHack(left, right))
7166 if (right.shorthand && isComponentOf(right, left)) {
7167 // maybe `left` can be overridden by `right` which is a shorthand?
7168 if (!right.important && left.important)
7171 if (!sameVendorPrefixesIn([left], right.components))
7174 if (!anyValue(validator.isFunction, left) && overridingFunction(right, validator))
7177 if (!isMergeableShorthand(right)) {
7182 component = findComponentIn(right, left);
7183 mayOverride = compactable[left.name].canOverride;
7184 if (everyValuesPair(mayOverride.bind(null, validator), left, component)) {
7187 } else if (right.shorthand && overridesNonComponentShorthand(right, left)) {
7188 // `right` is a shorthand while `left` can be overriden by it, think `border` and `border-top`
7189 if (!right.important && left.important) {
7193 if (!sameVendorPrefixesIn([left], right.components)) {
7197 if (!anyValue(validator.isFunction, left) && overridingFunction(right, validator)) {
7201 overriddenComponents = left.shorthand ?
7205 for (k = overriddenComponents.length - 1; k >= 0; k--) {
7206 overriddenComponent = overriddenComponents[k];
7207 overridingComponent = findComponentIn(right, overriddenComponent);
7208 mayOverride = compactable[overriddenComponent.name].canOverride;
7210 if (!everyValuesPair(mayOverride.bind(null, validator), left, overridingComponent)) {
7211 continue traverseLoop;
7216 } else if (withMerging && left.shorthand && !right.shorthand && isComponentOf(left, right, true)) {
7217 // maybe `right` can be pulled into `left` which is a shorthand?
7218 if (right.important && !left.important)
7221 if (!right.important && left.important) {
7222 right.unused = true;
7226 // Pending more clever algorithm in #527
7227 if (moreSameShorthands(properties, i - 1, left.name))
7230 if (overridingFunction(left, validator))
7233 if (!isMergeableShorthand(left))
7236 component = findComponentIn(left, right);
7237 if (everyValuesPair(mayOverride.bind(null, validator), component, right)) {
7238 var disabledBackgroundMerging =
7239 !compatibility.properties.backgroundClipMerging && component.name.indexOf('background-clip') > -1 ||
7240 !compatibility.properties.backgroundOriginMerging && component.name.indexOf('background-origin') > -1 ||
7241 !compatibility.properties.backgroundSizeMerging && component.name.indexOf('background-size') > -1;
7242 var nonMergeableValue = compactable[right.name].nonMergeableValue === right.value[0][1];
7244 if (disabledBackgroundMerging || nonMergeableValue)
7247 if (!compatibility.properties.merging && wouldBreakCompatibility(left, validator))
7250 if (component.value[0][1] != right.value[0][1] && (hasInherit(left) || hasInherit(right)))
7253 if (wouldResultInLongerValue(left, right))
7256 if (!left.multiplex && right.multiplex)
7257 turnIntoMultiplex(left, multiplexSize(right));
7259 override(component, right);
7262 } else if (withMerging && left.shorthand && right.shorthand && left.name == right.name) {
7263 // merge if all components can be merged
7265 if (!left.multiplex && right.multiplex)
7268 if (!right.important && left.important) {
7269 right.unused = true;
7270 continue propertyLoop;
7273 if (right.important && !left.important) {
7278 if (!isMergeableShorthand(right)) {
7283 for (k = left.components.length - 1; k >= 0; k--) {
7284 var leftComponent = left.components[k];
7285 var rightComponent = right.components[k];
7287 mayOverride = compactable[leftComponent.name].canOverride;
7288 if (!everyValuesPair(mayOverride.bind(null, validator), leftComponent, rightComponent))
7289 continue propertyLoop;
7292 overrideShorthand(left, right);
7294 } else if (withMerging && left.shorthand && right.shorthand && isComponentOf(left, right)) {
7295 // border is a shorthand but any of its components is a shorthand too
7297 if (!left.important && right.important)
7300 component = findComponentIn(left, right);
7301 mayOverride = compactable[right.name].canOverride;
7302 if (!everyValuesPair(mayOverride.bind(null, validator), component, right))
7305 if (left.important && !right.important) {
7306 right.unused = true;
7310 var rightRestored = compactable[right.name].restore(right, compactable);
7311 if (rightRestored.length > 1)
7314 component = findComponentIn(left, right);
7315 override(component, right);
7317 } else if (left.name == right.name) {
7318 // two non-shorthands should be merged based on understandability
7321 if (right.shorthand) {
7322 for (k = right.components.length - 1; k >= 0 && overridable; k--) {
7323 overriddenComponent = left.components[k];
7324 overridingComponent = right.components[k];
7325 mayOverride = compactable[overridingComponent.name].canOverride;
7327 overridable = overridable && everyValuesPair(mayOverride.bind(null, validator), overriddenComponent, overridingComponent);
7330 mayOverride = compactable[right.name].canOverride;
7331 overridable = everyValuesPair(mayOverride.bind(null, validator), left, right);
7334 if (left.important && !right.important && overridable) {
7335 right.unused = true;
7339 if (!left.important && right.important && overridable) {
7354 module.exports = overrideProperties;
7356 },{"../../../tokenizer/marker":83,"../../../tokenizer/token":84,"../../../writer/one-time":98,"../../restore-from-optimizing":56,"../clone":20,"../compactable":21,"../restore-with-components":48,"./every-values-pair":30,"./find-component-in":31,"./has-inherit":32,"./is-component-of":33,"./is-mergeable-shorthand":34,"./overrides-non-component-shorthand":38,"./vendor-prefixes":41}],38:[function(require,module,exports){
7357 var compactable = require('../compactable');
7359 function overridesNonComponentShorthand(property1, property2) {
7360 return property1.name in compactable &&
7361 'overridesShorthands' in compactable[property1.name] &&
7362 compactable[property1.name].overridesShorthands.indexOf(property2.name) > -1;
7365 module.exports = overridesNonComponentShorthand;
7367 },{"../compactable":21}],39:[function(require,module,exports){
7368 var compactable = require('../compactable');
7369 var InvalidPropertyError = require('../invalid-property-error');
7371 function populateComponents(properties, validator, warnings) {
7375 for (var i = properties.length - 1; i >= 0; i--) {
7376 var property = properties[i];
7377 var descriptor = compactable[property.name];
7379 if (descriptor && descriptor.shorthand) {
7380 property.shorthand = true;
7381 property.dirty = true;
7384 property.components = descriptor.breakUp(property, compactable, validator);
7386 if (descriptor.shorthandComponents) {
7387 for (j = 0, m = property.components.length; j < m; j++) {
7388 component = property.components[j];
7389 component.components = compactable[component.name].breakUp(component, compactable, validator);
7393 if (e instanceof InvalidPropertyError) {
7394 property.components = []; // this will set property.unused to true below
7395 warnings.push(e.message);
7401 if (property.components.length > 0)
7402 property.multiplex = property.components[0].multiplex;
7404 property.unused = true;
7409 module.exports = populateComponents;
7411 },{"../compactable":21,"../invalid-property-error":23}],40:[function(require,module,exports){
7412 var sameVendorPrefixes = require('./vendor-prefixes').same;
7414 function understandable(validator, value1, value2, _position, isPaired) {
7415 if (!sameVendorPrefixes(value1, value2)) {
7419 if (isPaired && validator.isVariable(value1) !== validator.isVariable(value2)) {
7426 module.exports = understandable;
7428 },{"./vendor-prefixes":41}],41:[function(require,module,exports){
7429 var VENDOR_PREFIX_PATTERN = /(?:^|\W)(\-\w+\-)/g;
7431 function unique(value) {
7435 while ((match = VENDOR_PREFIX_PATTERN.exec(value)) !== null) {
7436 if (prefixes.indexOf(match[0]) == -1) {
7437 prefixes.push(match[0]);
7444 function same(value1, value2) {
7445 return unique(value1).sort().join(',') == unique(value2).sort().join(',');
7453 },{}],42:[function(require,module,exports){
7454 var isMergeable = require('./is-mergeable');
7456 var optimizeProperties = require('./properties/optimize');
7458 var cloneArray = require('../../utils/clone-array');
7460 var Token = require('../../tokenizer/token');
7462 var serializeBody = require('../../writer/one-time').body;
7463 var serializeRules = require('../../writer/one-time').rules;
7465 function reduceNonAdjacent(tokens, context) {
7466 var options = context.options;
7467 var mergeablePseudoClasses = options.compatibility.selectors.mergeablePseudoClasses;
7468 var mergeablePseudoElements = options.compatibility.selectors.mergeablePseudoElements;
7469 var multiplePseudoMerging = options.compatibility.selectors.multiplePseudoMerging;
7470 var candidates = {};
7473 for (var i = tokens.length - 1; i >= 0; i--) {
7474 var token = tokens[i];
7476 if (token[0] != Token.RULE) {
7478 } else if (token[2].length === 0) {
7482 var selectorAsString = serializeRules(token[1]);
7483 var isComplexAndNotSpecial = token[1].length > 1 &&
7484 isMergeable(selectorAsString, mergeablePseudoClasses, mergeablePseudoElements, multiplePseudoMerging);
7485 var wrappedSelectors = wrappedSelectorsFrom(token[1]);
7486 var selectors = isComplexAndNotSpecial ?
7487 [selectorAsString].concat(wrappedSelectors) :
7490 for (var j = 0, m = selectors.length; j < m; j++) {
7491 var selector = selectors[j];
7493 if (!candidates[selector])
7494 candidates[selector] = [];
7496 repeated.push(selector);
7498 candidates[selector].push({
7500 list: wrappedSelectors,
7501 isPartial: isComplexAndNotSpecial && j > 0,
7502 isComplex: isComplexAndNotSpecial && j === 0
7507 reduceSimpleNonAdjacentCases(tokens, repeated, candidates, options, context);
7508 reduceComplexNonAdjacentCases(tokens, candidates, options, context);
7511 function wrappedSelectorsFrom(list) {
7514 for (var i = 0; i < list.length; i++) {
7515 wrapped.push([list[i][1]]);
7521 function reduceSimpleNonAdjacentCases(tokens, repeated, candidates, options, context) {
7522 function filterOut(idx, bodies) {
7523 return data[idx].isPartial && bodies.length === 0;
7526 function reduceBody(token, newBody, processedCount, tokenIdx) {
7527 if (!data[processedCount - tokenIdx - 1].isPartial)
7531 for (var i = 0, l = repeated.length; i < l; i++) {
7532 var selector = repeated[i];
7533 var data = candidates[selector];
7535 reduceSelector(tokens, data, {
7536 filterOut: filterOut,
7537 callback: reduceBody
7538 }, options, context);
7542 function reduceComplexNonAdjacentCases(tokens, candidates, options, context) {
7543 var mergeablePseudoClasses = options.compatibility.selectors.mergeablePseudoClasses;
7544 var mergeablePseudoElements = options.compatibility.selectors.mergeablePseudoElements;
7545 var multiplePseudoMerging = options.compatibility.selectors.multiplePseudoMerging;
7546 var localContext = {};
7548 function filterOut(idx) {
7549 return localContext.data[idx].where < localContext.intoPosition;
7552 function collectReducedBodies(token, newBody, processedCount, tokenIdx) {
7554 localContext.reducedBodies.push(newBody);
7558 for (var complexSelector in candidates) {
7559 var into = candidates[complexSelector];
7560 if (!into[0].isComplex)
7563 var intoPosition = into[into.length - 1].where;
7564 var intoToken = tokens[intoPosition];
7565 var reducedBodies = [];
7567 var selectors = isMergeable(complexSelector, mergeablePseudoClasses, mergeablePseudoElements, multiplePseudoMerging) ?
7571 localContext.intoPosition = intoPosition;
7572 localContext.reducedBodies = reducedBodies;
7574 for (var j = 0, m = selectors.length; j < m; j++) {
7575 var selector = selectors[j];
7576 var data = candidates[selector];
7578 if (data.length < 2)
7579 continue allSelectors;
7581 localContext.data = data;
7583 reduceSelector(tokens, data, {
7584 filterOut: filterOut,
7585 callback: collectReducedBodies
7586 }, options, context);
7588 if (serializeBody(reducedBodies[reducedBodies.length - 1]) != serializeBody(reducedBodies[0]))
7589 continue allSelectors;
7592 intoToken[2] = reducedBodies[0];
7596 function reduceSelector(tokens, data, context, options, outerContext) {
7598 var bodiesAsList = [];
7599 var processedTokens = [];
7601 for (var j = data.length - 1; j >= 0; j--) {
7602 if (context.filterOut(j, bodies))
7605 var where = data[j].where;
7606 var token = tokens[where];
7607 var clonedBody = cloneArray(token[2]);
7609 bodies = bodies.concat(clonedBody);
7610 bodiesAsList.push(clonedBody);
7611 processedTokens.push(where);
7614 optimizeProperties(bodies, true, false, outerContext);
7616 var processedCount = processedTokens.length;
7617 var propertyIdx = bodies.length - 1;
7618 var tokenIdx = processedCount - 1;
7620 while (tokenIdx >= 0) {
7621 if ((tokenIdx === 0 || (bodies[propertyIdx] && bodiesAsList[tokenIdx].indexOf(bodies[propertyIdx]) > -1)) && propertyIdx > -1) {
7626 var newBody = bodies.splice(propertyIdx + 1);
7627 context.callback(tokens[processedTokens[tokenIdx]], newBody, processedCount, tokenIdx);
7633 module.exports = reduceNonAdjacent;
7635 },{"../../tokenizer/token":84,"../../utils/clone-array":86,"../../writer/one-time":98,"./is-mergeable":24,"./properties/optimize":36}],43:[function(require,module,exports){
7636 var Token = require('../../tokenizer/token');
7638 var serializeAll = require('../../writer/one-time').all;
7640 var FONT_FACE_SCOPE = '@font-face';
7642 function removeDuplicateFontAtRules(tokens) {
7643 var fontAtRules = [];
7648 for (i = 0, l = tokens.length; i < l; i++) {
7651 if (token[0] != Token.AT_RULE_BLOCK && token[1][0][1] != FONT_FACE_SCOPE) {
7655 key = serializeAll([token]);
7657 if (fontAtRules.indexOf(key) > -1) {
7660 fontAtRules.push(key);
7665 module.exports = removeDuplicateFontAtRules;
7667 },{"../../tokenizer/token":84,"../../writer/one-time":98}],44:[function(require,module,exports){
7668 var Token = require('../../tokenizer/token');
7670 var serializeAll = require('../../writer/one-time').all;
7671 var serializeRules = require('../../writer/one-time').rules;
7673 function removeDuplicateMediaQueries(tokens) {
7674 var candidates = {};
7680 for (i = 0, l = tokens.length; i < l; i++) {
7682 if (token[0] != Token.NESTED_BLOCK) {
7686 key = serializeRules(token[1]) + '%' + serializeAll(token[2]);
7687 candidate = candidates[key];
7693 candidates[key] = token;
7697 module.exports = removeDuplicateMediaQueries;
7699 },{"../../tokenizer/token":84,"../../writer/one-time":98}],45:[function(require,module,exports){
7700 var Token = require('../../tokenizer/token');
7702 var serializeBody = require('../../writer/one-time').body;
7703 var serializeRules = require('../../writer/one-time').rules;
7705 function removeDuplicates(tokens) {
7707 var moreThanOnce = [];
7711 for (var i = 0, l = tokens.length; i < l; i++) {
7713 if (token[0] != Token.RULE)
7716 id = serializeRules(token[1]);
7718 if (matched[id] && matched[id].length == 1)
7719 moreThanOnce.push(id);
7721 matched[id] = matched[id] || [];
7723 matched[id].push(i);
7726 for (i = 0, l = moreThanOnce.length; i < l; i++) {
7727 id = moreThanOnce[i];
7730 for (var j = matched[id].length - 1; j >= 0; j--) {
7731 token = tokens[matched[id][j]];
7732 body = serializeBody(token[2]);
7734 if (bodies.indexOf(body) > -1)
7742 module.exports = removeDuplicates;
7744 },{"../../tokenizer/token":84,"../../writer/one-time":98}],46:[function(require,module,exports){
7745 var populateComponents = require('./properties/populate-components');
7747 var wrapForOptimizing = require('../wrap-for-optimizing').single;
7748 var restoreFromOptimizing = require('../restore-from-optimizing');
7750 var Token = require('../../tokenizer/token');
7752 var animationNameRegex = /^(\-moz\-|\-o\-|\-webkit\-)?animation-name$/;
7753 var animationRegex = /^(\-moz\-|\-o\-|\-webkit\-)?animation$/;
7754 var keyframeRegex = /^@(\-moz\-|\-o\-|\-webkit\-)?keyframes /;
7755 var importantRegex = /\s{0,31}!important$/;
7756 var optionalMatchingQuotesRegex = /^(['"]?)(.*)\1$/;
7758 function normalize(value) {
7760 .replace(optionalMatchingQuotesRegex, '$2')
7761 .replace(importantRegex, '');
7764 function removeUnusedAtRules(tokens, context) {
7765 removeUnusedAtRule(tokens, matchCounterStyle, markCounterStylesAsUsed, context);
7766 removeUnusedAtRule(tokens, matchFontFace, markFontFacesAsUsed, context);
7767 removeUnusedAtRule(tokens, matchKeyframe, markKeyframesAsUsed, context);
7768 removeUnusedAtRule(tokens, matchNamespace, markNamespacesAsUsed, context);
7771 function removeUnusedAtRule(tokens, matchCallback, markCallback, context) {
7779 for (i = 0, l = tokens.length; i < l; i++) {
7780 matchCallback(tokens[i], atRules);
7783 if (Object.keys(atRules).length === 0) {
7787 markUsedAtRules(tokens, markCallback, atRules, context);
7789 for (atRule in atRules) {
7790 atRuleTokens = atRules[atRule];
7792 for (i = 0, l = atRuleTokens.length; i < l; i++) {
7793 atRuleToken = atRuleTokens[i];
7794 zeroAt = atRuleToken[0] == Token.AT_RULE ? 1 : 2;
7795 atRuleToken[zeroAt] = [];
7800 function markUsedAtRules(tokens, markCallback, atRules, context) {
7801 var boundMarkCallback = markCallback(atRules);
7804 for (i = 0, l = tokens.length; i < l; i++) {
7805 switch (tokens[i][0]) {
7807 boundMarkCallback(tokens[i], context);
7809 case Token.NESTED_BLOCK:
7810 markUsedAtRules(tokens[i][2], markCallback, atRules, context);
7815 function matchCounterStyle(token, atRules) {
7818 if (token[0] == Token.AT_RULE_BLOCK && token[1][0][1].indexOf('@counter-style') === 0) {
7819 match = token[1][0][1].split(' ')[1];
7820 atRules[match] = atRules[match] || [];
7821 atRules[match].push(token);
7825 function markCounterStylesAsUsed(atRules) {
7826 return function (token, context) {
7828 var wrappedProperty;
7831 for (i = 0, l = token[2].length; i < l; i++) {
7832 property = token[2][i];
7834 if (property[1][1] == 'list-style') {
7835 wrappedProperty = wrapForOptimizing(property);
7836 populateComponents([wrappedProperty], context.validator, context.warnings);
7838 if (wrappedProperty.components[0].value[0][1] in atRules) {
7839 delete atRules[property[2][1]];
7842 restoreFromOptimizing([wrappedProperty]);
7845 if (property[1][1] == 'list-style-type' && property[2][1] in atRules) {
7846 delete atRules[property[2][1]];
7852 function matchFontFace(token, atRules) {
7857 if (token[0] == Token.AT_RULE_BLOCK && token[1][0][1] == '@font-face') {
7858 for (i = 0, l = token[2].length; i < l; i++) {
7859 property = token[2][i];
7861 if (property[1][1] == 'font-family') {
7862 match = normalize(property[2][1].toLowerCase());
7863 atRules[match] = atRules[match] || [];
7864 atRules[match].push(token);
7871 function markFontFacesAsUsed(atRules) {
7872 return function (token, context) {
7874 var wrappedProperty;
7876 var normalizedMatch;
7880 for (i = 0, l = token[2].length; i < l; i++) {
7881 property = token[2][i];
7883 if (property[1][1] == 'font') {
7884 wrappedProperty = wrapForOptimizing(property);
7885 populateComponents([wrappedProperty], context.validator, context.warnings);
7886 component = wrappedProperty.components[6];
7888 for (j = 0, m = component.value.length; j < m; j++) {
7889 normalizedMatch = normalize(component.value[j][1].toLowerCase());
7891 if (normalizedMatch in atRules) {
7892 delete atRules[normalizedMatch];
7896 restoreFromOptimizing([wrappedProperty]);
7899 if (property[1][1] == 'font-family') {
7900 for (j = 2, m = property.length; j < m; j++) {
7901 normalizedMatch = normalize(property[j][1].toLowerCase());
7903 if (normalizedMatch in atRules) {
7904 delete atRules[normalizedMatch];
7912 function matchKeyframe(token, atRules) {
7915 if (token[0] == Token.NESTED_BLOCK && keyframeRegex.test(token[1][0][1])) {
7916 match = token[1][0][1].split(' ')[1];
7917 atRules[match] = atRules[match] || [];
7918 atRules[match].push(token);
7922 function markKeyframesAsUsed(atRules) {
7923 return function (token, context) {
7925 var wrappedProperty;
7930 for (i = 0, l = token[2].length; i < l; i++) {
7931 property = token[2][i];
7933 if (animationRegex.test(property[1][1])) {
7934 wrappedProperty = wrapForOptimizing(property);
7935 populateComponents([wrappedProperty], context.validator, context.warnings);
7936 component = wrappedProperty.components[7];
7938 for (j = 0, m = component.value.length; j < m; j++) {
7939 if (component.value[j][1] in atRules) {
7940 delete atRules[component.value[j][1]];
7944 restoreFromOptimizing([wrappedProperty]);
7947 if (animationNameRegex.test(property[1][1])) {
7948 for (j = 2, m = property.length; j < m; j++) {
7949 if (property[j][1] in atRules) {
7950 delete atRules[property[j][1]];
7958 function matchNamespace(token, atRules) {
7961 if (token[0] == Token.AT_RULE && token[1].indexOf('@namespace') === 0) {
7962 match = token[1].split(' ')[1];
7963 atRules[match] = atRules[match] || [];
7964 atRules[match].push(token);
7968 function markNamespacesAsUsed(atRules) {
7969 var namespaceRegex = new RegExp(Object.keys(atRules).join('\\\||') + '\\\|', 'g');
7971 return function (token) {
7974 var normalizedMatch;
7978 for (i = 0, l = token[1].length; i < l; i++) {
7979 scope = token[1][i];
7980 match = scope[1].match(namespaceRegex);
7982 for (j = 0, m = match.length; j < m; j++) {
7983 normalizedMatch = match[j].substring(0, match[j].length - 1);
7985 if (normalizedMatch in atRules) {
7986 delete atRules[normalizedMatch];
7993 module.exports = removeUnusedAtRules;
7995 },{"../../tokenizer/token":84,"../restore-from-optimizing":56,"../wrap-for-optimizing":58,"./properties/populate-components":39}],47:[function(require,module,exports){
7996 // TODO: it'd be great to merge it with the other canReorder functionality
7998 var rulesOverlap = require('./rules-overlap');
7999 var specificitiesOverlap = require('./specificities-overlap');
8001 var FLEX_PROPERTIES = /align\-items|box\-align|box\-pack|flex|justify/;
8002 var BORDER_PROPERTIES = /^border\-(top|right|bottom|left|color|style|width|radius)/;
8004 function canReorder(left, right, cache) {
8005 for (var i = right.length - 1; i >= 0; i--) {
8006 for (var j = left.length - 1; j >= 0; j--) {
8007 if (!canReorderSingle(left[j], right[i], cache))
8015 function canReorderSingle(left, right, cache) {
8016 var leftName = left[0];
8017 var leftValue = left[1];
8018 var leftNameRoot = left[2];
8019 var leftSelector = left[5];
8020 var leftInSpecificSelector = left[6];
8021 var rightName = right[0];
8022 var rightValue = right[1];
8023 var rightNameRoot = right[2];
8024 var rightSelector = right[5];
8025 var rightInSpecificSelector = right[6];
8027 if (leftName == 'font' && rightName == 'line-height' || rightName == 'font' && leftName == 'line-height')
8029 if (FLEX_PROPERTIES.test(leftName) && FLEX_PROPERTIES.test(rightName))
8031 if (leftNameRoot == rightNameRoot && unprefixed(leftName) == unprefixed(rightName) && (vendorPrefixed(leftName) ^ vendorPrefixed(rightName)))
8033 if (leftNameRoot == 'border' && BORDER_PROPERTIES.test(rightNameRoot) && (leftName == 'border' || leftName == rightNameRoot || (leftValue != rightValue && sameBorderComponent(leftName, rightName))))
8035 if (rightNameRoot == 'border' && BORDER_PROPERTIES.test(leftNameRoot) && (rightName == 'border' || rightName == leftNameRoot || (leftValue != rightValue && sameBorderComponent(leftName, rightName))))
8037 if (leftNameRoot == 'border' && rightNameRoot == 'border' && leftName != rightName && (isSideBorder(leftName) && isStyleBorder(rightName) || isStyleBorder(leftName) && isSideBorder(rightName)))
8039 if (leftNameRoot != rightNameRoot)
8041 if (leftName == rightName && leftNameRoot == rightNameRoot && (leftValue == rightValue || withDifferentVendorPrefix(leftValue, rightValue)))
8043 if (leftName != rightName && leftNameRoot == rightNameRoot && leftName != leftNameRoot && rightName != rightNameRoot)
8045 if (leftName != rightName && leftNameRoot == rightNameRoot && leftValue == rightValue)
8047 if (rightInSpecificSelector && leftInSpecificSelector && !inheritable(leftNameRoot) && !inheritable(rightNameRoot) && !rulesOverlap(rightSelector, leftSelector, false))
8049 if (!specificitiesOverlap(leftSelector, rightSelector, cache))
8055 function vendorPrefixed(name) {
8056 return /^\-(?:moz|webkit|ms|o)\-/.test(name);
8059 function unprefixed(name) {
8060 return name.replace(/^\-(?:moz|webkit|ms|o)\-/, '');
8063 function sameBorderComponent(name1, name2) {
8064 return name1.split('-').pop() == name2.split('-').pop();
8067 function isSideBorder(name) {
8068 return name == 'border-top' || name == 'border-right' || name == 'border-bottom' || name == 'border-left';
8071 function isStyleBorder(name) {
8072 return name == 'border-color' || name == 'border-style' || name == 'border-width';
8075 function withDifferentVendorPrefix(value1, value2) {
8076 return vendorPrefixed(value1) && vendorPrefixed(value2) && value1.split('-')[1] != value2.split('-')[2];
8079 function inheritable(name) {
8080 // According to http://www.w3.org/TR/CSS21/propidx.html
8081 // Others will be catched by other, preceeding rules
8082 return name == 'font' || name == 'line-height' || name == 'list-style';
8086 canReorder: canReorder,
8087 canReorderSingle: canReorderSingle
8090 },{"./rules-overlap":51,"./specificities-overlap":52}],48:[function(require,module,exports){
8091 var compactable = require('./compactable');
8093 function restoreWithComponents(property) {
8094 var descriptor = compactable[property.name];
8096 if (descriptor && descriptor.shorthand) {
8097 return descriptor.restore(property, compactable);
8099 return property.value;
8103 module.exports = restoreWithComponents;
8105 },{"./compactable":21}],49:[function(require,module,exports){
8106 var shallowClone = require('./clone').shallow;
8108 var Token = require('../../tokenizer/token');
8109 var Marker = require('../../tokenizer/marker');
8111 function isInheritOnly(values) {
8112 for (var i = 0, l = values.length; i < l; i++) {
8113 var value = values[i][1];
8115 if (value != 'inherit' && value != Marker.COMMA && value != Marker.FORWARD_SLASH)
8122 function background(property, compactable, lastInMultiplex) {
8123 var components = property.components;
8125 var needsOne, needsBoth;
8127 function restoreValue(component) {
8128 Array.prototype.unshift.apply(restored, component.value);
8131 function isDefaultValue(component) {
8132 var descriptor = compactable[component.name];
8134 if (descriptor.doubleValues && descriptor.defaultValue.length == 1) {
8135 return component.value[0][1] == descriptor.defaultValue[0] && (component.value[1] ? component.value[1][1] == descriptor.defaultValue[0] : true);
8136 } else if (descriptor.doubleValues && descriptor.defaultValue.length != 1) {
8137 return component.value[0][1] == descriptor.defaultValue[0] && (component.value[1] ? component.value[1][1] : component.value[0][1]) == descriptor.defaultValue[1];
8139 return component.value[0][1] == descriptor.defaultValue;
8143 for (var i = components.length - 1; i >= 0; i--) {
8144 var component = components[i];
8145 var isDefault = isDefaultValue(component);
8147 if (component.name == 'background-clip') {
8148 var originComponent = components[i - 1];
8149 var isOriginDefault = isDefaultValue(originComponent);
8151 needsOne = component.value[0][1] == originComponent.value[0][1];
8153 needsBoth = !needsOne && (
8154 (isOriginDefault && !isDefault) ||
8155 (!isOriginDefault && !isDefault) ||
8156 (!isOriginDefault && isDefault && component.value[0][1] != originComponent.value[0][1]));
8159 restoreValue(originComponent);
8160 } else if (needsBoth) {
8161 restoreValue(component);
8162 restoreValue(originComponent);
8166 } else if (component.name == 'background-size') {
8167 var positionComponent = components[i - 1];
8168 var isPositionDefault = isDefaultValue(positionComponent);
8170 needsOne = !isPositionDefault && isDefault;
8172 needsBoth = !needsOne &&
8173 (isPositionDefault && !isDefault || !isPositionDefault && !isDefault);
8176 restoreValue(positionComponent);
8177 } else if (needsBoth) {
8178 restoreValue(component);
8179 restored.unshift([Token.PROPERTY_VALUE, Marker.FORWARD_SLASH]);
8180 restoreValue(positionComponent);
8181 } else if (positionComponent.value.length == 1) {
8182 restoreValue(positionComponent);
8187 if (isDefault || compactable[component.name].multiplexLastOnly && !lastInMultiplex)
8190 restoreValue(component);
8194 if (restored.length === 0 && property.value.length == 1 && property.value[0][1] == '0')
8195 restored.push(property.value[0]);
8197 if (restored.length === 0)
8198 restored.push([Token.PROPERTY_VALUE, compactable[property.name].defaultValue]);
8200 if (isInheritOnly(restored))
8201 return [restored[0]];
8206 function borderRadius(property, compactable) {
8207 if (property.multiplex) {
8208 var horizontal = shallowClone(property);
8209 var vertical = shallowClone(property);
8211 for (var i = 0; i < 4; i++) {
8212 var component = property.components[i];
8214 var horizontalComponent = shallowClone(property);
8215 horizontalComponent.value = [component.value[0]];
8216 horizontal.components.push(horizontalComponent);
8218 var verticalComponent = shallowClone(property);
8219 // FIXME: only shorthand compactor (see breakup#borderRadius) knows that border radius
8220 // longhands have two values, whereas tokenizer does not care about populating 2nd value
8221 // if it's missing, hence this fallback
8222 verticalComponent.value = [component.value[1] || component.value[0]];
8223 vertical.components.push(verticalComponent);
8226 var horizontalValues = fourValues(horizontal, compactable);
8227 var verticalValues = fourValues(vertical, compactable);
8229 if (horizontalValues.length == verticalValues.length &&
8230 horizontalValues[0][1] == verticalValues[0][1] &&
8231 (horizontalValues.length > 1 ? horizontalValues[1][1] == verticalValues[1][1] : true) &&
8232 (horizontalValues.length > 2 ? horizontalValues[2][1] == verticalValues[2][1] : true) &&
8233 (horizontalValues.length > 3 ? horizontalValues[3][1] == verticalValues[3][1] : true)) {
8234 return horizontalValues;
8236 return horizontalValues.concat([[Token.PROPERTY_VALUE, Marker.FORWARD_SLASH]]).concat(verticalValues);
8239 return fourValues(property, compactable);
8243 function font(property, compactable) {
8244 var components = property.components;
8247 var componentIndex = 0;
8248 var fontFamilyIndex = 0;
8250 if (property.value[0][1].indexOf(Marker.INTERNAL) === 0) {
8251 property.value[0][1] = property.value[0][1].substring(Marker.INTERNAL.length);
8252 return property.value;
8255 // first four components are optional
8256 while (componentIndex < 4) {
8257 component = components[componentIndex];
8259 if (component.value[0][1] != compactable[component.name].defaultValue) {
8260 Array.prototype.push.apply(restored, component.value);
8266 // then comes font-size
8267 Array.prototype.push.apply(restored, components[componentIndex].value);
8270 // then may come line-height
8271 if (components[componentIndex].value[0][1] != compactable[components[componentIndex].name].defaultValue) {
8272 Array.prototype.push.apply(restored, [[Token.PROPERTY_VALUE, Marker.FORWARD_SLASH]]);
8273 Array.prototype.push.apply(restored, components[componentIndex].value);
8278 // then comes font-family
8279 while (components[componentIndex].value[fontFamilyIndex]) {
8280 restored.push(components[componentIndex].value[fontFamilyIndex]);
8282 if (components[componentIndex].value[fontFamilyIndex + 1]) {
8283 restored.push([Token.PROPERTY_VALUE, Marker.COMMA]);
8289 if (isInheritOnly(restored)) {
8290 return [restored[0]];
8296 function fourValues(property) {
8297 var components = property.components;
8298 var value1 = components[0].value[0];
8299 var value2 = components[1].value[0];
8300 var value3 = components[2].value[0];
8301 var value4 = components[3].value[0];
8303 if (value1[1] == value2[1] && value1[1] == value3[1] && value1[1] == value4[1]) {
8305 } else if (value1[1] == value3[1] && value2[1] == value4[1]) {
8306 return [value1, value2];
8307 } else if (value2[1] == value4[1]) {
8308 return [value1, value2, value3];
8310 return [value1, value2, value3, value4];
8314 function multiplex(restoreWith) {
8315 return function (property, compactable) {
8316 if (!property.multiplex)
8317 return restoreWith(property, compactable, true);
8319 var multiplexSize = 0;
8321 var componentMultiplexSoFar = {};
8324 // At this point we don't know what's the multiplex size, e.g. how many background layers are there
8325 for (i = 0, l = property.components[0].value.length; i < l; i++) {
8326 if (property.components[0].value[i][1] == Marker.COMMA)
8330 for (i = 0; i <= multiplexSize; i++) {
8331 var _property = shallowClone(property);
8333 // We split multiplex into parts and restore them one by one
8334 for (var j = 0, m = property.components.length; j < m; j++) {
8335 var componentToClone = property.components[j];
8336 var _component = shallowClone(componentToClone);
8337 _property.components.push(_component);
8339 // The trick is some properties has more than one value, so we iterate over values looking for
8340 // a multiplex separator - a comma
8341 for (var k = componentMultiplexSoFar[_component.name] || 0, n = componentToClone.value.length; k < n; k++) {
8342 if (componentToClone.value[k][1] == Marker.COMMA) {
8343 componentMultiplexSoFar[_component.name] = k + 1;
8347 _component.value.push(componentToClone.value[k]);
8351 // No we can restore shorthand value
8352 var lastInMultiplex = i == multiplexSize;
8353 var _restored = restoreWith(_property, compactable, lastInMultiplex);
8354 Array.prototype.push.apply(restored, _restored);
8356 if (i < multiplexSize)
8357 restored.push([Token.PROPERTY_VALUE, Marker.COMMA]);
8364 function withoutDefaults(property, compactable) {
8365 var components = property.components;
8368 for (var i = components.length - 1; i >= 0; i--) {
8369 var component = components[i];
8370 var descriptor = compactable[component.name];
8372 if (component.value[0][1] != descriptor.defaultValue || ('keepUnlessDefault' in descriptor) && !isDefault(components, compactable, descriptor.keepUnlessDefault)) {
8373 restored.unshift(component.value[0]);
8377 if (restored.length === 0)
8378 restored.push([Token.PROPERTY_VALUE, compactable[property.name].defaultValue]);
8380 if (isInheritOnly(restored))
8381 return [restored[0]];
8386 function isDefault(components, compactable, propertyName) {
8390 for (i = 0, l = components.length; i < l; i++) {
8391 component = components[i];
8393 if (component.name == propertyName && component.value[0][1] == compactable[propertyName].defaultValue) {
8402 background: background,
8403 borderRadius: borderRadius,
8405 fourValues: fourValues,
8406 multiplex: multiplex,
8407 withoutDefaults: withoutDefaults
8410 },{"../../tokenizer/marker":83,"../../tokenizer/token":84,"./clone":20}],50:[function(require,module,exports){
8411 var canReorderSingle = require('./reorderable').canReorderSingle;
8412 var extractProperties = require('./extract-properties');
8413 var isMergeable = require('./is-mergeable');
8414 var tidyRuleDuplicates = require('./tidy-rule-duplicates');
8416 var Token = require('../../tokenizer/token');
8418 var cloneArray = require('../../utils/clone-array');
8420 var serializeBody = require('../../writer/one-time').body;
8421 var serializeRules = require('../../writer/one-time').rules;
8423 function naturalSorter(a, b) {
8424 return a > b ? 1 : -1;
8427 function cloneAndMergeSelectors(propertyA, propertyB) {
8428 var cloned = cloneArray(propertyA);
8429 cloned[5] = cloned[5].concat(propertyB[5]);
8434 function restructure(tokens, context) {
8435 var options = context.options;
8436 var mergeablePseudoClasses = options.compatibility.selectors.mergeablePseudoClasses;
8437 var mergeablePseudoElements = options.compatibility.selectors.mergeablePseudoElements;
8438 var mergeLimit = options.compatibility.selectors.mergeLimit;
8439 var multiplePseudoMerging = options.compatibility.selectors.multiplePseudoMerging;
8440 var specificityCache = context.cache.specificity;
8441 var movableTokens = {};
8442 var movedProperties = [];
8443 var multiPropertyMoveCache = {};
8444 var movedToBeDropped = [];
8445 var maxCombinationsLevel = 2;
8446 var ID_JOIN_CHARACTER = '%';
8448 function sendToMultiPropertyMoveCache(position, movedProperty, allFits) {
8449 for (var i = allFits.length - 1; i >= 0; i--) {
8450 var fit = allFits[i][0];
8451 var id = addToCache(movedProperty, fit);
8453 if (multiPropertyMoveCache[id].length > 1 && processMultiPropertyMove(position, multiPropertyMoveCache[id])) {
8454 removeAllMatchingFromCache(id);
8460 function addToCache(movedProperty, fit) {
8461 var id = cacheId(fit);
8462 multiPropertyMoveCache[id] = multiPropertyMoveCache[id] || [];
8463 multiPropertyMoveCache[id].push([movedProperty, fit]);
8467 function removeAllMatchingFromCache(matchId) {
8468 var matchSelectors = matchId.split(ID_JOIN_CHARACTER);
8469 var forRemoval = [];
8472 for (var id in multiPropertyMoveCache) {
8473 var selectors = id.split(ID_JOIN_CHARACTER);
8474 for (i = selectors.length - 1; i >= 0; i--) {
8475 if (matchSelectors.indexOf(selectors[i]) > -1) {
8476 forRemoval.push(id);
8482 for (i = forRemoval.length - 1; i >= 0; i--) {
8483 delete multiPropertyMoveCache[forRemoval[i]];
8487 function cacheId(cachedTokens) {
8489 for (var i = 0, l = cachedTokens.length; i < l; i++) {
8490 id.push(serializeRules(cachedTokens[i][1]));
8492 return id.join(ID_JOIN_CHARACTER);
8495 function tokensToMerge(sourceTokens) {
8496 var uniqueTokensWithBody = [];
8497 var mergeableTokens = [];
8499 for (var i = sourceTokens.length - 1; i >= 0; i--) {
8500 if (!isMergeable(serializeRules(sourceTokens[i][1]), mergeablePseudoClasses, mergeablePseudoElements, multiplePseudoMerging)) {
8504 mergeableTokens.unshift(sourceTokens[i]);
8505 if (sourceTokens[i][2].length > 0 && uniqueTokensWithBody.indexOf(sourceTokens[i]) == -1)
8506 uniqueTokensWithBody.push(sourceTokens[i]);
8509 return uniqueTokensWithBody.length > 1 ?
8514 function shortenIfPossible(position, movedProperty) {
8515 var name = movedProperty[0];
8516 var value = movedProperty[1];
8517 var key = movedProperty[4];
8518 var valueSize = name.length + value.length + 1;
8519 var allSelectors = [];
8520 var qualifiedTokens = [];
8522 var mergeableTokens = tokensToMerge(movableTokens[key]);
8523 if (mergeableTokens.length < 2)
8526 var allFits = findAllFits(mergeableTokens, valueSize, 1);
8527 var bestFit = allFits[0];
8529 return sendToMultiPropertyMoveCache(position, movedProperty, allFits);
8531 for (var i = bestFit[0].length - 1; i >=0; i--) {
8532 allSelectors = bestFit[0][i][1].concat(allSelectors);
8533 qualifiedTokens.unshift(bestFit[0][i]);
8536 allSelectors = tidyRuleDuplicates(allSelectors);
8537 dropAsNewTokenAt(position, [movedProperty], allSelectors, qualifiedTokens);
8540 function fitSorter(fit1, fit2) {
8541 return fit1[1] > fit2[1] ? 1 : (fit1[1] == fit2[1] ? 0 : -1);
8544 function findAllFits(mergeableTokens, propertySize, propertiesCount) {
8545 var combinations = allCombinations(mergeableTokens, propertySize, propertiesCount, maxCombinationsLevel - 1);
8546 return combinations.sort(fitSorter);
8549 function allCombinations(tokensVariant, propertySize, propertiesCount, level) {
8550 var differenceVariants = [[tokensVariant, sizeDifference(tokensVariant, propertySize, propertiesCount)]];
8551 if (tokensVariant.length > 2 && level > 0) {
8552 for (var i = tokensVariant.length - 1; i >= 0; i--) {
8553 var subVariant = Array.prototype.slice.call(tokensVariant, 0);
8554 subVariant.splice(i, 1);
8555 differenceVariants = differenceVariants.concat(allCombinations(subVariant, propertySize, propertiesCount, level - 1));
8559 return differenceVariants;
8562 function sizeDifference(tokensVariant, propertySize, propertiesCount) {
8563 var allSelectorsSize = 0;
8564 for (var i = tokensVariant.length - 1; i >= 0; i--) {
8565 allSelectorsSize += tokensVariant[i][2].length > propertiesCount ? serializeRules(tokensVariant[i][1]).length : -1;
8567 return allSelectorsSize - (tokensVariant.length - 1) * propertySize + 1;
8570 function dropAsNewTokenAt(position, properties, allSelectors, mergeableTokens) {
8572 var allProperties = [];
8574 for (i = mergeableTokens.length - 1; i >= 0; i--) {
8575 var mergeableToken = mergeableTokens[i];
8577 for (j = mergeableToken[2].length - 1; j >= 0; j--) {
8578 var mergeableProperty = mergeableToken[2][j];
8580 for (k = 0, m = properties.length; k < m; k++) {
8581 var property = properties[k];
8583 var mergeablePropertyName = mergeableProperty[1][1];
8584 var propertyName = property[0];
8585 var propertyBody = property[4];
8586 if (mergeablePropertyName == propertyName && serializeBody([mergeableProperty]) == propertyBody) {
8587 mergeableToken[2].splice(j, 1);
8594 for (i = properties.length - 1; i >= 0; i--) {
8595 allProperties.unshift(properties[i][3]);
8598 var newToken = [Token.RULE, allSelectors, allProperties];
8599 tokens.splice(position, 0, newToken);
8602 function dropPropertiesAt(position, movedProperty) {
8603 var key = movedProperty[4];
8604 var toMove = movableTokens[key];
8606 if (toMove && toMove.length > 1) {
8607 if (!shortenMultiMovesIfPossible(position, movedProperty))
8608 shortenIfPossible(position, movedProperty);
8612 function shortenMultiMovesIfPossible(position, movedProperty) {
8613 var candidates = [];
8614 var propertiesAndMergableTokens = [];
8615 var key = movedProperty[4];
8618 var mergeableTokens = tokensToMerge(movableTokens[key]);
8619 if (mergeableTokens.length < 2)
8623 for (var value in movableTokens) {
8624 var tokensList = movableTokens[value];
8626 for (j = mergeableTokens.length - 1; j >= 0; j--) {
8627 if (tokensList.indexOf(mergeableTokens[j]) == -1)
8628 continue movableLoop;
8631 candidates.push(value);
8634 if (candidates.length < 2)
8637 for (j = candidates.length - 1; j >= 0; j--) {
8638 for (k = movedProperties.length - 1; k >= 0; k--) {
8639 if (movedProperties[k][4] == candidates[j]) {
8640 propertiesAndMergableTokens.unshift([movedProperties[k], mergeableTokens]);
8646 return processMultiPropertyMove(position, propertiesAndMergableTokens);
8649 function processMultiPropertyMove(position, propertiesAndMergableTokens) {
8651 var properties = [];
8654 for (var i = propertiesAndMergableTokens.length - 1; i >= 0; i--) {
8655 property = propertiesAndMergableTokens[i][0];
8656 var fullValue = property[4];
8657 valueSize += fullValue.length + (i > 0 ? 1 : 0);
8659 properties.push(property);
8662 var mergeableTokens = propertiesAndMergableTokens[0][1];
8663 var bestFit = findAllFits(mergeableTokens, valueSize, properties.length)[0];
8667 var allSelectors = [];
8668 var qualifiedTokens = [];
8669 for (i = bestFit[0].length - 1; i >= 0; i--) {
8670 allSelectors = bestFit[0][i][1].concat(allSelectors);
8671 qualifiedTokens.unshift(bestFit[0][i]);
8674 allSelectors = tidyRuleDuplicates(allSelectors);
8675 dropAsNewTokenAt(position, properties, allSelectors, qualifiedTokens);
8677 for (i = properties.length - 1; i >= 0; i--) {
8678 property = properties[i];
8679 var index = movedProperties.indexOf(property);
8681 delete movableTokens[property[4]];
8683 if (index > -1 && movedToBeDropped.indexOf(index) == -1)
8684 movedToBeDropped.push(index);
8690 function boundToAnotherPropertyInCurrrentToken(property, movedProperty, token) {
8691 var propertyName = property[0];
8692 var movedPropertyName = movedProperty[0];
8693 if (propertyName != movedPropertyName)
8696 var key = movedProperty[4];
8697 var toMove = movableTokens[key];
8698 return toMove && toMove.indexOf(token) > -1;
8701 for (var i = tokens.length - 1; i >= 0; i--) {
8702 var token = tokens[i];
8707 if (token[0] == Token.RULE) {
8709 } else if (token[0] == Token.NESTED_BLOCK) {
8715 // We cache movedProperties.length as it may change in the loop
8716 var movedCount = movedProperties.length;
8718 var properties = extractProperties(token);
8719 movedToBeDropped = [];
8721 var unmovableInCurrentToken = [];
8722 for (j = properties.length - 1; j >= 0; j--) {
8723 for (k = j - 1; k >= 0; k--) {
8724 if (!canReorderSingle(properties[j], properties[k], specificityCache)) {
8725 unmovableInCurrentToken.push(j);
8731 for (j = properties.length - 1; j >= 0; j--) {
8732 var property = properties[j];
8733 var movedSameProperty = false;
8735 for (k = 0; k < movedCount; k++) {
8736 var movedProperty = movedProperties[k];
8738 if (movedToBeDropped.indexOf(k) == -1 && (!canReorderSingle(property, movedProperty, specificityCache) && !boundToAnotherPropertyInCurrrentToken(property, movedProperty, token) ||
8739 movableTokens[movedProperty[4]] && movableTokens[movedProperty[4]].length === mergeLimit)) {
8740 dropPropertiesAt(i + 1, movedProperty, token);
8742 if (movedToBeDropped.indexOf(k) == -1) {
8743 movedToBeDropped.push(k);
8744 delete movableTokens[movedProperty[4]];
8748 if (!movedSameProperty) {
8749 movedSameProperty = property[0] == movedProperty[0] && property[1] == movedProperty[1];
8751 if (movedSameProperty) {
8757 if (!isRule || unmovableInCurrentToken.indexOf(j) > -1)
8760 var key = property[4];
8762 if (movedSameProperty && movedProperties[samePropertyAt][5].length + property[5].length > mergeLimit) {
8763 dropPropertiesAt(i + 1, movedProperties[samePropertyAt]);
8764 movedProperties.splice(samePropertyAt, 1);
8765 movableTokens[key] = [token];
8766 movedSameProperty = false;
8768 movableTokens[key] = movableTokens[key] || [];
8769 movableTokens[key].push(token);
8772 if (movedSameProperty) {
8773 movedProperties[samePropertyAt] = cloneAndMergeSelectors(movedProperties[samePropertyAt], property);
8775 movedProperties.push(property);
8779 movedToBeDropped = movedToBeDropped.sort(naturalSorter);
8780 for (j = 0, m = movedToBeDropped.length; j < m; j++) {
8781 var dropAt = movedToBeDropped[j] - j;
8782 movedProperties.splice(dropAt, 1);
8786 var position = tokens[0] && tokens[0][0] == Token.AT_RULE && tokens[0][1].indexOf('@charset') === 0 ? 1 : 0;
8787 for (; position < tokens.length - 1; position++) {
8788 var isImportRule = tokens[position][0] === Token.AT_RULE && tokens[position][1].indexOf('@import') === 0;
8789 var isComment = tokens[position][0] === Token.COMMENT;
8790 if (!(isImportRule || isComment))
8794 for (i = 0; i < movedProperties.length; i++) {
8795 dropPropertiesAt(position, movedProperties[i]);
8799 module.exports = restructure;
8801 },{"../../tokenizer/token":84,"../../utils/clone-array":86,"../../writer/one-time":98,"./extract-properties":22,"./is-mergeable":24,"./reorderable":47,"./tidy-rule-duplicates":54}],51:[function(require,module,exports){
8802 var MODIFIER_PATTERN = /\-\-.+$/;
8804 function rulesOverlap(rule1, rule2, bemMode) {
8810 for (i = 0, l = rule1.length; i < l; i++) {
8811 scope1 = rule1[i][1];
8813 for (j = 0, m = rule2.length; j < m; j++) {
8814 scope2 = rule2[j][1];
8816 if (scope1 == scope2) {
8820 if (bemMode && withoutModifiers(scope1) == withoutModifiers(scope2)) {
8829 function withoutModifiers(scope) {
8830 return scope.replace(MODIFIER_PATTERN, '');
8833 module.exports = rulesOverlap;
8835 },{}],52:[function(require,module,exports){
8836 var specificity = require('./specificity');
8838 function specificitiesOverlap(selector1, selector2, cache) {
8844 for (i = 0, l = selector1.length; i < l; i++) {
8845 specificity1 = findSpecificity(selector1[i][1], cache);
8847 for (j = 0, m = selector2.length; j < m; j++) {
8848 specificity2 = findSpecificity(selector2[j][1], cache);
8850 if (specificity1[0] === specificity2[0] && specificity1[1] === specificity2[1] && specificity1[2] === specificity2[2]) {
8859 function findSpecificity(selector, cache) {
8862 if (!(selector in cache)) {
8863 cache[selector] = value = specificity(selector);
8866 return value || cache[selector];
8869 module.exports = specificitiesOverlap;
8871 },{"./specificity":53}],53:[function(require,module,exports){
8872 var Marker = require('../../tokenizer/marker');
8875 ADJACENT_SIBLING: '+',
8879 NON_ADJACENT_SIBLING: '~',
8883 var LETTER_PATTERN = /[a-zA-Z]/;
8884 var NOT_PREFIX = ':not(';
8885 var SEPARATOR_PATTERN = /[\s,\(>~\+]/;
8887 function specificity(selector) {
8888 var result = [0, 0, 0];
8893 var roundBracketLevel = 0;
8894 var couldIntroduceNewTypeSelector;
8895 var withinNotPseudoClass = false;
8896 var wasPseudoClass = false;
8899 for (i = 0, l = selector.length; i < l; i++) {
8900 character = selector[i];
8904 } else if (character == Marker.SINGLE_QUOTE && !isDoubleQuoted && !isSingleQuoted) {
8905 isSingleQuoted = true;
8906 } else if (character == Marker.SINGLE_QUOTE && !isDoubleQuoted && isSingleQuoted) {
8907 isSingleQuoted = false;
8908 } else if (character == Marker.DOUBLE_QUOTE && !isDoubleQuoted && !isSingleQuoted) {
8909 isDoubleQuoted = true;
8910 } else if (character == Marker.DOUBLE_QUOTE && isDoubleQuoted && !isSingleQuoted) {
8911 isDoubleQuoted = false;
8912 } else if (isSingleQuoted || isDoubleQuoted) {
8914 } else if (roundBracketLevel > 0 && !withinNotPseudoClass) {
8916 } else if (character == Marker.OPEN_ROUND_BRACKET) {
8917 roundBracketLevel++;
8918 } else if (character == Marker.CLOSE_ROUND_BRACKET && roundBracketLevel == 1) {
8919 roundBracketLevel--;
8920 withinNotPseudoClass = false;
8921 } else if (character == Marker.CLOSE_ROUND_BRACKET) {
8922 roundBracketLevel--;
8923 } else if (character == Selector.HASH) {
8925 } else if (character == Selector.DOT || character == Marker.OPEN_SQUARE_BRACKET) {
8927 } else if (character == Selector.PSEUDO && !wasPseudoClass && !isNotPseudoClass(selector, i)) {
8929 withinNotPseudoClass = false;
8930 } else if (character == Selector.PSEUDO) {
8931 withinNotPseudoClass = true;
8932 } else if ((i === 0 || couldIntroduceNewTypeSelector) && LETTER_PATTERN.test(character)) {
8936 isEscaped = character == Marker.BACK_SLASH;
8937 wasPseudoClass = character == Selector.PSEUDO;
8938 couldIntroduceNewTypeSelector = !isEscaped && SEPARATOR_PATTERN.test(character);
8944 function isNotPseudoClass(selector, index) {
8945 return selector.indexOf(NOT_PREFIX, index) === index;
8948 module.exports = specificity;
8950 },{"../../tokenizer/marker":83}],54:[function(require,module,exports){
8951 function ruleSorter(s1, s2) {
8952 return s1[1] > s2[1] ? 1 : -1;
8955 function tidyRuleDuplicates(rules) {
8959 for (var i = 0, l = rules.length; i < l; i++) {
8960 var rule = rules[i];
8962 if (repeated.indexOf(rule[1]) == -1) {
8963 repeated.push(rule[1]);
8968 return list.sort(ruleSorter);
8971 module.exports = tidyRuleDuplicates;
8973 },{}],55:[function(require,module,exports){
8974 function removeUnused(properties) {
8975 for (var i = properties.length - 1; i >= 0; i--) {
8976 var property = properties[i];
8978 if (property.unused) {
8979 property.all.splice(property.position, 1);
8984 module.exports = removeUnused;
8986 },{}],56:[function(require,module,exports){
8987 var Hack = require('./hack');
8989 var Marker = require('../tokenizer/marker');
8991 var ASTERISK_HACK = '*';
8992 var BACKSLASH_HACK = '\\';
8993 var IMPORTANT_TOKEN = '!important';
8994 var UNDERSCORE_HACK = '_';
8995 var BANG_HACK = '!ie';
8997 function restoreFromOptimizing(properties, restoreCallback) {
9003 for (i = properties.length - 1; i >= 0; i--) {
9004 property = properties[i];
9006 if (property.unused) {
9010 if (!property.dirty && !property.important && !property.hack) {
9014 if (restoreCallback) {
9015 restored = restoreCallback(property);
9016 property.value = restored;
9018 restored = property.value;
9021 if (property.important) {
9022 restoreImportant(property);
9025 if (property.hack) {
9026 restoreHack(property);
9029 if ('all' in property) {
9030 current = property.all[property.position];
9031 current[1][1] = property.name;
9033 current.splice(2, current.length - 1);
9034 Array.prototype.push.apply(current, restored);
9039 function restoreImportant(property) {
9040 property.value[property.value.length - 1][1] += IMPORTANT_TOKEN;
9043 function restoreHack(property) {
9044 if (property.hack[0] == Hack.UNDERSCORE) {
9045 property.name = UNDERSCORE_HACK + property.name;
9046 } else if (property.hack[0] == Hack.ASTERISK) {
9047 property.name = ASTERISK_HACK + property.name;
9048 } else if (property.hack[0] == Hack.BACKSLASH) {
9049 property.value[property.value.length - 1][1] += BACKSLASH_HACK + property.hack[1];
9050 } else if (property.hack[0] == Hack.BANG) {
9051 property.value[property.value.length - 1][1] += Marker.SPACE + BANG_HACK;
9055 module.exports = restoreFromOptimizing;
9057 },{"../tokenizer/marker":83,"./hack":8}],57:[function(require,module,exports){
9058 var functionNoVendorRegexStr = '[A-Z]+(\\-|[A-Z]|[0-9])+\\(.*?\\)';
9059 var functionVendorRegexStr = '\\-(\\-|[A-Z]|[0-9])+\\(.*?\\)';
9060 var variableRegexStr = 'var\\(\\-\\-[^\\)]+\\)';
9061 var functionAnyRegexStr = '(' + variableRegexStr + '|' + functionNoVendorRegexStr + '|' + functionVendorRegexStr + ')';
9063 var calcRegex = new RegExp('^(\\-moz\\-|\\-webkit\\-)?calc\\([^\\)]+\\)$', 'i');
9064 var decimalRegex = /[0-9]/;
9065 var functionAnyRegex = new RegExp('^' + functionAnyRegexStr + '$', 'i');
9066 var hslColorRegex = /^hsl\(\s{0,31}[\-\.]?\d+\s{0,31},\s{0,31}\.?\d+%\s{0,31},\s{0,31}\.?\d+%\s{0,31}\)|hsla\(\s{0,31}[\-\.]?\d+\s{0,31},\s{0,31}\.?\d+%\s{0,31},\s{0,31}\.?\d+%\s{0,31},\s{0,31}\.?\d+\s{0,31}\)$/;
9067 var identifierRegex = /^(\-[a-z0-9_][a-z0-9\-_]*|[a-z][a-z0-9\-_]*)$/i;
9068 var namedEntityRegex = /^[a-z]+$/i;
9069 var prefixRegex = /^-([a-z0-9]|-)*$/i;
9070 var rgbColorRegex = /^rgb\(\s{0,31}[\d]{1,3}\s{0,31},\s{0,31}[\d]{1,3}\s{0,31},\s{0,31}[\d]{1,3}\s{0,31}\)|rgba\(\s{0,31}[\d]{1,3}\s{0,31},\s{0,31}[\d]{1,3}\s{0,31},\s{0,31}[\d]{1,3}\s{0,31},\s{0,31}[\.\d]+\s{0,31}\)$/;
9071 var timingFunctionRegex = /^(cubic\-bezier|steps)\([^\)]+\)$/;
9072 var validTimeUnits = ['ms', 's'];
9073 var urlRegex = /^url\([\s\S]+\)$/i;
9074 var variableRegex = new RegExp('^' + variableRegexStr + '$', 'i');
9076 var eightValueColorRegex = /^#[0-9a-f]{8}$/i;
9077 var fourValueColorRegex = /^#[0-9a-f]{4}$/i;
9078 var sixValueColorRegex = /^#[0-9a-f]{6}$/i;
9079 var threeValueColorRegex = /^#[0-9a-f]{3}$/i;
9081 var DECIMAL_DOT = '.';
9082 var MINUS_SIGN = '-';
9083 var PLUS_SIGN = '+';
9104 '*-timing-function': [
9113 'animation-direction': [
9115 'alternate-reverse',
9119 'animation-fill-mode': [
9125 'animation-iteration-count': [
9131 'animation-play-state': [
9135 'background-attachment': [
9141 'background-clip': [
9148 'background-origin': [
9154 'background-position': [
9161 'background-repeat': [
9170 'background-size': [
9175 'border-collapse': [
9228 'table-column-group',
9229 'table-footer-group',
9230 'table-header-group',
9300 'list-style-position': [
9304 'list-style-type': [
9308 'decimal-leading-zero',
9310 'decimal|disc', // this is the default value of list-style-type, see comment in compactable.js
9341 'left|right', // this is the default value of list-style-type, see comment in compactable.js
9344 'text-decoration': [
9405 function isColor(value) {
9406 return value != 'auto' &&
9408 isKeyword('color')(value) ||
9409 isHexColor(value) ||
9410 isColorFunction(value) ||
9411 isNamedEntity(value)
9415 function isColorFunction(value) {
9416 return isRgbColor(value) || isHslColor(value);
9419 function isDynamicUnit(value) {
9420 return calcRegex.test(value);
9423 function isFunction(value) {
9424 return functionAnyRegex.test(value);
9427 function isHexColor(value) {
9428 return threeValueColorRegex.test(value) || fourValueColorRegex.test(value) || sixValueColorRegex.test(value) || eightValueColorRegex.test(value);
9431 function isHslColor(value) {
9432 return hslColorRegex.test(value);
9435 function isIdentifier(value) {
9436 return identifierRegex.test(value);
9439 function isImage(value) {
9440 return value == 'none' || value == 'inherit' || isUrl(value);
9443 function isKeyword(propertyName) {
9444 return function(value) {
9445 return Keywords[propertyName].indexOf(value) > -1;
9449 function isNamedEntity(value) {
9450 return namedEntityRegex.test(value);
9453 function isNumber(value) {
9454 return scanForNumber(value) == value.length;
9457 function isRgbColor(value) {
9458 return rgbColorRegex.test(value);
9461 function isPrefixed(value) {
9462 return prefixRegex.test(value);
9465 function isPositiveNumber(value) {
9466 return isNumber(value) &&
9467 parseFloat(value) >= 0;
9470 function isVariable(value) {
9471 return variableRegex.test(value);
9474 function isTime(value) {
9475 var numberUpTo = scanForNumber(value);
9477 return numberUpTo == value.length && parseInt(value) === 0 ||
9478 numberUpTo > -1 && validTimeUnits.indexOf(value.slice(numberUpTo + 1)) > -1;
9481 function isTimingFunction() {
9482 var isTimingFunctionKeyword = isKeyword('*-timing-function');
9484 return function (value) {
9485 return isTimingFunctionKeyword(value) || timingFunctionRegex.test(value);
9489 function isUnit(validUnits, value) {
9490 var numberUpTo = scanForNumber(value);
9492 return numberUpTo == value.length && parseInt(value) === 0 ||
9493 numberUpTo > -1 && validUnits.indexOf(value.slice(numberUpTo + 1)) > -1 ||
9498 function isUrl(value) {
9499 return urlRegex.test(value);
9502 function isZIndex(value) {
9503 return value == 'auto' ||
9505 isKeyword('^')(value);
9508 function scanForNumber(value) {
9510 var hasSign = false;
9514 for (i = 0, l = value.length; i < l; i++) {
9515 character = value[i];
9517 if (i === 0 && (character == PLUS_SIGN || character == MINUS_SIGN)) {
9519 } else if (i > 0 && hasSign && (character == PLUS_SIGN || character == MINUS_SIGN)) {
9521 } else if (character == DECIMAL_DOT && !hasDot) {
9523 } else if (character == DECIMAL_DOT && hasDot) {
9525 } else if (decimalRegex.test(character)) {
9535 function validator(compatibility) {
9536 var validUnits = Units.slice(0).filter(function (value) {
9537 return !(value in compatibility.units) || compatibility.units[value] === true;
9541 colorOpacity: compatibility.colors.opacity,
9542 isAnimationDirectionKeyword: isKeyword('animation-direction'),
9543 isAnimationFillModeKeyword: isKeyword('animation-fill-mode'),
9544 isAnimationIterationCountKeyword: isKeyword('animation-iteration-count'),
9545 isAnimationNameKeyword: isKeyword('animation-name'),
9546 isAnimationPlayStateKeyword: isKeyword('animation-play-state'),
9547 isTimingFunction: isTimingFunction(),
9548 isBackgroundAttachmentKeyword: isKeyword('background-attachment'),
9549 isBackgroundClipKeyword: isKeyword('background-clip'),
9550 isBackgroundOriginKeyword: isKeyword('background-origin'),
9551 isBackgroundPositionKeyword: isKeyword('background-position'),
9552 isBackgroundRepeatKeyword: isKeyword('background-repeat'),
9553 isBackgroundSizeKeyword: isKeyword('background-size'),
9555 isColorFunction: isColorFunction,
9556 isDynamicUnit: isDynamicUnit,
9557 isFontKeyword: isKeyword('font'),
9558 isFontSizeKeyword: isKeyword('font-size'),
9559 isFontStretchKeyword: isKeyword('font-stretch'),
9560 isFontStyleKeyword: isKeyword('font-style'),
9561 isFontVariantKeyword: isKeyword('font-variant'),
9562 isFontWeightKeyword: isKeyword('font-weight'),
9563 isFunction: isFunction,
9564 isGlobal: isKeyword('^'),
9565 isHslColor: isHslColor,
9566 isIdentifier: isIdentifier,
9568 isKeyword: isKeyword,
9569 isLineHeightKeyword: isKeyword('line-height'),
9570 isListStylePositionKeyword: isKeyword('list-style-position'),
9571 isListStyleTypeKeyword: isKeyword('list-style-type'),
9573 isPrefixed: isPrefixed,
9574 isPositiveNumber: isPositiveNumber,
9575 isRgbColor: isRgbColor,
9576 isStyleKeyword: isKeyword('*-style'),
9578 isUnit: isUnit.bind(null, validUnits),
9580 isVariable: isVariable,
9581 isWidth: isKeyword('width'),
9586 module.exports = validator;
9588 },{}],58:[function(require,module,exports){
9589 var Hack = require('./hack');
9591 var Marker = require('../tokenizer/marker');
9592 var Token = require('../tokenizer/token');
9598 BANG_SUFFIX_PATTERN: /!\w+$/,
9599 IMPORTANT_TOKEN: '!important',
9600 IMPORTANT_TOKEN_PATTERN: new RegExp('!important$', 'i'),
9601 IMPORTANT_WORD: 'important',
9602 IMPORTANT_WORD_PATTERN: new RegExp('important$', 'i'),
9603 SUFFIX_BANG_PATTERN: /!$/,
9605 VARIABLE_REFERENCE_PATTERN: /var\(--.+\)$/
9608 function wrapAll(properties, includeVariable, skipProperties) {
9614 for (i = properties.length - 1; i >= 0; i--) {
9615 property = properties[i];
9617 if (property[0] != Token.PROPERTY) {
9621 if (!includeVariable && someVariableReferences(property)) {
9625 if (skipProperties && skipProperties.indexOf(property[1][1]) > -1) {
9629 single = wrapSingle(property);
9630 single.all = properties;
9631 single.position = i;
9632 wrapped.unshift(single);
9638 function someVariableReferences(property) {
9642 // skipping `property` and property name tokens
9643 for (i = 2, l = property.length; i < l; i++) {
9644 value = property[i];
9646 if (value[0] != Token.PROPERTY_VALUE) {
9650 if (isVariableReference(value[1])) {
9658 function isVariableReference(value) {
9659 return Match.VARIABLE_REFERENCE_PATTERN.test(value);
9662 function isMultiplex(property) {
9666 for (i = 3, l = property.length; i < l; i++) {
9667 value = property[i];
9669 if (value[0] == Token.PROPERTY_VALUE && (value[1] == Marker.COMMA || value[1] == Marker.FORWARD_SLASH)) {
9677 function hackFrom(property) {
9679 var name = property[1][1];
9680 var lastValue = property[property.length - 1];
9682 if (name[0] == Match.UNDERSCORE) {
9683 match = [Hack.UNDERSCORE];
9684 } else if (name[0] == Match.ASTERISK) {
9685 match = [Hack.ASTERISK];
9686 } else if (lastValue[1][0] == Match.BANG && !lastValue[1].match(Match.IMPORTANT_WORD_PATTERN)) {
9687 match = [Hack.BANG];
9688 } else if (lastValue[1].indexOf(Match.BANG) > 0 && !lastValue[1].match(Match.IMPORTANT_WORD_PATTERN) && Match.BANG_SUFFIX_PATTERN.test(lastValue[1])) {
9689 match = [Hack.BANG];
9690 } else if (lastValue[1].indexOf(Match.BACKSLASH) > 0 && lastValue[1].indexOf(Match.BACKSLASH) == lastValue[1].length - Match.BACKSLASH.length - 1) {
9691 match = [Hack.BACKSLASH, lastValue[1].substring(lastValue[1].indexOf(Match.BACKSLASH) + 1)];
9692 } else if (lastValue[1].indexOf(Match.BACKSLASH) === 0 && lastValue[1].length == 2) {
9693 match = [Hack.BACKSLASH, lastValue[1].substring(1)];
9699 function isImportant(property) {
9700 if (property.length < 3)
9703 var lastValue = property[property.length - 1];
9704 if (Match.IMPORTANT_TOKEN_PATTERN.test(lastValue[1])) {
9706 } else if (Match.IMPORTANT_WORD_PATTERN.test(lastValue[1]) && Match.SUFFIX_BANG_PATTERN.test(property[property.length - 2][1])) {
9713 function stripImportant(property) {
9714 var lastValue = property[property.length - 1];
9715 var oneButLastValue = property[property.length - 2];
9717 if (Match.IMPORTANT_TOKEN_PATTERN.test(lastValue[1])) {
9718 lastValue[1] = lastValue[1].replace(Match.IMPORTANT_TOKEN_PATTERN, '');
9720 lastValue[1] = lastValue[1].replace(Match.IMPORTANT_WORD_PATTERN, '');
9721 oneButLastValue[1] = oneButLastValue[1].replace(Match.SUFFIX_BANG_PATTERN, '');
9724 if (lastValue[1].length === 0) {
9728 if (oneButLastValue[1].length === 0) {
9733 function stripPrefixHack(property) {
9734 property[1][1] = property[1][1].substring(1);
9737 function stripSuffixHack(property, hackFrom) {
9738 var lastValue = property[property.length - 1];
9739 lastValue[1] = lastValue[1]
9740 .substring(0, lastValue[1].indexOf(hackFrom[0] == Hack.BACKSLASH ? Match.BACKSLASH : Match.BANG))
9743 if (lastValue[1].length === 0) {
9748 function wrapSingle(property) {
9749 var importantProperty = isImportant(property);
9750 if (importantProperty) {
9751 stripImportant(property);
9754 var whichHack = hackFrom(property);
9755 if (whichHack[0] == Hack.ASTERISK || whichHack[0] == Hack.UNDERSCORE) {
9756 stripPrefixHack(property);
9757 } else if (whichHack[0] == Hack.BACKSLASH || whichHack[0] == Hack.BANG) {
9758 stripSuffixHack(property, whichHack);
9762 block: property[2] && property[2][0] == Token.PROPERTY_BLOCK,
9766 important: importantProperty,
9767 name: property[1][1],
9768 multiplex: property.length > 3 ? isMultiplex(property) : false,
9772 value: property.slice(2)
9781 },{"../tokenizer/marker":83,"../tokenizer/token":84,"./hack":8}],59:[function(require,module,exports){
9785 opacity: true // rgba / hsla
9788 backgroundClipMerging: true, // background-clip to shorthand
9789 backgroundOriginMerging: true, // background-origin to shorthand
9790 backgroundSizeMerging: true, // background-size to shorthand
9791 colors: true, // any kind of color transformations, like `#ff00ff` to `#f0f` or `#fff` into `red`
9792 ieBangHack: false, // !ie suffix hacks on IE<8
9793 ieFilters: false, // whether to preserve `filter` and `-ms-filter` properties
9794 iePrefixHack: false, // underscore / asterisk prefix hacks on IE
9795 ieSuffixHack: false, // \9 suffix hacks on IE6-9
9796 merging: true, // merging properties into one
9797 shorterLengthUnits: false, // optimize pixel units into `pt`, `pc` or `in` units
9798 spaceAfterClosingBrace: true, // 'url() no-repeat' to 'url()no-repeat'
9799 urlQuotes: false, // whether to wrap content of `url()` into quotes or not
9800 zeroUnits: true // 0[unit] -> 0
9803 adjacentSpace: false, // div+ nav Android stock browser hack
9804 ie7Hack: false, // *+html hack
9805 mergeablePseudoClasses: [
9827 ':nth-last-of-type',
9834 ], // selectors with these pseudo-classes can be merged as these are universally supported
9835 mergeablePseudoElements: [
9840 ], // selectors with these pseudo-elements can be merged as these are universally supported
9841 mergeLimit: 8191, // number of rules that can be safely merged together
9842 multiplePseudoMerging: true
9851 vm: true, // vm is vmin on IE9+ see https://developer.mozilla.org/en-US/docs/Web/CSS/length
9859 DEFAULTS.ie11 = DEFAULTS['*'];
9861 DEFAULTS.ie10 = DEFAULTS['*'];
9863 DEFAULTS.ie9 = merge(DEFAULTS['*'], {
9870 DEFAULTS.ie8 = merge(DEFAULTS.ie9, {
9875 backgroundClipMerging: false,
9876 backgroundOriginMerging: false,
9877 backgroundSizeMerging: false,
9882 mergeablePseudoClasses: [
9891 mergeablePseudoElements: []
9904 DEFAULTS.ie7 = merge(DEFAULTS.ie8, {
9910 mergeablePseudoClasses: [
9919 function compatibilityFrom(source) {
9920 return merge(DEFAULTS['*'], calculateSource(source));
9923 function merge(source, target) {
9924 for (var key in source) {
9925 var value = source[key];
9927 if (typeof value === 'object' && !Array.isArray(value)) {
9928 target[key] = merge(value, target[key] || {});
9930 target[key] = key in target ? target[key] : value;
9937 function calculateSource(source) {
9938 if (typeof source == 'object')
9941 if (!/[,\+\-]/.test(source))
9942 return DEFAULTS[source] || DEFAULTS['*'];
9944 var parts = source.split(',');
9945 var template = parts[0] in DEFAULTS ?
9946 DEFAULTS[parts.shift()] :
9951 parts.forEach(function (part) {
9952 var isAdd = part[0] == '+';
9953 var key = part.substring(1).split('.');
9955 var option = key[1];
9957 source[group] = source[group] || {};
9958 source[group][option] = isAdd;
9961 return merge(template, source);
9964 module.exports = compatibilityFrom;
9966 },{}],60:[function(require,module,exports){
9967 var loadRemoteResource = require('../reader/load-remote-resource');
9969 function fetchFrom(callback) {
9970 return callback || loadRemoteResource;
9973 module.exports = fetchFrom;
9975 },{"../reader/load-remote-resource":74}],61:[function(require,module,exports){
9976 var systemLineBreak = require('os').EOL;
9978 var override = require('../utils/override');
9981 AfterAtRule: 'afterAtRule',
9982 AfterBlockBegins: 'afterBlockBegins',
9983 AfterBlockEnds: 'afterBlockEnds',
9984 AfterComment: 'afterComment',
9985 AfterProperty: 'afterProperty',
9986 AfterRuleBegins: 'afterRuleBegins',
9987 AfterRuleEnds: 'afterRuleEnds',
9988 BeforeBlockEnds: 'beforeBlockEnds',
9989 BetweenSelectors: 'betweenSelectors'
9993 CarriageReturnLineFeed: '\r\n',
9995 System: systemLineBreak
10004 AroundSelectorRelation: 'aroundSelectorRelation',
10005 BeforeBlockBegins: 'beforeBlockBegins',
10006 BeforeValue: 'beforeValue'
10010 breaks: breaks(false),
10011 breakWith: BreakWith.System,
10013 indentWith: IndentWith.Space,
10014 spaces: spaces(false),
10016 semicolonAfterLastProperty: false
10019 var BEAUTIFY_ALIAS = 'beautify';
10020 var KEEP_BREAKS_ALIAS = 'keep-breaks';
10022 var OPTION_SEPARATOR = ';';
10023 var OPTION_NAME_VALUE_SEPARATOR = ':';
10024 var HASH_VALUES_OPTION_SEPARATOR = ',';
10025 var HASH_VALUES_NAME_VALUE_SEPARATOR = '=';
10027 var FALSE_KEYWORD_1 = 'false';
10028 var FALSE_KEYWORD_2 = 'off';
10029 var TRUE_KEYWORD_1 = 'true';
10030 var TRUE_KEYWORD_2 = 'on';
10032 function breaks(value) {
10033 var breakOptions = {};
10035 breakOptions[Breaks.AfterAtRule] = value;
10036 breakOptions[Breaks.AfterBlockBegins] = value;
10037 breakOptions[Breaks.AfterBlockEnds] = value;
10038 breakOptions[Breaks.AfterComment] = value;
10039 breakOptions[Breaks.AfterProperty] = value;
10040 breakOptions[Breaks.AfterRuleBegins] = value;
10041 breakOptions[Breaks.AfterRuleEnds] = value;
10042 breakOptions[Breaks.BeforeBlockEnds] = value;
10043 breakOptions[Breaks.BetweenSelectors] = value;
10045 return breakOptions;
10048 function spaces(value) {
10049 var spaceOptions = {};
10051 spaceOptions[Spaces.AroundSelectorRelation] = value;
10052 spaceOptions[Spaces.BeforeBlockBegins] = value;
10053 spaceOptions[Spaces.BeforeValue] = value;
10055 return spaceOptions;
10058 function formatFrom(source) {
10059 if (source === undefined || source === false) {
10063 if (typeof source == 'object' && 'breakWith' in source) {
10064 source = override(source, { breakWith: mapBreakWith(source.breakWith) });
10067 if (typeof source == 'object' && 'indentBy' in source) {
10068 source = override(source, { indentBy: parseInt(source.indentBy) });
10071 if (typeof source == 'object' && 'indentWith' in source) {
10072 source = override(source, { indentWith: mapIndentWith(source.indentWith) });
10075 if (typeof source == 'object') {
10076 return override(DEFAULTS, source);
10079 if (typeof source == 'object') {
10080 return override(DEFAULTS, source);
10083 if (typeof source == 'string' && source == BEAUTIFY_ALIAS) {
10084 return override(DEFAULTS, {
10085 breaks: breaks(true),
10087 spaces: spaces(true)
10091 if (typeof source == 'string' && source == KEEP_BREAKS_ALIAS) {
10092 return override(DEFAULTS, {
10095 afterBlockBegins: true,
10096 afterBlockEnds: true,
10097 afterComment: true,
10098 afterRuleEnds: true,
10099 beforeBlockEnds: true
10104 if (typeof source == 'string') {
10105 return override(DEFAULTS, toHash(source));
10111 function toHash(string) {
10113 .split(OPTION_SEPARATOR)
10114 .reduce(function (accumulator, directive) {
10115 var parts = directive.split(OPTION_NAME_VALUE_SEPARATOR);
10116 var name = parts[0];
10117 var value = parts[1];
10119 if (name == 'breaks' || name == 'spaces') {
10120 accumulator[name] = hashValuesToHash(value);
10121 } else if (name == 'indentBy' || name == 'wrapAt') {
10122 accumulator[name] = parseInt(value);
10123 } else if (name == 'indentWith') {
10124 accumulator[name] = mapIndentWith(value);
10125 } else if (name == 'breakWith') {
10126 accumulator[name] = mapBreakWith(value);
10129 return accumulator;
10133 function hashValuesToHash(string) {
10135 .split(HASH_VALUES_OPTION_SEPARATOR)
10136 .reduce(function (accumulator, directive) {
10137 var parts = directive.split(HASH_VALUES_NAME_VALUE_SEPARATOR);
10138 var name = parts[0];
10139 var value = parts[1];
10141 accumulator[name] = normalizeValue(value);
10143 return accumulator;
10148 function normalizeValue(value) {
10150 case FALSE_KEYWORD_1:
10151 case FALSE_KEYWORD_2:
10153 case TRUE_KEYWORD_1:
10154 case TRUE_KEYWORD_2:
10161 function mapBreakWith(value) {
10165 case BreakWith.CarriageReturnLineFeed:
10166 return BreakWith.CarriageReturnLineFeed;
10169 case BreakWith.LineFeed:
10170 return BreakWith.LineFeed;
10172 return systemLineBreak;
10176 function mapIndentWith(value) {
10179 return IndentWith.Space;
10181 return IndentWith.Tab;
10190 formatFrom: formatFrom
10193 },{"../utils/override":95,"os":109}],62:[function(require,module,exports){
10194 (function (process){
10195 var url = require('url');
10197 var override = require('../utils/override');
10199 function inlineRequestFrom(option) {
10201 /* jshint camelcase: false */
10202 proxyOptionsFrom(process.env.HTTP_PROXY || process.env.http_proxy),
10207 function proxyOptionsFrom(httpProxy) {
10210 hostname: url.parse(httpProxy).hostname,
10211 port: parseInt(url.parse(httpProxy).port)
10216 module.exports = inlineRequestFrom;
10218 }).call(this,require('_process'))
10219 },{"../utils/override":95,"_process":112,"url":162}],63:[function(require,module,exports){
10220 var DEFAULT_TIMEOUT = 5000;
10222 function inlineTimeoutFrom(option) {
10223 return option || DEFAULT_TIMEOUT;
10226 module.exports = inlineTimeoutFrom;
10228 },{}],64:[function(require,module,exports){
10229 function inlineOptionsFrom(rules) {
10230 if (Array.isArray(rules)) {
10234 if (rules === false) {
10238 return undefined === rules ?
10243 module.exports = inlineOptionsFrom;
10245 },{}],65:[function(require,module,exports){
10246 var roundingPrecisionFrom = require('./rounding-precision').roundingPrecisionFrom;
10248 var override = require('../utils/override');
10250 var OptimizationLevel = {
10258 DEFAULTS[OptimizationLevel.Zero] = {};
10259 DEFAULTS[OptimizationLevel.One] = {
10260 cleanupCharsets: true,
10261 normalizeUrls: true,
10262 optimizeBackground: true,
10263 optimizeBorderRadius: true,
10264 optimizeFilter: true,
10265 optimizeFontWeight: true,
10266 optimizeOutline: true,
10268 removeNegativePaddings: true,
10269 removeQuotes: true,
10270 removeWhitespace: true,
10271 replaceMultipleZeros: true,
10272 replaceTimeUnits: true,
10273 replaceZeroUnits: true,
10274 roundingPrecision: roundingPrecisionFrom(undefined),
10275 selectorsSortingMethod: 'standard',
10276 specialComments: 'all',
10278 tidyBlockScopes: true,
10279 tidySelectors: true,
10282 DEFAULTS[OptimizationLevel.Two] = {
10283 mergeAdjacentRules: true,
10284 mergeIntoShorthands: true,
10286 mergeNonAdjacentRules: true,
10287 mergeSemantically: false,
10288 overrideProperties: true,
10290 reduceNonAdjacentRules: true,
10291 removeDuplicateFontRules: true,
10292 removeDuplicateMediaBlocks: true,
10293 removeDuplicateRules: true,
10294 removeUnusedAtRules: false,
10295 restructureRules: false,
10299 var ALL_KEYWORD_1 = '*';
10300 var ALL_KEYWORD_2 = 'all';
10301 var FALSE_KEYWORD_1 = 'false';
10302 var FALSE_KEYWORD_2 = 'off';
10303 var TRUE_KEYWORD_1 = 'true';
10304 var TRUE_KEYWORD_2 = 'on';
10306 var LIST_VALUE_SEPARATOR = ',';
10307 var OPTION_SEPARATOR = ';';
10308 var OPTION_VALUE_SEPARATOR = ':';
10312 function optimizationLevelFrom(source) {
10313 var level = override(DEFAULTS, {});
10314 var Zero = OptimizationLevel.Zero;
10315 var One = OptimizationLevel.One;
10316 var Two = OptimizationLevel.Two;
10319 if (undefined === source) {
10324 if (typeof source == 'string') {
10325 source = parseInt(source);
10328 if (typeof source == 'number' && source === parseInt(Two)) {
10332 if (typeof source == 'number' && source === parseInt(One)) {
10337 if (typeof source == 'number' && source === parseInt(Zero)) {
10343 if (typeof source == 'object') {
10344 source = covertValuesToHashes(source);
10347 if (One in source && 'roundingPrecision' in source[One]) {
10348 source[One].roundingPrecision = roundingPrecisionFrom(source[One].roundingPrecision);
10351 if (Two in source && 'skipProperties' in source[Two] && typeof(source[Two].skipProperties) == 'string') {
10352 source[Two].skipProperties = source[Two].skipProperties.split(LIST_VALUE_SEPARATOR);
10355 if (Zero in source || One in source || Two in source) {
10356 level[Zero] = override(level[Zero], source[Zero]);
10359 if (One in source && ALL_KEYWORD_1 in source[One]) {
10360 level[One] = override(level[One], defaults(One, normalizeValue(source[One][ALL_KEYWORD_1])));
10361 delete source[One][ALL_KEYWORD_1];
10364 if (One in source && ALL_KEYWORD_2 in source[One]) {
10365 level[One] = override(level[One], defaults(One, normalizeValue(source[One][ALL_KEYWORD_2])));
10366 delete source[One][ALL_KEYWORD_2];
10369 if (One in source || Two in source) {
10370 level[One] = override(level[One], source[One]);
10375 if (Two in source && ALL_KEYWORD_1 in source[Two]) {
10376 level[Two] = override(level[Two], defaults(Two, normalizeValue(source[Two][ALL_KEYWORD_1])));
10377 delete source[Two][ALL_KEYWORD_1];
10380 if (Two in source && ALL_KEYWORD_2 in source[Two]) {
10381 level[Two] = override(level[Two], defaults(Two, normalizeValue(source[Two][ALL_KEYWORD_2])));
10382 delete source[Two][ALL_KEYWORD_2];
10385 if (Two in source) {
10386 level[Two] = override(level[Two], source[Two]);
10394 function defaults(level, value) {
10395 var options = override(DEFAULTS[level], {});
10398 for (key in options) {
10399 if (typeof options[key] == 'boolean') {
10400 options[key] = value;
10407 function normalizeValue(value) {
10409 case FALSE_KEYWORD_1:
10410 case FALSE_KEYWORD_2:
10412 case TRUE_KEYWORD_1:
10413 case TRUE_KEYWORD_2:
10420 function covertValuesToHashes(source) {
10421 var clonedSource = override(source, {});
10425 for (i = 0; i <= 2; i++) {
10428 if (level in clonedSource && (clonedSource[level] === undefined || clonedSource[level] === false)) {
10429 delete clonedSource[level];
10432 if (level in clonedSource && clonedSource[level] === true) {
10433 clonedSource[level] = {};
10436 if (level in clonedSource && typeof clonedSource[level] == 'string') {
10437 clonedSource[level] = covertToHash(clonedSource[level], level);
10441 return clonedSource;
10444 function covertToHash(asString, level) {
10446 .split(OPTION_SEPARATOR)
10447 .reduce(function (accumulator, directive) {
10448 var parts = directive.split(OPTION_VALUE_SEPARATOR);
10449 var name = parts[0];
10450 var value = parts[1];
10451 var normalizedValue = normalizeValue(value);
10453 if (ALL_KEYWORD_1 == name || ALL_KEYWORD_2 == name) {
10454 accumulator = override(accumulator, defaults(level, normalizedValue));
10456 accumulator[name] = normalizedValue;
10459 return accumulator;
10464 OptimizationLevel: OptimizationLevel,
10465 optimizationLevelFrom: optimizationLevelFrom,
10468 },{"../utils/override":95,"./rounding-precision":68}],66:[function(require,module,exports){
10469 (function (process){
10470 var path = require('path');
10472 function rebaseToFrom(option) {
10473 return option ? path.resolve(option) : process.cwd();
10476 module.exports = rebaseToFrom;
10478 }).call(this,require('_process'))
10479 },{"_process":112,"path":110}],67:[function(require,module,exports){
10480 function rebaseFrom(rebaseOption) {
10481 return undefined === rebaseOption ? true : !!rebaseOption;
10484 module.exports = rebaseFrom;
10486 },{}],68:[function(require,module,exports){
10487 var override = require('../utils/override');
10489 var INTEGER_PATTERN = /^\d+$/;
10491 var ALL_UNITS = ['*', 'all'];
10492 var DEFAULT_PRECISION = 'off'; // all precision changes are disabled
10493 var DIRECTIVES_SEPARATOR = ','; // e.g. *=5,px=3
10494 var DIRECTIVE_VALUE_SEPARATOR = '='; // e.g. *=5
10496 function roundingPrecisionFrom(source) {
10497 return override(defaults(DEFAULT_PRECISION), buildPrecisionFrom(source));
10500 function defaults(value) {
10521 function buildPrecisionFrom(source) {
10522 if (source === null || source === undefined) {
10526 if (typeof source == 'boolean') {
10530 if (typeof source == 'number' && source == -1) {
10531 return defaults(DEFAULT_PRECISION);
10534 if (typeof source == 'number') {
10535 return defaults(source);
10538 if (typeof source == 'string' && INTEGER_PATTERN.test(source)) {
10539 return defaults(parseInt(source));
10542 if (typeof source == 'string' && source == DEFAULT_PRECISION) {
10543 return defaults(DEFAULT_PRECISION);
10546 if (typeof source == 'object') {
10551 .split(DIRECTIVES_SEPARATOR)
10552 .reduce(function (accumulator, directive) {
10553 var directiveParts = directive.split(DIRECTIVE_VALUE_SEPARATOR);
10554 var name = directiveParts[0];
10555 var value = parseInt(directiveParts[1]);
10557 if (isNaN(value) || value == -1) {
10558 value = DEFAULT_PRECISION;
10561 if (ALL_UNITS.indexOf(name) > -1) {
10562 accumulator = override(accumulator, defaults(value));
10564 accumulator[name] = value;
10567 return accumulator;
10572 DEFAULT: DEFAULT_PRECISION,
10573 roundingPrecisionFrom: roundingPrecisionFrom
10576 },{"../utils/override":95}],69:[function(require,module,exports){
10577 (function (global,Buffer){
10578 var fs = require('fs');
10579 var path = require('path');
10581 var isAllowedResource = require('./is-allowed-resource');
10582 var matchDataUri = require('./match-data-uri');
10583 var rebaseLocalMap = require('./rebase-local-map');
10584 var rebaseRemoteMap = require('./rebase-remote-map');
10586 var Token = require('../tokenizer/token');
10587 var hasProtocol = require('../utils/has-protocol');
10588 var isDataUriResource = require('../utils/is-data-uri-resource');
10589 var isRemoteResource = require('../utils/is-remote-resource');
10591 var MAP_MARKER_PATTERN = /^\/\*# sourceMappingURL=(\S+) \*\/$/;
10593 function applySourceMaps(tokens, context, callback) {
10594 var applyContext = {
10595 callback: callback,
10596 fetch: context.options.fetch,
10598 inline: context.options.inline,
10599 inlineRequest: context.options.inlineRequest,
10600 inlineTimeout: context.options.inlineTimeout,
10601 inputSourceMapTracker: context.inputSourceMapTracker,
10602 localOnly: context.localOnly,
10603 processedTokens: [],
10604 rebaseTo: context.options.rebaseTo,
10605 sourceTokens: tokens,
10606 warnings: context.warnings
10609 return context.options.sourceMap && tokens.length > 0 ?
10610 doApplySourceMaps(applyContext) :
10614 function doApplySourceMaps(applyContext) {
10615 var singleSourceTokens = [];
10616 var lastSource = findTokenSource(applyContext.sourceTokens[0]);
10621 for (l = applyContext.sourceTokens.length; applyContext.index < l; applyContext.index++) {
10622 token = applyContext.sourceTokens[applyContext.index];
10623 source = findTokenSource(token);
10625 if (source != lastSource) {
10626 singleSourceTokens = [];
10627 lastSource = source;
10630 singleSourceTokens.push(token);
10631 applyContext.processedTokens.push(token);
10633 if (token[0] == Token.COMMENT && MAP_MARKER_PATTERN.test(token[1])) {
10634 return fetchAndApplySourceMap(token[1], source, singleSourceTokens, applyContext);
10638 return applyContext.callback(applyContext.processedTokens);
10641 function findTokenSource(token) {
10645 if (token[0] == Token.AT_RULE || token[0] == Token.COMMENT) {
10646 metadata = token[2][0];
10648 scope = token[1][0];
10649 metadata = scope[2][0];
10652 return metadata[2];
10655 function fetchAndApplySourceMap(sourceMapComment, source, singleSourceTokens, applyContext) {
10656 return extractInputSourceMapFrom(sourceMapComment, applyContext, function (inputSourceMap) {
10657 if (inputSourceMap) {
10658 applyContext.inputSourceMapTracker.track(source, inputSourceMap);
10659 applySourceMapRecursively(singleSourceTokens, applyContext.inputSourceMapTracker);
10662 applyContext.index++;
10663 return doApplySourceMaps(applyContext);
10667 function extractInputSourceMapFrom(sourceMapComment, applyContext, whenSourceMapReady) {
10668 var uri = MAP_MARKER_PATTERN.exec(sourceMapComment)[1];
10673 if (isDataUriResource(uri)) {
10674 sourceMap = extractInputSourceMapFromDataUri(uri);
10675 return whenSourceMapReady(sourceMap);
10676 } else if (isRemoteResource(uri)) {
10677 return loadInputSourceMapFromRemoteUri(uri, applyContext, function (sourceMap) {
10681 parsedMap = JSON.parse(sourceMap);
10682 rebasedMap = rebaseRemoteMap(parsedMap, uri);
10683 whenSourceMapReady(rebasedMap);
10685 whenSourceMapReady(null);
10689 // at this point `uri` is already rebased, see lib/reader/rebase.js#rebaseSourceMapComment
10690 // it is rebased to be consistent with rebasing other URIs
10691 // however here we need to resolve it back to read it from disk
10692 absoluteUri = path.resolve(applyContext.rebaseTo, uri);
10693 sourceMap = loadInputSourceMapFromLocalUri(absoluteUri, applyContext);
10696 rebasedMap = rebaseLocalMap(sourceMap, absoluteUri, applyContext.rebaseTo);
10697 return whenSourceMapReady(rebasedMap);
10699 return whenSourceMapReady(null);
10704 function extractInputSourceMapFromDataUri(uri) {
10705 var dataUriMatch = matchDataUri(uri);
10706 var charset = dataUriMatch[2] ? dataUriMatch[2].split(/[=;]/)[2] : 'us-ascii';
10707 var encoding = dataUriMatch[3] ? dataUriMatch[3].split(';')[1] : 'utf8';
10708 var data = encoding == 'utf8' ? global.unescape(dataUriMatch[4]) : dataUriMatch[4];
10710 var buffer = new Buffer(data, encoding);
10711 buffer.charset = charset;
10713 return JSON.parse(buffer.toString());
10716 function loadInputSourceMapFromRemoteUri(uri, applyContext, whenLoaded) {
10717 var isAllowed = isAllowedResource(uri, true, applyContext.inline);
10718 var isRuntimeResource = !hasProtocol(uri);
10720 if (applyContext.localOnly) {
10721 applyContext.warnings.push('Cannot fetch remote resource from "' + uri + '" as no callback given.');
10722 return whenLoaded(null);
10723 } else if (isRuntimeResource) {
10724 applyContext.warnings.push('Cannot fetch "' + uri + '" as no protocol given.');
10725 return whenLoaded(null);
10726 } else if (!isAllowed) {
10727 applyContext.warnings.push('Cannot fetch "' + uri + '" as resource is not allowed.');
10728 return whenLoaded(null);
10731 applyContext.fetch(uri, applyContext.inlineRequest, applyContext.inlineTimeout, function (error, body) {
10733 applyContext.warnings.push('Missing source map at "' + uri + '" - ' + error);
10734 return whenLoaded(null);
10741 function loadInputSourceMapFromLocalUri(uri, applyContext) {
10742 var isAllowed = isAllowedResource(uri, false, applyContext.inline);
10745 if (!fs.existsSync(uri) || !fs.statSync(uri).isFile()) {
10746 applyContext.warnings.push('Ignoring local source map at "' + uri + '" as resource is missing.');
10748 } else if (!isAllowed) {
10749 applyContext.warnings.push('Cannot fetch "' + uri + '" as resource is not allowed.');
10753 sourceMap = fs.readFileSync(uri, 'utf-8');
10754 return JSON.parse(sourceMap);
10757 function applySourceMapRecursively(tokens, inputSourceMapTracker) {
10761 for (i = 0, l = tokens.length; i < l; i++) {
10764 switch (token[0]) {
10765 case Token.AT_RULE:
10766 applySourceMapTo(token, inputSourceMapTracker);
10768 case Token.AT_RULE_BLOCK:
10769 applySourceMapRecursively(token[1], inputSourceMapTracker);
10770 applySourceMapRecursively(token[2], inputSourceMapTracker);
10772 case Token.AT_RULE_BLOCK_SCOPE:
10773 applySourceMapTo(token, inputSourceMapTracker);
10775 case Token.NESTED_BLOCK:
10776 applySourceMapRecursively(token[1], inputSourceMapTracker);
10777 applySourceMapRecursively(token[2], inputSourceMapTracker);
10779 case Token.NESTED_BLOCK_SCOPE:
10780 applySourceMapTo(token, inputSourceMapTracker);
10782 case Token.COMMENT:
10783 applySourceMapTo(token, inputSourceMapTracker);
10785 case Token.PROPERTY:
10786 applySourceMapRecursively(token, inputSourceMapTracker);
10788 case Token.PROPERTY_BLOCK:
10789 applySourceMapRecursively(token[1], inputSourceMapTracker);
10791 case Token.PROPERTY_NAME:
10792 applySourceMapTo(token, inputSourceMapTracker);
10794 case Token.PROPERTY_VALUE:
10795 applySourceMapTo(token, inputSourceMapTracker);
10798 applySourceMapRecursively(token[1], inputSourceMapTracker);
10799 applySourceMapRecursively(token[2], inputSourceMapTracker);
10801 case Token.RULE_SCOPE:
10802 applySourceMapTo(token, inputSourceMapTracker);
10809 function applySourceMapTo(token, inputSourceMapTracker) {
10810 var value = token[1];
10811 var metadata = token[2];
10812 var newMetadata = [];
10815 for (i = 0, l = metadata.length; i < l; i++) {
10816 newMetadata.push(inputSourceMapTracker.originalPositionFor(metadata[i], value.length));
10819 token[2] = newMetadata;
10822 module.exports = applySourceMaps;
10824 }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer)
10825 },{"../tokenizer/token":84,"../utils/has-protocol":88,"../utils/is-data-uri-resource":89,"../utils/is-remote-resource":93,"./is-allowed-resource":72,"./match-data-uri":75,"./rebase-local-map":78,"./rebase-remote-map":79,"buffer":4,"fs":3,"path":110}],70:[function(require,module,exports){
10826 var split = require('../utils/split');
10828 var BRACE_PREFIX = /^\(/;
10829 var BRACE_SUFFIX = /\)$/;
10830 var IMPORT_PREFIX_PATTERN = /^@import/i;
10831 var QUOTE_PREFIX_PATTERN = /['"]\s*/;
10832 var QUOTE_SUFFIX_PATTERN = /\s*['"]/;
10833 var URL_PREFIX_PATTERN = /^url\(\s*/i;
10834 var URL_SUFFIX_PATTERN = /\s*\)/i;
10836 function extractImportUrlAndMedia(atRuleValue) {
10842 stripped = atRuleValue
10843 .replace(IMPORT_PREFIX_PATTERN, '')
10845 .replace(URL_PREFIX_PATTERN, '(')
10846 .replace(URL_SUFFIX_PATTERN, ')')
10847 .replace(QUOTE_PREFIX_PATTERN, '')
10848 .replace(QUOTE_SUFFIX_PATTERN, '');
10850 parts = split(stripped, ' ');
10853 .replace(BRACE_PREFIX, '')
10854 .replace(BRACE_SUFFIX, '');
10855 mediaQuery = parts.slice(1).join(' ');
10857 return [uri, mediaQuery];
10860 module.exports = extractImportUrlAndMedia;
10862 },{"../utils/split":96}],71:[function(require,module,exports){
10863 var SourceMapConsumer = require('source-map').SourceMapConsumer;
10865 function inputSourceMapTracker() {
10869 all: all.bind(null, maps),
10870 isTracking: isTracking.bind(null, maps),
10871 originalPositionFor: originalPositionFor.bind(null, maps),
10872 track: track.bind(null, maps)
10876 function all(maps) {
10880 function isTracking(maps, source) {
10881 return source in maps;
10884 function originalPositionFor(maps, metadata, range, selectorFallbacks) {
10885 var line = metadata[0];
10886 var column = metadata[1];
10887 var source = metadata[2];
10890 column: column + range
10892 var originalPosition;
10894 while (!originalPosition && position.column > column) {
10896 originalPosition = maps[source].originalPositionFor(position);
10899 if (!originalPosition || originalPosition.column < 0) {
10903 if (originalPosition.line === null && line > 1 && selectorFallbacks > 0) {
10904 return originalPositionFor(maps, [line - 1, column, source], range, selectorFallbacks - 1);
10907 return originalPosition.line !== null ?
10908 toMetadata(originalPosition) :
10912 function toMetadata(asHash) {
10913 return [asHash.line, asHash.column, asHash.source];
10916 function track(maps, source, data) {
10917 maps[source] = new SourceMapConsumer(data);
10920 module.exports = inputSourceMapTracker;
10922 },{"source-map":154}],72:[function(require,module,exports){
10923 var path = require('path');
10924 var url = require('url');
10926 var isRemoteResource = require('../utils/is-remote-resource');
10927 var hasProtocol = require('../utils/has-protocol');
10929 var HTTP_PROTOCOL = 'http:';
10931 function isAllowedResource(uri, isRemote, rules) {
10934 var allowed = isRemote ? false : true;
10937 var normalizedRule;
10940 if (rules.length === 0) {
10944 if (isRemote && !hasProtocol(uri)) {
10945 uri = HTTP_PROTOCOL + uri;
10949 url.parse(uri).host :
10952 absoluteUri = isRemote ?
10956 for (i = 0; i < rules.length; i++) {
10958 isNegated = rule[0] == '!';
10959 normalizedRule = rule.substring(1);
10961 if (isNegated && isRemote && isRemoteRule(normalizedRule)) {
10962 allowed = allowed && !isAllowedResource(uri, true, [normalizedRule]);
10963 } else if (isNegated && !isRemote && !isRemoteRule(normalizedRule)) {
10964 allowed = allowed && !isAllowedResource(uri, false, [normalizedRule]);
10965 } else if (isNegated) {
10966 allowed = allowed && true;
10967 } else if (rule == 'all') {
10969 } else if (isRemote && rule == 'local') {
10970 allowed = allowed || false;
10971 } else if (isRemote && rule == 'remote') {
10973 } else if (!isRemote && rule == 'remote') {
10975 } else if (!isRemote && rule == 'local') {
10977 } else if (rule === match) {
10979 } else if (rule === uri) {
10981 } else if (isRemote && absoluteUri.indexOf(rule) === 0) {
10983 } else if (!isRemote && absoluteUri.indexOf(path.resolve(rule)) === 0) {
10985 } else if (isRemote != isRemoteRule(normalizedRule)) {
10986 allowed = allowed && true;
10995 function isRemoteRule(rule) {
10996 return isRemoteResource(rule) || url.parse(HTTP_PROTOCOL + '//' + rule).host == rule;
10999 module.exports = isAllowedResource;
11001 },{"../utils/has-protocol":88,"../utils/is-remote-resource":93,"path":110,"url":162}],73:[function(require,module,exports){
11002 var fs = require('fs');
11003 var path = require('path');
11005 var isAllowedResource = require('./is-allowed-resource');
11007 var hasProtocol = require('../utils/has-protocol');
11008 var isRemoteResource = require('../utils/is-remote-resource');
11010 function loadOriginalSources(context, callback) {
11011 var loadContext = {
11012 callback: callback,
11013 fetch: context.options.fetch,
11015 inline: context.options.inline,
11016 inlineRequest: context.options.inlineRequest,
11017 inlineTimeout: context.options.inlineTimeout,
11018 localOnly: context.localOnly,
11019 rebaseTo: context.options.rebaseTo,
11020 sourcesContent: context.sourcesContent,
11021 uriToSource: uriToSourceMapping(context.inputSourceMapTracker.all()),
11022 warnings: context.warnings
11025 return context.options.sourceMap && context.options.sourceMapInlineSources ?
11026 doLoadOriginalSources(loadContext) :
11030 function uriToSourceMapping(allSourceMapConsumers) {
11037 for (source in allSourceMapConsumers) {
11038 consumer = allSourceMapConsumers[source];
11040 for (i = 0, l = consumer.sources.length; i < l; i++) {
11041 uri = consumer.sources[i];
11042 source = consumer.sourceContentFor(uri, true);
11044 mapping[uri] = source;
11051 function doLoadOriginalSources(loadContext) {
11052 var uris = Object.keys(loadContext.uriToSource);
11057 for (total = uris.length; loadContext.index < total; loadContext.index++) {
11058 uri = uris[loadContext.index];
11059 source = loadContext.uriToSource[uri];
11062 loadContext.sourcesContent[uri] = source;
11064 return loadOriginalSource(uri, loadContext);
11068 return loadContext.callback();
11071 function loadOriginalSource(uri, loadContext) {
11074 if (isRemoteResource(uri)) {
11075 return loadOriginalSourceFromRemoteUri(uri, loadContext, function (content) {
11076 loadContext.index++;
11077 loadContext.sourcesContent[uri] = content;
11078 return doLoadOriginalSources(loadContext);
11081 content = loadOriginalSourceFromLocalUri(uri, loadContext);
11082 loadContext.index++;
11083 loadContext.sourcesContent[uri] = content;
11084 return doLoadOriginalSources(loadContext);
11088 function loadOriginalSourceFromRemoteUri(uri, loadContext, whenLoaded) {
11089 var isAllowed = isAllowedResource(uri, true, loadContext.inline);
11090 var isRuntimeResource = !hasProtocol(uri);
11092 if (loadContext.localOnly) {
11093 loadContext.warnings.push('Cannot fetch remote resource from "' + uri + '" as no callback given.');
11094 return whenLoaded(null);
11095 } else if (isRuntimeResource) {
11096 loadContext.warnings.push('Cannot fetch "' + uri + '" as no protocol given.');
11097 return whenLoaded(null);
11098 } else if (!isAllowed) {
11099 loadContext.warnings.push('Cannot fetch "' + uri + '" as resource is not allowed.');
11100 return whenLoaded(null);
11103 loadContext.fetch(uri, loadContext.inlineRequest, loadContext.inlineTimeout, function (error, content) {
11105 loadContext.warnings.push('Missing original source at "' + uri + '" - ' + error);
11108 whenLoaded(content);
11112 function loadOriginalSourceFromLocalUri(relativeUri, loadContext) {
11113 var isAllowed = isAllowedResource(relativeUri, false, loadContext.inline);
11114 var absoluteUri = path.resolve(loadContext.rebaseTo, relativeUri);
11116 if (!fs.existsSync(absoluteUri) || !fs.statSync(absoluteUri).isFile()) {
11117 loadContext.warnings.push('Ignoring local source map at "' + absoluteUri + '" as resource is missing.');
11119 } else if (!isAllowed) {
11120 loadContext.warnings.push('Cannot fetch "' + absoluteUri + '" as resource is not allowed.');
11124 return fs.readFileSync(absoluteUri, 'utf8');
11127 module.exports = loadOriginalSources;
11129 },{"../utils/has-protocol":88,"../utils/is-remote-resource":93,"./is-allowed-resource":72,"fs":3,"path":110}],74:[function(require,module,exports){
11130 var http = require('http');
11131 var https = require('https');
11132 var url = require('url');
11134 var isHttpResource = require('../utils/is-http-resource');
11135 var isHttpsResource = require('../utils/is-https-resource');
11136 var override = require('../utils/override');
11138 var HTTP_PROTOCOL = 'http:';
11140 function loadRemoteResource(uri, inlineRequest, inlineTimeout, callback) {
11141 var proxyProtocol = inlineRequest.protocol || inlineRequest.hostname;
11142 var errorHandled = false;
11143 var requestOptions;
11146 requestOptions = override(
11148 inlineRequest || {}
11151 if (inlineRequest.hostname !== undefined) {
11152 // overwrite as we always expect a http proxy currently
11153 requestOptions.protocol = inlineRequest.protocol || HTTP_PROTOCOL;
11154 requestOptions.path = requestOptions.href;
11157 fetch = (proxyProtocol && !isHttpsResource(proxyProtocol)) || isHttpResource(uri) ?
11161 fetch(requestOptions, function (res) {
11165 if (errorHandled) {
11169 if (res.statusCode < 200 || res.statusCode > 399) {
11170 return callback(res.statusCode, null);
11171 } else if (res.statusCode > 299) {
11172 movedUri = url.resolve(uri, res.headers.location);
11173 return loadRemoteResource(movedUri, inlineRequest, inlineTimeout, callback);
11176 res.on('data', function (chunk) {
11177 chunks.push(chunk.toString());
11179 res.on('end', function () {
11180 var body = chunks.join('');
11181 callback(null, body);
11184 .on('error', function (res) {
11185 if (errorHandled) {
11189 errorHandled = true;
11190 callback(res.message, null);
11192 .on('timeout', function () {
11193 if (errorHandled) {
11197 errorHandled = true;
11198 callback('timeout', null);
11200 .setTimeout(inlineTimeout);
11203 module.exports = loadRemoteResource;
11205 },{"../utils/is-http-resource":90,"../utils/is-https-resource":91,"../utils/override":95,"http":155,"https":104,"url":162}],75:[function(require,module,exports){
11206 var DATA_URI_PATTERN = /^data:(\S*?)?(;charset=[^;]+)?(;[^,]+?)?,(.+)/;
11208 function matchDataUri(uri) {
11209 return DATA_URI_PATTERN.exec(uri);
11212 module.exports = matchDataUri;
11214 },{}],76:[function(require,module,exports){
11215 var UNIX_SEPARATOR = '/';
11216 var WINDOWS_SEPARATOR_PATTERN = /\\/g;
11218 function normalizePath(path) {
11219 return path.replace(WINDOWS_SEPARATOR_PATTERN, UNIX_SEPARATOR);
11222 module.exports = normalizePath;
11224 },{}],77:[function(require,module,exports){
11225 (function (Buffer,process){
11226 var fs = require('fs');
11227 var path = require('path');
11229 var applySourceMaps = require('./apply-source-maps');
11230 var extractImportUrlAndMedia = require('./extract-import-url-and-media');
11231 var isAllowedResource = require('./is-allowed-resource');
11232 var loadOriginalSources = require('./load-original-sources');
11233 var normalizePath = require('./normalize-path');
11234 var rebase = require('./rebase');
11235 var rebaseLocalMap = require('./rebase-local-map');
11236 var rebaseRemoteMap = require('./rebase-remote-map');
11237 var restoreImport = require('./restore-import');
11239 var tokenize = require('../tokenizer/tokenize');
11240 var Token = require('../tokenizer/token');
11241 var Marker = require('../tokenizer/marker');
11242 var hasProtocol = require('../utils/has-protocol');
11243 var isImport = require('../utils/is-import');
11244 var isRemoteResource = require('../utils/is-remote-resource');
11246 var UNKNOWN_URI = 'uri:unknown';
11248 function readSources(input, context, callback) {
11249 return doReadSources(input, context, function (tokens) {
11250 return applySourceMaps(tokens, context, function () {
11251 return loadOriginalSources(context, function () { return callback(tokens); });
11256 function doReadSources(input, context, callback) {
11257 if (typeof input == 'string') {
11258 return fromString(input, context, callback);
11259 } else if (Buffer.isBuffer(input)) {
11260 return fromString(input.toString(), context, callback);
11261 } else if (Array.isArray(input)) {
11262 return fromArray(input, context, callback);
11263 } else if (typeof input == 'object') {
11264 return fromHash(input, context, callback);
11268 function fromString(input, context, callback) {
11269 context.source = undefined;
11270 context.sourcesContent[undefined] = input;
11271 context.stats.originalSize += input.length;
11273 return fromStyles(input, context, { inline: context.options.inline }, callback);
11276 function fromArray(input, context, callback) {
11277 var inputAsImports = input.reduce(function (accumulator, uriOrHash) {
11278 if (typeof uriOrHash === 'string') {
11279 return addStringSource(uriOrHash, accumulator);
11281 return addHashSource(uriOrHash, context, accumulator);
11286 return fromStyles(inputAsImports.join(''), context, { inline: ['all'] }, callback);
11289 function fromHash(input, context, callback) {
11290 var inputAsImports = addHashSource(input, context, []);
11291 return fromStyles(inputAsImports.join(''), context, { inline: ['all'] }, callback);
11294 function addStringSource(input, imports) {
11295 imports.push(restoreAsImport(normalizeUri(input)));
11299 function addHashSource(input, context, imports) {
11304 for (uri in input) {
11305 source = input[uri];
11306 normalizedUri = normalizeUri(uri);
11308 imports.push(restoreAsImport(normalizedUri));
11310 context.sourcesContent[normalizedUri] = source.styles;
11312 if (source.sourceMap) {
11313 trackSourceMap(source.sourceMap, normalizedUri, context);
11320 function normalizeUri(uri) {
11321 var currentPath = path.resolve('');
11323 var relativeToCurrentPath;
11326 if (isRemoteResource(uri)) {
11330 absoluteUri = path.isAbsolute(uri) ?
11333 relativeToCurrentPath = path.relative(currentPath, absoluteUri);
11334 normalizedUri = normalizePath(relativeToCurrentPath);
11336 return normalizedUri;
11339 function trackSourceMap(sourceMap, uri, context) {
11340 var parsedMap = typeof sourceMap == 'string' ?
11341 JSON.parse(sourceMap) :
11343 var rebasedMap = isRemoteResource(uri) ?
11344 rebaseRemoteMap(parsedMap, uri) :
11345 rebaseLocalMap(parsedMap, uri || UNKNOWN_URI, context.options.rebaseTo);
11347 context.inputSourceMapTracker.track(uri, rebasedMap);
11350 function restoreAsImport(uri) {
11351 return restoreImport('url(' + uri + ')', '') + Marker.SEMICOLON;
11354 function fromStyles(styles, context, parentInlinerContext, callback) {
11356 var rebaseConfig = {};
11358 if (!context.source) {
11359 rebaseConfig.fromBase = path.resolve('');
11360 rebaseConfig.toBase = context.options.rebaseTo;
11361 } else if (isRemoteResource(context.source)) {
11362 rebaseConfig.fromBase = context.source;
11363 rebaseConfig.toBase = context.source;
11364 } else if (path.isAbsolute(context.source)) {
11365 rebaseConfig.fromBase = path.dirname(context.source);
11366 rebaseConfig.toBase = context.options.rebaseTo;
11368 rebaseConfig.fromBase = path.dirname(path.resolve(context.source));
11369 rebaseConfig.toBase = context.options.rebaseTo;
11372 tokens = tokenize(styles, context);
11373 tokens = rebase(tokens, context.options.rebase, context.validator, rebaseConfig);
11375 return allowsAnyImports(parentInlinerContext.inline) ?
11376 inline(tokens, context, parentInlinerContext, callback) :
11380 function allowsAnyImports(inline) {
11381 return !(inline.length == 1 && inline[0] == 'none');
11384 function inline(tokens, externalContext, parentInlinerContext, callback) {
11385 var inlinerContext = {
11386 afterContent: false,
11387 callback: callback,
11388 errors: externalContext.errors,
11389 externalContext: externalContext,
11390 fetch: externalContext.options.fetch,
11391 inlinedStylesheets: parentInlinerContext.inlinedStylesheets || externalContext.inlinedStylesheets,
11392 inline: parentInlinerContext.inline,
11393 inlineRequest: externalContext.options.inlineRequest,
11394 inlineTimeout: externalContext.options.inlineTimeout,
11395 isRemote: parentInlinerContext.isRemote || false,
11396 localOnly: externalContext.localOnly,
11398 rebaseTo: externalContext.options.rebaseTo,
11399 sourceTokens: tokens,
11400 warnings: externalContext.warnings
11403 return doInlineImports(inlinerContext);
11406 function doInlineImports(inlinerContext) {
11410 for (i = 0, l = inlinerContext.sourceTokens.length; i < l; i++) {
11411 token = inlinerContext.sourceTokens[i];
11413 if (token[0] == Token.AT_RULE && isImport(token[1])) {
11414 inlinerContext.sourceTokens.splice(0, i);
11415 return inlineStylesheet(token, inlinerContext);
11416 } else if (token[0] == Token.AT_RULE || token[0] == Token.COMMENT) {
11417 inlinerContext.outputTokens.push(token);
11419 inlinerContext.outputTokens.push(token);
11420 inlinerContext.afterContent = true;
11424 inlinerContext.sourceTokens = [];
11425 return inlinerContext.callback(inlinerContext.outputTokens);
11428 function inlineStylesheet(token, inlinerContext) {
11429 var uriAndMediaQuery = extractImportUrlAndMedia(token[1]);
11430 var uri = uriAndMediaQuery[0];
11431 var mediaQuery = uriAndMediaQuery[1];
11432 var metadata = token[2];
11434 return isRemoteResource(uri) ?
11435 inlineRemoteStylesheet(uri, mediaQuery, metadata, inlinerContext) :
11436 inlineLocalStylesheet(uri, mediaQuery, metadata, inlinerContext);
11439 function inlineRemoteStylesheet(uri, mediaQuery, metadata, inlinerContext) {
11440 var isAllowed = isAllowedResource(uri, true, inlinerContext.inline);
11441 var originalUri = uri;
11442 var isLoaded = uri in inlinerContext.externalContext.sourcesContent;
11443 var isRuntimeResource = !hasProtocol(uri);
11445 if (inlinerContext.inlinedStylesheets.indexOf(uri) > -1) {
11446 inlinerContext.warnings.push('Ignoring remote @import of "' + uri + '" as it has already been imported.');
11447 inlinerContext.sourceTokens = inlinerContext.sourceTokens.slice(1);
11448 return doInlineImports(inlinerContext);
11449 } else if (inlinerContext.localOnly && inlinerContext.afterContent) {
11450 inlinerContext.warnings.push('Ignoring remote @import of "' + uri + '" as no callback given and after other content.');
11451 inlinerContext.sourceTokens = inlinerContext.sourceTokens.slice(1);
11452 return doInlineImports(inlinerContext);
11453 } else if (isRuntimeResource) {
11454 inlinerContext.warnings.push('Skipping remote @import of "' + uri + '" as no protocol given.');
11455 inlinerContext.outputTokens = inlinerContext.outputTokens.concat(inlinerContext.sourceTokens.slice(0, 1));
11456 inlinerContext.sourceTokens = inlinerContext.sourceTokens.slice(1);
11457 return doInlineImports(inlinerContext);
11458 } else if (inlinerContext.localOnly && !isLoaded) {
11459 inlinerContext.warnings.push('Skipping remote @import of "' + uri + '" as no callback given.');
11460 inlinerContext.outputTokens = inlinerContext.outputTokens.concat(inlinerContext.sourceTokens.slice(0, 1));
11461 inlinerContext.sourceTokens = inlinerContext.sourceTokens.slice(1);
11462 return doInlineImports(inlinerContext);
11463 } else if (!isAllowed && inlinerContext.afterContent) {
11464 inlinerContext.warnings.push('Ignoring remote @import of "' + uri + '" as resource is not allowed and after other content.');
11465 inlinerContext.sourceTokens = inlinerContext.sourceTokens.slice(1);
11466 return doInlineImports(inlinerContext);
11467 } else if (!isAllowed) {
11468 inlinerContext.warnings.push('Skipping remote @import of "' + uri + '" as resource is not allowed.');
11469 inlinerContext.outputTokens = inlinerContext.outputTokens.concat(inlinerContext.sourceTokens.slice(0, 1));
11470 inlinerContext.sourceTokens = inlinerContext.sourceTokens.slice(1);
11471 return doInlineImports(inlinerContext);
11474 inlinerContext.inlinedStylesheets.push(uri);
11476 function whenLoaded(error, importedStyles) {
11478 inlinerContext.errors.push('Broken @import declaration of "' + uri + '" - ' + error);
11480 return process.nextTick(function () {
11481 inlinerContext.outputTokens = inlinerContext.outputTokens.concat(inlinerContext.sourceTokens.slice(0, 1));
11482 inlinerContext.sourceTokens = inlinerContext.sourceTokens.slice(1);
11483 doInlineImports(inlinerContext);
11487 inlinerContext.inline = inlinerContext.externalContext.options.inline;
11488 inlinerContext.isRemote = true;
11490 inlinerContext.externalContext.source = originalUri;
11491 inlinerContext.externalContext.sourcesContent[uri] = importedStyles;
11492 inlinerContext.externalContext.stats.originalSize += importedStyles.length;
11494 return fromStyles(importedStyles, inlinerContext.externalContext, inlinerContext, function (importedTokens) {
11495 importedTokens = wrapInMedia(importedTokens, mediaQuery, metadata);
11497 inlinerContext.outputTokens = inlinerContext.outputTokens.concat(importedTokens);
11498 inlinerContext.sourceTokens = inlinerContext.sourceTokens.slice(1);
11500 return doInlineImports(inlinerContext);
11505 whenLoaded(null, inlinerContext.externalContext.sourcesContent[uri]) :
11506 inlinerContext.fetch(uri, inlinerContext.inlineRequest, inlinerContext.inlineTimeout, whenLoaded);
11509 function inlineLocalStylesheet(uri, mediaQuery, metadata, inlinerContext) {
11510 var currentPath = path.resolve('');
11511 var absoluteUri = path.isAbsolute(uri) ?
11512 path.resolve(currentPath, uri[0] == '/' ? uri.substring(1) : uri) :
11513 path.resolve(inlinerContext.rebaseTo, uri);
11514 var relativeToCurrentPath = path.relative(currentPath, absoluteUri);
11515 var importedStyles;
11516 var isAllowed = isAllowedResource(uri, false, inlinerContext.inline);
11517 var normalizedPath = normalizePath(relativeToCurrentPath);
11518 var isLoaded = normalizedPath in inlinerContext.externalContext.sourcesContent;
11520 if (inlinerContext.inlinedStylesheets.indexOf(absoluteUri) > -1) {
11521 inlinerContext.warnings.push('Ignoring local @import of "' + uri + '" as it has already been imported.');
11522 } else if (!isLoaded && (!fs.existsSync(absoluteUri) || !fs.statSync(absoluteUri).isFile())) {
11523 inlinerContext.errors.push('Ignoring local @import of "' + uri + '" as resource is missing.');
11524 } else if (!isAllowed && inlinerContext.afterContent) {
11525 inlinerContext.warnings.push('Ignoring local @import of "' + uri + '" as resource is not allowed and after other content.');
11526 } else if (inlinerContext.afterContent) {
11527 inlinerContext.warnings.push('Ignoring local @import of "' + uri + '" as after other content.');
11528 } else if (!isAllowed) {
11529 inlinerContext.warnings.push('Skipping local @import of "' + uri + '" as resource is not allowed.');
11530 inlinerContext.outputTokens = inlinerContext.outputTokens.concat(inlinerContext.sourceTokens.slice(0, 1));
11532 importedStyles = isLoaded ?
11533 inlinerContext.externalContext.sourcesContent[normalizedPath] :
11534 fs.readFileSync(absoluteUri, 'utf-8');
11536 inlinerContext.inlinedStylesheets.push(absoluteUri);
11537 inlinerContext.inline = inlinerContext.externalContext.options.inline;
11539 inlinerContext.externalContext.source = normalizedPath;
11540 inlinerContext.externalContext.sourcesContent[normalizedPath] = importedStyles;
11541 inlinerContext.externalContext.stats.originalSize += importedStyles.length;
11543 return fromStyles(importedStyles, inlinerContext.externalContext, inlinerContext, function (importedTokens) {
11544 importedTokens = wrapInMedia(importedTokens, mediaQuery, metadata);
11546 inlinerContext.outputTokens = inlinerContext.outputTokens.concat(importedTokens);
11547 inlinerContext.sourceTokens = inlinerContext.sourceTokens.slice(1);
11549 return doInlineImports(inlinerContext);
11553 inlinerContext.sourceTokens = inlinerContext.sourceTokens.slice(1);
11555 return doInlineImports(inlinerContext);
11558 function wrapInMedia(tokens, mediaQuery, metadata) {
11560 return [[Token.NESTED_BLOCK, [[Token.NESTED_BLOCK_SCOPE, '@media ' + mediaQuery, metadata]], tokens]];
11566 module.exports = readSources;
11568 }).call(this,{"isBuffer":require("../../../is-buffer/index.js")},require('_process'))
11569 },{"../../../is-buffer/index.js":107,"../tokenizer/marker":83,"../tokenizer/token":84,"../tokenizer/tokenize":85,"../utils/has-protocol":88,"../utils/is-import":92,"../utils/is-remote-resource":93,"./apply-source-maps":69,"./extract-import-url-and-media":70,"./is-allowed-resource":72,"./load-original-sources":73,"./normalize-path":76,"./rebase":80,"./rebase-local-map":78,"./rebase-remote-map":79,"./restore-import":81,"_process":112,"fs":3,"path":110}],78:[function(require,module,exports){
11570 var path = require('path');
11572 function rebaseLocalMap(sourceMap, sourceUri, rebaseTo) {
11573 var currentPath = path.resolve('');
11574 var absoluteUri = path.resolve(currentPath, sourceUri);
11575 var absoluteUriDirectory = path.dirname(absoluteUri);
11577 sourceMap.sources = sourceMap.sources.map(function(source) {
11578 return path.relative(rebaseTo, path.resolve(absoluteUriDirectory, source));
11584 module.exports = rebaseLocalMap;
11586 },{"path":110}],79:[function(require,module,exports){
11587 var path = require('path');
11588 var url = require('url');
11590 function rebaseRemoteMap(sourceMap, sourceUri) {
11591 var sourceDirectory = path.dirname(sourceUri);
11593 sourceMap.sources = sourceMap.sources.map(function(source) {
11594 return url.resolve(sourceDirectory, source);
11600 module.exports = rebaseRemoteMap;
11602 },{"path":110,"url":162}],80:[function(require,module,exports){
11603 var extractImportUrlAndMedia = require('./extract-import-url-and-media');
11604 var restoreImport = require('./restore-import');
11605 var rewriteUrl = require('./rewrite-url');
11607 var Token = require('../tokenizer/token');
11608 var isImport = require('../utils/is-import');
11610 var SOURCE_MAP_COMMENT_PATTERN = /^\/\*# sourceMappingURL=(\S+) \*\/$/;
11612 function rebase(tokens, rebaseAll, validator, rebaseConfig) {
11614 rebaseEverything(tokens, validator, rebaseConfig) :
11615 rebaseAtRules(tokens, validator, rebaseConfig);
11618 function rebaseEverything(tokens, validator, rebaseConfig) {
11622 for (i = 0, l = tokens.length; i < l; i++) {
11625 switch (token[0]) {
11626 case Token.AT_RULE:
11627 rebaseAtRule(token, validator, rebaseConfig);
11629 case Token.AT_RULE_BLOCK:
11630 rebaseProperties(token[2], validator, rebaseConfig);
11632 case Token.COMMENT:
11633 rebaseSourceMapComment(token, rebaseConfig);
11635 case Token.NESTED_BLOCK:
11636 rebaseEverything(token[2], validator, rebaseConfig);
11639 rebaseProperties(token[2], validator, rebaseConfig);
11647 function rebaseAtRules(tokens, validator, rebaseConfig) {
11651 for (i = 0, l = tokens.length; i < l; i++) {
11654 switch (token[0]) {
11655 case Token.AT_RULE:
11656 rebaseAtRule(token, validator, rebaseConfig);
11664 function rebaseAtRule(token, validator, rebaseConfig) {
11665 if (!isImport(token[1])) {
11669 var uriAndMediaQuery = extractImportUrlAndMedia(token[1]);
11670 var newUrl = rewriteUrl(uriAndMediaQuery[0], rebaseConfig);
11671 var mediaQuery = uriAndMediaQuery[1];
11673 token[1] = restoreImport(newUrl, mediaQuery);
11676 function rebaseSourceMapComment(token, rebaseConfig) {
11677 var matches = SOURCE_MAP_COMMENT_PATTERN.exec(token[1]);
11679 if (matches && matches[1].indexOf('data:') === -1) {
11680 token[1] = token[1].replace(matches[1], rewriteUrl(matches[1], rebaseConfig, true));
11684 function rebaseProperties(properties, validator, rebaseConfig) {
11690 for (i = 0, l = properties.length; i < l; i++) {
11691 property = properties[i];
11693 for (j = 2 /* 0 is Token.PROPERTY, 1 is name */, m = property.length; j < m; j++) {
11694 value = property[j][1];
11696 if (validator.isUrl(value)) {
11697 property[j][1] = rewriteUrl(value, rebaseConfig);
11703 module.exports = rebase;
11705 },{"../tokenizer/token":84,"../utils/is-import":92,"./extract-import-url-and-media":70,"./restore-import":81,"./rewrite-url":82}],81:[function(require,module,exports){
11706 function restoreImport(uri, mediaQuery) {
11707 return ('@import ' + uri + ' ' + mediaQuery).trim();
11710 module.exports = restoreImport;
11712 },{}],82:[function(require,module,exports){
11713 (function (process){
11714 var path = require('path');
11715 var url = require('url');
11717 var DOUBLE_QUOTE = '"';
11718 var SINGLE_QUOTE = '\'';
11719 var URL_PREFIX = 'url(';
11720 var URL_SUFFIX = ')';
11722 var QUOTE_PREFIX_PATTERN = /^["']/;
11723 var QUOTE_SUFFIX_PATTERN = /["']$/;
11724 var ROUND_BRACKETS_PATTERN = /[\(\)]/;
11725 var URL_PREFIX_PATTERN = /^url\(/i;
11726 var URL_SUFFIX_PATTERN = /\)$/;
11727 var WHITESPACE_PATTERN = /\s/;
11729 var isWindows = process.platform == 'win32';
11731 function rebase(uri, rebaseConfig) {
11732 if (!rebaseConfig) {
11736 if (isAbsolute(uri) && !isRemote(rebaseConfig.toBase)) {
11740 if (isRemote(uri) || isSVGMarker(uri) || isInternal(uri)) {
11745 return '\'' + uri + '\'';
11748 if (isRemote(rebaseConfig.toBase)) {
11749 return url.resolve(rebaseConfig.toBase, uri);
11752 return rebaseConfig.absolute ?
11753 normalize(absolute(uri, rebaseConfig)) :
11754 normalize(relative(uri, rebaseConfig));
11757 function isAbsolute(uri) {
11758 return path.isAbsolute(uri);
11761 function isSVGMarker(uri) {
11762 return uri[0] == '#';
11765 function isInternal(uri) {
11766 return /^\w+:\w+/.test(uri);
11769 function isRemote(uri) {
11770 return /^[^:]+?:\/\//.test(uri) || uri.indexOf('//') === 0;
11773 function isData(uri) {
11774 return uri.indexOf('data:') === 0;
11777 function absolute(uri, rebaseConfig) {
11779 .resolve(path.join(rebaseConfig.fromBase || '', uri))
11780 .replace(rebaseConfig.toBase, '');
11783 function relative(uri, rebaseConfig) {
11784 return path.relative(rebaseConfig.toBase, path.join(rebaseConfig.fromBase || '', uri));
11787 function normalize(uri) {
11788 return isWindows ? uri.replace(/\\/g, '/') : uri;
11791 function quoteFor(unquotedUrl) {
11792 if (unquotedUrl.indexOf(SINGLE_QUOTE) > -1) {
11793 return DOUBLE_QUOTE;
11794 } else if (unquotedUrl.indexOf(DOUBLE_QUOTE) > -1) {
11795 return SINGLE_QUOTE;
11796 } else if (hasWhitespace(unquotedUrl) || hasRoundBrackets(unquotedUrl)) {
11797 return SINGLE_QUOTE;
11803 function hasWhitespace(url) {
11804 return WHITESPACE_PATTERN.test(url);
11807 function hasRoundBrackets(url) {
11808 return ROUND_BRACKETS_PATTERN.test(url);
11811 function rewriteUrl(originalUrl, rebaseConfig, pathOnly) {
11812 var strippedUrl = originalUrl
11813 .replace(URL_PREFIX_PATTERN, '')
11814 .replace(URL_SUFFIX_PATTERN, '')
11817 var unquotedUrl = strippedUrl
11818 .replace(QUOTE_PREFIX_PATTERN, '')
11819 .replace(QUOTE_SUFFIX_PATTERN, '')
11822 var quote = strippedUrl[0] == SINGLE_QUOTE || strippedUrl[0] == DOUBLE_QUOTE ?
11824 quoteFor(unquotedUrl);
11827 rebase(unquotedUrl, rebaseConfig) :
11828 URL_PREFIX + quote + rebase(unquotedUrl, rebaseConfig) + quote + URL_SUFFIX;
11831 module.exports = rewriteUrl;
11833 }).call(this,require('_process'))
11834 },{"_process":112,"path":110,"url":162}],83:[function(require,module,exports){
11839 CARRIAGE_RETURN: '\r',
11840 CLOSE_CURLY_BRACKET: '}',
11841 CLOSE_ROUND_BRACKET: ')',
11842 CLOSE_SQUARE_BRACKET: ']',
11847 FORWARD_SLASH: '/',
11848 INTERNAL: '-clean-css-',
11849 NEW_LINE_NIX: '\n',
11850 OPEN_CURLY_BRACKET: '{',
11851 OPEN_ROUND_BRACKET: '(',
11852 OPEN_SQUARE_BRACKET: '[',
11854 SINGLE_QUOTE: '\'',
11860 module.exports = Marker;
11862 },{}],84:[function(require,module,exports){
11864 AT_RULE: 'at-rule', // e.g. `@import`, `@charset`
11865 AT_RULE_BLOCK: 'at-rule-block', // e.g. `@font-face{...}`
11866 AT_RULE_BLOCK_SCOPE: 'at-rule-block-scope', // e.g. `@font-face`
11867 COMMENT: 'comment', // e.g. `/* comment */`
11868 NESTED_BLOCK: 'nested-block', // e.g. `@media screen{...}`, `@keyframes animation {...}`
11869 NESTED_BLOCK_SCOPE: 'nested-block-scope', // e.g. `@media`, `@keyframes`
11870 PROPERTY: 'property', // e.g. `color:red`
11871 PROPERTY_BLOCK: 'property-block', // e.g. `--var:{color:red}`
11872 PROPERTY_NAME: 'property-name', // e.g. `color`
11873 PROPERTY_VALUE: 'property-value', // e.g. `red`
11874 RAW: 'raw', // e.g. anything between /* clean-css ignore:start */ and /* clean-css ignore:end */ comments
11875 RULE: 'rule', // e.g `div > a{...}`
11876 RULE_SCOPE: 'rule-scope' // e.g `div > a`
11879 module.exports = Token;
11881 },{}],85:[function(require,module,exports){
11882 var Marker = require('./marker');
11883 var Token = require('./token');
11885 var formatPosition = require('../utils/format-position');
11889 COMMENT: 'comment',
11890 DOUBLE_QUOTE: 'double-quote',
11892 SINGLE_QUOTE: 'single-quote'
11900 var BLOCK_RULES = [
11906 '@-webkit-keyframes',
11912 var IGNORE_END_COMMENT_PATTERN = /\/\* clean\-css ignore:end \*\/$/;
11913 var IGNORE_START_COMMENT_PATTERN = /^\/\* clean\-css ignore:start \*\//;
11915 var PAGE_MARGIN_BOXES = [
11918 '@bottom-left-corner',
11920 '@bottom-right-corner',
11929 '@top-left-corner',
11931 '@top-right-corner'
11934 var EXTRA_PAGE_BOXES = [
11938 '@page-float-bottom',
11943 var REPEAT_PATTERN = /^\[\s{0,31}\d+\s{0,31}\]$/;
11944 var RULE_WORD_SEPARATOR_PATTERN = /[\s\(]/;
11945 var TAIL_BROKEN_VALUE_PATTERN = /[\s|\}]*$/;
11947 function tokenize(source, externalContext) {
11948 var internalContext = {
11949 level: Level.BLOCK,
11951 source: externalContext.source || undefined,
11958 return intoTokens(source, externalContext, internalContext, false);
11961 function intoTokens(source, externalContext, internalContext, isNested) {
11962 var allTokens = [];
11963 var newTokens = allTokens;
11966 var ruleTokens = [];
11969 var metadatas = [];
11970 var level = internalContext.level;
11974 var serializedBuffer;
11975 var serializedBufferPart;
11976 var roundBracketLevel = 0;
11981 var isCarriageReturn;
11982 var isCommentStart;
11983 var wasCommentStart = false;
11985 var wasCommentEnd = false;
11986 var isCommentEndMarker;
11988 var wasEscaped = false;
11990 var seekingValue = false;
11991 var seekingPropertyBlockClosing = false;
11992 var position = internalContext.position;
11993 var lastCommentStartAt;
11995 for (; position.index < source.length; position.index++) {
11996 var character = source[position.index];
11998 isQuoted = level == Level.SINGLE_QUOTE || level == Level.DOUBLE_QUOTE;
11999 isSpace = character == Marker.SPACE || character == Marker.TAB;
12000 isNewLineNix = character == Marker.NEW_LINE_NIX;
12001 isNewLineWin = character == Marker.NEW_LINE_NIX && source[position.index - 1] == Marker.CARRIAGE_RETURN;
12002 isCarriageReturn = character == Marker.CARRIAGE_RETURN && source[position.index + 1] && source[position.index + 1] != Marker.NEW_LINE_NIX;
12003 isCommentStart = !wasCommentEnd && level != Level.COMMENT && !isQuoted && character == Marker.ASTERISK && source[position.index - 1] == Marker.FORWARD_SLASH;
12004 isCommentEndMarker = !wasCommentStart && !isQuoted && character == Marker.FORWARD_SLASH && source[position.index - 1] == Marker.ASTERISK;
12005 isCommentEnd = level == Level.COMMENT && isCommentEndMarker;
12006 roundBracketLevel = Math.max(roundBracketLevel, 0);
12008 metadata = buffer.length === 0 ?
12009 [position.line, position.column, position.source] :
12013 // previous character was a backslash
12014 buffer.push(character);
12015 } else if (!isCommentEnd && level == Level.COMMENT) {
12016 buffer.push(character);
12017 } else if (!isCommentStart && !isCommentEnd && isRaw) {
12018 buffer.push(character);
12019 } else if (isCommentStart && (level == Level.BLOCK || level == Level.RULE) && buffer.length > 1) {
12020 // comment start within block preceded by some content, e.g. div/*<--
12021 metadatas.push(metadata);
12022 buffer.push(character);
12023 buffers.push(buffer.slice(0, buffer.length - 2));
12025 buffer = buffer.slice(buffer.length - 2);
12026 metadata = [position.line, position.column - 1, position.source];
12028 levels.push(level);
12029 level = Level.COMMENT;
12030 } else if (isCommentStart) {
12031 // comment start, e.g. /*<--
12032 levels.push(level);
12033 level = Level.COMMENT;
12034 buffer.push(character);
12035 } else if (isCommentEnd && isIgnoreStartComment(buffer)) {
12036 // ignore:start comment end, e.g. /* clean-css ignore:start */<--
12037 serializedBuffer = buffer.join('').trim() + character;
12038 lastToken = [Token.COMMENT, serializedBuffer, [originalMetadata(metadata, serializedBuffer, externalContext)]];
12039 newTokens.push(lastToken);
12042 metadata = metadatas.pop() || null;
12043 buffer = buffers.pop() || [];
12044 } else if (isCommentEnd && isIgnoreEndComment(buffer)) {
12045 // ignore:start comment end, e.g. /* clean-css ignore:end */<--
12046 serializedBuffer = buffer.join('') + character;
12047 lastCommentStartAt = serializedBuffer.lastIndexOf(Marker.FORWARD_SLASH + Marker.ASTERISK);
12049 serializedBufferPart = serializedBuffer.substring(0, lastCommentStartAt);
12050 lastToken = [Token.RAW, serializedBufferPart, [originalMetadata(metadata, serializedBufferPart, externalContext)]];
12051 newTokens.push(lastToken);
12053 serializedBufferPart = serializedBuffer.substring(lastCommentStartAt);
12054 metadata = [position.line, position.column - serializedBufferPart.length + 1, position.source];
12055 lastToken = [Token.COMMENT, serializedBufferPart, [originalMetadata(metadata, serializedBufferPart, externalContext)]];
12056 newTokens.push(lastToken);
12059 level = levels.pop();
12060 metadata = metadatas.pop() || null;
12061 buffer = buffers.pop() || [];
12062 } else if (isCommentEnd) {
12063 // comment end, e.g. /* comment */<--
12064 serializedBuffer = buffer.join('').trim() + character;
12065 lastToken = [Token.COMMENT, serializedBuffer, [originalMetadata(metadata, serializedBuffer, externalContext)]];
12066 newTokens.push(lastToken);
12068 level = levels.pop();
12069 metadata = metadatas.pop() || null;
12070 buffer = buffers.pop() || [];
12071 } else if (isCommentEndMarker && source[position.index + 1] != Marker.ASTERISK) {
12072 externalContext.warnings.push('Unexpected \'*/\' at ' + formatPosition([position.line, position.column, position.source]) + '.');
12074 } else if (character == Marker.SINGLE_QUOTE && !isQuoted) {
12075 // single quotation start, e.g. a[href^='https<--
12076 levels.push(level);
12077 level = Level.SINGLE_QUOTE;
12078 buffer.push(character);
12079 } else if (character == Marker.SINGLE_QUOTE && level == Level.SINGLE_QUOTE) {
12080 // single quotation end, e.g. a[href^='https'<--
12081 level = levels.pop();
12082 buffer.push(character);
12083 } else if (character == Marker.DOUBLE_QUOTE && !isQuoted) {
12084 // double quotation start, e.g. a[href^="<--
12085 levels.push(level);
12086 level = Level.DOUBLE_QUOTE;
12087 buffer.push(character);
12088 } else if (character == Marker.DOUBLE_QUOTE && level == Level.DOUBLE_QUOTE) {
12089 // double quotation end, e.g. a[href^="https"<--
12090 level = levels.pop();
12091 buffer.push(character);
12092 } else if (!isCommentStart && !isCommentEnd && character != Marker.CLOSE_ROUND_BRACKET && character != Marker.OPEN_ROUND_BRACKET && level != Level.COMMENT && !isQuoted && roundBracketLevel > 0) {
12093 // character inside any function, e.g. hsla(.<--
12094 buffer.push(character);
12095 } else if (character == Marker.OPEN_ROUND_BRACKET && !isQuoted && level != Level.COMMENT && !seekingValue) {
12096 // round open bracket, e.g. @import url(<--
12097 buffer.push(character);
12099 roundBracketLevel++;
12100 } else if (character == Marker.CLOSE_ROUND_BRACKET && !isQuoted && level != Level.COMMENT && !seekingValue) {
12101 // round open bracket, e.g. @import url(test.css)<--
12102 buffer.push(character);
12104 roundBracketLevel--;
12105 } else if (character == Marker.SEMICOLON && level == Level.BLOCK && buffer[0] == Marker.AT) {
12106 // semicolon ending rule at block level, e.g. @import '...';<--
12107 serializedBuffer = buffer.join('').trim();
12108 allTokens.push([Token.AT_RULE, serializedBuffer, [originalMetadata(metadata, serializedBuffer, externalContext)]]);
12111 } else if (character == Marker.COMMA && level == Level.BLOCK && ruleToken) {
12112 // comma separator at block level, e.g. a,div,<--
12113 serializedBuffer = buffer.join('').trim();
12114 ruleToken[1].push([tokenScopeFrom(ruleToken[0]), serializedBuffer, [originalMetadata(metadata, serializedBuffer, externalContext, ruleToken[1].length)]]);
12117 } else if (character == Marker.COMMA && level == Level.BLOCK && tokenTypeFrom(buffer) == Token.AT_RULE) {
12118 // comma separator at block level, e.g. @import url(...) screen,<--
12119 // keep iterating as end semicolon will create the token
12120 buffer.push(character);
12121 } else if (character == Marker.COMMA && level == Level.BLOCK) {
12122 // comma separator at block level, e.g. a,<--
12123 ruleToken = [tokenTypeFrom(buffer), [], []];
12124 serializedBuffer = buffer.join('').trim();
12125 ruleToken[1].push([tokenScopeFrom(ruleToken[0]), serializedBuffer, [originalMetadata(metadata, serializedBuffer, externalContext, 0)]]);
12128 } else if (character == Marker.OPEN_CURLY_BRACKET && level == Level.BLOCK && ruleToken && ruleToken[0] == Token.NESTED_BLOCK) {
12129 // open brace opening at-rule at block level, e.g. @media{<--
12130 serializedBuffer = buffer.join('').trim();
12131 ruleToken[1].push([Token.NESTED_BLOCK_SCOPE, serializedBuffer, [originalMetadata(metadata, serializedBuffer, externalContext)]]);
12132 allTokens.push(ruleToken);
12134 levels.push(level);
12139 ruleToken[2] = intoTokens(source, externalContext, internalContext, true);
12141 } else if (character == Marker.OPEN_CURLY_BRACKET && level == Level.BLOCK && tokenTypeFrom(buffer) == Token.NESTED_BLOCK) {
12142 // open brace opening at-rule at block level, e.g. @media{<--
12143 serializedBuffer = buffer.join('').trim();
12144 ruleToken = ruleToken || [Token.NESTED_BLOCK, [], []];
12145 ruleToken[1].push([Token.NESTED_BLOCK_SCOPE, serializedBuffer, [originalMetadata(metadata, serializedBuffer, externalContext)]]);
12146 allTokens.push(ruleToken);
12148 levels.push(level);
12153 ruleToken[2] = intoTokens(source, externalContext, internalContext, true);
12155 } else if (character == Marker.OPEN_CURLY_BRACKET && level == Level.BLOCK) {
12156 // open brace opening rule at block level, e.g. div{<--
12157 serializedBuffer = buffer.join('').trim();
12158 ruleToken = ruleToken || [tokenTypeFrom(buffer), [], []];
12159 ruleToken[1].push([tokenScopeFrom(ruleToken[0]), serializedBuffer, [originalMetadata(metadata, serializedBuffer, externalContext, ruleToken[1].length)]]);
12160 newTokens = ruleToken[2];
12161 allTokens.push(ruleToken);
12163 levels.push(level);
12164 level = Level.RULE;
12166 } else if (character == Marker.OPEN_CURLY_BRACKET && level == Level.RULE && seekingValue) {
12167 // open brace opening rule at rule level, e.g. div{--variable:{<--
12168 ruleTokens.push(ruleToken);
12169 ruleToken = [Token.PROPERTY_BLOCK, []];
12170 propertyToken.push(ruleToken);
12171 newTokens = ruleToken[1];
12173 levels.push(level);
12174 level = Level.RULE;
12175 seekingValue = false;
12176 } else if (character == Marker.OPEN_CURLY_BRACKET && level == Level.RULE && isPageMarginBox(buffer)) {
12177 // open brace opening page-margin box at rule level, e.g. @page{@top-center{<--
12178 serializedBuffer = buffer.join('').trim();
12179 ruleTokens.push(ruleToken);
12180 ruleToken = [Token.AT_RULE_BLOCK, [], []];
12181 ruleToken[1].push([Token.AT_RULE_BLOCK_SCOPE, serializedBuffer, [originalMetadata(metadata, serializedBuffer, externalContext)]]);
12182 newTokens.push(ruleToken);
12183 newTokens = ruleToken[2];
12185 levels.push(level);
12186 level = Level.RULE;
12188 } else if (character == Marker.COLON && level == Level.RULE && !seekingValue) {
12189 // colon at rule level, e.g. a{color:<--
12190 serializedBuffer = buffer.join('').trim();
12191 propertyToken = [Token.PROPERTY, [Token.PROPERTY_NAME, serializedBuffer, [originalMetadata(metadata, serializedBuffer, externalContext)]]];
12192 newTokens.push(propertyToken);
12194 seekingValue = true;
12196 } else if (character == Marker.SEMICOLON && level == Level.RULE && propertyToken && ruleTokens.length > 0 && buffer.length > 0 && buffer[0] == Marker.AT) {
12197 // semicolon at rule level for at-rule, e.g. a{--color:{@apply(--other-color);<--
12198 serializedBuffer = buffer.join('').trim();
12199 ruleToken[1].push([Token.AT_RULE, serializedBuffer, [originalMetadata(metadata, serializedBuffer, externalContext)]]);
12202 } else if (character == Marker.SEMICOLON && level == Level.RULE && propertyToken && buffer.length > 0) {
12203 // semicolon at rule level, e.g. a{color:red;<--
12204 serializedBuffer = buffer.join('').trim();
12205 propertyToken.push([Token.PROPERTY_VALUE, serializedBuffer, [originalMetadata(metadata, serializedBuffer, externalContext)]]);
12207 propertyToken = null;
12208 seekingValue = false;
12210 } else if (character == Marker.SEMICOLON && level == Level.RULE && propertyToken && buffer.length === 0) {
12211 // semicolon after bracketed value at rule level, e.g. a{color:rgb(...);<--
12212 propertyToken = null;
12213 seekingValue = false;
12214 } else if (character == Marker.SEMICOLON && level == Level.RULE && buffer.length > 0 && buffer[0] == Marker.AT) {
12215 // semicolon for at-rule at rule level, e.g. a{@apply(--variable);<--
12216 serializedBuffer = buffer.join('');
12217 newTokens.push([Token.AT_RULE, serializedBuffer, [originalMetadata(metadata, serializedBuffer, externalContext)]]);
12219 seekingValue = false;
12221 } else if (character == Marker.SEMICOLON && level == Level.RULE && seekingPropertyBlockClosing) {
12222 // close brace after a property block at rule level, e.g. a{--custom:{color:red;};<--
12223 seekingPropertyBlockClosing = false;
12225 } else if (character == Marker.SEMICOLON && level == Level.RULE && buffer.length === 0) {
12226 // stray semicolon at rule level, e.g. a{;<--
12228 } else if (character == Marker.CLOSE_CURLY_BRACKET && level == Level.RULE && propertyToken && seekingValue && buffer.length > 0 && ruleTokens.length > 0) {
12229 // close brace at rule level, e.g. a{--color:{color:red}<--
12230 serializedBuffer = buffer.join('');
12231 propertyToken.push([Token.PROPERTY_VALUE, serializedBuffer, [originalMetadata(metadata, serializedBuffer, externalContext)]]);
12232 propertyToken = null;
12233 ruleToken = ruleTokens.pop();
12234 newTokens = ruleToken[2];
12236 level = levels.pop();
12237 seekingValue = false;
12239 } else if (character == Marker.CLOSE_CURLY_BRACKET && level == Level.RULE && propertyToken && buffer.length > 0 && buffer[0] == Marker.AT && ruleTokens.length > 0) {
12240 // close brace at rule level for at-rule, e.g. a{--color:{@apply(--other-color)}<--
12241 serializedBuffer = buffer.join('');
12242 ruleToken[1].push([Token.AT_RULE, serializedBuffer, [originalMetadata(metadata, serializedBuffer, externalContext)]]);
12243 propertyToken = null;
12244 ruleToken = ruleTokens.pop();
12245 newTokens = ruleToken[2];
12247 level = levels.pop();
12248 seekingValue = false;
12250 } else if (character == Marker.CLOSE_CURLY_BRACKET && level == Level.RULE && propertyToken && ruleTokens.length > 0) {
12251 // close brace at rule level after space, e.g. a{--color:{color:red }<--
12252 propertyToken = null;
12253 ruleToken = ruleTokens.pop();
12254 newTokens = ruleToken[2];
12256 level = levels.pop();
12257 seekingValue = false;
12258 } else if (character == Marker.CLOSE_CURLY_BRACKET && level == Level.RULE && propertyToken && buffer.length > 0) {
12259 // close brace at rule level, e.g. a{color:red}<--
12260 serializedBuffer = buffer.join('');
12261 propertyToken.push([Token.PROPERTY_VALUE, serializedBuffer, [originalMetadata(metadata, serializedBuffer, externalContext)]]);
12262 propertyToken = null;
12263 ruleToken = ruleTokens.pop();
12264 newTokens = allTokens;
12266 level = levels.pop();
12267 seekingValue = false;
12269 } else if (character == Marker.CLOSE_CURLY_BRACKET && level == Level.RULE && buffer.length > 0 && buffer[0] == Marker.AT) {
12270 // close brace after at-rule at rule level, e.g. a{@apply(--variable)}<--
12271 propertyToken = null;
12273 serializedBuffer = buffer.join('').trim();
12274 newTokens.push([Token.AT_RULE, serializedBuffer, [originalMetadata(metadata, serializedBuffer, externalContext)]]);
12275 newTokens = allTokens;
12277 level = levels.pop();
12278 seekingValue = false;
12280 } else if (character == Marker.CLOSE_CURLY_BRACKET && level == Level.RULE && levels[levels.length - 1] == Level.RULE) {
12281 // close brace after a property block at rule level, e.g. a{--custom:{color:red;}<--
12282 propertyToken = null;
12283 ruleToken = ruleTokens.pop();
12284 newTokens = ruleToken[2];
12286 level = levels.pop();
12287 seekingValue = false;
12288 seekingPropertyBlockClosing = true;
12290 } else if (character == Marker.CLOSE_CURLY_BRACKET && level == Level.RULE) {
12291 // close brace after a rule, e.g. a{color:red;}<--
12292 propertyToken = null;
12294 newTokens = allTokens;
12296 level = levels.pop();
12297 seekingValue = false;
12298 } else if (character == Marker.CLOSE_CURLY_BRACKET && level == Level.BLOCK && !isNested && position.index <= source.length - 1) {
12299 // stray close brace at block level, e.g. a{color:red}color:blue}<--
12300 externalContext.warnings.push('Unexpected \'}\' at ' + formatPosition([position.line, position.column, position.source]) + '.');
12301 buffer.push(character);
12302 } else if (character == Marker.CLOSE_CURLY_BRACKET && level == Level.BLOCK) {
12303 // close brace at block level, e.g. @media screen {...}<--
12305 } else if (character == Marker.OPEN_ROUND_BRACKET && level == Level.RULE && seekingValue) {
12306 // round open bracket, e.g. a{color:hsla(<--
12307 buffer.push(character);
12308 roundBracketLevel++;
12309 } else if (character == Marker.CLOSE_ROUND_BRACKET && level == Level.RULE && seekingValue && roundBracketLevel == 1) {
12310 // round close bracket, e.g. a{color:hsla(0,0%,0%)<--
12311 buffer.push(character);
12312 serializedBuffer = buffer.join('').trim();
12313 propertyToken.push([Token.PROPERTY_VALUE, serializedBuffer, [originalMetadata(metadata, serializedBuffer, externalContext)]]);
12315 roundBracketLevel--;
12317 } else if (character == Marker.CLOSE_ROUND_BRACKET && level == Level.RULE && seekingValue) {
12318 // round close bracket within other brackets, e.g. a{width:calc((10rem / 2)<--
12319 buffer.push(character);
12320 roundBracketLevel--;
12321 } else if (character == Marker.FORWARD_SLASH && source[position.index + 1] != Marker.ASTERISK && level == Level.RULE && seekingValue && buffer.length > 0) {
12322 // forward slash within a property, e.g. a{background:url(image.png) 0 0/<--
12323 serializedBuffer = buffer.join('').trim();
12324 propertyToken.push([Token.PROPERTY_VALUE, serializedBuffer, [originalMetadata(metadata, serializedBuffer, externalContext)]]);
12325 propertyToken.push([Token.PROPERTY_VALUE, character, [[position.line, position.column, position.source]]]);
12328 } else if (character == Marker.FORWARD_SLASH && source[position.index + 1] != Marker.ASTERISK && level == Level.RULE && seekingValue) {
12329 // forward slash within a property after space, e.g. a{background:url(image.png) 0 0 /<--
12330 propertyToken.push([Token.PROPERTY_VALUE, character, [[position.line, position.column, position.source]]]);
12333 } else if (character == Marker.COMMA && level == Level.RULE && seekingValue && buffer.length > 0) {
12334 // comma within a property, e.g. a{background:url(image.png),<--
12335 serializedBuffer = buffer.join('').trim();
12336 propertyToken.push([Token.PROPERTY_VALUE, serializedBuffer, [originalMetadata(metadata, serializedBuffer, externalContext)]]);
12337 propertyToken.push([Token.PROPERTY_VALUE, character, [[position.line, position.column, position.source]]]);
12340 } else if (character == Marker.COMMA && level == Level.RULE && seekingValue) {
12341 // comma within a property after space, e.g. a{background:url(image.png) ,<--
12342 propertyToken.push([Token.PROPERTY_VALUE, character, [[position.line, position.column, position.source]]]);
12345 } else if (character == Marker.CLOSE_SQUARE_BRACKET && propertyToken && propertyToken.length > 1 && buffer.length > 0 && isRepeatToken(buffer)) {
12346 buffer.push(character);
12347 serializedBuffer = buffer.join('').trim();
12348 propertyToken[propertyToken.length - 1][1] += serializedBuffer;
12351 } else if ((isSpace || (isNewLineNix && !isNewLineWin)) && level == Level.RULE && seekingValue && propertyToken && buffer.length > 0) {
12352 // space or *nix newline within property, e.g. a{margin:0 <--
12353 serializedBuffer = buffer.join('').trim();
12354 propertyToken.push([Token.PROPERTY_VALUE, serializedBuffer, [originalMetadata(metadata, serializedBuffer, externalContext)]]);
12357 } else if (isNewLineWin && level == Level.RULE && seekingValue && propertyToken && buffer.length > 1) {
12358 // win newline within property, e.g. a{margin:0\r\n<--
12359 serializedBuffer = buffer.join('').trim();
12360 propertyToken.push([Token.PROPERTY_VALUE, serializedBuffer, [originalMetadata(metadata, serializedBuffer, externalContext)]]);
12363 } else if (isNewLineWin && level == Level.RULE && seekingValue) {
12366 } else if (buffer.length == 1 && isNewLineWin) {
12367 // ignore windows newline which is composed of two characters
12369 } else if (buffer.length > 0 || !isSpace && !isNewLineNix && !isNewLineWin && !isCarriageReturn) {
12371 buffer.push(character);
12374 wasEscaped = isEscaped;
12375 isEscaped = !wasEscaped && character == Marker.BACK_SLASH;
12376 wasCommentStart = isCommentStart;
12377 wasCommentEnd = isCommentEnd;
12379 position.line = (isNewLineWin || isNewLineNix || isCarriageReturn) ? position.line + 1 : position.line;
12380 position.column = (isNewLineWin || isNewLineNix || isCarriageReturn) ? 0 : position.column + 1;
12383 if (seekingValue) {
12384 externalContext.warnings.push('Missing \'}\' at ' + formatPosition([position.line, position.column, position.source]) + '.');
12387 if (seekingValue && buffer.length > 0) {
12388 serializedBuffer = buffer.join('').replace(TAIL_BROKEN_VALUE_PATTERN, '');
12389 propertyToken.push([Token.PROPERTY_VALUE, serializedBuffer, [originalMetadata(metadata, serializedBuffer, externalContext)]]);
12394 if (buffer.length > 0) {
12395 externalContext.warnings.push('Invalid character(s) \'' + buffer.join('') + '\' at ' + formatPosition(metadata) + '. Ignoring.');
12401 function isIgnoreStartComment(buffer) {
12402 return IGNORE_START_COMMENT_PATTERN.test(buffer.join('') + Marker.FORWARD_SLASH);
12405 function isIgnoreEndComment(buffer) {
12406 return IGNORE_END_COMMENT_PATTERN.test(buffer.join('') + Marker.FORWARD_SLASH);
12409 function originalMetadata(metadata, value, externalContext, selectorFallbacks) {
12410 var source = metadata[2];
12412 return externalContext.inputSourceMapTracker.isTracking(source) ?
12413 externalContext.inputSourceMapTracker.originalPositionFor(metadata, value.length, selectorFallbacks) :
12417 function tokenTypeFrom(buffer) {
12418 var isAtRule = buffer[0] == Marker.AT || buffer[0] == Marker.UNDERSCORE;
12419 var ruleWord = buffer.join('').split(RULE_WORD_SEPARATOR_PATTERN)[0];
12421 if (isAtRule && BLOCK_RULES.indexOf(ruleWord) > -1) {
12422 return Token.NESTED_BLOCK;
12423 } else if (isAtRule && AT_RULES.indexOf(ruleWord) > -1) {
12424 return Token.AT_RULE;
12425 } else if (isAtRule) {
12426 return Token.AT_RULE_BLOCK;
12432 function tokenScopeFrom(tokenType) {
12433 if (tokenType == Token.RULE) {
12434 return Token.RULE_SCOPE;
12435 } else if (tokenType == Token.NESTED_BLOCK) {
12436 return Token.NESTED_BLOCK_SCOPE;
12437 } else if (tokenType == Token.AT_RULE_BLOCK) {
12438 return Token.AT_RULE_BLOCK_SCOPE;
12442 function isPageMarginBox(buffer) {
12443 var serializedBuffer = buffer.join('').trim();
12445 return PAGE_MARGIN_BOXES.indexOf(serializedBuffer) > -1 || EXTRA_PAGE_BOXES.indexOf(serializedBuffer) > -1;
12448 function isRepeatToken(buffer) {
12449 return REPEAT_PATTERN.test(buffer.join('') + Marker.CLOSE_SQUARE_BRACKET);
12452 module.exports = tokenize;
12454 },{"../utils/format-position":87,"./marker":83,"./token":84}],86:[function(require,module,exports){
12455 function cloneArray(array) {
12456 var cloned = array.slice(0);
12458 for (var i = 0, l = cloned.length; i < l; i++) {
12459 if (Array.isArray(cloned[i]))
12460 cloned[i] = cloneArray(cloned[i]);
12466 module.exports = cloneArray;
12468 },{}],87:[function(require,module,exports){
12469 function formatPosition(metadata) {
12470 var line = metadata[0];
12471 var column = metadata[1];
12472 var source = metadata[2];
12475 source + ':' + line + ':' + column :
12476 line + ':' + column;
12479 module.exports = formatPosition;
12481 },{}],88:[function(require,module,exports){
12482 var NO_PROTOCOL_RESOURCE_PATTERN = /^\/\//;
12484 function hasProtocol(uri) {
12485 return !NO_PROTOCOL_RESOURCE_PATTERN.test(uri);
12488 module.exports = hasProtocol;
12490 },{}],89:[function(require,module,exports){
12491 var DATA_URI_PATTERN = /^data:(\S*?)?(;charset=[^;]+)?(;[^,]+?)?,(.+)/;
12493 function isDataUriResource(uri) {
12494 return DATA_URI_PATTERN.test(uri);
12497 module.exports = isDataUriResource;
12499 },{}],90:[function(require,module,exports){
12500 var HTTP_RESOURCE_PATTERN = /^http:\/\//;
12502 function isHttpResource(uri) {
12503 return HTTP_RESOURCE_PATTERN.test(uri);
12506 module.exports = isHttpResource;
12508 },{}],91:[function(require,module,exports){
12509 var HTTPS_RESOURCE_PATTERN = /^https:\/\//;
12511 function isHttpsResource(uri) {
12512 return HTTPS_RESOURCE_PATTERN.test(uri);
12515 module.exports = isHttpsResource;
12517 },{}],92:[function(require,module,exports){
12518 var IMPORT_PREFIX_PATTERN = /^@import/i;
12520 function isImport(value) {
12521 return IMPORT_PREFIX_PATTERN.test(value);
12524 module.exports = isImport;
12526 },{}],93:[function(require,module,exports){
12527 var REMOTE_RESOURCE_PATTERN = /^(\w+:\/\/|\/\/)/;
12529 function isRemoteResource(uri) {
12530 return REMOTE_RESOURCE_PATTERN.test(uri);
12533 module.exports = isRemoteResource;
12535 },{}],94:[function(require,module,exports){
12536 // adapted from http://nedbatchelder.com/blog/200712.html#e20071211T054956
12538 var NUMBER_PATTERN = /([0-9]+)/;
12540 function naturalCompare(value1, value2) {
12541 var keys1 = ('' + value1).split(NUMBER_PATTERN).map(tryParseInt);
12542 var keys2 = ('' + value2).split(NUMBER_PATTERN).map(tryParseInt);
12545 var compareFirst = Math.min(keys1.length, keys2.length);
12548 for (i = 0, l = compareFirst; i < l; i++) {
12552 if (key1 != key2) {
12553 return key1 > key2 ? 1 : -1;
12557 return keys1.length > keys2.length ? 1 : (keys1.length == keys2.length ? 0 : -1);
12560 function tryParseInt(value) {
12561 return ('' + parseInt(value)) == value ?
12566 module.exports = naturalCompare;
12568 },{}],95:[function(require,module,exports){
12569 function override(source1, source2) {
12575 for (key1 in source1) {
12576 item = source1[key1];
12578 if (Array.isArray(item)) {
12579 target[key1] = item.slice(0);
12580 } else if (typeof item == 'object' && item !== null) {
12581 target[key1] = override(item, {});
12583 target[key1] = item;
12587 for (key2 in source2) {
12588 item = source2[key2];
12590 if (key2 in target && Array.isArray(item)) {
12591 target[key2] = item.slice(0);
12592 } else if (key2 in target && typeof item == 'object' && item !== null) {
12593 target[key2] = override(target[key2], item);
12595 target[key2] = item;
12602 module.exports = override;
12604 },{}],96:[function(require,module,exports){
12605 var Marker = require('../tokenizer/marker');
12607 function split(value, separator) {
12608 var openLevel = Marker.OPEN_ROUND_BRACKET;
12609 var closeLevel = Marker.CLOSE_ROUND_BRACKET;
12615 var len = value.length;
12618 if (value.indexOf(separator) == -1) {
12622 if (value.indexOf(openLevel) == -1) {
12623 return value.split(separator);
12626 while (cursor < len) {
12627 if (value[cursor] == openLevel) {
12629 } else if (value[cursor] == closeLevel) {
12633 if (level === 0 && cursor > 0 && cursor + 1 < len && value[cursor] == separator) {
12634 parts.push(value.substring(lastStart, cursor));
12635 lastStart = cursor + 1;
12641 if (lastStart < cursor + 1) {
12642 lastValue = value.substring(lastStart);
12643 lastCharacter = lastValue[lastValue.length - 1];
12644 if (lastCharacter == separator) {
12645 lastValue = lastValue.substring(0, lastValue.length - 1);
12648 parts.push(lastValue);
12654 module.exports = split;
12656 },{"../tokenizer/marker":83}],97:[function(require,module,exports){
12657 var emptyCharacter = '';
12659 var Breaks = require('../options/format').Breaks;
12660 var Spaces = require('../options/format').Spaces;
12662 var Marker = require('../tokenizer/marker');
12663 var Token = require('../tokenizer/token');
12665 function supportsAfterClosingBrace(token) {
12666 return token[1][1] == 'background' || token[1][1] == 'transform' || token[1][1] == 'src';
12669 function afterClosingBrace(token, valueIndex) {
12670 return token[valueIndex][1][token[valueIndex][1].length - 1] == Marker.CLOSE_ROUND_BRACKET;
12673 function afterComma(token, valueIndex) {
12674 return token[valueIndex][1] == Marker.COMMA;
12677 function afterSlash(token, valueIndex) {
12678 return token[valueIndex][1] == Marker.FORWARD_SLASH;
12681 function beforeComma(token, valueIndex) {
12682 return token[valueIndex + 1] && token[valueIndex + 1][1] == Marker.COMMA;
12685 function beforeSlash(token, valueIndex) {
12686 return token[valueIndex + 1] && token[valueIndex + 1][1] == Marker.FORWARD_SLASH;
12689 function inFilter(token) {
12690 return token[1][1] == 'filter' || token[1][1] == '-ms-filter';
12693 function disallowsSpace(context, token, valueIndex) {
12694 return !context.spaceAfterClosingBrace && supportsAfterClosingBrace(token) && afterClosingBrace(token, valueIndex) ||
12695 beforeSlash(token, valueIndex) ||
12696 afterSlash(token, valueIndex) ||
12697 beforeComma(token, valueIndex) ||
12698 afterComma(token, valueIndex);
12701 function rules(context, tokens) {
12702 var store = context.store;
12704 for (var i = 0, l = tokens.length; i < l; i++) {
12705 store(context, tokens[i]);
12708 store(context, comma(context));
12713 function body(context, tokens) {
12714 var lastPropertyAt = lastPropertyIndex(tokens);
12716 for (var i = 0, l = tokens.length; i < l; i++) {
12717 property(context, tokens, i, lastPropertyAt);
12721 function lastPropertyIndex(tokens) {
12722 var index = tokens.length - 1;
12724 for (; index >= 0; index--) {
12725 if (tokens[index][0] != Token.COMMENT) {
12733 function property(context, tokens, position, lastPropertyAt) {
12734 var store = context.store;
12735 var token = tokens[position];
12736 var isPropertyBlock = token[2][0] == Token.PROPERTY_BLOCK;
12738 var needsSemicolon;
12739 if ( context.format ) {
12740 if ( context.format.semicolonAfterLastProperty || isPropertyBlock ) {
12741 needsSemicolon = true;
12742 } else if ( position < lastPropertyAt ) {
12743 needsSemicolon = true;
12745 needsSemicolon = false;
12748 needsSemicolon = position < lastPropertyAt || isPropertyBlock;
12751 var isLast = position === lastPropertyAt;
12753 switch (token[0]) {
12754 case Token.AT_RULE:
12755 store(context, token);
12756 store(context, semicolon(context, Breaks.AfterProperty, false));
12758 case Token.AT_RULE_BLOCK:
12759 rules(context, token[1]);
12760 store(context, openBrace(context, Breaks.AfterRuleBegins, true));
12761 body(context, token[2]);
12762 store(context, closeBrace(context, Breaks.AfterRuleEnds, false, isLast));
12764 case Token.COMMENT:
12765 store(context, token);
12767 case Token.PROPERTY:
12768 store(context, token[1]);
12769 store(context, colon(context));
12770 value(context, token);
12771 store(context, needsSemicolon ? semicolon(context, Breaks.AfterProperty, isLast) : emptyCharacter);
12774 store(context, token);
12778 function value(context, token) {
12779 var store = context.store;
12782 if (token[2][0] == Token.PROPERTY_BLOCK) {
12783 store(context, openBrace(context, Breaks.AfterBlockBegins, false));
12784 body(context, token[2][1]);
12785 store(context, closeBrace(context, Breaks.AfterBlockEnds, false, true));
12787 for (j = 2, m = token.length; j < m; j++) {
12788 store(context, token[j]);
12790 if (j < m - 1 && (inFilter(token) || !disallowsSpace(context, token, j))) {
12791 store(context, Marker.SPACE);
12797 function allowsBreak(context, where) {
12798 return context.format && context.format.breaks[where];
12801 function allowsSpace(context, where) {
12802 return context.format && context.format.spaces[where];
12805 function openBrace(context, where, needsPrefixSpace) {
12806 if (context.format) {
12807 context.indentBy += context.format.indentBy;
12808 context.indentWith = context.format.indentWith.repeat(context.indentBy);
12809 return (needsPrefixSpace && allowsSpace(context, Spaces.BeforeBlockBegins) ? Marker.SPACE : emptyCharacter) +
12810 Marker.OPEN_CURLY_BRACKET +
12811 (allowsBreak(context, where) ? context.format.breakWith : emptyCharacter) +
12812 context.indentWith;
12814 return Marker.OPEN_CURLY_BRACKET;
12818 function closeBrace(context, where, beforeBlockEnd, isLast) {
12819 if (context.format) {
12820 context.indentBy -= context.format.indentBy;
12821 context.indentWith = context.format.indentWith.repeat(context.indentBy);
12822 return (allowsBreak(context, Breaks.AfterProperty) || beforeBlockEnd && allowsBreak(context, Breaks.BeforeBlockEnds) ? context.format.breakWith : emptyCharacter) +
12823 context.indentWith +
12824 Marker.CLOSE_CURLY_BRACKET +
12825 (isLast ? emptyCharacter : (allowsBreak(context, where) ? context.format.breakWith : emptyCharacter) + context.indentWith);
12827 return Marker.CLOSE_CURLY_BRACKET;
12831 function colon(context) {
12832 return context.format ?
12833 Marker.COLON + (allowsSpace(context, Spaces.BeforeValue) ? Marker.SPACE : emptyCharacter) :
12837 function semicolon(context, where, isLast) {
12838 return context.format ?
12839 Marker.SEMICOLON + (isLast || !allowsBreak(context, where) ? emptyCharacter : context.format.breakWith + context.indentWith) :
12843 function comma(context) {
12844 return context.format ?
12845 Marker.COMMA + (allowsBreak(context, Breaks.BetweenSelectors) ? context.format.breakWith : emptyCharacter) + context.indentWith :
12849 function all(context, tokens) {
12850 var store = context.store;
12855 for (i = 0, l = tokens.length; i < l; i++) {
12857 isLast = i == l - 1;
12859 switch (token[0]) {
12860 case Token.AT_RULE:
12861 store(context, token);
12862 store(context, semicolon(context, Breaks.AfterAtRule, isLast));
12864 case Token.AT_RULE_BLOCK:
12865 rules(context, token[1]);
12866 store(context, openBrace(context, Breaks.AfterRuleBegins, true));
12867 body(context, token[2]);
12868 store(context, closeBrace(context, Breaks.AfterRuleEnds, false, isLast));
12870 case Token.NESTED_BLOCK:
12871 rules(context, token[1]);
12872 store(context, openBrace(context, Breaks.AfterBlockBegins, true));
12873 all(context, token[2]);
12874 store(context, closeBrace(context, Breaks.AfterBlockEnds, true, isLast));
12876 case Token.COMMENT:
12877 store(context, token);
12878 store(context, allowsBreak(context, Breaks.AfterComment) ? context.format.breakWith : emptyCharacter);
12881 store(context, token);
12884 rules(context, token[1]);
12885 store(context, openBrace(context, Breaks.AfterRuleBegins, true));
12886 body(context, token[2]);
12887 store(context, closeBrace(context, Breaks.AfterRuleEnds, false, isLast));
12896 property: property,
12901 },{"../options/format":61,"../tokenizer/marker":83,"../tokenizer/token":84}],98:[function(require,module,exports){
12902 var helpers = require('./helpers');
12904 function store(serializeContext, token) {
12905 serializeContext.output.push(typeof token == 'string' ? token : token[1]);
12908 function context() {
12917 function all(tokens) {
12918 var oneTimeContext = context();
12919 helpers.all(oneTimeContext, tokens);
12920 return oneTimeContext.output.join('');
12923 function body(tokens) {
12924 var oneTimeContext = context();
12925 helpers.body(oneTimeContext, tokens);
12926 return oneTimeContext.output.join('');
12929 function property(tokens, position) {
12930 var oneTimeContext = context();
12931 helpers.property(oneTimeContext, tokens, position, true);
12932 return oneTimeContext.output.join('');
12935 function rules(tokens) {
12936 var oneTimeContext = context();
12937 helpers.rules(oneTimeContext, tokens);
12938 return oneTimeContext.output.join('');
12941 function value(tokens) {
12942 var oneTimeContext = context();
12943 helpers.value(oneTimeContext, tokens);
12944 return oneTimeContext.output.join('');
12950 property: property,
12955 },{"./helpers":97}],99:[function(require,module,exports){
12956 var all = require('./helpers').all;
12958 function store(serializeContext, token) {
12959 var value = typeof token == 'string' ?
12962 var wrap = serializeContext.wrap;
12964 wrap(serializeContext, value);
12965 track(serializeContext, value);
12966 serializeContext.output.push(value);
12969 function wrap(serializeContext, value) {
12970 if (serializeContext.column + value.length > serializeContext.format.wrapAt) {
12971 track(serializeContext, serializeContext.format.breakWith);
12972 serializeContext.output.push(serializeContext.format.breakWith);
12976 function track(serializeContext, value) {
12977 var parts = value.split('\n');
12979 serializeContext.line += parts.length - 1;
12980 serializeContext.column = parts.length > 1 ? 0 : (serializeContext.column + parts.pop().length);
12983 function serializeStyles(tokens, context) {
12984 var serializeContext = {
12986 format: context.options.format,
12991 spaceAfterClosingBrace: context.options.compatibility.properties.spaceAfterClosingBrace,
12993 wrap: context.options.format.wrapAt ?
12995 function () { /* noop */ }
12998 all(serializeContext, tokens);
13001 styles: serializeContext.output.join('')
13005 module.exports = serializeStyles;
13007 },{"./helpers":97}],100:[function(require,module,exports){
13008 (function (process){
13009 var SourceMapGenerator = require('source-map').SourceMapGenerator;
13010 var all = require('./helpers').all;
13012 var isRemoteResource = require('../utils/is-remote-resource');
13014 var isWindows = process.platform == 'win32';
13016 var NIX_SEPARATOR_PATTERN = /\//g;
13017 var UNKNOWN_SOURCE = '$stdin';
13018 var WINDOWS_SEPARATOR = '\\';
13020 function store(serializeContext, element) {
13021 var fromString = typeof element == 'string';
13022 var value = fromString ? element : element[1];
13023 var mappings = fromString ? null : element[2];
13024 var wrap = serializeContext.wrap;
13026 wrap(serializeContext, value);
13027 track(serializeContext, value, mappings);
13028 serializeContext.output.push(value);
13031 function wrap(serializeContext, value) {
13032 if (serializeContext.column + value.length > serializeContext.format.wrapAt) {
13033 track(serializeContext, serializeContext.format.breakWith, false);
13034 serializeContext.output.push(serializeContext.format.breakWith);
13038 function track(serializeContext, value, mappings) {
13039 var parts = value.split('\n');
13042 trackAllMappings(serializeContext, mappings);
13045 serializeContext.line += parts.length - 1;
13046 serializeContext.column = parts.length > 1 ? 0 : (serializeContext.column + parts.pop().length);
13049 function trackAllMappings(serializeContext, mappings) {
13050 for (var i = 0, l = mappings.length; i < l; i++) {
13051 trackMapping(serializeContext, mappings[i]);
13055 function trackMapping(serializeContext, mapping) {
13056 var line = mapping[0];
13057 var column = mapping[1];
13058 var originalSource = mapping[2];
13059 var source = originalSource;
13060 var storedSource = source || UNKNOWN_SOURCE;
13062 if (isWindows && source && !isRemoteResource(source)) {
13063 storedSource = source.replace(NIX_SEPARATOR_PATTERN, WINDOWS_SEPARATOR);
13066 serializeContext.outputMap.addMapping({
13068 line: serializeContext.line,
13069 column: serializeContext.column
13071 source: storedSource,
13078 if (serializeContext.inlineSources && (originalSource in serializeContext.sourcesContent)) {
13079 serializeContext.outputMap.setSourceContent(storedSource, serializeContext.sourcesContent[originalSource]);
13083 function serializeStylesAndSourceMap(tokens, context) {
13084 var serializeContext = {
13086 format: context.options.format,
13089 inlineSources: context.options.sourceMapInlineSources,
13092 outputMap: new SourceMapGenerator(),
13093 sourcesContent: context.sourcesContent,
13094 spaceAfterClosingBrace: context.options.compatibility.properties.spaceAfterClosingBrace,
13096 wrap: context.options.format.wrapAt ?
13098 function () { /* noop */ }
13101 all(serializeContext, tokens);
13104 sourceMap: serializeContext.outputMap,
13105 styles: serializeContext.output.join('')
13109 module.exports = serializeStylesAndSourceMap;
13111 }).call(this,require('_process'))
13112 },{"../utils/is-remote-resource":93,"./helpers":97,"_process":112,"source-map":154}],101:[function(require,module,exports){
13113 (function (Buffer){
13114 // Copyright Joyent, Inc. and other Node contributors.
13116 // Permission is hereby granted, free of charge, to any person obtaining a
13117 // copy of this software and associated documentation files (the
13118 // "Software"), to deal in the Software without restriction, including
13119 // without limitation the rights to use, copy, modify, merge, publish,
13120 // distribute, sublicense, and/or sell copies of the Software, and to permit
13121 // persons to whom the Software is furnished to do so, subject to the
13122 // following conditions:
13124 // The above copyright notice and this permission notice shall be included
13125 // in all copies or substantial portions of the Software.
13127 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
13128 // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
13129 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
13130 // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
13131 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
13132 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
13133 // USE OR OTHER DEALINGS IN THE SOFTWARE.
13135 // NOTE: These type checking functions intentionally don't use `instanceof`
13136 // because it is fragile and can be easily faked with `Object.create()`.
13138 function isArray(arg) {
13139 if (Array.isArray) {
13140 return Array.isArray(arg);
13142 return objectToString(arg) === '[object Array]';
13144 exports.isArray = isArray;
13146 function isBoolean(arg) {
13147 return typeof arg === 'boolean';
13149 exports.isBoolean = isBoolean;
13151 function isNull(arg) {
13152 return arg === null;
13154 exports.isNull = isNull;
13156 function isNullOrUndefined(arg) {
13157 return arg == null;
13159 exports.isNullOrUndefined = isNullOrUndefined;
13161 function isNumber(arg) {
13162 return typeof arg === 'number';
13164 exports.isNumber = isNumber;
13166 function isString(arg) {
13167 return typeof arg === 'string';
13169 exports.isString = isString;
13171 function isSymbol(arg) {
13172 return typeof arg === 'symbol';
13174 exports.isSymbol = isSymbol;
13176 function isUndefined(arg) {
13177 return arg === void 0;
13179 exports.isUndefined = isUndefined;
13181 function isRegExp(re) {
13182 return objectToString(re) === '[object RegExp]';
13184 exports.isRegExp = isRegExp;
13186 function isObject(arg) {
13187 return typeof arg === 'object' && arg !== null;
13189 exports.isObject = isObject;
13191 function isDate(d) {
13192 return objectToString(d) === '[object Date]';
13194 exports.isDate = isDate;
13196 function isError(e) {
13197 return (objectToString(e) === '[object Error]' || e instanceof Error);
13199 exports.isError = isError;
13201 function isFunction(arg) {
13202 return typeof arg === 'function';
13204 exports.isFunction = isFunction;
13206 function isPrimitive(arg) {
13207 return arg === null ||
13208 typeof arg === 'boolean' ||
13209 typeof arg === 'number' ||
13210 typeof arg === 'string' ||
13211 typeof arg === 'symbol' || // ES6 symbol
13212 typeof arg === 'undefined';
13214 exports.isPrimitive = isPrimitive;
13216 exports.isBuffer = Buffer.isBuffer;
13218 function objectToString(o) {
13219 return Object.prototype.toString.call(o);
13222 }).call(this,{"isBuffer":require("../../is-buffer/index.js")})
13223 },{"../../is-buffer/index.js":107}],102:[function(require,module,exports){
13224 // Copyright Joyent, Inc. and other Node contributors.
13226 // Permission is hereby granted, free of charge, to any person obtaining a
13227 // copy of this software and associated documentation files (the
13228 // "Software"), to deal in the Software without restriction, including
13229 // without limitation the rights to use, copy, modify, merge, publish,
13230 // distribute, sublicense, and/or sell copies of the Software, and to permit
13231 // persons to whom the Software is furnished to do so, subject to the
13232 // following conditions:
13234 // The above copyright notice and this permission notice shall be included
13235 // in all copies or substantial portions of the Software.
13237 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
13238 // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
13239 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
13240 // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
13241 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
13242 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
13243 // USE OR OTHER DEALINGS IN THE SOFTWARE.
13245 var objectCreate = Object.create || objectCreatePolyfill
13246 var objectKeys = Object.keys || objectKeysPolyfill
13247 var bind = Function.prototype.bind || functionBindPolyfill
13249 function EventEmitter() {
13250 if (!this._events || !Object.prototype.hasOwnProperty.call(this, '_events')) {
13251 this._events = objectCreate(null);
13252 this._eventsCount = 0;
13255 this._maxListeners = this._maxListeners || undefined;
13257 module.exports = EventEmitter;
13259 // Backwards-compat with node 0.10.x
13260 EventEmitter.EventEmitter = EventEmitter;
13262 EventEmitter.prototype._events = undefined;
13263 EventEmitter.prototype._maxListeners = undefined;
13265 // By default EventEmitters will print a warning if more than 10 listeners are
13266 // added to it. This is a useful default which helps finding memory leaks.
13267 var defaultMaxListeners = 10;
13269 var hasDefineProperty;
13272 if (Object.defineProperty) Object.defineProperty(o, 'x', { value: 0 });
13273 hasDefineProperty = o.x === 0;
13274 } catch (err) { hasDefineProperty = false }
13275 if (hasDefineProperty) {
13276 Object.defineProperty(EventEmitter, 'defaultMaxListeners', {
13279 return defaultMaxListeners;
13281 set: function(arg) {
13282 // check whether the input is a positive number (whose value is zero or
13283 // greater and not a NaN).
13284 if (typeof arg !== 'number' || arg < 0 || arg !== arg)
13285 throw new TypeError('"defaultMaxListeners" must be a positive number');
13286 defaultMaxListeners = arg;
13290 EventEmitter.defaultMaxListeners = defaultMaxListeners;
13293 // Obviously not all Emitters should be limited to 10. This function allows
13294 // that to be increased. Set to zero for unlimited.
13295 EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
13296 if (typeof n !== 'number' || n < 0 || isNaN(n))
13297 throw new TypeError('"n" argument must be a positive number');
13298 this._maxListeners = n;
13302 function $getMaxListeners(that) {
13303 if (that._maxListeners === undefined)
13304 return EventEmitter.defaultMaxListeners;
13305 return that._maxListeners;
13308 EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
13309 return $getMaxListeners(this);
13312 // These standalone emit* functions are used to optimize calling of event
13313 // handlers for fast cases because emit() itself often has a variable number of
13314 // arguments and can be deoptimized because of that. These functions always have
13315 // the same number of arguments and thus do not get deoptimized, so the code
13316 // inside them can execute faster.
13317 function emitNone(handler, isFn, self) {
13319 handler.call(self);
13321 var len = handler.length;
13322 var listeners = arrayClone(handler, len);
13323 for (var i = 0; i < len; ++i)
13324 listeners[i].call(self);
13327 function emitOne(handler, isFn, self, arg1) {
13329 handler.call(self, arg1);
13331 var len = handler.length;
13332 var listeners = arrayClone(handler, len);
13333 for (var i = 0; i < len; ++i)
13334 listeners[i].call(self, arg1);
13337 function emitTwo(handler, isFn, self, arg1, arg2) {
13339 handler.call(self, arg1, arg2);
13341 var len = handler.length;
13342 var listeners = arrayClone(handler, len);
13343 for (var i = 0; i < len; ++i)
13344 listeners[i].call(self, arg1, arg2);
13347 function emitThree(handler, isFn, self, arg1, arg2, arg3) {
13349 handler.call(self, arg1, arg2, arg3);
13351 var len = handler.length;
13352 var listeners = arrayClone(handler, len);
13353 for (var i = 0; i < len; ++i)
13354 listeners[i].call(self, arg1, arg2, arg3);
13358 function emitMany(handler, isFn, self, args) {
13360 handler.apply(self, args);
13362 var len = handler.length;
13363 var listeners = arrayClone(handler, len);
13364 for (var i = 0; i < len; ++i)
13365 listeners[i].apply(self, args);
13369 EventEmitter.prototype.emit = function emit(type) {
13370 var er, handler, len, args, i, events;
13371 var doError = (type === 'error');
13373 events = this._events;
13375 doError = (doError && events.error == null);
13379 // If there is no 'error' event listener then throw.
13381 if (arguments.length > 1)
13383 if (er instanceof Error) {
13384 throw er; // Unhandled 'error' event
13386 // At least give some kind of context to the user
13387 var err = new Error('Unhandled "error" event. (' + er + ')');
13394 handler = events[type];
13399 var isFn = typeof handler === 'function';
13400 len = arguments.length;
13404 emitNone(handler, isFn, this);
13407 emitOne(handler, isFn, this, arguments[1]);
13410 emitTwo(handler, isFn, this, arguments[1], arguments[2]);
13413 emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]);
13417 args = new Array(len - 1);
13418 for (i = 1; i < len; i++)
13419 args[i - 1] = arguments[i];
13420 emitMany(handler, isFn, this, args);
13426 function _addListener(target, type, listener, prepend) {
13431 if (typeof listener !== 'function')
13432 throw new TypeError('"listener" argument must be a function');
13434 events = target._events;
13436 events = target._events = objectCreate(null);
13437 target._eventsCount = 0;
13439 // To avoid recursion in the case that type === "newListener"! Before
13440 // adding it to the listeners, first emit "newListener".
13441 if (events.newListener) {
13442 target.emit('newListener', type,
13443 listener.listener ? listener.listener : listener);
13445 // Re-assign `events` because a newListener handler could have caused the
13446 // this._events to be assigned to a new object
13447 events = target._events;
13449 existing = events[type];
13453 // Optimize the case of one listener. Don't need the extra array object.
13454 existing = events[type] = listener;
13455 ++target._eventsCount;
13457 if (typeof existing === 'function') {
13458 // Adding the second element, need to change to array.
13459 existing = events[type] =
13460 prepend ? [listener, existing] : [existing, listener];
13462 // If we've already got an array, just append.
13464 existing.unshift(listener);
13466 existing.push(listener);
13470 // Check for listener leak
13471 if (!existing.warned) {
13472 m = $getMaxListeners(target);
13473 if (m && m > 0 && existing.length > m) {
13474 existing.warned = true;
13475 var w = new Error('Possible EventEmitter memory leak detected. ' +
13476 existing.length + ' "' + String(type) + '" listeners ' +
13477 'added. Use emitter.setMaxListeners() to ' +
13478 'increase limit.');
13479 w.name = 'MaxListenersExceededWarning';
13480 w.emitter = target;
13482 w.count = existing.length;
13483 if (typeof console === 'object' && console.warn) {
13484 console.warn('%s: %s', w.name, w.message);
13493 EventEmitter.prototype.addListener = function addListener(type, listener) {
13494 return _addListener(this, type, listener, false);
13497 EventEmitter.prototype.on = EventEmitter.prototype.addListener;
13499 EventEmitter.prototype.prependListener =
13500 function prependListener(type, listener) {
13501 return _addListener(this, type, listener, true);
13504 function onceWrapper() {
13506 this.target.removeListener(this.type, this.wrapFn);
13508 switch (arguments.length) {
13510 return this.listener.call(this.target);
13512 return this.listener.call(this.target, arguments[0]);
13514 return this.listener.call(this.target, arguments[0], arguments[1]);
13516 return this.listener.call(this.target, arguments[0], arguments[1],
13519 var args = new Array(arguments.length);
13520 for (var i = 0; i < args.length; ++i)
13521 args[i] = arguments[i];
13522 this.listener.apply(this.target, args);
13527 function _onceWrap(target, type, listener) {
13528 var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };
13529 var wrapped = bind.call(onceWrapper, state);
13530 wrapped.listener = listener;
13531 state.wrapFn = wrapped;
13535 EventEmitter.prototype.once = function once(type, listener) {
13536 if (typeof listener !== 'function')
13537 throw new TypeError('"listener" argument must be a function');
13538 this.on(type, _onceWrap(this, type, listener));
13542 EventEmitter.prototype.prependOnceListener =
13543 function prependOnceListener(type, listener) {
13544 if (typeof listener !== 'function')
13545 throw new TypeError('"listener" argument must be a function');
13546 this.prependListener(type, _onceWrap(this, type, listener));
13550 // Emits a 'removeListener' event if and only if the listener was removed.
13551 EventEmitter.prototype.removeListener =
13552 function removeListener(type, listener) {
13553 var list, events, position, i, originalListener;
13555 if (typeof listener !== 'function')
13556 throw new TypeError('"listener" argument must be a function');
13558 events = this._events;
13562 list = events[type];
13566 if (list === listener || list.listener === listener) {
13567 if (--this._eventsCount === 0)
13568 this._events = objectCreate(null);
13570 delete events[type];
13571 if (events.removeListener)
13572 this.emit('removeListener', type, list.listener || listener);
13574 } else if (typeof list !== 'function') {
13577 for (i = list.length - 1; i >= 0; i--) {
13578 if (list[i] === listener || list[i].listener === listener) {
13579 originalListener = list[i].listener;
13588 if (position === 0)
13591 spliceOne(list, position);
13593 if (list.length === 1)
13594 events[type] = list[0];
13596 if (events.removeListener)
13597 this.emit('removeListener', type, originalListener || listener);
13603 EventEmitter.prototype.removeAllListeners =
13604 function removeAllListeners(type) {
13605 var listeners, events, i;
13607 events = this._events;
13611 // not listening for removeListener, no need to emit
13612 if (!events.removeListener) {
13613 if (arguments.length === 0) {
13614 this._events = objectCreate(null);
13615 this._eventsCount = 0;
13616 } else if (events[type]) {
13617 if (--this._eventsCount === 0)
13618 this._events = objectCreate(null);
13620 delete events[type];
13625 // emit removeListener for all listeners on all events
13626 if (arguments.length === 0) {
13627 var keys = objectKeys(events);
13629 for (i = 0; i < keys.length; ++i) {
13631 if (key === 'removeListener') continue;
13632 this.removeAllListeners(key);
13634 this.removeAllListeners('removeListener');
13635 this._events = objectCreate(null);
13636 this._eventsCount = 0;
13640 listeners = events[type];
13642 if (typeof listeners === 'function') {
13643 this.removeListener(type, listeners);
13644 } else if (listeners) {
13646 for (i = listeners.length - 1; i >= 0; i--) {
13647 this.removeListener(type, listeners[i]);
13654 function _listeners(target, type, unwrap) {
13655 var events = target._events;
13660 var evlistener = events[type];
13664 if (typeof evlistener === 'function')
13665 return unwrap ? [evlistener.listener || evlistener] : [evlistener];
13667 return unwrap ? unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
13670 EventEmitter.prototype.listeners = function listeners(type) {
13671 return _listeners(this, type, true);
13674 EventEmitter.prototype.rawListeners = function rawListeners(type) {
13675 return _listeners(this, type, false);
13678 EventEmitter.listenerCount = function(emitter, type) {
13679 if (typeof emitter.listenerCount === 'function') {
13680 return emitter.listenerCount(type);
13682 return listenerCount.call(emitter, type);
13686 EventEmitter.prototype.listenerCount = listenerCount;
13687 function listenerCount(type) {
13688 var events = this._events;
13691 var evlistener = events[type];
13693 if (typeof evlistener === 'function') {
13695 } else if (evlistener) {
13696 return evlistener.length;
13703 EventEmitter.prototype.eventNames = function eventNames() {
13704 return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : [];
13707 // About 1.5x faster than the two-arg version of Array#splice().
13708 function spliceOne(list, index) {
13709 for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1)
13714 function arrayClone(arr, n) {
13715 var copy = new Array(n);
13716 for (var i = 0; i < n; ++i)
13721 function unwrapListeners(arr) {
13722 var ret = new Array(arr.length);
13723 for (var i = 0; i < ret.length; ++i) {
13724 ret[i] = arr[i].listener || arr[i];
13729 function objectCreatePolyfill(proto) {
13730 var F = function() {};
13731 F.prototype = proto;
13734 function objectKeysPolyfill(obj) {
13736 for (var k in obj) if (Object.prototype.hasOwnProperty.call(obj, k)) {
13741 function functionBindPolyfill(context) {
13743 return function () {
13744 return fn.apply(context, arguments);
13748 },{}],103:[function(require,module,exports){
13749 (function (global){
13750 /*! https://mths.be/he v1.2.0 by @mathias | MIT license */
13753 // Detect free variables `exports`.
13754 var freeExports = typeof exports == 'object' && exports;
13756 // Detect free variable `module`.
13757 var freeModule = typeof module == 'object' && module &&
13758 module.exports == freeExports && module;
13760 // Detect free variable `global`, from Node.js or Browserified code,
13761 // and use it as `root`.
13762 var freeGlobal = typeof global == 'object' && global;
13763 if (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal) {
13767 /*--------------------------------------------------------------------------*/
13769 // All astral symbols.
13770 var regexAstralSymbols = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g;
13771 // All ASCII symbols (not just printable ASCII) except those listed in the
13772 // first column of the overrides table.
13773 // https://html.spec.whatwg.org/multipage/syntax.html#table-charref-overrides
13774 var regexAsciiWhitelist = /[\x01-\x7F]/g;
13775 // All BMP symbols that are not ASCII newlines, printable ASCII symbols, or
13776 // code points listed in the first column of the overrides table on
13777 // https://html.spec.whatwg.org/multipage/syntax.html#table-charref-overrides.
13778 var regexBmpWhitelist = /[\x01-\t\x0B\f\x0E-\x1F\x7F\x81\x8D\x8F\x90\x9D\xA0-\uFFFF]/g;
13780 var regexEncodeNonAscii = /<\u20D2|=\u20E5|>\u20D2|\u205F\u200A|\u219D\u0338|\u2202\u0338|\u2220\u20D2|\u2229\uFE00|\u222A\uFE00|\u223C\u20D2|\u223D\u0331|\u223E\u0333|\u2242\u0338|\u224B\u0338|\u224D\u20D2|\u224E\u0338|\u224F\u0338|\u2250\u0338|\u2261\u20E5|\u2264\u20D2|\u2265\u20D2|\u2266\u0338|\u2267\u0338|\u2268\uFE00|\u2269\uFE00|\u226A\u0338|\u226A\u20D2|\u226B\u0338|\u226B\u20D2|\u227F\u0338|\u2282\u20D2|\u2283\u20D2|\u228A\uFE00|\u228B\uFE00|\u228F\u0338|\u2290\u0338|\u2293\uFE00|\u2294\uFE00|\u22B4\u20D2|\u22B5\u20D2|\u22D8\u0338|\u22D9\u0338|\u22DA\uFE00|\u22DB\uFE00|\u22F5\u0338|\u22F9\u0338|\u2933\u0338|\u29CF\u0338|\u29D0\u0338|\u2A6D\u0338|\u2A70\u0338|\u2A7D\u0338|\u2A7E\u0338|\u2AA1\u0338|\u2AA2\u0338|\u2AAC\uFE00|\u2AAD\uFE00|\u2AAF\u0338|\u2AB0\u0338|\u2AC5\u0338|\u2AC6\u0338|\u2ACB\uFE00|\u2ACC\uFE00|\u2AFD\u20E5|[\xA0-\u0113\u0116-\u0122\u0124-\u012B\u012E-\u014D\u0150-\u017E\u0192\u01B5\u01F5\u0237\u02C6\u02C7\u02D8-\u02DD\u0311\u0391-\u03A1\u03A3-\u03A9\u03B1-\u03C9\u03D1\u03D2\u03D5\u03D6\u03DC\u03DD\u03F0\u03F1\u03F5\u03F6\u0401-\u040C\u040E-\u044F\u0451-\u045C\u045E\u045F\u2002-\u2005\u2007-\u2010\u2013-\u2016\u2018-\u201A\u201C-\u201E\u2020-\u2022\u2025\u2026\u2030-\u2035\u2039\u203A\u203E\u2041\u2043\u2044\u204F\u2057\u205F-\u2063\u20AC\u20DB\u20DC\u2102\u2105\u210A-\u2113\u2115-\u211E\u2122\u2124\u2127-\u2129\u212C\u212D\u212F-\u2131\u2133-\u2138\u2145-\u2148\u2153-\u215E\u2190-\u219B\u219D-\u21A7\u21A9-\u21AE\u21B0-\u21B3\u21B5-\u21B7\u21BA-\u21DB\u21DD\u21E4\u21E5\u21F5\u21FD-\u2205\u2207-\u2209\u220B\u220C\u220F-\u2214\u2216-\u2218\u221A\u221D-\u2238\u223A-\u2257\u2259\u225A\u225C\u225F-\u2262\u2264-\u228B\u228D-\u229B\u229D-\u22A5\u22A7-\u22B0\u22B2-\u22BB\u22BD-\u22DB\u22DE-\u22E3\u22E6-\u22F7\u22F9-\u22FE\u2305\u2306\u2308-\u2310\u2312\u2313\u2315\u2316\u231C-\u231F\u2322\u2323\u232D\u232E\u2336\u233D\u233F\u237C\u23B0\u23B1\u23B4-\u23B6\u23DC-\u23DF\u23E2\u23E7\u2423\u24C8\u2500\u2502\u250C\u2510\u2514\u2518\u251C\u2524\u252C\u2534\u253C\u2550-\u256C\u2580\u2584\u2588\u2591-\u2593\u25A1\u25AA\u25AB\u25AD\u25AE\u25B1\u25B3-\u25B5\u25B8\u25B9\u25BD-\u25BF\u25C2\u25C3\u25CA\u25CB\u25EC\u25EF\u25F8-\u25FC\u2605\u2606\u260E\u2640\u2642\u2660\u2663\u2665\u2666\u266A\u266D-\u266F\u2713\u2717\u2720\u2736\u2758\u2772\u2773\u27C8\u27C9\u27E6-\u27ED\u27F5-\u27FA\u27FC\u27FF\u2902-\u2905\u290C-\u2913\u2916\u2919-\u2920\u2923-\u292A\u2933\u2935-\u2939\u293C\u293D\u2945\u2948-\u294B\u294E-\u2976\u2978\u2979\u297B-\u297F\u2985\u2986\u298B-\u2996\u299A\u299C\u299D\u29A4-\u29B7\u29B9\u29BB\u29BC\u29BE-\u29C5\u29C9\u29CD-\u29D0\u29DC-\u29DE\u29E3-\u29E5\u29EB\u29F4\u29F6\u2A00-\u2A02\u2A04\u2A06\u2A0C\u2A0D\u2A10-\u2A17\u2A22-\u2A27\u2A29\u2A2A\u2A2D-\u2A31\u2A33-\u2A3C\u2A3F\u2A40\u2A42-\u2A4D\u2A50\u2A53-\u2A58\u2A5A-\u2A5D\u2A5F\u2A66\u2A6A\u2A6D-\u2A75\u2A77-\u2A9A\u2A9D-\u2AA2\u2AA4-\u2AB0\u2AB3-\u2AC8\u2ACB\u2ACC\u2ACF-\u2ADB\u2AE4\u2AE6-\u2AE9\u2AEB-\u2AF3\u2AFD\uFB00-\uFB04]|\uD835[\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDCCF\uDD04\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDD6B]/g;
13781 var encodeMap = {'\xAD':'shy','\u200C':'zwnj','\u200D':'zwj','\u200E':'lrm','\u2063':'ic','\u2062':'it','\u2061':'af','\u200F':'rlm','\u200B':'ZeroWidthSpace','\u2060':'NoBreak','\u0311':'DownBreve','\u20DB':'tdot','\u20DC':'DotDot','\t':'Tab','\n':'NewLine','\u2008':'puncsp','\u205F':'MediumSpace','\u2009':'thinsp','\u200A':'hairsp','\u2004':'emsp13','\u2002':'ensp','\u2005':'emsp14','\u2003':'emsp','\u2007':'numsp','\xA0':'nbsp','\u205F\u200A':'ThickSpace','\u203E':'oline','_':'lowbar','\u2010':'dash','\u2013':'ndash','\u2014':'mdash','\u2015':'horbar',',':'comma',';':'semi','\u204F':'bsemi',':':'colon','\u2A74':'Colone','!':'excl','\xA1':'iexcl','?':'quest','\xBF':'iquest','.':'period','\u2025':'nldr','\u2026':'mldr','\xB7':'middot','\'':'apos','\u2018':'lsquo','\u2019':'rsquo','\u201A':'sbquo','\u2039':'lsaquo','\u203A':'rsaquo','"':'quot','\u201C':'ldquo','\u201D':'rdquo','\u201E':'bdquo','\xAB':'laquo','\xBB':'raquo','(':'lpar',')':'rpar','[':'lsqb',']':'rsqb','{':'lcub','}':'rcub','\u2308':'lceil','\u2309':'rceil','\u230A':'lfloor','\u230B':'rfloor','\u2985':'lopar','\u2986':'ropar','\u298B':'lbrke','\u298C':'rbrke','\u298D':'lbrkslu','\u298E':'rbrksld','\u298F':'lbrksld','\u2990':'rbrkslu','\u2991':'langd','\u2992':'rangd','\u2993':'lparlt','\u2994':'rpargt','\u2995':'gtlPar','\u2996':'ltrPar','\u27E6':'lobrk','\u27E7':'robrk','\u27E8':'lang','\u27E9':'rang','\u27EA':'Lang','\u27EB':'Rang','\u27EC':'loang','\u27ED':'roang','\u2772':'lbbrk','\u2773':'rbbrk','\u2016':'Vert','\xA7':'sect','\xB6':'para','@':'commat','*':'ast','/':'sol','undefined':null,'&':'amp','#':'num','%':'percnt','\u2030':'permil','\u2031':'pertenk','\u2020':'dagger','\u2021':'Dagger','\u2022':'bull','\u2043':'hybull','\u2032':'prime','\u2033':'Prime','\u2034':'tprime','\u2057':'qprime','\u2035':'bprime','\u2041':'caret','`':'grave','\xB4':'acute','\u02DC':'tilde','^':'Hat','\xAF':'macr','\u02D8':'breve','\u02D9':'dot','\xA8':'die','\u02DA':'ring','\u02DD':'dblac','\xB8':'cedil','\u02DB':'ogon','\u02C6':'circ','\u02C7':'caron','\xB0':'deg','\xA9':'copy','\xAE':'reg','\u2117':'copysr','\u2118':'wp','\u211E':'rx','\u2127':'mho','\u2129':'iiota','\u2190':'larr','\u219A':'nlarr','\u2192':'rarr','\u219B':'nrarr','\u2191':'uarr','\u2193':'darr','\u2194':'harr','\u21AE':'nharr','\u2195':'varr','\u2196':'nwarr','\u2197':'nearr','\u2198':'searr','\u2199':'swarr','\u219D':'rarrw','\u219D\u0338':'nrarrw','\u219E':'Larr','\u219F':'Uarr','\u21A0':'Rarr','\u21A1':'Darr','\u21A2':'larrtl','\u21A3':'rarrtl','\u21A4':'mapstoleft','\u21A5':'mapstoup','\u21A6':'map','\u21A7':'mapstodown','\u21A9':'larrhk','\u21AA':'rarrhk','\u21AB':'larrlp','\u21AC':'rarrlp','\u21AD':'harrw','\u21B0':'lsh','\u21B1':'rsh','\u21B2':'ldsh','\u21B3':'rdsh','\u21B5':'crarr','\u21B6':'cularr','\u21B7':'curarr','\u21BA':'olarr','\u21BB':'orarr','\u21BC':'lharu','\u21BD':'lhard','\u21BE':'uharr','\u21BF':'uharl','\u21C0':'rharu','\u21C1':'rhard','\u21C2':'dharr','\u21C3':'dharl','\u21C4':'rlarr','\u21C5':'udarr','\u21C6':'lrarr','\u21C7':'llarr','\u21C8':'uuarr','\u21C9':'rrarr','\u21CA':'ddarr','\u21CB':'lrhar','\u21CC':'rlhar','\u21D0':'lArr','\u21CD':'nlArr','\u21D1':'uArr','\u21D2':'rArr','\u21CF':'nrArr','\u21D3':'dArr','\u21D4':'iff','\u21CE':'nhArr','\u21D5':'vArr','\u21D6':'nwArr','\u21D7':'neArr','\u21D8':'seArr','\u21D9':'swArr','\u21DA':'lAarr','\u21DB':'rAarr','\u21DD':'zigrarr','\u21E4':'larrb','\u21E5':'rarrb','\u21F5':'duarr','\u21FD':'loarr','\u21FE':'roarr','\u21FF':'hoarr','\u2200':'forall','\u2201':'comp','\u2202':'part','\u2202\u0338':'npart','\u2203':'exist','\u2204':'nexist','\u2205':'empty','\u2207':'Del','\u2208':'in','\u2209':'notin','\u220B':'ni','\u220C':'notni','\u03F6':'bepsi','\u220F':'prod','\u2210':'coprod','\u2211':'sum','+':'plus','\xB1':'pm','\xF7':'div','\xD7':'times','<':'lt','\u226E':'nlt','<\u20D2':'nvlt','=':'equals','\u2260':'ne','=\u20E5':'bne','\u2A75':'Equal','>':'gt','\u226F':'ngt','>\u20D2':'nvgt','\xAC':'not','|':'vert','\xA6':'brvbar','\u2212':'minus','\u2213':'mp','\u2214':'plusdo','\u2044':'frasl','\u2216':'setmn','\u2217':'lowast','\u2218':'compfn','\u221A':'Sqrt','\u221D':'prop','\u221E':'infin','\u221F':'angrt','\u2220':'ang','\u2220\u20D2':'nang','\u2221':'angmsd','\u2222':'angsph','\u2223':'mid','\u2224':'nmid','\u2225':'par','\u2226':'npar','\u2227':'and','\u2228':'or','\u2229':'cap','\u2229\uFE00':'caps','\u222A':'cup','\u222A\uFE00':'cups','\u222B':'int','\u222C':'Int','\u222D':'tint','\u2A0C':'qint','\u222E':'oint','\u222F':'Conint','\u2230':'Cconint','\u2231':'cwint','\u2232':'cwconint','\u2233':'awconint','\u2234':'there4','\u2235':'becaus','\u2236':'ratio','\u2237':'Colon','\u2238':'minusd','\u223A':'mDDot','\u223B':'homtht','\u223C':'sim','\u2241':'nsim','\u223C\u20D2':'nvsim','\u223D':'bsim','\u223D\u0331':'race','\u223E':'ac','\u223E\u0333':'acE','\u223F':'acd','\u2240':'wr','\u2242':'esim','\u2242\u0338':'nesim','\u2243':'sime','\u2244':'nsime','\u2245':'cong','\u2247':'ncong','\u2246':'simne','\u2248':'ap','\u2249':'nap','\u224A':'ape','\u224B':'apid','\u224B\u0338':'napid','\u224C':'bcong','\u224D':'CupCap','\u226D':'NotCupCap','\u224D\u20D2':'nvap','\u224E':'bump','\u224E\u0338':'nbump','\u224F':'bumpe','\u224F\u0338':'nbumpe','\u2250':'doteq','\u2250\u0338':'nedot','\u2251':'eDot','\u2252':'efDot','\u2253':'erDot','\u2254':'colone','\u2255':'ecolon','\u2256':'ecir','\u2257':'cire','\u2259':'wedgeq','\u225A':'veeeq','\u225C':'trie','\u225F':'equest','\u2261':'equiv','\u2262':'nequiv','\u2261\u20E5':'bnequiv','\u2264':'le','\u2270':'nle','\u2264\u20D2':'nvle','\u2265':'ge','\u2271':'nge','\u2265\u20D2':'nvge','\u2266':'lE','\u2266\u0338':'nlE','\u2267':'gE','\u2267\u0338':'ngE','\u2268\uFE00':'lvnE','\u2268':'lnE','\u2269':'gnE','\u2269\uFE00':'gvnE','\u226A':'ll','\u226A\u0338':'nLtv','\u226A\u20D2':'nLt','\u226B':'gg','\u226B\u0338':'nGtv','\u226B\u20D2':'nGt','\u226C':'twixt','\u2272':'lsim','\u2274':'nlsim','\u2273':'gsim','\u2275':'ngsim','\u2276':'lg','\u2278':'ntlg','\u2277':'gl','\u2279':'ntgl','\u227A':'pr','\u2280':'npr','\u227B':'sc','\u2281':'nsc','\u227C':'prcue','\u22E0':'nprcue','\u227D':'sccue','\u22E1':'nsccue','\u227E':'prsim','\u227F':'scsim','\u227F\u0338':'NotSucceedsTilde','\u2282':'sub','\u2284':'nsub','\u2282\u20D2':'vnsub','\u2283':'sup','\u2285':'nsup','\u2283\u20D2':'vnsup','\u2286':'sube','\u2288':'nsube','\u2287':'supe','\u2289':'nsupe','\u228A\uFE00':'vsubne','\u228A':'subne','\u228B\uFE00':'vsupne','\u228B':'supne','\u228D':'cupdot','\u228E':'uplus','\u228F':'sqsub','\u228F\u0338':'NotSquareSubset','\u2290':'sqsup','\u2290\u0338':'NotSquareSuperset','\u2291':'sqsube','\u22E2':'nsqsube','\u2292':'sqsupe','\u22E3':'nsqsupe','\u2293':'sqcap','\u2293\uFE00':'sqcaps','\u2294':'sqcup','\u2294\uFE00':'sqcups','\u2295':'oplus','\u2296':'ominus','\u2297':'otimes','\u2298':'osol','\u2299':'odot','\u229A':'ocir','\u229B':'oast','\u229D':'odash','\u229E':'plusb','\u229F':'minusb','\u22A0':'timesb','\u22A1':'sdotb','\u22A2':'vdash','\u22AC':'nvdash','\u22A3':'dashv','\u22A4':'top','\u22A5':'bot','\u22A7':'models','\u22A8':'vDash','\u22AD':'nvDash','\u22A9':'Vdash','\u22AE':'nVdash','\u22AA':'Vvdash','\u22AB':'VDash','\u22AF':'nVDash','\u22B0':'prurel','\u22B2':'vltri','\u22EA':'nltri','\u22B3':'vrtri','\u22EB':'nrtri','\u22B4':'ltrie','\u22EC':'nltrie','\u22B4\u20D2':'nvltrie','\u22B5':'rtrie','\u22ED':'nrtrie','\u22B5\u20D2':'nvrtrie','\u22B6':'origof','\u22B7':'imof','\u22B8':'mumap','\u22B9':'hercon','\u22BA':'intcal','\u22BB':'veebar','\u22BD':'barvee','\u22BE':'angrtvb','\u22BF':'lrtri','\u22C0':'Wedge','\u22C1':'Vee','\u22C2':'xcap','\u22C3':'xcup','\u22C4':'diam','\u22C5':'sdot','\u22C6':'Star','\u22C7':'divonx','\u22C8':'bowtie','\u22C9':'ltimes','\u22CA':'rtimes','\u22CB':'lthree','\u22CC':'rthree','\u22CD':'bsime','\u22CE':'cuvee','\u22CF':'cuwed','\u22D0':'Sub','\u22D1':'Sup','\u22D2':'Cap','\u22D3':'Cup','\u22D4':'fork','\u22D5':'epar','\u22D6':'ltdot','\u22D7':'gtdot','\u22D8':'Ll','\u22D8\u0338':'nLl','\u22D9':'Gg','\u22D9\u0338':'nGg','\u22DA\uFE00':'lesg','\u22DA':'leg','\u22DB':'gel','\u22DB\uFE00':'gesl','\u22DE':'cuepr','\u22DF':'cuesc','\u22E6':'lnsim','\u22E7':'gnsim','\u22E8':'prnsim','\u22E9':'scnsim','\u22EE':'vellip','\u22EF':'ctdot','\u22F0':'utdot','\u22F1':'dtdot','\u22F2':'disin','\u22F3':'isinsv','\u22F4':'isins','\u22F5':'isindot','\u22F5\u0338':'notindot','\u22F6':'notinvc','\u22F7':'notinvb','\u22F9':'isinE','\u22F9\u0338':'notinE','\u22FA':'nisd','\u22FB':'xnis','\u22FC':'nis','\u22FD':'notnivc','\u22FE':'notnivb','\u2305':'barwed','\u2306':'Barwed','\u230C':'drcrop','\u230D':'dlcrop','\u230E':'urcrop','\u230F':'ulcrop','\u2310':'bnot','\u2312':'profline','\u2313':'profsurf','\u2315':'telrec','\u2316':'target','\u231C':'ulcorn','\u231D':'urcorn','\u231E':'dlcorn','\u231F':'drcorn','\u2322':'frown','\u2323':'smile','\u232D':'cylcty','\u232E':'profalar','\u2336':'topbot','\u233D':'ovbar','\u233F':'solbar','\u237C':'angzarr','\u23B0':'lmoust','\u23B1':'rmoust','\u23B4':'tbrk','\u23B5':'bbrk','\u23B6':'bbrktbrk','\u23DC':'OverParenthesis','\u23DD':'UnderParenthesis','\u23DE':'OverBrace','\u23DF':'UnderBrace','\u23E2':'trpezium','\u23E7':'elinters','\u2423':'blank','\u2500':'boxh','\u2502':'boxv','\u250C':'boxdr','\u2510':'boxdl','\u2514':'boxur','\u2518':'boxul','\u251C':'boxvr','\u2524':'boxvl','\u252C':'boxhd','\u2534':'boxhu','\u253C':'boxvh','\u2550':'boxH','\u2551':'boxV','\u2552':'boxdR','\u2553':'boxDr','\u2554':'boxDR','\u2555':'boxdL','\u2556':'boxDl','\u2557':'boxDL','\u2558':'boxuR','\u2559':'boxUr','\u255A':'boxUR','\u255B':'boxuL','\u255C':'boxUl','\u255D':'boxUL','\u255E':'boxvR','\u255F':'boxVr','\u2560':'boxVR','\u2561':'boxvL','\u2562':'boxVl','\u2563':'boxVL','\u2564':'boxHd','\u2565':'boxhD','\u2566':'boxHD','\u2567':'boxHu','\u2568':'boxhU','\u2569':'boxHU','\u256A':'boxvH','\u256B':'boxVh','\u256C':'boxVH','\u2580':'uhblk','\u2584':'lhblk','\u2588':'block','\u2591':'blk14','\u2592':'blk12','\u2593':'blk34','\u25A1':'squ','\u25AA':'squf','\u25AB':'EmptyVerySmallSquare','\u25AD':'rect','\u25AE':'marker','\u25B1':'fltns','\u25B3':'xutri','\u25B4':'utrif','\u25B5':'utri','\u25B8':'rtrif','\u25B9':'rtri','\u25BD':'xdtri','\u25BE':'dtrif','\u25BF':'dtri','\u25C2':'ltrif','\u25C3':'ltri','\u25CA':'loz','\u25CB':'cir','\u25EC':'tridot','\u25EF':'xcirc','\u25F8':'ultri','\u25F9':'urtri','\u25FA':'lltri','\u25FB':'EmptySmallSquare','\u25FC':'FilledSmallSquare','\u2605':'starf','\u2606':'star','\u260E':'phone','\u2640':'female','\u2642':'male','\u2660':'spades','\u2663':'clubs','\u2665':'hearts','\u2666':'diams','\u266A':'sung','\u2713':'check','\u2717':'cross','\u2720':'malt','\u2736':'sext','\u2758':'VerticalSeparator','\u27C8':'bsolhsub','\u27C9':'suphsol','\u27F5':'xlarr','\u27F6':'xrarr','\u27F7':'xharr','\u27F8':'xlArr','\u27F9':'xrArr','\u27FA':'xhArr','\u27FC':'xmap','\u27FF':'dzigrarr','\u2902':'nvlArr','\u2903':'nvrArr','\u2904':'nvHarr','\u2905':'Map','\u290C':'lbarr','\u290D':'rbarr','\u290E':'lBarr','\u290F':'rBarr','\u2910':'RBarr','\u2911':'DDotrahd','\u2912':'UpArrowBar','\u2913':'DownArrowBar','\u2916':'Rarrtl','\u2919':'latail','\u291A':'ratail','\u291B':'lAtail','\u291C':'rAtail','\u291D':'larrfs','\u291E':'rarrfs','\u291F':'larrbfs','\u2920':'rarrbfs','\u2923':'nwarhk','\u2924':'nearhk','\u2925':'searhk','\u2926':'swarhk','\u2927':'nwnear','\u2928':'toea','\u2929':'tosa','\u292A':'swnwar','\u2933':'rarrc','\u2933\u0338':'nrarrc','\u2935':'cudarrr','\u2936':'ldca','\u2937':'rdca','\u2938':'cudarrl','\u2939':'larrpl','\u293C':'curarrm','\u293D':'cularrp','\u2945':'rarrpl','\u2948':'harrcir','\u2949':'Uarrocir','\u294A':'lurdshar','\u294B':'ldrushar','\u294E':'LeftRightVector','\u294F':'RightUpDownVector','\u2950':'DownLeftRightVector','\u2951':'LeftUpDownVector','\u2952':'LeftVectorBar','\u2953':'RightVectorBar','\u2954':'RightUpVectorBar','\u2955':'RightDownVectorBar','\u2956':'DownLeftVectorBar','\u2957':'DownRightVectorBar','\u2958':'LeftUpVectorBar','\u2959':'LeftDownVectorBar','\u295A':'LeftTeeVector','\u295B':'RightTeeVector','\u295C':'RightUpTeeVector','\u295D':'RightDownTeeVector','\u295E':'DownLeftTeeVector','\u295F':'DownRightTeeVector','\u2960':'LeftUpTeeVector','\u2961':'LeftDownTeeVector','\u2962':'lHar','\u2963':'uHar','\u2964':'rHar','\u2965':'dHar','\u2966':'luruhar','\u2967':'ldrdhar','\u2968':'ruluhar','\u2969':'rdldhar','\u296A':'lharul','\u296B':'llhard','\u296C':'rharul','\u296D':'lrhard','\u296E':'udhar','\u296F':'duhar','\u2970':'RoundImplies','\u2971':'erarr','\u2972':'simrarr','\u2973':'larrsim','\u2974':'rarrsim','\u2975':'rarrap','\u2976':'ltlarr','\u2978':'gtrarr','\u2979':'subrarr','\u297B':'suplarr','\u297C':'lfisht','\u297D':'rfisht','\u297E':'ufisht','\u297F':'dfisht','\u299A':'vzigzag','\u299C':'vangrt','\u299D':'angrtvbd','\u29A4':'ange','\u29A5':'range','\u29A6':'dwangle','\u29A7':'uwangle','\u29A8':'angmsdaa','\u29A9':'angmsdab','\u29AA':'angmsdac','\u29AB':'angmsdad','\u29AC':'angmsdae','\u29AD':'angmsdaf','\u29AE':'angmsdag','\u29AF':'angmsdah','\u29B0':'bemptyv','\u29B1':'demptyv','\u29B2':'cemptyv','\u29B3':'raemptyv','\u29B4':'laemptyv','\u29B5':'ohbar','\u29B6':'omid','\u29B7':'opar','\u29B9':'operp','\u29BB':'olcross','\u29BC':'odsold','\u29BE':'olcir','\u29BF':'ofcir','\u29C0':'olt','\u29C1':'ogt','\u29C2':'cirscir','\u29C3':'cirE','\u29C4':'solb','\u29C5':'bsolb','\u29C9':'boxbox','\u29CD':'trisb','\u29CE':'rtriltri','\u29CF':'LeftTriangleBar','\u29CF\u0338':'NotLeftTriangleBar','\u29D0':'RightTriangleBar','\u29D0\u0338':'NotRightTriangleBar','\u29DC':'iinfin','\u29DD':'infintie','\u29DE':'nvinfin','\u29E3':'eparsl','\u29E4':'smeparsl','\u29E5':'eqvparsl','\u29EB':'lozf','\u29F4':'RuleDelayed','\u29F6':'dsol','\u2A00':'xodot','\u2A01':'xoplus','\u2A02':'xotime','\u2A04':'xuplus','\u2A06':'xsqcup','\u2A0D':'fpartint','\u2A10':'cirfnint','\u2A11':'awint','\u2A12':'rppolint','\u2A13':'scpolint','\u2A14':'npolint','\u2A15':'pointint','\u2A16':'quatint','\u2A17':'intlarhk','\u2A22':'pluscir','\u2A23':'plusacir','\u2A24':'simplus','\u2A25':'plusdu','\u2A26':'plussim','\u2A27':'plustwo','\u2A29':'mcomma','\u2A2A':'minusdu','\u2A2D':'loplus','\u2A2E':'roplus','\u2A2F':'Cross','\u2A30':'timesd','\u2A31':'timesbar','\u2A33':'smashp','\u2A34':'lotimes','\u2A35':'rotimes','\u2A36':'otimesas','\u2A37':'Otimes','\u2A38':'odiv','\u2A39':'triplus','\u2A3A':'triminus','\u2A3B':'tritime','\u2A3C':'iprod','\u2A3F':'amalg','\u2A40':'capdot','\u2A42':'ncup','\u2A43':'ncap','\u2A44':'capand','\u2A45':'cupor','\u2A46':'cupcap','\u2A47':'capcup','\u2A48':'cupbrcap','\u2A49':'capbrcup','\u2A4A':'cupcup','\u2A4B':'capcap','\u2A4C':'ccups','\u2A4D':'ccaps','\u2A50':'ccupssm','\u2A53':'And','\u2A54':'Or','\u2A55':'andand','\u2A56':'oror','\u2A57':'orslope','\u2A58':'andslope','\u2A5A':'andv','\u2A5B':'orv','\u2A5C':'andd','\u2A5D':'ord','\u2A5F':'wedbar','\u2A66':'sdote','\u2A6A':'simdot','\u2A6D':'congdot','\u2A6D\u0338':'ncongdot','\u2A6E':'easter','\u2A6F':'apacir','\u2A70':'apE','\u2A70\u0338':'napE','\u2A71':'eplus','\u2A72':'pluse','\u2A73':'Esim','\u2A77':'eDDot','\u2A78':'equivDD','\u2A79':'ltcir','\u2A7A':'gtcir','\u2A7B':'ltquest','\u2A7C':'gtquest','\u2A7D':'les','\u2A7D\u0338':'nles','\u2A7E':'ges','\u2A7E\u0338':'nges','\u2A7F':'lesdot','\u2A80':'gesdot','\u2A81':'lesdoto','\u2A82':'gesdoto','\u2A83':'lesdotor','\u2A84':'gesdotol','\u2A85':'lap','\u2A86':'gap','\u2A87':'lne','\u2A88':'gne','\u2A89':'lnap','\u2A8A':'gnap','\u2A8B':'lEg','\u2A8C':'gEl','\u2A8D':'lsime','\u2A8E':'gsime','\u2A8F':'lsimg','\u2A90':'gsiml','\u2A91':'lgE','\u2A92':'glE','\u2A93':'lesges','\u2A94':'gesles','\u2A95':'els','\u2A96':'egs','\u2A97':'elsdot','\u2A98':'egsdot','\u2A99':'el','\u2A9A':'eg','\u2A9D':'siml','\u2A9E':'simg','\u2A9F':'simlE','\u2AA0':'simgE','\u2AA1':'LessLess','\u2AA1\u0338':'NotNestedLessLess','\u2AA2':'GreaterGreater','\u2AA2\u0338':'NotNestedGreaterGreater','\u2AA4':'glj','\u2AA5':'gla','\u2AA6':'ltcc','\u2AA7':'gtcc','\u2AA8':'lescc','\u2AA9':'gescc','\u2AAA':'smt','\u2AAB':'lat','\u2AAC':'smte','\u2AAC\uFE00':'smtes','\u2AAD':'late','\u2AAD\uFE00':'lates','\u2AAE':'bumpE','\u2AAF':'pre','\u2AAF\u0338':'npre','\u2AB0':'sce','\u2AB0\u0338':'nsce','\u2AB3':'prE','\u2AB4':'scE','\u2AB5':'prnE','\u2AB6':'scnE','\u2AB7':'prap','\u2AB8':'scap','\u2AB9':'prnap','\u2ABA':'scnap','\u2ABB':'Pr','\u2ABC':'Sc','\u2ABD':'subdot','\u2ABE':'supdot','\u2ABF':'subplus','\u2AC0':'supplus','\u2AC1':'submult','\u2AC2':'supmult','\u2AC3':'subedot','\u2AC4':'supedot','\u2AC5':'subE','\u2AC5\u0338':'nsubE','\u2AC6':'supE','\u2AC6\u0338':'nsupE','\u2AC7':'subsim','\u2AC8':'supsim','\u2ACB\uFE00':'vsubnE','\u2ACB':'subnE','\u2ACC\uFE00':'vsupnE','\u2ACC':'supnE','\u2ACF':'csub','\u2AD0':'csup','\u2AD1':'csube','\u2AD2':'csupe','\u2AD3':'subsup','\u2AD4':'supsub','\u2AD5':'subsub','\u2AD6':'supsup','\u2AD7':'suphsub','\u2AD8':'supdsub','\u2AD9':'forkv','\u2ADA':'topfork','\u2ADB':'mlcp','\u2AE4':'Dashv','\u2AE6':'Vdashl','\u2AE7':'Barv','\u2AE8':'vBar','\u2AE9':'vBarv','\u2AEB':'Vbar','\u2AEC':'Not','\u2AED':'bNot','\u2AEE':'rnmid','\u2AEF':'cirmid','\u2AF0':'midcir','\u2AF1':'topcir','\u2AF2':'nhpar','\u2AF3':'parsim','\u2AFD':'parsl','\u2AFD\u20E5':'nparsl','\u266D':'flat','\u266E':'natur','\u266F':'sharp','\xA4':'curren','\xA2':'cent','$':'dollar','\xA3':'pound','\xA5':'yen','\u20AC':'euro','\xB9':'sup1','\xBD':'half','\u2153':'frac13','\xBC':'frac14','\u2155':'frac15','\u2159':'frac16','\u215B':'frac18','\xB2':'sup2','\u2154':'frac23','\u2156':'frac25','\xB3':'sup3','\xBE':'frac34','\u2157':'frac35','\u215C':'frac38','\u2158':'frac45','\u215A':'frac56','\u215D':'frac58','\u215E':'frac78','\uD835\uDCB6':'ascr','\uD835\uDD52':'aopf','\uD835\uDD1E':'afr','\uD835\uDD38':'Aopf','\uD835\uDD04':'Afr','\uD835\uDC9C':'Ascr','\xAA':'ordf','\xE1':'aacute','\xC1':'Aacute','\xE0':'agrave','\xC0':'Agrave','\u0103':'abreve','\u0102':'Abreve','\xE2':'acirc','\xC2':'Acirc','\xE5':'aring','\xC5':'angst','\xE4':'auml','\xC4':'Auml','\xE3':'atilde','\xC3':'Atilde','\u0105':'aogon','\u0104':'Aogon','\u0101':'amacr','\u0100':'Amacr','\xE6':'aelig','\xC6':'AElig','\uD835\uDCB7':'bscr','\uD835\uDD53':'bopf','\uD835\uDD1F':'bfr','\uD835\uDD39':'Bopf','\u212C':'Bscr','\uD835\uDD05':'Bfr','\uD835\uDD20':'cfr','\uD835\uDCB8':'cscr','\uD835\uDD54':'copf','\u212D':'Cfr','\uD835\uDC9E':'Cscr','\u2102':'Copf','\u0107':'cacute','\u0106':'Cacute','\u0109':'ccirc','\u0108':'Ccirc','\u010D':'ccaron','\u010C':'Ccaron','\u010B':'cdot','\u010A':'Cdot','\xE7':'ccedil','\xC7':'Ccedil','\u2105':'incare','\uD835\uDD21':'dfr','\u2146':'dd','\uD835\uDD55':'dopf','\uD835\uDCB9':'dscr','\uD835\uDC9F':'Dscr','\uD835\uDD07':'Dfr','\u2145':'DD','\uD835\uDD3B':'Dopf','\u010F':'dcaron','\u010E':'Dcaron','\u0111':'dstrok','\u0110':'Dstrok','\xF0':'eth','\xD0':'ETH','\u2147':'ee','\u212F':'escr','\uD835\uDD22':'efr','\uD835\uDD56':'eopf','\u2130':'Escr','\uD835\uDD08':'Efr','\uD835\uDD3C':'Eopf','\xE9':'eacute','\xC9':'Eacute','\xE8':'egrave','\xC8':'Egrave','\xEA':'ecirc','\xCA':'Ecirc','\u011B':'ecaron','\u011A':'Ecaron','\xEB':'euml','\xCB':'Euml','\u0117':'edot','\u0116':'Edot','\u0119':'eogon','\u0118':'Eogon','\u0113':'emacr','\u0112':'Emacr','\uD835\uDD23':'ffr','\uD835\uDD57':'fopf','\uD835\uDCBB':'fscr','\uD835\uDD09':'Ffr','\uD835\uDD3D':'Fopf','\u2131':'Fscr','\uFB00':'fflig','\uFB03':'ffilig','\uFB04':'ffllig','\uFB01':'filig','fj':'fjlig','\uFB02':'fllig','\u0192':'fnof','\u210A':'gscr','\uD835\uDD58':'gopf','\uD835\uDD24':'gfr','\uD835\uDCA2':'Gscr','\uD835\uDD3E':'Gopf','\uD835\uDD0A':'Gfr','\u01F5':'gacute','\u011F':'gbreve','\u011E':'Gbreve','\u011D':'gcirc','\u011C':'Gcirc','\u0121':'gdot','\u0120':'Gdot','\u0122':'Gcedil','\uD835\uDD25':'hfr','\u210E':'planckh','\uD835\uDCBD':'hscr','\uD835\uDD59':'hopf','\u210B':'Hscr','\u210C':'Hfr','\u210D':'Hopf','\u0125':'hcirc','\u0124':'Hcirc','\u210F':'hbar','\u0127':'hstrok','\u0126':'Hstrok','\uD835\uDD5A':'iopf','\uD835\uDD26':'ifr','\uD835\uDCBE':'iscr','\u2148':'ii','\uD835\uDD40':'Iopf','\u2110':'Iscr','\u2111':'Im','\xED':'iacute','\xCD':'Iacute','\xEC':'igrave','\xCC':'Igrave','\xEE':'icirc','\xCE':'Icirc','\xEF':'iuml','\xCF':'Iuml','\u0129':'itilde','\u0128':'Itilde','\u0130':'Idot','\u012F':'iogon','\u012E':'Iogon','\u012B':'imacr','\u012A':'Imacr','\u0133':'ijlig','\u0132':'IJlig','\u0131':'imath','\uD835\uDCBF':'jscr','\uD835\uDD5B':'jopf','\uD835\uDD27':'jfr','\uD835\uDCA5':'Jscr','\uD835\uDD0D':'Jfr','\uD835\uDD41':'Jopf','\u0135':'jcirc','\u0134':'Jcirc','\u0237':'jmath','\uD835\uDD5C':'kopf','\uD835\uDCC0':'kscr','\uD835\uDD28':'kfr','\uD835\uDCA6':'Kscr','\uD835\uDD42':'Kopf','\uD835\uDD0E':'Kfr','\u0137':'kcedil','\u0136':'Kcedil','\uD835\uDD29':'lfr','\uD835\uDCC1':'lscr','\u2113':'ell','\uD835\uDD5D':'lopf','\u2112':'Lscr','\uD835\uDD0F':'Lfr','\uD835\uDD43':'Lopf','\u013A':'lacute','\u0139':'Lacute','\u013E':'lcaron','\u013D':'Lcaron','\u013C':'lcedil','\u013B':'Lcedil','\u0142':'lstrok','\u0141':'Lstrok','\u0140':'lmidot','\u013F':'Lmidot','\uD835\uDD2A':'mfr','\uD835\uDD5E':'mopf','\uD835\uDCC2':'mscr','\uD835\uDD10':'Mfr','\uD835\uDD44':'Mopf','\u2133':'Mscr','\uD835\uDD2B':'nfr','\uD835\uDD5F':'nopf','\uD835\uDCC3':'nscr','\u2115':'Nopf','\uD835\uDCA9':'Nscr','\uD835\uDD11':'Nfr','\u0144':'nacute','\u0143':'Nacute','\u0148':'ncaron','\u0147':'Ncaron','\xF1':'ntilde','\xD1':'Ntilde','\u0146':'ncedil','\u0145':'Ncedil','\u2116':'numero','\u014B':'eng','\u014A':'ENG','\uD835\uDD60':'oopf','\uD835\uDD2C':'ofr','\u2134':'oscr','\uD835\uDCAA':'Oscr','\uD835\uDD12':'Ofr','\uD835\uDD46':'Oopf','\xBA':'ordm','\xF3':'oacute','\xD3':'Oacute','\xF2':'ograve','\xD2':'Ograve','\xF4':'ocirc','\xD4':'Ocirc','\xF6':'ouml','\xD6':'Ouml','\u0151':'odblac','\u0150':'Odblac','\xF5':'otilde','\xD5':'Otilde','\xF8':'oslash','\xD8':'Oslash','\u014D':'omacr','\u014C':'Omacr','\u0153':'oelig','\u0152':'OElig','\uD835\uDD2D':'pfr','\uD835\uDCC5':'pscr','\uD835\uDD61':'popf','\u2119':'Popf','\uD835\uDD13':'Pfr','\uD835\uDCAB':'Pscr','\uD835\uDD62':'qopf','\uD835\uDD2E':'qfr','\uD835\uDCC6':'qscr','\uD835\uDCAC':'Qscr','\uD835\uDD14':'Qfr','\u211A':'Qopf','\u0138':'kgreen','\uD835\uDD2F':'rfr','\uD835\uDD63':'ropf','\uD835\uDCC7':'rscr','\u211B':'Rscr','\u211C':'Re','\u211D':'Ropf','\u0155':'racute','\u0154':'Racute','\u0159':'rcaron','\u0158':'Rcaron','\u0157':'rcedil','\u0156':'Rcedil','\uD835\uDD64':'sopf','\uD835\uDCC8':'sscr','\uD835\uDD30':'sfr','\uD835\uDD4A':'Sopf','\uD835\uDD16':'Sfr','\uD835\uDCAE':'Sscr','\u24C8':'oS','\u015B':'sacute','\u015A':'Sacute','\u015D':'scirc','\u015C':'Scirc','\u0161':'scaron','\u0160':'Scaron','\u015F':'scedil','\u015E':'Scedil','\xDF':'szlig','\uD835\uDD31':'tfr','\uD835\uDCC9':'tscr','\uD835\uDD65':'topf','\uD835\uDCAF':'Tscr','\uD835\uDD17':'Tfr','\uD835\uDD4B':'Topf','\u0165':'tcaron','\u0164':'Tcaron','\u0163':'tcedil','\u0162':'Tcedil','\u2122':'trade','\u0167':'tstrok','\u0166':'Tstrok','\uD835\uDCCA':'uscr','\uD835\uDD66':'uopf','\uD835\uDD32':'ufr','\uD835\uDD4C':'Uopf','\uD835\uDD18':'Ufr','\uD835\uDCB0':'Uscr','\xFA':'uacute','\xDA':'Uacute','\xF9':'ugrave','\xD9':'Ugrave','\u016D':'ubreve','\u016C':'Ubreve','\xFB':'ucirc','\xDB':'Ucirc','\u016F':'uring','\u016E':'Uring','\xFC':'uuml','\xDC':'Uuml','\u0171':'udblac','\u0170':'Udblac','\u0169':'utilde','\u0168':'Utilde','\u0173':'uogon','\u0172':'Uogon','\u016B':'umacr','\u016A':'Umacr','\uD835\uDD33':'vfr','\uD835\uDD67':'vopf','\uD835\uDCCB':'vscr','\uD835\uDD19':'Vfr','\uD835\uDD4D':'Vopf','\uD835\uDCB1':'Vscr','\uD835\uDD68':'wopf','\uD835\uDCCC':'wscr','\uD835\uDD34':'wfr','\uD835\uDCB2':'Wscr','\uD835\uDD4E':'Wopf','\uD835\uDD1A':'Wfr','\u0175':'wcirc','\u0174':'Wcirc','\uD835\uDD35':'xfr','\uD835\uDCCD':'xscr','\uD835\uDD69':'xopf','\uD835\uDD4F':'Xopf','\uD835\uDD1B':'Xfr','\uD835\uDCB3':'Xscr','\uD835\uDD36':'yfr','\uD835\uDCCE':'yscr','\uD835\uDD6A':'yopf','\uD835\uDCB4':'Yscr','\uD835\uDD1C':'Yfr','\uD835\uDD50':'Yopf','\xFD':'yacute','\xDD':'Yacute','\u0177':'ycirc','\u0176':'Ycirc','\xFF':'yuml','\u0178':'Yuml','\uD835\uDCCF':'zscr','\uD835\uDD37':'zfr','\uD835\uDD6B':'zopf','\u2128':'Zfr','\u2124':'Zopf','\uD835\uDCB5':'Zscr','\u017A':'zacute','\u0179':'Zacute','\u017E':'zcaron','\u017D':'Zcaron','\u017C':'zdot','\u017B':'Zdot','\u01B5':'imped','\xFE':'thorn','\xDE':'THORN','\u0149':'napos','\u03B1':'alpha','\u0391':'Alpha','\u03B2':'beta','\u0392':'Beta','\u03B3':'gamma','\u0393':'Gamma','\u03B4':'delta','\u0394':'Delta','\u03B5':'epsi','\u03F5':'epsiv','\u0395':'Epsilon','\u03DD':'gammad','\u03DC':'Gammad','\u03B6':'zeta','\u0396':'Zeta','\u03B7':'eta','\u0397':'Eta','\u03B8':'theta','\u03D1':'thetav','\u0398':'Theta','\u03B9':'iota','\u0399':'Iota','\u03BA':'kappa','\u03F0':'kappav','\u039A':'Kappa','\u03BB':'lambda','\u039B':'Lambda','\u03BC':'mu','\xB5':'micro','\u039C':'Mu','\u03BD':'nu','\u039D':'Nu','\u03BE':'xi','\u039E':'Xi','\u03BF':'omicron','\u039F':'Omicron','\u03C0':'pi','\u03D6':'piv','\u03A0':'Pi','\u03C1':'rho','\u03F1':'rhov','\u03A1':'Rho','\u03C3':'sigma','\u03A3':'Sigma','\u03C2':'sigmaf','\u03C4':'tau','\u03A4':'Tau','\u03C5':'upsi','\u03A5':'Upsilon','\u03D2':'Upsi','\u03C6':'phi','\u03D5':'phiv','\u03A6':'Phi','\u03C7':'chi','\u03A7':'Chi','\u03C8':'psi','\u03A8':'Psi','\u03C9':'omega','\u03A9':'ohm','\u0430':'acy','\u0410':'Acy','\u0431':'bcy','\u0411':'Bcy','\u0432':'vcy','\u0412':'Vcy','\u0433':'gcy','\u0413':'Gcy','\u0453':'gjcy','\u0403':'GJcy','\u0434':'dcy','\u0414':'Dcy','\u0452':'djcy','\u0402':'DJcy','\u0435':'iecy','\u0415':'IEcy','\u0451':'iocy','\u0401':'IOcy','\u0454':'jukcy','\u0404':'Jukcy','\u0436':'zhcy','\u0416':'ZHcy','\u0437':'zcy','\u0417':'Zcy','\u0455':'dscy','\u0405':'DScy','\u0438':'icy','\u0418':'Icy','\u0456':'iukcy','\u0406':'Iukcy','\u0457':'yicy','\u0407':'YIcy','\u0439':'jcy','\u0419':'Jcy','\u0458':'jsercy','\u0408':'Jsercy','\u043A':'kcy','\u041A':'Kcy','\u045C':'kjcy','\u040C':'KJcy','\u043B':'lcy','\u041B':'Lcy','\u0459':'ljcy','\u0409':'LJcy','\u043C':'mcy','\u041C':'Mcy','\u043D':'ncy','\u041D':'Ncy','\u045A':'njcy','\u040A':'NJcy','\u043E':'ocy','\u041E':'Ocy','\u043F':'pcy','\u041F':'Pcy','\u0440':'rcy','\u0420':'Rcy','\u0441':'scy','\u0421':'Scy','\u0442':'tcy','\u0422':'Tcy','\u045B':'tshcy','\u040B':'TSHcy','\u0443':'ucy','\u0423':'Ucy','\u045E':'ubrcy','\u040E':'Ubrcy','\u0444':'fcy','\u0424':'Fcy','\u0445':'khcy','\u0425':'KHcy','\u0446':'tscy','\u0426':'TScy','\u0447':'chcy','\u0427':'CHcy','\u045F':'dzcy','\u040F':'DZcy','\u0448':'shcy','\u0428':'SHcy','\u0449':'shchcy','\u0429':'SHCHcy','\u044A':'hardcy','\u042A':'HARDcy','\u044B':'ycy','\u042B':'Ycy','\u044C':'softcy','\u042C':'SOFTcy','\u044D':'ecy','\u042D':'Ecy','\u044E':'yucy','\u042E':'YUcy','\u044F':'yacy','\u042F':'YAcy','\u2135':'aleph','\u2136':'beth','\u2137':'gimel','\u2138':'daleth'};
13783 var regexEscape = /["&'<>`]/g;
13789 // See https://mathiasbynens.be/notes/ambiguous-ampersands: in HTML, the
13790 // following is not strictly necessary unless it’s part of a tag or an
13791 // unquoted attribute value. We’re only escaping it to support those
13792 // situations, and for XML support.
13794 // In Internet Explorer ≤ 8, the backtick character can be used
13795 // to break out of (un)quoted attribute values or HTML comments.
13796 // See http://html5sec.org/#102, http://html5sec.org/#108, and
13797 // http://html5sec.org/#133.
13801 var regexInvalidEntity = /&#(?:[xX][^a-fA-F0-9]|[^0-9xX])/;
13802 var regexInvalidRawCodePoint = /[\0-\x08\x0B\x0E-\x1F\x7F-\x9F\uFDD0-\uFDEF\uFFFE\uFFFF]|[\uD83F\uD87F\uD8BF\uD8FF\uD93F\uD97F\uD9BF\uD9FF\uDA3F\uDA7F\uDABF\uDAFF\uDB3F\uDB7F\uDBBF\uDBFF][\uDFFE\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/;
13803 var regexDecode = /&(CounterClockwiseContourIntegral|DoubleLongLeftRightArrow|ClockwiseContourIntegral|NotNestedGreaterGreater|NotSquareSupersetEqual|DiacriticalDoubleAcute|NotRightTriangleEqual|NotSucceedsSlantEqual|NotPrecedesSlantEqual|CloseCurlyDoubleQuote|NegativeVeryThinSpace|DoubleContourIntegral|FilledVerySmallSquare|CapitalDifferentialD|OpenCurlyDoubleQuote|EmptyVerySmallSquare|NestedGreaterGreater|DoubleLongRightArrow|NotLeftTriangleEqual|NotGreaterSlantEqual|ReverseUpEquilibrium|DoubleLeftRightArrow|NotSquareSubsetEqual|NotDoubleVerticalBar|RightArrowLeftArrow|NotGreaterFullEqual|NotRightTriangleBar|SquareSupersetEqual|DownLeftRightVector|DoubleLongLeftArrow|leftrightsquigarrow|LeftArrowRightArrow|NegativeMediumSpace|blacktriangleright|RightDownVectorBar|PrecedesSlantEqual|RightDoubleBracket|SucceedsSlantEqual|NotLeftTriangleBar|RightTriangleEqual|SquareIntersection|RightDownTeeVector|ReverseEquilibrium|NegativeThickSpace|longleftrightarrow|Longleftrightarrow|LongLeftRightArrow|DownRightTeeVector|DownRightVectorBar|GreaterSlantEqual|SquareSubsetEqual|LeftDownVectorBar|LeftDoubleBracket|VerticalSeparator|rightleftharpoons|NotGreaterGreater|NotSquareSuperset|blacktriangleleft|blacktriangledown|NegativeThinSpace|LeftDownTeeVector|NotLessSlantEqual|leftrightharpoons|DoubleUpDownArrow|DoubleVerticalBar|LeftTriangleEqual|FilledSmallSquare|twoheadrightarrow|NotNestedLessLess|DownLeftTeeVector|DownLeftVectorBar|RightAngleBracket|NotTildeFullEqual|NotReverseElement|RightUpDownVector|DiacriticalTilde|NotSucceedsTilde|circlearrowright|NotPrecedesEqual|rightharpoondown|DoubleRightArrow|NotSucceedsEqual|NonBreakingSpace|NotRightTriangle|LessEqualGreater|RightUpTeeVector|LeftAngleBracket|GreaterFullEqual|DownArrowUpArrow|RightUpVectorBar|twoheadleftarrow|GreaterEqualLess|downharpoonright|RightTriangleBar|ntrianglerighteq|NotSupersetEqual|LeftUpDownVector|DiacriticalAcute|rightrightarrows|vartriangleright|UpArrowDownArrow|DiacriticalGrave|UnderParenthesis|EmptySmallSquare|LeftUpVectorBar|leftrightarrows|DownRightVector|downharpoonleft|trianglerighteq|ShortRightArrow|OverParenthesis|DoubleLeftArrow|DoubleDownArrow|NotSquareSubset|bigtriangledown|ntrianglelefteq|UpperRightArrow|curvearrowright|vartriangleleft|NotLeftTriangle|nleftrightarrow|LowerRightArrow|NotHumpDownHump|NotGreaterTilde|rightthreetimes|LeftUpTeeVector|NotGreaterEqual|straightepsilon|LeftTriangleBar|rightsquigarrow|ContourIntegral|rightleftarrows|CloseCurlyQuote|RightDownVector|LeftRightVector|nLeftrightarrow|leftharpoondown|circlearrowleft|SquareSuperset|OpenCurlyQuote|hookrightarrow|HorizontalLine|DiacriticalDot|NotLessGreater|ntriangleright|DoubleRightTee|InvisibleComma|InvisibleTimes|LowerLeftArrow|DownLeftVector|NotSubsetEqual|curvearrowleft|trianglelefteq|NotVerticalBar|TildeFullEqual|downdownarrows|NotGreaterLess|RightTeeVector|ZeroWidthSpace|looparrowright|LongRightArrow|doublebarwedge|ShortLeftArrow|ShortDownArrow|RightVectorBar|GreaterGreater|ReverseElement|rightharpoonup|LessSlantEqual|leftthreetimes|upharpoonright|rightarrowtail|LeftDownVector|Longrightarrow|NestedLessLess|UpperLeftArrow|nshortparallel|leftleftarrows|leftrightarrow|Leftrightarrow|LeftRightArrow|longrightarrow|upharpoonleft|RightArrowBar|ApplyFunction|LeftTeeVector|leftarrowtail|NotEqualTilde|varsubsetneqq|varsupsetneqq|RightTeeArrow|SucceedsEqual|SucceedsTilde|LeftVectorBar|SupersetEqual|hookleftarrow|DifferentialD|VerticalTilde|VeryThinSpace|blacktriangle|bigtriangleup|LessFullEqual|divideontimes|leftharpoonup|UpEquilibrium|ntriangleleft|RightTriangle|measuredangle|shortparallel|longleftarrow|Longleftarrow|LongLeftArrow|DoubleLeftTee|Poincareplane|PrecedesEqual|triangleright|DoubleUpArrow|RightUpVector|fallingdotseq|looparrowleft|PrecedesTilde|NotTildeEqual|NotTildeTilde|smallsetminus|Proportional|triangleleft|triangledown|UnderBracket|NotHumpEqual|exponentiale|ExponentialE|NotLessTilde|HilbertSpace|RightCeiling|blacklozenge|varsupsetneq|HumpDownHump|GreaterEqual|VerticalLine|LeftTeeArrow|NotLessEqual|DownTeeArrow|LeftTriangle|varsubsetneq|Intersection|NotCongruent|DownArrowBar|LeftUpVector|LeftArrowBar|risingdotseq|GreaterTilde|RoundImplies|SquareSubset|ShortUpArrow|NotSuperset|quaternions|precnapprox|backepsilon|preccurlyeq|OverBracket|blacksquare|MediumSpace|VerticalBar|circledcirc|circleddash|CircleMinus|CircleTimes|LessGreater|curlyeqprec|curlyeqsucc|diamondsuit|UpDownArrow|Updownarrow|RuleDelayed|Rrightarrow|updownarrow|RightVector|nRightarrow|nrightarrow|eqslantless|LeftCeiling|Equilibrium|SmallCircle|expectation|NotSucceeds|thickapprox|GreaterLess|SquareUnion|NotPrecedes|NotLessLess|straightphi|succnapprox|succcurlyeq|SubsetEqual|sqsupseteq|Proportion|Laplacetrf|ImaginaryI|supsetneqq|NotGreater|gtreqqless|NotElement|ThickSpace|TildeEqual|TildeTilde|Fouriertrf|rmoustache|EqualTilde|eqslantgtr|UnderBrace|LeftVector|UpArrowBar|nLeftarrow|nsubseteqq|subsetneqq|nsupseteqq|nleftarrow|succapprox|lessapprox|UpTeeArrow|upuparrows|curlywedge|lesseqqgtr|varepsilon|varnothing|RightFloor|complement|CirclePlus|sqsubseteq|Lleftarrow|circledast|RightArrow|Rightarrow|rightarrow|lmoustache|Bernoullis|precapprox|mapstoleft|mapstodown|longmapsto|dotsquare|downarrow|DoubleDot|nsubseteq|supsetneq|leftarrow|nsupseteq|subsetneq|ThinSpace|ngeqslant|subseteqq|HumpEqual|NotSubset|triangleq|NotCupCap|lesseqgtr|heartsuit|TripleDot|Leftarrow|Coproduct|Congruent|varpropto|complexes|gvertneqq|LeftArrow|LessTilde|supseteqq|MinusPlus|CircleDot|nleqslant|NotExists|gtreqless|nparallel|UnionPlus|LeftFloor|checkmark|CenterDot|centerdot|Mellintrf|gtrapprox|bigotimes|OverBrace|spadesuit|therefore|pitchfork|rationals|PlusMinus|Backslash|Therefore|DownBreve|backsimeq|backprime|DownArrow|nshortmid|Downarrow|lvertneqq|eqvparsl|imagline|imagpart|infintie|integers|Integral|intercal|LessLess|Uarrocir|intlarhk|sqsupset|angmsdaf|sqsubset|llcorner|vartheta|cupbrcap|lnapprox|Superset|SuchThat|succnsim|succneqq|angmsdag|biguplus|curlyvee|trpezium|Succeeds|NotTilde|bigwedge|angmsdah|angrtvbd|triminus|cwconint|fpartint|lrcorner|smeparsl|subseteq|urcorner|lurdshar|laemptyv|DDotrahd|approxeq|ldrushar|awconint|mapstoup|backcong|shortmid|triangle|geqslant|gesdotol|timesbar|circledR|circledS|setminus|multimap|naturals|scpolint|ncongdot|RightTee|boxminus|gnapprox|boxtimes|andslope|thicksim|angmsdaa|varsigma|cirfnint|rtriltri|angmsdab|rppolint|angmsdac|barwedge|drbkarow|clubsuit|thetasym|bsolhsub|capbrcup|dzigrarr|doteqdot|DotEqual|dotminus|UnderBar|NotEqual|realpart|otimesas|ulcorner|hksearow|hkswarow|parallel|PartialD|elinters|emptyset|plusacir|bbrktbrk|angmsdad|pointint|bigoplus|angmsdae|Precedes|bigsqcup|varkappa|notindot|supseteq|precneqq|precnsim|profalar|profline|profsurf|leqslant|lesdotor|raemptyv|subplus|notnivb|notnivc|subrarr|zigrarr|vzigzag|submult|subedot|Element|between|cirscir|larrbfs|larrsim|lotimes|lbrksld|lbrkslu|lozenge|ldrdhar|dbkarow|bigcirc|epsilon|simrarr|simplus|ltquest|Epsilon|luruhar|gtquest|maltese|npolint|eqcolon|npreceq|bigodot|ddagger|gtrless|bnequiv|harrcir|ddotseq|equivDD|backsim|demptyv|nsqsube|nsqsupe|Upsilon|nsubset|upsilon|minusdu|nsucceq|swarrow|nsupset|coloneq|searrow|boxplus|napprox|natural|asympeq|alefsym|congdot|nearrow|bigstar|diamond|supplus|tritime|LeftTee|nvinfin|triplus|NewLine|nvltrie|nvrtrie|nwarrow|nexists|Diamond|ruluhar|Implies|supmult|angzarr|suplarr|suphsub|questeq|because|digamma|Because|olcross|bemptyv|omicron|Omicron|rotimes|NoBreak|intprod|angrtvb|orderof|uwangle|suphsol|lesdoto|orslope|DownTee|realine|cudarrl|rdldhar|OverBar|supedot|lessdot|supdsub|topfork|succsim|rbrkslu|rbrksld|pertenk|cudarrr|isindot|planckh|lessgtr|pluscir|gesdoto|plussim|plustwo|lesssim|cularrp|rarrsim|Cayleys|notinva|notinvb|notinvc|UpArrow|Uparrow|uparrow|NotLess|dwangle|precsim|Product|curarrm|Cconint|dotplus|rarrbfs|ccupssm|Cedilla|cemptyv|notniva|quatint|frac35|frac38|frac45|frac56|frac58|frac78|tridot|xoplus|gacute|gammad|Gammad|lfisht|lfloor|bigcup|sqsupe|gbreve|Gbreve|lharul|sqsube|sqcups|Gcedil|apacir|llhard|lmidot|Lmidot|lmoust|andand|sqcaps|approx|Abreve|spades|circeq|tprime|divide|topcir|Assign|topbot|gesdot|divonx|xuplus|timesd|gesles|atilde|solbar|SOFTcy|loplus|timesb|lowast|lowbar|dlcorn|dlcrop|softcy|dollar|lparlt|thksim|lrhard|Atilde|lsaquo|smashp|bigvee|thinsp|wreath|bkarow|lsquor|lstrok|Lstrok|lthree|ltimes|ltlarr|DotDot|simdot|ltrPar|weierp|xsqcup|angmsd|sigmav|sigmaf|zeetrf|Zcaron|zcaron|mapsto|vsupne|thetav|cirmid|marker|mcomma|Zacute|vsubnE|there4|gtlPar|vsubne|bottom|gtrarr|SHCHcy|shchcy|midast|midcir|middot|minusb|minusd|gtrdot|bowtie|sfrown|mnplus|models|colone|seswar|Colone|mstpos|searhk|gtrsim|nacute|Nacute|boxbox|telrec|hairsp|Tcedil|nbumpe|scnsim|ncaron|Ncaron|ncedil|Ncedil|hamilt|Scedil|nearhk|hardcy|HARDcy|tcedil|Tcaron|commat|nequiv|nesear|tcaron|target|hearts|nexist|varrho|scedil|Scaron|scaron|hellip|Sacute|sacute|hercon|swnwar|compfn|rtimes|rthree|rsquor|rsaquo|zacute|wedgeq|homtht|barvee|barwed|Barwed|rpargt|horbar|conint|swarhk|roplus|nltrie|hslash|hstrok|Hstrok|rmoust|Conint|bprime|hybull|hyphen|iacute|Iacute|supsup|supsub|supsim|varphi|coprod|brvbar|agrave|Supset|supset|igrave|Igrave|notinE|Agrave|iiiint|iinfin|copysr|wedbar|Verbar|vangrt|becaus|incare|verbar|inodot|bullet|drcorn|intcal|drcrop|cularr|vellip|Utilde|bumpeq|cupcap|dstrok|Dstrok|CupCap|cupcup|cupdot|eacute|Eacute|supdot|iquest|easter|ecaron|Ecaron|ecolon|isinsv|utilde|itilde|Itilde|curarr|succeq|Bumpeq|cacute|ulcrop|nparsl|Cacute|nprcue|egrave|Egrave|nrarrc|nrarrw|subsup|subsub|nrtrie|jsercy|nsccue|Jsercy|kappav|kcedil|Kcedil|subsim|ulcorn|nsimeq|egsdot|veebar|kgreen|capand|elsdot|Subset|subset|curren|aacute|lacute|Lacute|emptyv|ntilde|Ntilde|lagran|lambda|Lambda|capcap|Ugrave|langle|subdot|emsp13|numero|emsp14|nvdash|nvDash|nVdash|nVDash|ugrave|ufisht|nvHarr|larrfs|nvlArr|larrhk|larrlp|larrpl|nvrArr|Udblac|nwarhk|larrtl|nwnear|oacute|Oacute|latail|lAtail|sstarf|lbrace|odblac|Odblac|lbrack|udblac|odsold|eparsl|lcaron|Lcaron|ograve|Ograve|lcedil|Lcedil|Aacute|ssmile|ssetmn|squarf|ldquor|capcup|ominus|cylcty|rharul|eqcirc|dagger|rfloor|rfisht|Dagger|daleth|equals|origof|capdot|equest|dcaron|Dcaron|rdquor|oslash|Oslash|otilde|Otilde|otimes|Otimes|urcrop|Ubreve|ubreve|Yacute|Uacute|uacute|Rcedil|rcedil|urcorn|parsim|Rcaron|Vdashl|rcaron|Tstrok|percnt|period|permil|Exists|yacute|rbrack|rbrace|phmmat|ccaron|Ccaron|planck|ccedil|plankv|tstrok|female|plusdo|plusdu|ffilig|plusmn|ffllig|Ccedil|rAtail|dfisht|bernou|ratail|Rarrtl|rarrtl|angsph|rarrpl|rarrlp|rarrhk|xwedge|xotime|forall|ForAll|Vvdash|vsupnE|preceq|bigcap|frac12|frac13|frac14|primes|rarrfs|prnsim|frac15|Square|frac16|square|lesdot|frac18|frac23|propto|prurel|rarrap|rangle|puncsp|frac25|Racute|qprime|racute|lesges|frac34|abreve|AElig|eqsim|utdot|setmn|urtri|Equal|Uring|seArr|uring|searr|dashv|Dashv|mumap|nabla|iogon|Iogon|sdote|sdotb|scsim|napid|napos|equiv|natur|Acirc|dblac|erarr|nbump|iprod|erDot|ucirc|awint|esdot|angrt|ncong|isinE|scnap|Scirc|scirc|ndash|isins|Ubrcy|nearr|neArr|isinv|nedot|ubrcy|acute|Ycirc|iukcy|Iukcy|xutri|nesim|caret|jcirc|Jcirc|caron|twixt|ddarr|sccue|exist|jmath|sbquo|ngeqq|angst|ccaps|lceil|ngsim|UpTee|delta|Delta|rtrif|nharr|nhArr|nhpar|rtrie|jukcy|Jukcy|kappa|rsquo|Kappa|nlarr|nlArr|TSHcy|rrarr|aogon|Aogon|fflig|xrarr|tshcy|ccirc|nleqq|filig|upsih|nless|dharl|nlsim|fjlig|ropar|nltri|dharr|robrk|roarr|fllig|fltns|roang|rnmid|subnE|subne|lAarr|trisb|Ccirc|acirc|ccups|blank|VDash|forkv|Vdash|langd|cedil|blk12|blk14|laquo|strns|diams|notin|vDash|larrb|blk34|block|disin|uplus|vdash|vBarv|aelig|starf|Wedge|check|xrArr|lates|lbarr|lBarr|notni|lbbrk|bcong|frasl|lbrke|frown|vrtri|vprop|vnsup|gamma|Gamma|wedge|xodot|bdquo|srarr|doteq|ldquo|boxdl|boxdL|gcirc|Gcirc|boxDl|boxDL|boxdr|boxdR|boxDr|TRADE|trade|rlhar|boxDR|vnsub|npart|vltri|rlarr|boxhd|boxhD|nprec|gescc|nrarr|nrArr|boxHd|boxHD|boxhu|boxhU|nrtri|boxHu|clubs|boxHU|times|colon|Colon|gimel|xlArr|Tilde|nsime|tilde|nsmid|nspar|THORN|thorn|xlarr|nsube|nsubE|thkap|xhArr|comma|nsucc|boxul|boxuL|nsupe|nsupE|gneqq|gnsim|boxUl|boxUL|grave|boxur|boxuR|boxUr|boxUR|lescc|angle|bepsi|boxvh|varpi|boxvH|numsp|Theta|gsime|gsiml|theta|boxVh|boxVH|boxvl|gtcir|gtdot|boxvL|boxVl|boxVL|crarr|cross|Cross|nvsim|boxvr|nwarr|nwArr|sqsup|dtdot|Uogon|lhard|lharu|dtrif|ocirc|Ocirc|lhblk|duarr|odash|sqsub|Hacek|sqcup|llarr|duhar|oelig|OElig|ofcir|boxvR|uogon|lltri|boxVr|csube|uuarr|ohbar|csupe|ctdot|olarr|olcir|harrw|oline|sqcap|omacr|Omacr|omega|Omega|boxVR|aleph|lneqq|lnsim|loang|loarr|rharu|lobrk|hcirc|operp|oplus|rhard|Hcirc|orarr|Union|order|ecirc|Ecirc|cuepr|szlig|cuesc|breve|reals|eDDot|Breve|hoarr|lopar|utrif|rdquo|Umacr|umacr|efDot|swArr|ultri|alpha|rceil|ovbar|swarr|Wcirc|wcirc|smtes|smile|bsemi|lrarr|aring|parsl|lrhar|bsime|uhblk|lrtri|cupor|Aring|uharr|uharl|slarr|rbrke|bsolb|lsime|rbbrk|RBarr|lsimg|phone|rBarr|rbarr|icirc|lsquo|Icirc|emacr|Emacr|ratio|simne|plusb|simlE|simgE|simeq|pluse|ltcir|ltdot|empty|xharr|xdtri|iexcl|Alpha|ltrie|rarrw|pound|ltrif|xcirc|bumpe|prcue|bumpE|asymp|amacr|cuvee|Sigma|sigma|iiint|udhar|iiota|ijlig|IJlig|supnE|imacr|Imacr|prime|Prime|image|prnap|eogon|Eogon|rarrc|mdash|mDDot|cuwed|imath|supne|imped|Amacr|udarr|prsim|micro|rarrb|cwint|raquo|infin|eplus|range|rangd|Ucirc|radic|minus|amalg|veeeq|rAarr|epsiv|ycirc|quest|sharp|quot|zwnj|Qscr|race|qscr|Qopf|qopf|qint|rang|Rang|Zscr|zscr|Zopf|zopf|rarr|rArr|Rarr|Pscr|pscr|prop|prod|prnE|prec|ZHcy|zhcy|prap|Zeta|zeta|Popf|popf|Zdot|plus|zdot|Yuml|yuml|phiv|YUcy|yucy|Yscr|yscr|perp|Yopf|yopf|part|para|YIcy|Ouml|rcub|yicy|YAcy|rdca|ouml|osol|Oscr|rdsh|yacy|real|oscr|xvee|andd|rect|andv|Xscr|oror|ordm|ordf|xscr|ange|aopf|Aopf|rHar|Xopf|opar|Oopf|xopf|xnis|rhov|oopf|omid|xmap|oint|apid|apos|ogon|ascr|Ascr|odot|odiv|xcup|xcap|ocir|oast|nvlt|nvle|nvgt|nvge|nvap|Wscr|wscr|auml|ntlg|ntgl|nsup|nsub|nsim|Nscr|nscr|nsce|Wopf|ring|npre|wopf|npar|Auml|Barv|bbrk|Nopf|nopf|nmid|nLtv|beta|ropf|Ropf|Beta|beth|nles|rpar|nleq|bnot|bNot|nldr|NJcy|rscr|Rscr|Vscr|vscr|rsqb|njcy|bopf|nisd|Bopf|rtri|Vopf|nGtv|ngtr|vopf|boxh|boxH|boxv|nges|ngeq|boxV|bscr|scap|Bscr|bsim|Vert|vert|bsol|bull|bump|caps|cdot|ncup|scnE|ncap|nbsp|napE|Cdot|cent|sdot|Vbar|nang|vBar|chcy|Mscr|mscr|sect|semi|CHcy|Mopf|mopf|sext|circ|cire|mldr|mlcp|cirE|comp|shcy|SHcy|vArr|varr|cong|copf|Copf|copy|COPY|malt|male|macr|lvnE|cscr|ltri|sime|ltcc|simg|Cscr|siml|csub|Uuml|lsqb|lsim|uuml|csup|Lscr|lscr|utri|smid|lpar|cups|smte|lozf|darr|Lopf|Uscr|solb|lopf|sopf|Sopf|lneq|uscr|spar|dArr|lnap|Darr|dash|Sqrt|LJcy|ljcy|lHar|dHar|Upsi|upsi|diam|lesg|djcy|DJcy|leqq|dopf|Dopf|dscr|Dscr|dscy|ldsh|ldca|squf|DScy|sscr|Sscr|dsol|lcub|late|star|Star|Uopf|Larr|lArr|larr|uopf|dtri|dzcy|sube|subE|Lang|lang|Kscr|kscr|Kopf|kopf|KJcy|kjcy|KHcy|khcy|DZcy|ecir|edot|eDot|Jscr|jscr|succ|Jopf|jopf|Edot|uHar|emsp|ensp|Iuml|iuml|eopf|isin|Iscr|iscr|Eopf|epar|sung|epsi|escr|sup1|sup2|sup3|Iota|iota|supe|supE|Iopf|iopf|IOcy|iocy|Escr|esim|Esim|imof|Uarr|QUOT|uArr|uarr|euml|IEcy|iecy|Idot|Euml|euro|excl|Hscr|hscr|Hopf|hopf|TScy|tscy|Tscr|hbar|tscr|flat|tbrk|fnof|hArr|harr|half|fopf|Fopf|tdot|gvnE|fork|trie|gtcc|fscr|Fscr|gdot|gsim|Gscr|gscr|Gopf|gopf|gneq|Gdot|tosa|gnap|Topf|topf|geqq|toea|GJcy|gjcy|tint|gesl|mid|Sfr|ggg|top|ges|gla|glE|glj|geq|gne|gEl|gel|gnE|Gcy|gcy|gap|Tfr|tfr|Tcy|tcy|Hat|Tau|Ffr|tau|Tab|hfr|Hfr|ffr|Fcy|fcy|icy|Icy|iff|ETH|eth|ifr|Ifr|Eta|eta|int|Int|Sup|sup|ucy|Ucy|Sum|sum|jcy|ENG|ufr|Ufr|eng|Jcy|jfr|els|ell|egs|Efr|efr|Jfr|uml|kcy|Kcy|Ecy|ecy|kfr|Kfr|lap|Sub|sub|lat|lcy|Lcy|leg|Dot|dot|lEg|leq|les|squ|div|die|lfr|Lfr|lgE|Dfr|dfr|Del|deg|Dcy|dcy|lne|lnE|sol|loz|smt|Cup|lrm|cup|lsh|Lsh|sim|shy|map|Map|mcy|Mcy|mfr|Mfr|mho|gfr|Gfr|sfr|cir|Chi|chi|nap|Cfr|vcy|Vcy|cfr|Scy|scy|ncy|Ncy|vee|Vee|Cap|cap|nfr|scE|sce|Nfr|nge|ngE|nGg|vfr|Vfr|ngt|bot|nGt|nis|niv|Rsh|rsh|nle|nlE|bne|Bfr|bfr|nLl|nlt|nLt|Bcy|bcy|not|Not|rlm|wfr|Wfr|npr|nsc|num|ocy|ast|Ocy|ofr|xfr|Xfr|Ofr|ogt|ohm|apE|olt|Rho|ape|rho|Rfr|rfr|ord|REG|ang|reg|orv|And|and|AMP|Rcy|amp|Afr|ycy|Ycy|yen|yfr|Yfr|rcy|par|pcy|Pcy|pfr|Pfr|phi|Phi|afr|Acy|acy|zcy|Zcy|piv|acE|acd|zfr|Zfr|pre|prE|psi|Psi|qfr|Qfr|zwj|Or|ge|Gg|gt|gg|el|oS|lt|Lt|LT|Re|lg|gl|eg|ne|Im|it|le|DD|wp|wr|nu|Nu|dd|lE|Sc|sc|pi|Pi|ee|af|ll|Ll|rx|gE|xi|pm|Xi|ic|pr|Pr|in|ni|mp|mu|ac|Mu|or|ap|Gt|GT|ii);|&(Aacute|Agrave|Atilde|Ccedil|Eacute|Egrave|Iacute|Igrave|Ntilde|Oacute|Ograve|Oslash|Otilde|Uacute|Ugrave|Yacute|aacute|agrave|atilde|brvbar|ccedil|curren|divide|eacute|egrave|frac12|frac14|frac34|iacute|igrave|iquest|middot|ntilde|oacute|ograve|oslash|otilde|plusmn|uacute|ugrave|yacute|AElig|Acirc|Aring|Ecirc|Icirc|Ocirc|THORN|Ucirc|acirc|acute|aelig|aring|cedil|ecirc|icirc|iexcl|laquo|micro|ocirc|pound|raquo|szlig|thorn|times|ucirc|Auml|COPY|Euml|Iuml|Ouml|QUOT|Uuml|auml|cent|copy|euml|iuml|macr|nbsp|ordf|ordm|ouml|para|quot|sect|sup1|sup2|sup3|uuml|yuml|AMP|ETH|REG|amp|deg|eth|not|reg|shy|uml|yen|GT|LT|gt|lt)(?!;)([=a-zA-Z0-9]?)|&#([0-9]+)(;?)|&#[xX]([a-fA-F0-9]+)(;?)|&([0-9a-zA-Z]+)/g;
13804 var decodeMap = {'aacute':'\xE1','Aacute':'\xC1','abreve':'\u0103','Abreve':'\u0102','ac':'\u223E','acd':'\u223F','acE':'\u223E\u0333','acirc':'\xE2','Acirc':'\xC2','acute':'\xB4','acy':'\u0430','Acy':'\u0410','aelig':'\xE6','AElig':'\xC6','af':'\u2061','afr':'\uD835\uDD1E','Afr':'\uD835\uDD04','agrave':'\xE0','Agrave':'\xC0','alefsym':'\u2135','aleph':'\u2135','alpha':'\u03B1','Alpha':'\u0391','amacr':'\u0101','Amacr':'\u0100','amalg':'\u2A3F','amp':'&','AMP':'&','and':'\u2227','And':'\u2A53','andand':'\u2A55','andd':'\u2A5C','andslope':'\u2A58','andv':'\u2A5A','ang':'\u2220','ange':'\u29A4','angle':'\u2220','angmsd':'\u2221','angmsdaa':'\u29A8','angmsdab':'\u29A9','angmsdac':'\u29AA','angmsdad':'\u29AB','angmsdae':'\u29AC','angmsdaf':'\u29AD','angmsdag':'\u29AE','angmsdah':'\u29AF','angrt':'\u221F','angrtvb':'\u22BE','angrtvbd':'\u299D','angsph':'\u2222','angst':'\xC5','angzarr':'\u237C','aogon':'\u0105','Aogon':'\u0104','aopf':'\uD835\uDD52','Aopf':'\uD835\uDD38','ap':'\u2248','apacir':'\u2A6F','ape':'\u224A','apE':'\u2A70','apid':'\u224B','apos':'\'','ApplyFunction':'\u2061','approx':'\u2248','approxeq':'\u224A','aring':'\xE5','Aring':'\xC5','ascr':'\uD835\uDCB6','Ascr':'\uD835\uDC9C','Assign':'\u2254','ast':'*','asymp':'\u2248','asympeq':'\u224D','atilde':'\xE3','Atilde':'\xC3','auml':'\xE4','Auml':'\xC4','awconint':'\u2233','awint':'\u2A11','backcong':'\u224C','backepsilon':'\u03F6','backprime':'\u2035','backsim':'\u223D','backsimeq':'\u22CD','Backslash':'\u2216','Barv':'\u2AE7','barvee':'\u22BD','barwed':'\u2305','Barwed':'\u2306','barwedge':'\u2305','bbrk':'\u23B5','bbrktbrk':'\u23B6','bcong':'\u224C','bcy':'\u0431','Bcy':'\u0411','bdquo':'\u201E','becaus':'\u2235','because':'\u2235','Because':'\u2235','bemptyv':'\u29B0','bepsi':'\u03F6','bernou':'\u212C','Bernoullis':'\u212C','beta':'\u03B2','Beta':'\u0392','beth':'\u2136','between':'\u226C','bfr':'\uD835\uDD1F','Bfr':'\uD835\uDD05','bigcap':'\u22C2','bigcirc':'\u25EF','bigcup':'\u22C3','bigodot':'\u2A00','bigoplus':'\u2A01','bigotimes':'\u2A02','bigsqcup':'\u2A06','bigstar':'\u2605','bigtriangledown':'\u25BD','bigtriangleup':'\u25B3','biguplus':'\u2A04','bigvee':'\u22C1','bigwedge':'\u22C0','bkarow':'\u290D','blacklozenge':'\u29EB','blacksquare':'\u25AA','blacktriangle':'\u25B4','blacktriangledown':'\u25BE','blacktriangleleft':'\u25C2','blacktriangleright':'\u25B8','blank':'\u2423','blk12':'\u2592','blk14':'\u2591','blk34':'\u2593','block':'\u2588','bne':'=\u20E5','bnequiv':'\u2261\u20E5','bnot':'\u2310','bNot':'\u2AED','bopf':'\uD835\uDD53','Bopf':'\uD835\uDD39','bot':'\u22A5','bottom':'\u22A5','bowtie':'\u22C8','boxbox':'\u29C9','boxdl':'\u2510','boxdL':'\u2555','boxDl':'\u2556','boxDL':'\u2557','boxdr':'\u250C','boxdR':'\u2552','boxDr':'\u2553','boxDR':'\u2554','boxh':'\u2500','boxH':'\u2550','boxhd':'\u252C','boxhD':'\u2565','boxHd':'\u2564','boxHD':'\u2566','boxhu':'\u2534','boxhU':'\u2568','boxHu':'\u2567','boxHU':'\u2569','boxminus':'\u229F','boxplus':'\u229E','boxtimes':'\u22A0','boxul':'\u2518','boxuL':'\u255B','boxUl':'\u255C','boxUL':'\u255D','boxur':'\u2514','boxuR':'\u2558','boxUr':'\u2559','boxUR':'\u255A','boxv':'\u2502','boxV':'\u2551','boxvh':'\u253C','boxvH':'\u256A','boxVh':'\u256B','boxVH':'\u256C','boxvl':'\u2524','boxvL':'\u2561','boxVl':'\u2562','boxVL':'\u2563','boxvr':'\u251C','boxvR':'\u255E','boxVr':'\u255F','boxVR':'\u2560','bprime':'\u2035','breve':'\u02D8','Breve':'\u02D8','brvbar':'\xA6','bscr':'\uD835\uDCB7','Bscr':'\u212C','bsemi':'\u204F','bsim':'\u223D','bsime':'\u22CD','bsol':'\\','bsolb':'\u29C5','bsolhsub':'\u27C8','bull':'\u2022','bullet':'\u2022','bump':'\u224E','bumpe':'\u224F','bumpE':'\u2AAE','bumpeq':'\u224F','Bumpeq':'\u224E','cacute':'\u0107','Cacute':'\u0106','cap':'\u2229','Cap':'\u22D2','capand':'\u2A44','capbrcup':'\u2A49','capcap':'\u2A4B','capcup':'\u2A47','capdot':'\u2A40','CapitalDifferentialD':'\u2145','caps':'\u2229\uFE00','caret':'\u2041','caron':'\u02C7','Cayleys':'\u212D','ccaps':'\u2A4D','ccaron':'\u010D','Ccaron':'\u010C','ccedil':'\xE7','Ccedil':'\xC7','ccirc':'\u0109','Ccirc':'\u0108','Cconint':'\u2230','ccups':'\u2A4C','ccupssm':'\u2A50','cdot':'\u010B','Cdot':'\u010A','cedil':'\xB8','Cedilla':'\xB8','cemptyv':'\u29B2','cent':'\xA2','centerdot':'\xB7','CenterDot':'\xB7','cfr':'\uD835\uDD20','Cfr':'\u212D','chcy':'\u0447','CHcy':'\u0427','check':'\u2713','checkmark':'\u2713','chi':'\u03C7','Chi':'\u03A7','cir':'\u25CB','circ':'\u02C6','circeq':'\u2257','circlearrowleft':'\u21BA','circlearrowright':'\u21BB','circledast':'\u229B','circledcirc':'\u229A','circleddash':'\u229D','CircleDot':'\u2299','circledR':'\xAE','circledS':'\u24C8','CircleMinus':'\u2296','CirclePlus':'\u2295','CircleTimes':'\u2297','cire':'\u2257','cirE':'\u29C3','cirfnint':'\u2A10','cirmid':'\u2AEF','cirscir':'\u29C2','ClockwiseContourIntegral':'\u2232','CloseCurlyDoubleQuote':'\u201D','CloseCurlyQuote':'\u2019','clubs':'\u2663','clubsuit':'\u2663','colon':':','Colon':'\u2237','colone':'\u2254','Colone':'\u2A74','coloneq':'\u2254','comma':',','commat':'@','comp':'\u2201','compfn':'\u2218','complement':'\u2201','complexes':'\u2102','cong':'\u2245','congdot':'\u2A6D','Congruent':'\u2261','conint':'\u222E','Conint':'\u222F','ContourIntegral':'\u222E','copf':'\uD835\uDD54','Copf':'\u2102','coprod':'\u2210','Coproduct':'\u2210','copy':'\xA9','COPY':'\xA9','copysr':'\u2117','CounterClockwiseContourIntegral':'\u2233','crarr':'\u21B5','cross':'\u2717','Cross':'\u2A2F','cscr':'\uD835\uDCB8','Cscr':'\uD835\uDC9E','csub':'\u2ACF','csube':'\u2AD1','csup':'\u2AD0','csupe':'\u2AD2','ctdot':'\u22EF','cudarrl':'\u2938','cudarrr':'\u2935','cuepr':'\u22DE','cuesc':'\u22DF','cularr':'\u21B6','cularrp':'\u293D','cup':'\u222A','Cup':'\u22D3','cupbrcap':'\u2A48','cupcap':'\u2A46','CupCap':'\u224D','cupcup':'\u2A4A','cupdot':'\u228D','cupor':'\u2A45','cups':'\u222A\uFE00','curarr':'\u21B7','curarrm':'\u293C','curlyeqprec':'\u22DE','curlyeqsucc':'\u22DF','curlyvee':'\u22CE','curlywedge':'\u22CF','curren':'\xA4','curvearrowleft':'\u21B6','curvearrowright':'\u21B7','cuvee':'\u22CE','cuwed':'\u22CF','cwconint':'\u2232','cwint':'\u2231','cylcty':'\u232D','dagger':'\u2020','Dagger':'\u2021','daleth':'\u2138','darr':'\u2193','dArr':'\u21D3','Darr':'\u21A1','dash':'\u2010','dashv':'\u22A3','Dashv':'\u2AE4','dbkarow':'\u290F','dblac':'\u02DD','dcaron':'\u010F','Dcaron':'\u010E','dcy':'\u0434','Dcy':'\u0414','dd':'\u2146','DD':'\u2145','ddagger':'\u2021','ddarr':'\u21CA','DDotrahd':'\u2911','ddotseq':'\u2A77','deg':'\xB0','Del':'\u2207','delta':'\u03B4','Delta':'\u0394','demptyv':'\u29B1','dfisht':'\u297F','dfr':'\uD835\uDD21','Dfr':'\uD835\uDD07','dHar':'\u2965','dharl':'\u21C3','dharr':'\u21C2','DiacriticalAcute':'\xB4','DiacriticalDot':'\u02D9','DiacriticalDoubleAcute':'\u02DD','DiacriticalGrave':'`','DiacriticalTilde':'\u02DC','diam':'\u22C4','diamond':'\u22C4','Diamond':'\u22C4','diamondsuit':'\u2666','diams':'\u2666','die':'\xA8','DifferentialD':'\u2146','digamma':'\u03DD','disin':'\u22F2','div':'\xF7','divide':'\xF7','divideontimes':'\u22C7','divonx':'\u22C7','djcy':'\u0452','DJcy':'\u0402','dlcorn':'\u231E','dlcrop':'\u230D','dollar':'$','dopf':'\uD835\uDD55','Dopf':'\uD835\uDD3B','dot':'\u02D9','Dot':'\xA8','DotDot':'\u20DC','doteq':'\u2250','doteqdot':'\u2251','DotEqual':'\u2250','dotminus':'\u2238','dotplus':'\u2214','dotsquare':'\u22A1','doublebarwedge':'\u2306','DoubleContourIntegral':'\u222F','DoubleDot':'\xA8','DoubleDownArrow':'\u21D3','DoubleLeftArrow':'\u21D0','DoubleLeftRightArrow':'\u21D4','DoubleLeftTee':'\u2AE4','DoubleLongLeftArrow':'\u27F8','DoubleLongLeftRightArrow':'\u27FA','DoubleLongRightArrow':'\u27F9','DoubleRightArrow':'\u21D2','DoubleRightTee':'\u22A8','DoubleUpArrow':'\u21D1','DoubleUpDownArrow':'\u21D5','DoubleVerticalBar':'\u2225','downarrow':'\u2193','Downarrow':'\u21D3','DownArrow':'\u2193','DownArrowBar':'\u2913','DownArrowUpArrow':'\u21F5','DownBreve':'\u0311','downdownarrows':'\u21CA','downharpoonleft':'\u21C3','downharpoonright':'\u21C2','DownLeftRightVector':'\u2950','DownLeftTeeVector':'\u295E','DownLeftVector':'\u21BD','DownLeftVectorBar':'\u2956','DownRightTeeVector':'\u295F','DownRightVector':'\u21C1','DownRightVectorBar':'\u2957','DownTee':'\u22A4','DownTeeArrow':'\u21A7','drbkarow':'\u2910','drcorn':'\u231F','drcrop':'\u230C','dscr':'\uD835\uDCB9','Dscr':'\uD835\uDC9F','dscy':'\u0455','DScy':'\u0405','dsol':'\u29F6','dstrok':'\u0111','Dstrok':'\u0110','dtdot':'\u22F1','dtri':'\u25BF','dtrif':'\u25BE','duarr':'\u21F5','duhar':'\u296F','dwangle':'\u29A6','dzcy':'\u045F','DZcy':'\u040F','dzigrarr':'\u27FF','eacute':'\xE9','Eacute':'\xC9','easter':'\u2A6E','ecaron':'\u011B','Ecaron':'\u011A','ecir':'\u2256','ecirc':'\xEA','Ecirc':'\xCA','ecolon':'\u2255','ecy':'\u044D','Ecy':'\u042D','eDDot':'\u2A77','edot':'\u0117','eDot':'\u2251','Edot':'\u0116','ee':'\u2147','efDot':'\u2252','efr':'\uD835\uDD22','Efr':'\uD835\uDD08','eg':'\u2A9A','egrave':'\xE8','Egrave':'\xC8','egs':'\u2A96','egsdot':'\u2A98','el':'\u2A99','Element':'\u2208','elinters':'\u23E7','ell':'\u2113','els':'\u2A95','elsdot':'\u2A97','emacr':'\u0113','Emacr':'\u0112','empty':'\u2205','emptyset':'\u2205','EmptySmallSquare':'\u25FB','emptyv':'\u2205','EmptyVerySmallSquare':'\u25AB','emsp':'\u2003','emsp13':'\u2004','emsp14':'\u2005','eng':'\u014B','ENG':'\u014A','ensp':'\u2002','eogon':'\u0119','Eogon':'\u0118','eopf':'\uD835\uDD56','Eopf':'\uD835\uDD3C','epar':'\u22D5','eparsl':'\u29E3','eplus':'\u2A71','epsi':'\u03B5','epsilon':'\u03B5','Epsilon':'\u0395','epsiv':'\u03F5','eqcirc':'\u2256','eqcolon':'\u2255','eqsim':'\u2242','eqslantgtr':'\u2A96','eqslantless':'\u2A95','Equal':'\u2A75','equals':'=','EqualTilde':'\u2242','equest':'\u225F','Equilibrium':'\u21CC','equiv':'\u2261','equivDD':'\u2A78','eqvparsl':'\u29E5','erarr':'\u2971','erDot':'\u2253','escr':'\u212F','Escr':'\u2130','esdot':'\u2250','esim':'\u2242','Esim':'\u2A73','eta':'\u03B7','Eta':'\u0397','eth':'\xF0','ETH':'\xD0','euml':'\xEB','Euml':'\xCB','euro':'\u20AC','excl':'!','exist':'\u2203','Exists':'\u2203','expectation':'\u2130','exponentiale':'\u2147','ExponentialE':'\u2147','fallingdotseq':'\u2252','fcy':'\u0444','Fcy':'\u0424','female':'\u2640','ffilig':'\uFB03','fflig':'\uFB00','ffllig':'\uFB04','ffr':'\uD835\uDD23','Ffr':'\uD835\uDD09','filig':'\uFB01','FilledSmallSquare':'\u25FC','FilledVerySmallSquare':'\u25AA','fjlig':'fj','flat':'\u266D','fllig':'\uFB02','fltns':'\u25B1','fnof':'\u0192','fopf':'\uD835\uDD57','Fopf':'\uD835\uDD3D','forall':'\u2200','ForAll':'\u2200','fork':'\u22D4','forkv':'\u2AD9','Fouriertrf':'\u2131','fpartint':'\u2A0D','frac12':'\xBD','frac13':'\u2153','frac14':'\xBC','frac15':'\u2155','frac16':'\u2159','frac18':'\u215B','frac23':'\u2154','frac25':'\u2156','frac34':'\xBE','frac35':'\u2157','frac38':'\u215C','frac45':'\u2158','frac56':'\u215A','frac58':'\u215D','frac78':'\u215E','frasl':'\u2044','frown':'\u2322','fscr':'\uD835\uDCBB','Fscr':'\u2131','gacute':'\u01F5','gamma':'\u03B3','Gamma':'\u0393','gammad':'\u03DD','Gammad':'\u03DC','gap':'\u2A86','gbreve':'\u011F','Gbreve':'\u011E','Gcedil':'\u0122','gcirc':'\u011D','Gcirc':'\u011C','gcy':'\u0433','Gcy':'\u0413','gdot':'\u0121','Gdot':'\u0120','ge':'\u2265','gE':'\u2267','gel':'\u22DB','gEl':'\u2A8C','geq':'\u2265','geqq':'\u2267','geqslant':'\u2A7E','ges':'\u2A7E','gescc':'\u2AA9','gesdot':'\u2A80','gesdoto':'\u2A82','gesdotol':'\u2A84','gesl':'\u22DB\uFE00','gesles':'\u2A94','gfr':'\uD835\uDD24','Gfr':'\uD835\uDD0A','gg':'\u226B','Gg':'\u22D9','ggg':'\u22D9','gimel':'\u2137','gjcy':'\u0453','GJcy':'\u0403','gl':'\u2277','gla':'\u2AA5','glE':'\u2A92','glj':'\u2AA4','gnap':'\u2A8A','gnapprox':'\u2A8A','gne':'\u2A88','gnE':'\u2269','gneq':'\u2A88','gneqq':'\u2269','gnsim':'\u22E7','gopf':'\uD835\uDD58','Gopf':'\uD835\uDD3E','grave':'`','GreaterEqual':'\u2265','GreaterEqualLess':'\u22DB','GreaterFullEqual':'\u2267','GreaterGreater':'\u2AA2','GreaterLess':'\u2277','GreaterSlantEqual':'\u2A7E','GreaterTilde':'\u2273','gscr':'\u210A','Gscr':'\uD835\uDCA2','gsim':'\u2273','gsime':'\u2A8E','gsiml':'\u2A90','gt':'>','Gt':'\u226B','GT':'>','gtcc':'\u2AA7','gtcir':'\u2A7A','gtdot':'\u22D7','gtlPar':'\u2995','gtquest':'\u2A7C','gtrapprox':'\u2A86','gtrarr':'\u2978','gtrdot':'\u22D7','gtreqless':'\u22DB','gtreqqless':'\u2A8C','gtrless':'\u2277','gtrsim':'\u2273','gvertneqq':'\u2269\uFE00','gvnE':'\u2269\uFE00','Hacek':'\u02C7','hairsp':'\u200A','half':'\xBD','hamilt':'\u210B','hardcy':'\u044A','HARDcy':'\u042A','harr':'\u2194','hArr':'\u21D4','harrcir':'\u2948','harrw':'\u21AD','Hat':'^','hbar':'\u210F','hcirc':'\u0125','Hcirc':'\u0124','hearts':'\u2665','heartsuit':'\u2665','hellip':'\u2026','hercon':'\u22B9','hfr':'\uD835\uDD25','Hfr':'\u210C','HilbertSpace':'\u210B','hksearow':'\u2925','hkswarow':'\u2926','hoarr':'\u21FF','homtht':'\u223B','hookleftarrow':'\u21A9','hookrightarrow':'\u21AA','hopf':'\uD835\uDD59','Hopf':'\u210D','horbar':'\u2015','HorizontalLine':'\u2500','hscr':'\uD835\uDCBD','Hscr':'\u210B','hslash':'\u210F','hstrok':'\u0127','Hstrok':'\u0126','HumpDownHump':'\u224E','HumpEqual':'\u224F','hybull':'\u2043','hyphen':'\u2010','iacute':'\xED','Iacute':'\xCD','ic':'\u2063','icirc':'\xEE','Icirc':'\xCE','icy':'\u0438','Icy':'\u0418','Idot':'\u0130','iecy':'\u0435','IEcy':'\u0415','iexcl':'\xA1','iff':'\u21D4','ifr':'\uD835\uDD26','Ifr':'\u2111','igrave':'\xEC','Igrave':'\xCC','ii':'\u2148','iiiint':'\u2A0C','iiint':'\u222D','iinfin':'\u29DC','iiota':'\u2129','ijlig':'\u0133','IJlig':'\u0132','Im':'\u2111','imacr':'\u012B','Imacr':'\u012A','image':'\u2111','ImaginaryI':'\u2148','imagline':'\u2110','imagpart':'\u2111','imath':'\u0131','imof':'\u22B7','imped':'\u01B5','Implies':'\u21D2','in':'\u2208','incare':'\u2105','infin':'\u221E','infintie':'\u29DD','inodot':'\u0131','int':'\u222B','Int':'\u222C','intcal':'\u22BA','integers':'\u2124','Integral':'\u222B','intercal':'\u22BA','Intersection':'\u22C2','intlarhk':'\u2A17','intprod':'\u2A3C','InvisibleComma':'\u2063','InvisibleTimes':'\u2062','iocy':'\u0451','IOcy':'\u0401','iogon':'\u012F','Iogon':'\u012E','iopf':'\uD835\uDD5A','Iopf':'\uD835\uDD40','iota':'\u03B9','Iota':'\u0399','iprod':'\u2A3C','iquest':'\xBF','iscr':'\uD835\uDCBE','Iscr':'\u2110','isin':'\u2208','isindot':'\u22F5','isinE':'\u22F9','isins':'\u22F4','isinsv':'\u22F3','isinv':'\u2208','it':'\u2062','itilde':'\u0129','Itilde':'\u0128','iukcy':'\u0456','Iukcy':'\u0406','iuml':'\xEF','Iuml':'\xCF','jcirc':'\u0135','Jcirc':'\u0134','jcy':'\u0439','Jcy':'\u0419','jfr':'\uD835\uDD27','Jfr':'\uD835\uDD0D','jmath':'\u0237','jopf':'\uD835\uDD5B','Jopf':'\uD835\uDD41','jscr':'\uD835\uDCBF','Jscr':'\uD835\uDCA5','jsercy':'\u0458','Jsercy':'\u0408','jukcy':'\u0454','Jukcy':'\u0404','kappa':'\u03BA','Kappa':'\u039A','kappav':'\u03F0','kcedil':'\u0137','Kcedil':'\u0136','kcy':'\u043A','Kcy':'\u041A','kfr':'\uD835\uDD28','Kfr':'\uD835\uDD0E','kgreen':'\u0138','khcy':'\u0445','KHcy':'\u0425','kjcy':'\u045C','KJcy':'\u040C','kopf':'\uD835\uDD5C','Kopf':'\uD835\uDD42','kscr':'\uD835\uDCC0','Kscr':'\uD835\uDCA6','lAarr':'\u21DA','lacute':'\u013A','Lacute':'\u0139','laemptyv':'\u29B4','lagran':'\u2112','lambda':'\u03BB','Lambda':'\u039B','lang':'\u27E8','Lang':'\u27EA','langd':'\u2991','langle':'\u27E8','lap':'\u2A85','Laplacetrf':'\u2112','laquo':'\xAB','larr':'\u2190','lArr':'\u21D0','Larr':'\u219E','larrb':'\u21E4','larrbfs':'\u291F','larrfs':'\u291D','larrhk':'\u21A9','larrlp':'\u21AB','larrpl':'\u2939','larrsim':'\u2973','larrtl':'\u21A2','lat':'\u2AAB','latail':'\u2919','lAtail':'\u291B','late':'\u2AAD','lates':'\u2AAD\uFE00','lbarr':'\u290C','lBarr':'\u290E','lbbrk':'\u2772','lbrace':'{','lbrack':'[','lbrke':'\u298B','lbrksld':'\u298F','lbrkslu':'\u298D','lcaron':'\u013E','Lcaron':'\u013D','lcedil':'\u013C','Lcedil':'\u013B','lceil':'\u2308','lcub':'{','lcy':'\u043B','Lcy':'\u041B','ldca':'\u2936','ldquo':'\u201C','ldquor':'\u201E','ldrdhar':'\u2967','ldrushar':'\u294B','ldsh':'\u21B2','le':'\u2264','lE':'\u2266','LeftAngleBracket':'\u27E8','leftarrow':'\u2190','Leftarrow':'\u21D0','LeftArrow':'\u2190','LeftArrowBar':'\u21E4','LeftArrowRightArrow':'\u21C6','leftarrowtail':'\u21A2','LeftCeiling':'\u2308','LeftDoubleBracket':'\u27E6','LeftDownTeeVector':'\u2961','LeftDownVector':'\u21C3','LeftDownVectorBar':'\u2959','LeftFloor':'\u230A','leftharpoondown':'\u21BD','leftharpoonup':'\u21BC','leftleftarrows':'\u21C7','leftrightarrow':'\u2194','Leftrightarrow':'\u21D4','LeftRightArrow':'\u2194','leftrightarrows':'\u21C6','leftrightharpoons':'\u21CB','leftrightsquigarrow':'\u21AD','LeftRightVector':'\u294E','LeftTee':'\u22A3','LeftTeeArrow':'\u21A4','LeftTeeVector':'\u295A','leftthreetimes':'\u22CB','LeftTriangle':'\u22B2','LeftTriangleBar':'\u29CF','LeftTriangleEqual':'\u22B4','LeftUpDownVector':'\u2951','LeftUpTeeVector':'\u2960','LeftUpVector':'\u21BF','LeftUpVectorBar':'\u2958','LeftVector':'\u21BC','LeftVectorBar':'\u2952','leg':'\u22DA','lEg':'\u2A8B','leq':'\u2264','leqq':'\u2266','leqslant':'\u2A7D','les':'\u2A7D','lescc':'\u2AA8','lesdot':'\u2A7F','lesdoto':'\u2A81','lesdotor':'\u2A83','lesg':'\u22DA\uFE00','lesges':'\u2A93','lessapprox':'\u2A85','lessdot':'\u22D6','lesseqgtr':'\u22DA','lesseqqgtr':'\u2A8B','LessEqualGreater':'\u22DA','LessFullEqual':'\u2266','LessGreater':'\u2276','lessgtr':'\u2276','LessLess':'\u2AA1','lesssim':'\u2272','LessSlantEqual':'\u2A7D','LessTilde':'\u2272','lfisht':'\u297C','lfloor':'\u230A','lfr':'\uD835\uDD29','Lfr':'\uD835\uDD0F','lg':'\u2276','lgE':'\u2A91','lHar':'\u2962','lhard':'\u21BD','lharu':'\u21BC','lharul':'\u296A','lhblk':'\u2584','ljcy':'\u0459','LJcy':'\u0409','ll':'\u226A','Ll':'\u22D8','llarr':'\u21C7','llcorner':'\u231E','Lleftarrow':'\u21DA','llhard':'\u296B','lltri':'\u25FA','lmidot':'\u0140','Lmidot':'\u013F','lmoust':'\u23B0','lmoustache':'\u23B0','lnap':'\u2A89','lnapprox':'\u2A89','lne':'\u2A87','lnE':'\u2268','lneq':'\u2A87','lneqq':'\u2268','lnsim':'\u22E6','loang':'\u27EC','loarr':'\u21FD','lobrk':'\u27E6','longleftarrow':'\u27F5','Longleftarrow':'\u27F8','LongLeftArrow':'\u27F5','longleftrightarrow':'\u27F7','Longleftrightarrow':'\u27FA','LongLeftRightArrow':'\u27F7','longmapsto':'\u27FC','longrightarrow':'\u27F6','Longrightarrow':'\u27F9','LongRightArrow':'\u27F6','looparrowleft':'\u21AB','looparrowright':'\u21AC','lopar':'\u2985','lopf':'\uD835\uDD5D','Lopf':'\uD835\uDD43','loplus':'\u2A2D','lotimes':'\u2A34','lowast':'\u2217','lowbar':'_','LowerLeftArrow':'\u2199','LowerRightArrow':'\u2198','loz':'\u25CA','lozenge':'\u25CA','lozf':'\u29EB','lpar':'(','lparlt':'\u2993','lrarr':'\u21C6','lrcorner':'\u231F','lrhar':'\u21CB','lrhard':'\u296D','lrm':'\u200E','lrtri':'\u22BF','lsaquo':'\u2039','lscr':'\uD835\uDCC1','Lscr':'\u2112','lsh':'\u21B0','Lsh':'\u21B0','lsim':'\u2272','lsime':'\u2A8D','lsimg':'\u2A8F','lsqb':'[','lsquo':'\u2018','lsquor':'\u201A','lstrok':'\u0142','Lstrok':'\u0141','lt':'<','Lt':'\u226A','LT':'<','ltcc':'\u2AA6','ltcir':'\u2A79','ltdot':'\u22D6','lthree':'\u22CB','ltimes':'\u22C9','ltlarr':'\u2976','ltquest':'\u2A7B','ltri':'\u25C3','ltrie':'\u22B4','ltrif':'\u25C2','ltrPar':'\u2996','lurdshar':'\u294A','luruhar':'\u2966','lvertneqq':'\u2268\uFE00','lvnE':'\u2268\uFE00','macr':'\xAF','male':'\u2642','malt':'\u2720','maltese':'\u2720','map':'\u21A6','Map':'\u2905','mapsto':'\u21A6','mapstodown':'\u21A7','mapstoleft':'\u21A4','mapstoup':'\u21A5','marker':'\u25AE','mcomma':'\u2A29','mcy':'\u043C','Mcy':'\u041C','mdash':'\u2014','mDDot':'\u223A','measuredangle':'\u2221','MediumSpace':'\u205F','Mellintrf':'\u2133','mfr':'\uD835\uDD2A','Mfr':'\uD835\uDD10','mho':'\u2127','micro':'\xB5','mid':'\u2223','midast':'*','midcir':'\u2AF0','middot':'\xB7','minus':'\u2212','minusb':'\u229F','minusd':'\u2238','minusdu':'\u2A2A','MinusPlus':'\u2213','mlcp':'\u2ADB','mldr':'\u2026','mnplus':'\u2213','models':'\u22A7','mopf':'\uD835\uDD5E','Mopf':'\uD835\uDD44','mp':'\u2213','mscr':'\uD835\uDCC2','Mscr':'\u2133','mstpos':'\u223E','mu':'\u03BC','Mu':'\u039C','multimap':'\u22B8','mumap':'\u22B8','nabla':'\u2207','nacute':'\u0144','Nacute':'\u0143','nang':'\u2220\u20D2','nap':'\u2249','napE':'\u2A70\u0338','napid':'\u224B\u0338','napos':'\u0149','napprox':'\u2249','natur':'\u266E','natural':'\u266E','naturals':'\u2115','nbsp':'\xA0','nbump':'\u224E\u0338','nbumpe':'\u224F\u0338','ncap':'\u2A43','ncaron':'\u0148','Ncaron':'\u0147','ncedil':'\u0146','Ncedil':'\u0145','ncong':'\u2247','ncongdot':'\u2A6D\u0338','ncup':'\u2A42','ncy':'\u043D','Ncy':'\u041D','ndash':'\u2013','ne':'\u2260','nearhk':'\u2924','nearr':'\u2197','neArr':'\u21D7','nearrow':'\u2197','nedot':'\u2250\u0338','NegativeMediumSpace':'\u200B','NegativeThickSpace':'\u200B','NegativeThinSpace':'\u200B','NegativeVeryThinSpace':'\u200B','nequiv':'\u2262','nesear':'\u2928','nesim':'\u2242\u0338','NestedGreaterGreater':'\u226B','NestedLessLess':'\u226A','NewLine':'\n','nexist':'\u2204','nexists':'\u2204','nfr':'\uD835\uDD2B','Nfr':'\uD835\uDD11','nge':'\u2271','ngE':'\u2267\u0338','ngeq':'\u2271','ngeqq':'\u2267\u0338','ngeqslant':'\u2A7E\u0338','nges':'\u2A7E\u0338','nGg':'\u22D9\u0338','ngsim':'\u2275','ngt':'\u226F','nGt':'\u226B\u20D2','ngtr':'\u226F','nGtv':'\u226B\u0338','nharr':'\u21AE','nhArr':'\u21CE','nhpar':'\u2AF2','ni':'\u220B','nis':'\u22FC','nisd':'\u22FA','niv':'\u220B','njcy':'\u045A','NJcy':'\u040A','nlarr':'\u219A','nlArr':'\u21CD','nldr':'\u2025','nle':'\u2270','nlE':'\u2266\u0338','nleftarrow':'\u219A','nLeftarrow':'\u21CD','nleftrightarrow':'\u21AE','nLeftrightarrow':'\u21CE','nleq':'\u2270','nleqq':'\u2266\u0338','nleqslant':'\u2A7D\u0338','nles':'\u2A7D\u0338','nless':'\u226E','nLl':'\u22D8\u0338','nlsim':'\u2274','nlt':'\u226E','nLt':'\u226A\u20D2','nltri':'\u22EA','nltrie':'\u22EC','nLtv':'\u226A\u0338','nmid':'\u2224','NoBreak':'\u2060','NonBreakingSpace':'\xA0','nopf':'\uD835\uDD5F','Nopf':'\u2115','not':'\xAC','Not':'\u2AEC','NotCongruent':'\u2262','NotCupCap':'\u226D','NotDoubleVerticalBar':'\u2226','NotElement':'\u2209','NotEqual':'\u2260','NotEqualTilde':'\u2242\u0338','NotExists':'\u2204','NotGreater':'\u226F','NotGreaterEqual':'\u2271','NotGreaterFullEqual':'\u2267\u0338','NotGreaterGreater':'\u226B\u0338','NotGreaterLess':'\u2279','NotGreaterSlantEqual':'\u2A7E\u0338','NotGreaterTilde':'\u2275','NotHumpDownHump':'\u224E\u0338','NotHumpEqual':'\u224F\u0338','notin':'\u2209','notindot':'\u22F5\u0338','notinE':'\u22F9\u0338','notinva':'\u2209','notinvb':'\u22F7','notinvc':'\u22F6','NotLeftTriangle':'\u22EA','NotLeftTriangleBar':'\u29CF\u0338','NotLeftTriangleEqual':'\u22EC','NotLess':'\u226E','NotLessEqual':'\u2270','NotLessGreater':'\u2278','NotLessLess':'\u226A\u0338','NotLessSlantEqual':'\u2A7D\u0338','NotLessTilde':'\u2274','NotNestedGreaterGreater':'\u2AA2\u0338','NotNestedLessLess':'\u2AA1\u0338','notni':'\u220C','notniva':'\u220C','notnivb':'\u22FE','notnivc':'\u22FD','NotPrecedes':'\u2280','NotPrecedesEqual':'\u2AAF\u0338','NotPrecedesSlantEqual':'\u22E0','NotReverseElement':'\u220C','NotRightTriangle':'\u22EB','NotRightTriangleBar':'\u29D0\u0338','NotRightTriangleEqual':'\u22ED','NotSquareSubset':'\u228F\u0338','NotSquareSubsetEqual':'\u22E2','NotSquareSuperset':'\u2290\u0338','NotSquareSupersetEqual':'\u22E3','NotSubset':'\u2282\u20D2','NotSubsetEqual':'\u2288','NotSucceeds':'\u2281','NotSucceedsEqual':'\u2AB0\u0338','NotSucceedsSlantEqual':'\u22E1','NotSucceedsTilde':'\u227F\u0338','NotSuperset':'\u2283\u20D2','NotSupersetEqual':'\u2289','NotTilde':'\u2241','NotTildeEqual':'\u2244','NotTildeFullEqual':'\u2247','NotTildeTilde':'\u2249','NotVerticalBar':'\u2224','npar':'\u2226','nparallel':'\u2226','nparsl':'\u2AFD\u20E5','npart':'\u2202\u0338','npolint':'\u2A14','npr':'\u2280','nprcue':'\u22E0','npre':'\u2AAF\u0338','nprec':'\u2280','npreceq':'\u2AAF\u0338','nrarr':'\u219B','nrArr':'\u21CF','nrarrc':'\u2933\u0338','nrarrw':'\u219D\u0338','nrightarrow':'\u219B','nRightarrow':'\u21CF','nrtri':'\u22EB','nrtrie':'\u22ED','nsc':'\u2281','nsccue':'\u22E1','nsce':'\u2AB0\u0338','nscr':'\uD835\uDCC3','Nscr':'\uD835\uDCA9','nshortmid':'\u2224','nshortparallel':'\u2226','nsim':'\u2241','nsime':'\u2244','nsimeq':'\u2244','nsmid':'\u2224','nspar':'\u2226','nsqsube':'\u22E2','nsqsupe':'\u22E3','nsub':'\u2284','nsube':'\u2288','nsubE':'\u2AC5\u0338','nsubset':'\u2282\u20D2','nsubseteq':'\u2288','nsubseteqq':'\u2AC5\u0338','nsucc':'\u2281','nsucceq':'\u2AB0\u0338','nsup':'\u2285','nsupe':'\u2289','nsupE':'\u2AC6\u0338','nsupset':'\u2283\u20D2','nsupseteq':'\u2289','nsupseteqq':'\u2AC6\u0338','ntgl':'\u2279','ntilde':'\xF1','Ntilde':'\xD1','ntlg':'\u2278','ntriangleleft':'\u22EA','ntrianglelefteq':'\u22EC','ntriangleright':'\u22EB','ntrianglerighteq':'\u22ED','nu':'\u03BD','Nu':'\u039D','num':'#','numero':'\u2116','numsp':'\u2007','nvap':'\u224D\u20D2','nvdash':'\u22AC','nvDash':'\u22AD','nVdash':'\u22AE','nVDash':'\u22AF','nvge':'\u2265\u20D2','nvgt':'>\u20D2','nvHarr':'\u2904','nvinfin':'\u29DE','nvlArr':'\u2902','nvle':'\u2264\u20D2','nvlt':'<\u20D2','nvltrie':'\u22B4\u20D2','nvrArr':'\u2903','nvrtrie':'\u22B5\u20D2','nvsim':'\u223C\u20D2','nwarhk':'\u2923','nwarr':'\u2196','nwArr':'\u21D6','nwarrow':'\u2196','nwnear':'\u2927','oacute':'\xF3','Oacute':'\xD3','oast':'\u229B','ocir':'\u229A','ocirc':'\xF4','Ocirc':'\xD4','ocy':'\u043E','Ocy':'\u041E','odash':'\u229D','odblac':'\u0151','Odblac':'\u0150','odiv':'\u2A38','odot':'\u2299','odsold':'\u29BC','oelig':'\u0153','OElig':'\u0152','ofcir':'\u29BF','ofr':'\uD835\uDD2C','Ofr':'\uD835\uDD12','ogon':'\u02DB','ograve':'\xF2','Ograve':'\xD2','ogt':'\u29C1','ohbar':'\u29B5','ohm':'\u03A9','oint':'\u222E','olarr':'\u21BA','olcir':'\u29BE','olcross':'\u29BB','oline':'\u203E','olt':'\u29C0','omacr':'\u014D','Omacr':'\u014C','omega':'\u03C9','Omega':'\u03A9','omicron':'\u03BF','Omicron':'\u039F','omid':'\u29B6','ominus':'\u2296','oopf':'\uD835\uDD60','Oopf':'\uD835\uDD46','opar':'\u29B7','OpenCurlyDoubleQuote':'\u201C','OpenCurlyQuote':'\u2018','operp':'\u29B9','oplus':'\u2295','or':'\u2228','Or':'\u2A54','orarr':'\u21BB','ord':'\u2A5D','order':'\u2134','orderof':'\u2134','ordf':'\xAA','ordm':'\xBA','origof':'\u22B6','oror':'\u2A56','orslope':'\u2A57','orv':'\u2A5B','oS':'\u24C8','oscr':'\u2134','Oscr':'\uD835\uDCAA','oslash':'\xF8','Oslash':'\xD8','osol':'\u2298','otilde':'\xF5','Otilde':'\xD5','otimes':'\u2297','Otimes':'\u2A37','otimesas':'\u2A36','ouml':'\xF6','Ouml':'\xD6','ovbar':'\u233D','OverBar':'\u203E','OverBrace':'\u23DE','OverBracket':'\u23B4','OverParenthesis':'\u23DC','par':'\u2225','para':'\xB6','parallel':'\u2225','parsim':'\u2AF3','parsl':'\u2AFD','part':'\u2202','PartialD':'\u2202','pcy':'\u043F','Pcy':'\u041F','percnt':'%','period':'.','permil':'\u2030','perp':'\u22A5','pertenk':'\u2031','pfr':'\uD835\uDD2D','Pfr':'\uD835\uDD13','phi':'\u03C6','Phi':'\u03A6','phiv':'\u03D5','phmmat':'\u2133','phone':'\u260E','pi':'\u03C0','Pi':'\u03A0','pitchfork':'\u22D4','piv':'\u03D6','planck':'\u210F','planckh':'\u210E','plankv':'\u210F','plus':'+','plusacir':'\u2A23','plusb':'\u229E','pluscir':'\u2A22','plusdo':'\u2214','plusdu':'\u2A25','pluse':'\u2A72','PlusMinus':'\xB1','plusmn':'\xB1','plussim':'\u2A26','plustwo':'\u2A27','pm':'\xB1','Poincareplane':'\u210C','pointint':'\u2A15','popf':'\uD835\uDD61','Popf':'\u2119','pound':'\xA3','pr':'\u227A','Pr':'\u2ABB','prap':'\u2AB7','prcue':'\u227C','pre':'\u2AAF','prE':'\u2AB3','prec':'\u227A','precapprox':'\u2AB7','preccurlyeq':'\u227C','Precedes':'\u227A','PrecedesEqual':'\u2AAF','PrecedesSlantEqual':'\u227C','PrecedesTilde':'\u227E','preceq':'\u2AAF','precnapprox':'\u2AB9','precneqq':'\u2AB5','precnsim':'\u22E8','precsim':'\u227E','prime':'\u2032','Prime':'\u2033','primes':'\u2119','prnap':'\u2AB9','prnE':'\u2AB5','prnsim':'\u22E8','prod':'\u220F','Product':'\u220F','profalar':'\u232E','profline':'\u2312','profsurf':'\u2313','prop':'\u221D','Proportion':'\u2237','Proportional':'\u221D','propto':'\u221D','prsim':'\u227E','prurel':'\u22B0','pscr':'\uD835\uDCC5','Pscr':'\uD835\uDCAB','psi':'\u03C8','Psi':'\u03A8','puncsp':'\u2008','qfr':'\uD835\uDD2E','Qfr':'\uD835\uDD14','qint':'\u2A0C','qopf':'\uD835\uDD62','Qopf':'\u211A','qprime':'\u2057','qscr':'\uD835\uDCC6','Qscr':'\uD835\uDCAC','quaternions':'\u210D','quatint':'\u2A16','quest':'?','questeq':'\u225F','quot':'"','QUOT':'"','rAarr':'\u21DB','race':'\u223D\u0331','racute':'\u0155','Racute':'\u0154','radic':'\u221A','raemptyv':'\u29B3','rang':'\u27E9','Rang':'\u27EB','rangd':'\u2992','range':'\u29A5','rangle':'\u27E9','raquo':'\xBB','rarr':'\u2192','rArr':'\u21D2','Rarr':'\u21A0','rarrap':'\u2975','rarrb':'\u21E5','rarrbfs':'\u2920','rarrc':'\u2933','rarrfs':'\u291E','rarrhk':'\u21AA','rarrlp':'\u21AC','rarrpl':'\u2945','rarrsim':'\u2974','rarrtl':'\u21A3','Rarrtl':'\u2916','rarrw':'\u219D','ratail':'\u291A','rAtail':'\u291C','ratio':'\u2236','rationals':'\u211A','rbarr':'\u290D','rBarr':'\u290F','RBarr':'\u2910','rbbrk':'\u2773','rbrace':'}','rbrack':']','rbrke':'\u298C','rbrksld':'\u298E','rbrkslu':'\u2990','rcaron':'\u0159','Rcaron':'\u0158','rcedil':'\u0157','Rcedil':'\u0156','rceil':'\u2309','rcub':'}','rcy':'\u0440','Rcy':'\u0420','rdca':'\u2937','rdldhar':'\u2969','rdquo':'\u201D','rdquor':'\u201D','rdsh':'\u21B3','Re':'\u211C','real':'\u211C','realine':'\u211B','realpart':'\u211C','reals':'\u211D','rect':'\u25AD','reg':'\xAE','REG':'\xAE','ReverseElement':'\u220B','ReverseEquilibrium':'\u21CB','ReverseUpEquilibrium':'\u296F','rfisht':'\u297D','rfloor':'\u230B','rfr':'\uD835\uDD2F','Rfr':'\u211C','rHar':'\u2964','rhard':'\u21C1','rharu':'\u21C0','rharul':'\u296C','rho':'\u03C1','Rho':'\u03A1','rhov':'\u03F1','RightAngleBracket':'\u27E9','rightarrow':'\u2192','Rightarrow':'\u21D2','RightArrow':'\u2192','RightArrowBar':'\u21E5','RightArrowLeftArrow':'\u21C4','rightarrowtail':'\u21A3','RightCeiling':'\u2309','RightDoubleBracket':'\u27E7','RightDownTeeVector':'\u295D','RightDownVector':'\u21C2','RightDownVectorBar':'\u2955','RightFloor':'\u230B','rightharpoondown':'\u21C1','rightharpoonup':'\u21C0','rightleftarrows':'\u21C4','rightleftharpoons':'\u21CC','rightrightarrows':'\u21C9','rightsquigarrow':'\u219D','RightTee':'\u22A2','RightTeeArrow':'\u21A6','RightTeeVector':'\u295B','rightthreetimes':'\u22CC','RightTriangle':'\u22B3','RightTriangleBar':'\u29D0','RightTriangleEqual':'\u22B5','RightUpDownVector':'\u294F','RightUpTeeVector':'\u295C','RightUpVector':'\u21BE','RightUpVectorBar':'\u2954','RightVector':'\u21C0','RightVectorBar':'\u2953','ring':'\u02DA','risingdotseq':'\u2253','rlarr':'\u21C4','rlhar':'\u21CC','rlm':'\u200F','rmoust':'\u23B1','rmoustache':'\u23B1','rnmid':'\u2AEE','roang':'\u27ED','roarr':'\u21FE','robrk':'\u27E7','ropar':'\u2986','ropf':'\uD835\uDD63','Ropf':'\u211D','roplus':'\u2A2E','rotimes':'\u2A35','RoundImplies':'\u2970','rpar':')','rpargt':'\u2994','rppolint':'\u2A12','rrarr':'\u21C9','Rrightarrow':'\u21DB','rsaquo':'\u203A','rscr':'\uD835\uDCC7','Rscr':'\u211B','rsh':'\u21B1','Rsh':'\u21B1','rsqb':']','rsquo':'\u2019','rsquor':'\u2019','rthree':'\u22CC','rtimes':'\u22CA','rtri':'\u25B9','rtrie':'\u22B5','rtrif':'\u25B8','rtriltri':'\u29CE','RuleDelayed':'\u29F4','ruluhar':'\u2968','rx':'\u211E','sacute':'\u015B','Sacute':'\u015A','sbquo':'\u201A','sc':'\u227B','Sc':'\u2ABC','scap':'\u2AB8','scaron':'\u0161','Scaron':'\u0160','sccue':'\u227D','sce':'\u2AB0','scE':'\u2AB4','scedil':'\u015F','Scedil':'\u015E','scirc':'\u015D','Scirc':'\u015C','scnap':'\u2ABA','scnE':'\u2AB6','scnsim':'\u22E9','scpolint':'\u2A13','scsim':'\u227F','scy':'\u0441','Scy':'\u0421','sdot':'\u22C5','sdotb':'\u22A1','sdote':'\u2A66','searhk':'\u2925','searr':'\u2198','seArr':'\u21D8','searrow':'\u2198','sect':'\xA7','semi':';','seswar':'\u2929','setminus':'\u2216','setmn':'\u2216','sext':'\u2736','sfr':'\uD835\uDD30','Sfr':'\uD835\uDD16','sfrown':'\u2322','sharp':'\u266F','shchcy':'\u0449','SHCHcy':'\u0429','shcy':'\u0448','SHcy':'\u0428','ShortDownArrow':'\u2193','ShortLeftArrow':'\u2190','shortmid':'\u2223','shortparallel':'\u2225','ShortRightArrow':'\u2192','ShortUpArrow':'\u2191','shy':'\xAD','sigma':'\u03C3','Sigma':'\u03A3','sigmaf':'\u03C2','sigmav':'\u03C2','sim':'\u223C','simdot':'\u2A6A','sime':'\u2243','simeq':'\u2243','simg':'\u2A9E','simgE':'\u2AA0','siml':'\u2A9D','simlE':'\u2A9F','simne':'\u2246','simplus':'\u2A24','simrarr':'\u2972','slarr':'\u2190','SmallCircle':'\u2218','smallsetminus':'\u2216','smashp':'\u2A33','smeparsl':'\u29E4','smid':'\u2223','smile':'\u2323','smt':'\u2AAA','smte':'\u2AAC','smtes':'\u2AAC\uFE00','softcy':'\u044C','SOFTcy':'\u042C','sol':'/','solb':'\u29C4','solbar':'\u233F','sopf':'\uD835\uDD64','Sopf':'\uD835\uDD4A','spades':'\u2660','spadesuit':'\u2660','spar':'\u2225','sqcap':'\u2293','sqcaps':'\u2293\uFE00','sqcup':'\u2294','sqcups':'\u2294\uFE00','Sqrt':'\u221A','sqsub':'\u228F','sqsube':'\u2291','sqsubset':'\u228F','sqsubseteq':'\u2291','sqsup':'\u2290','sqsupe':'\u2292','sqsupset':'\u2290','sqsupseteq':'\u2292','squ':'\u25A1','square':'\u25A1','Square':'\u25A1','SquareIntersection':'\u2293','SquareSubset':'\u228F','SquareSubsetEqual':'\u2291','SquareSuperset':'\u2290','SquareSupersetEqual':'\u2292','SquareUnion':'\u2294','squarf':'\u25AA','squf':'\u25AA','srarr':'\u2192','sscr':'\uD835\uDCC8','Sscr':'\uD835\uDCAE','ssetmn':'\u2216','ssmile':'\u2323','sstarf':'\u22C6','star':'\u2606','Star':'\u22C6','starf':'\u2605','straightepsilon':'\u03F5','straightphi':'\u03D5','strns':'\xAF','sub':'\u2282','Sub':'\u22D0','subdot':'\u2ABD','sube':'\u2286','subE':'\u2AC5','subedot':'\u2AC3','submult':'\u2AC1','subne':'\u228A','subnE':'\u2ACB','subplus':'\u2ABF','subrarr':'\u2979','subset':'\u2282','Subset':'\u22D0','subseteq':'\u2286','subseteqq':'\u2AC5','SubsetEqual':'\u2286','subsetneq':'\u228A','subsetneqq':'\u2ACB','subsim':'\u2AC7','subsub':'\u2AD5','subsup':'\u2AD3','succ':'\u227B','succapprox':'\u2AB8','succcurlyeq':'\u227D','Succeeds':'\u227B','SucceedsEqual':'\u2AB0','SucceedsSlantEqual':'\u227D','SucceedsTilde':'\u227F','succeq':'\u2AB0','succnapprox':'\u2ABA','succneqq':'\u2AB6','succnsim':'\u22E9','succsim':'\u227F','SuchThat':'\u220B','sum':'\u2211','Sum':'\u2211','sung':'\u266A','sup':'\u2283','Sup':'\u22D1','sup1':'\xB9','sup2':'\xB2','sup3':'\xB3','supdot':'\u2ABE','supdsub':'\u2AD8','supe':'\u2287','supE':'\u2AC6','supedot':'\u2AC4','Superset':'\u2283','SupersetEqual':'\u2287','suphsol':'\u27C9','suphsub':'\u2AD7','suplarr':'\u297B','supmult':'\u2AC2','supne':'\u228B','supnE':'\u2ACC','supplus':'\u2AC0','supset':'\u2283','Supset':'\u22D1','supseteq':'\u2287','supseteqq':'\u2AC6','supsetneq':'\u228B','supsetneqq':'\u2ACC','supsim':'\u2AC8','supsub':'\u2AD4','supsup':'\u2AD6','swarhk':'\u2926','swarr':'\u2199','swArr':'\u21D9','swarrow':'\u2199','swnwar':'\u292A','szlig':'\xDF','Tab':'\t','target':'\u2316','tau':'\u03C4','Tau':'\u03A4','tbrk':'\u23B4','tcaron':'\u0165','Tcaron':'\u0164','tcedil':'\u0163','Tcedil':'\u0162','tcy':'\u0442','Tcy':'\u0422','tdot':'\u20DB','telrec':'\u2315','tfr':'\uD835\uDD31','Tfr':'\uD835\uDD17','there4':'\u2234','therefore':'\u2234','Therefore':'\u2234','theta':'\u03B8','Theta':'\u0398','thetasym':'\u03D1','thetav':'\u03D1','thickapprox':'\u2248','thicksim':'\u223C','ThickSpace':'\u205F\u200A','thinsp':'\u2009','ThinSpace':'\u2009','thkap':'\u2248','thksim':'\u223C','thorn':'\xFE','THORN':'\xDE','tilde':'\u02DC','Tilde':'\u223C','TildeEqual':'\u2243','TildeFullEqual':'\u2245','TildeTilde':'\u2248','times':'\xD7','timesb':'\u22A0','timesbar':'\u2A31','timesd':'\u2A30','tint':'\u222D','toea':'\u2928','top':'\u22A4','topbot':'\u2336','topcir':'\u2AF1','topf':'\uD835\uDD65','Topf':'\uD835\uDD4B','topfork':'\u2ADA','tosa':'\u2929','tprime':'\u2034','trade':'\u2122','TRADE':'\u2122','triangle':'\u25B5','triangledown':'\u25BF','triangleleft':'\u25C3','trianglelefteq':'\u22B4','triangleq':'\u225C','triangleright':'\u25B9','trianglerighteq':'\u22B5','tridot':'\u25EC','trie':'\u225C','triminus':'\u2A3A','TripleDot':'\u20DB','triplus':'\u2A39','trisb':'\u29CD','tritime':'\u2A3B','trpezium':'\u23E2','tscr':'\uD835\uDCC9','Tscr':'\uD835\uDCAF','tscy':'\u0446','TScy':'\u0426','tshcy':'\u045B','TSHcy':'\u040B','tstrok':'\u0167','Tstrok':'\u0166','twixt':'\u226C','twoheadleftarrow':'\u219E','twoheadrightarrow':'\u21A0','uacute':'\xFA','Uacute':'\xDA','uarr':'\u2191','uArr':'\u21D1','Uarr':'\u219F','Uarrocir':'\u2949','ubrcy':'\u045E','Ubrcy':'\u040E','ubreve':'\u016D','Ubreve':'\u016C','ucirc':'\xFB','Ucirc':'\xDB','ucy':'\u0443','Ucy':'\u0423','udarr':'\u21C5','udblac':'\u0171','Udblac':'\u0170','udhar':'\u296E','ufisht':'\u297E','ufr':'\uD835\uDD32','Ufr':'\uD835\uDD18','ugrave':'\xF9','Ugrave':'\xD9','uHar':'\u2963','uharl':'\u21BF','uharr':'\u21BE','uhblk':'\u2580','ulcorn':'\u231C','ulcorner':'\u231C','ulcrop':'\u230F','ultri':'\u25F8','umacr':'\u016B','Umacr':'\u016A','uml':'\xA8','UnderBar':'_','UnderBrace':'\u23DF','UnderBracket':'\u23B5','UnderParenthesis':'\u23DD','Union':'\u22C3','UnionPlus':'\u228E','uogon':'\u0173','Uogon':'\u0172','uopf':'\uD835\uDD66','Uopf':'\uD835\uDD4C','uparrow':'\u2191','Uparrow':'\u21D1','UpArrow':'\u2191','UpArrowBar':'\u2912','UpArrowDownArrow':'\u21C5','updownarrow':'\u2195','Updownarrow':'\u21D5','UpDownArrow':'\u2195','UpEquilibrium':'\u296E','upharpoonleft':'\u21BF','upharpoonright':'\u21BE','uplus':'\u228E','UpperLeftArrow':'\u2196','UpperRightArrow':'\u2197','upsi':'\u03C5','Upsi':'\u03D2','upsih':'\u03D2','upsilon':'\u03C5','Upsilon':'\u03A5','UpTee':'\u22A5','UpTeeArrow':'\u21A5','upuparrows':'\u21C8','urcorn':'\u231D','urcorner':'\u231D','urcrop':'\u230E','uring':'\u016F','Uring':'\u016E','urtri':'\u25F9','uscr':'\uD835\uDCCA','Uscr':'\uD835\uDCB0','utdot':'\u22F0','utilde':'\u0169','Utilde':'\u0168','utri':'\u25B5','utrif':'\u25B4','uuarr':'\u21C8','uuml':'\xFC','Uuml':'\xDC','uwangle':'\u29A7','vangrt':'\u299C','varepsilon':'\u03F5','varkappa':'\u03F0','varnothing':'\u2205','varphi':'\u03D5','varpi':'\u03D6','varpropto':'\u221D','varr':'\u2195','vArr':'\u21D5','varrho':'\u03F1','varsigma':'\u03C2','varsubsetneq':'\u228A\uFE00','varsubsetneqq':'\u2ACB\uFE00','varsupsetneq':'\u228B\uFE00','varsupsetneqq':'\u2ACC\uFE00','vartheta':'\u03D1','vartriangleleft':'\u22B2','vartriangleright':'\u22B3','vBar':'\u2AE8','Vbar':'\u2AEB','vBarv':'\u2AE9','vcy':'\u0432','Vcy':'\u0412','vdash':'\u22A2','vDash':'\u22A8','Vdash':'\u22A9','VDash':'\u22AB','Vdashl':'\u2AE6','vee':'\u2228','Vee':'\u22C1','veebar':'\u22BB','veeeq':'\u225A','vellip':'\u22EE','verbar':'|','Verbar':'\u2016','vert':'|','Vert':'\u2016','VerticalBar':'\u2223','VerticalLine':'|','VerticalSeparator':'\u2758','VerticalTilde':'\u2240','VeryThinSpace':'\u200A','vfr':'\uD835\uDD33','Vfr':'\uD835\uDD19','vltri':'\u22B2','vnsub':'\u2282\u20D2','vnsup':'\u2283\u20D2','vopf':'\uD835\uDD67','Vopf':'\uD835\uDD4D','vprop':'\u221D','vrtri':'\u22B3','vscr':'\uD835\uDCCB','Vscr':'\uD835\uDCB1','vsubne':'\u228A\uFE00','vsubnE':'\u2ACB\uFE00','vsupne':'\u228B\uFE00','vsupnE':'\u2ACC\uFE00','Vvdash':'\u22AA','vzigzag':'\u299A','wcirc':'\u0175','Wcirc':'\u0174','wedbar':'\u2A5F','wedge':'\u2227','Wedge':'\u22C0','wedgeq':'\u2259','weierp':'\u2118','wfr':'\uD835\uDD34','Wfr':'\uD835\uDD1A','wopf':'\uD835\uDD68','Wopf':'\uD835\uDD4E','wp':'\u2118','wr':'\u2240','wreath':'\u2240','wscr':'\uD835\uDCCC','Wscr':'\uD835\uDCB2','xcap':'\u22C2','xcirc':'\u25EF','xcup':'\u22C3','xdtri':'\u25BD','xfr':'\uD835\uDD35','Xfr':'\uD835\uDD1B','xharr':'\u27F7','xhArr':'\u27FA','xi':'\u03BE','Xi':'\u039E','xlarr':'\u27F5','xlArr':'\u27F8','xmap':'\u27FC','xnis':'\u22FB','xodot':'\u2A00','xopf':'\uD835\uDD69','Xopf':'\uD835\uDD4F','xoplus':'\u2A01','xotime':'\u2A02','xrarr':'\u27F6','xrArr':'\u27F9','xscr':'\uD835\uDCCD','Xscr':'\uD835\uDCB3','xsqcup':'\u2A06','xuplus':'\u2A04','xutri':'\u25B3','xvee':'\u22C1','xwedge':'\u22C0','yacute':'\xFD','Yacute':'\xDD','yacy':'\u044F','YAcy':'\u042F','ycirc':'\u0177','Ycirc':'\u0176','ycy':'\u044B','Ycy':'\u042B','yen':'\xA5','yfr':'\uD835\uDD36','Yfr':'\uD835\uDD1C','yicy':'\u0457','YIcy':'\u0407','yopf':'\uD835\uDD6A','Yopf':'\uD835\uDD50','yscr':'\uD835\uDCCE','Yscr':'\uD835\uDCB4','yucy':'\u044E','YUcy':'\u042E','yuml':'\xFF','Yuml':'\u0178','zacute':'\u017A','Zacute':'\u0179','zcaron':'\u017E','Zcaron':'\u017D','zcy':'\u0437','Zcy':'\u0417','zdot':'\u017C','Zdot':'\u017B','zeetrf':'\u2128','ZeroWidthSpace':'\u200B','zeta':'\u03B6','Zeta':'\u0396','zfr':'\uD835\uDD37','Zfr':'\u2128','zhcy':'\u0436','ZHcy':'\u0416','zigrarr':'\u21DD','zopf':'\uD835\uDD6B','Zopf':'\u2124','zscr':'\uD835\uDCCF','Zscr':'\uD835\uDCB5','zwj':'\u200D','zwnj':'\u200C'};
13805 var decodeMapLegacy = {'aacute':'\xE1','Aacute':'\xC1','acirc':'\xE2','Acirc':'\xC2','acute':'\xB4','aelig':'\xE6','AElig':'\xC6','agrave':'\xE0','Agrave':'\xC0','amp':'&','AMP':'&','aring':'\xE5','Aring':'\xC5','atilde':'\xE3','Atilde':'\xC3','auml':'\xE4','Auml':'\xC4','brvbar':'\xA6','ccedil':'\xE7','Ccedil':'\xC7','cedil':'\xB8','cent':'\xA2','copy':'\xA9','COPY':'\xA9','curren':'\xA4','deg':'\xB0','divide':'\xF7','eacute':'\xE9','Eacute':'\xC9','ecirc':'\xEA','Ecirc':'\xCA','egrave':'\xE8','Egrave':'\xC8','eth':'\xF0','ETH':'\xD0','euml':'\xEB','Euml':'\xCB','frac12':'\xBD','frac14':'\xBC','frac34':'\xBE','gt':'>','GT':'>','iacute':'\xED','Iacute':'\xCD','icirc':'\xEE','Icirc':'\xCE','iexcl':'\xA1','igrave':'\xEC','Igrave':'\xCC','iquest':'\xBF','iuml':'\xEF','Iuml':'\xCF','laquo':'\xAB','lt':'<','LT':'<','macr':'\xAF','micro':'\xB5','middot':'\xB7','nbsp':'\xA0','not':'\xAC','ntilde':'\xF1','Ntilde':'\xD1','oacute':'\xF3','Oacute':'\xD3','ocirc':'\xF4','Ocirc':'\xD4','ograve':'\xF2','Ograve':'\xD2','ordf':'\xAA','ordm':'\xBA','oslash':'\xF8','Oslash':'\xD8','otilde':'\xF5','Otilde':'\xD5','ouml':'\xF6','Ouml':'\xD6','para':'\xB6','plusmn':'\xB1','pound':'\xA3','quot':'"','QUOT':'"','raquo':'\xBB','reg':'\xAE','REG':'\xAE','sect':'\xA7','shy':'\xAD','sup1':'\xB9','sup2':'\xB2','sup3':'\xB3','szlig':'\xDF','thorn':'\xFE','THORN':'\xDE','times':'\xD7','uacute':'\xFA','Uacute':'\xDA','ucirc':'\xFB','Ucirc':'\xDB','ugrave':'\xF9','Ugrave':'\xD9','uml':'\xA8','uuml':'\xFC','Uuml':'\xDC','yacute':'\xFD','Yacute':'\xDD','yen':'\xA5','yuml':'\xFF'};
13806 var decodeMapNumeric = {'0':'\uFFFD','128':'\u20AC','130':'\u201A','131':'\u0192','132':'\u201E','133':'\u2026','134':'\u2020','135':'\u2021','136':'\u02C6','137':'\u2030','138':'\u0160','139':'\u2039','140':'\u0152','142':'\u017D','145':'\u2018','146':'\u2019','147':'\u201C','148':'\u201D','149':'\u2022','150':'\u2013','151':'\u2014','152':'\u02DC','153':'\u2122','154':'\u0161','155':'\u203A','156':'\u0153','158':'\u017E','159':'\u0178'};
13807 var invalidReferenceCodePoints = [1,2,3,4,5,6,7,8,11,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,64976,64977,64978,64979,64980,64981,64982,64983,64984,64985,64986,64987,64988,64989,64990,64991,64992,64993,64994,64995,64996,64997,64998,64999,65000,65001,65002,65003,65004,65005,65006,65007,65534,65535,131070,131071,196606,196607,262142,262143,327678,327679,393214,393215,458750,458751,524286,524287,589822,589823,655358,655359,720894,720895,786430,786431,851966,851967,917502,917503,983038,983039,1048574,1048575,1114110,1114111];
13809 /*--------------------------------------------------------------------------*/
13811 var stringFromCharCode = String.fromCharCode;
13814 var hasOwnProperty = object.hasOwnProperty;
13815 var has = function(object, propertyName) {
13816 return hasOwnProperty.call(object, propertyName);
13819 var contains = function(array, value) {
13821 var length = array.length;
13822 while (++index < length) {
13823 if (array[index] == value) {
13830 var merge = function(options, defaults) {
13836 for (key in defaults) {
13837 // A `hasOwnProperty` check is not needed here, since only recognized
13838 // option names are used anyway. Any others are ignored.
13839 result[key] = has(options, key) ? options[key] : defaults[key];
13844 // Modified version of `ucs2encode`; see https://mths.be/punycode.
13845 var codePointToSymbol = function(codePoint, strict) {
13847 if ((codePoint >= 0xD800 && codePoint <= 0xDFFF) || codePoint > 0x10FFFF) {
13849 // “Otherwise, if the number is in the range 0xD800 to 0xDFFF or is
13850 // greater than 0x10FFFF, then this is a parse error. Return a U+FFFD
13851 // REPLACEMENT CHARACTER.”
13853 parseError('character reference outside the permissible Unicode range');
13857 if (has(decodeMapNumeric, codePoint)) {
13859 parseError('disallowed character reference');
13861 return decodeMapNumeric[codePoint];
13863 if (strict && contains(invalidReferenceCodePoints, codePoint)) {
13864 parseError('disallowed character reference');
13866 if (codePoint > 0xFFFF) {
13867 codePoint -= 0x10000;
13868 output += stringFromCharCode(codePoint >>> 10 & 0x3FF | 0xD800);
13869 codePoint = 0xDC00 | codePoint & 0x3FF;
13871 output += stringFromCharCode(codePoint);
13875 var hexEscape = function(codePoint) {
13876 return '&#x' + codePoint.toString(16).toUpperCase() + ';';
13879 var decEscape = function(codePoint) {
13880 return '&#' + codePoint + ';';
13883 var parseError = function(message) {
13884 throw Error('Parse error: ' + message);
13887 /*--------------------------------------------------------------------------*/
13889 var encode = function(string, options) {
13890 options = merge(options, encode.options);
13891 var strict = options.strict;
13892 if (strict && regexInvalidRawCodePoint.test(string)) {
13893 parseError('forbidden code point');
13895 var encodeEverything = options.encodeEverything;
13896 var useNamedReferences = options.useNamedReferences;
13897 var allowUnsafeSymbols = options.allowUnsafeSymbols;
13898 var escapeCodePoint = options.decimal ? decEscape : hexEscape;
13900 var escapeBmpSymbol = function(symbol) {
13901 return escapeCodePoint(symbol.charCodeAt(0));
13904 if (encodeEverything) {
13905 // Encode ASCII symbols.
13906 string = string.replace(regexAsciiWhitelist, function(symbol) {
13907 // Use named references if requested & possible.
13908 if (useNamedReferences && has(encodeMap, symbol)) {
13909 return '&' + encodeMap[symbol] + ';';
13911 return escapeBmpSymbol(symbol);
13913 // Shorten a few escapes that represent two symbols, of which at least one
13914 // is within the ASCII range.
13915 if (useNamedReferences) {
13917 .replace(/>\u20D2/g, '>⃒')
13918 .replace(/<\u20D2/g, '<⃒')
13919 .replace(/fj/g, 'fj');
13921 // Encode non-ASCII symbols.
13922 if (useNamedReferences) {
13923 // Encode non-ASCII symbols that can be replaced with a named reference.
13924 string = string.replace(regexEncodeNonAscii, function(string) {
13925 // Note: there is no need to check `has(encodeMap, string)` here.
13926 return '&' + encodeMap[string] + ';';
13929 // Note: any remaining non-ASCII symbols are handled outside of the `if`.
13930 } else if (useNamedReferences) {
13931 // Apply named character references.
13932 // Encode `<>"'&` using named character references.
13933 if (!allowUnsafeSymbols) {
13934 string = string.replace(regexEscape, function(string) {
13935 return '&' + encodeMap[string] + ';'; // no need to check `has()` here
13938 // Shorten escapes that represent two symbols, of which at least one is
13941 .replace(/>\u20D2/g, '>⃒')
13942 .replace(/<\u20D2/g, '<⃒');
13943 // Encode non-ASCII symbols that can be replaced with a named reference.
13944 string = string.replace(regexEncodeNonAscii, function(string) {
13945 // Note: there is no need to check `has(encodeMap, string)` here.
13946 return '&' + encodeMap[string] + ';';
13948 } else if (!allowUnsafeSymbols) {
13949 // Encode `<>"'&` using hexadecimal escapes, now that they’re not handled
13950 // using named character references.
13951 string = string.replace(regexEscape, escapeBmpSymbol);
13954 // Encode astral symbols.
13955 .replace(regexAstralSymbols, function($0) {
13956 // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
13957 var high = $0.charCodeAt(0);
13958 var low = $0.charCodeAt(1);
13959 var codePoint = (high - 0xD800) * 0x400 + low - 0xDC00 + 0x10000;
13960 return escapeCodePoint(codePoint);
13962 // Encode any remaining BMP symbols that are not printable ASCII symbols
13963 // using a hexadecimal escape.
13964 .replace(regexBmpWhitelist, escapeBmpSymbol);
13966 // Expose default options (so they can be overridden globally).
13968 'allowUnsafeSymbols': false,
13969 'encodeEverything': false,
13971 'useNamedReferences': false,
13975 var decode = function(html, options) {
13976 options = merge(options, decode.options);
13977 var strict = options.strict;
13978 if (strict && regexInvalidEntity.test(html)) {
13979 parseError('malformed character reference');
13981 return html.replace(regexDecode, function($0, $1, $2, $3, $4, $5, $6, $7, $8) {
13991 // Note: there is no need to check `has(decodeMap, reference)`.
13992 return decodeMap[reference];
13996 // Decode named character references without trailing `;`, e.g. `&`.
13997 // This is only a parse error if it gets converted to `&`, or if it is
13998 // followed by `=` in an attribute context.
14001 if (next && options.isAttributeValue) {
14002 if (strict && next == '=') {
14003 parseError('`&` did not start a character reference');
14009 'named character reference was not terminated by a semicolon'
14012 // Note: there is no need to check `has(decodeMapLegacy, reference)`.
14013 return decodeMapLegacy[reference] + (next || '');
14018 // Decode decimal escapes, e.g. `𝌆`.
14021 if (strict && !semicolon) {
14022 parseError('character reference was not terminated by a semicolon');
14024 codePoint = parseInt(decDigits, 10);
14025 return codePointToSymbol(codePoint, strict);
14029 // Decode hexadecimal escapes, e.g. `𝌆`.
14032 if (strict && !semicolon) {
14033 parseError('character reference was not terminated by a semicolon');
14035 codePoint = parseInt(hexDigits, 16);
14036 return codePointToSymbol(codePoint, strict);
14039 // If we’re still here, `if ($7)` is implied; it’s an ambiguous
14040 // ampersand for sure. https://mths.be/notes/ambiguous-ampersands
14043 'named character reference was not terminated by a semicolon'
14049 // Expose default options (so they can be overridden globally).
14051 'isAttributeValue': false,
14055 var escape = function(string) {
14056 return string.replace(regexEscape, function($0) {
14057 // Note: there is no need to check `has(escapeMap, $0)` here.
14058 return escapeMap[$0];
14062 /*--------------------------------------------------------------------------*/
14065 'version': '1.2.0',
14072 // Some AMD build optimizers, like r.js, check for specific condition patterns
14073 // like the following:
14075 typeof define == 'function' &&
14076 typeof define.amd == 'object' &&
14079 define(function() {
14082 } else if (freeExports && !freeExports.nodeType) {
14083 if (freeModule) { // in Node.js, io.js, or RingoJS v0.8.0+
14084 freeModule.exports = he;
14085 } else { // in Narwhal or RingoJS v0.7.0-
14086 for (var key in he) {
14087 has(he, key) && (freeExports[key] = he[key]);
14090 } else { // in Rhino or a web browser
14096 }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
14097 },{}],104:[function(require,module,exports){
14098 var http = require('http')
14099 var url = require('url')
14101 var https = module.exports
14103 for (var key in http) {
14104 if (http.hasOwnProperty(key)) https[key] = http[key]
14107 https.request = function (params, cb) {
14108 params = validateParams(params)
14109 return http.request.call(this, params, cb)
14112 https.get = function (params, cb) {
14113 params = validateParams(params)
14114 return http.get.call(this, params, cb)
14117 function validateParams (params) {
14118 if (typeof params === 'string') {
14119 params = url.parse(params)
14121 if (!params.protocol) {
14122 params.protocol = 'https:'
14124 if (params.protocol !== 'https:') {
14125 throw new Error('Protocol "' + params.protocol + '" not supported. Expected "https:"')
14130 },{"http":155,"url":162}],105:[function(require,module,exports){
14131 exports.read = function (buffer, offset, isLE, mLen, nBytes) {
14133 var eLen = (nBytes * 8) - mLen - 1
14134 var eMax = (1 << eLen) - 1
14135 var eBias = eMax >> 1
14137 var i = isLE ? (nBytes - 1) : 0
14138 var d = isLE ? -1 : 1
14139 var s = buffer[offset + i]
14143 e = s & ((1 << (-nBits)) - 1)
14146 for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}
14148 m = e & ((1 << (-nBits)) - 1)
14151 for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}
14155 } else if (e === eMax) {
14156 return m ? NaN : ((s ? -1 : 1) * Infinity)
14158 m = m + Math.pow(2, mLen)
14161 return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
14164 exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
14166 var eLen = (nBytes * 8) - mLen - 1
14167 var eMax = (1 << eLen) - 1
14168 var eBias = eMax >> 1
14169 var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
14170 var i = isLE ? 0 : (nBytes - 1)
14171 var d = isLE ? 1 : -1
14172 var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
14174 value = Math.abs(value)
14176 if (isNaN(value) || value === Infinity) {
14177 m = isNaN(value) ? 1 : 0
14180 e = Math.floor(Math.log(value) / Math.LN2)
14181 if (value * (c = Math.pow(2, -e)) < 1) {
14185 if (e + eBias >= 1) {
14188 value += rt * Math.pow(2, 1 - eBias)
14190 if (value * c >= 2) {
14195 if (e + eBias >= eMax) {
14198 } else if (e + eBias >= 1) {
14199 m = ((value * c) - 1) * Math.pow(2, mLen)
14202 m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
14207 for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
14209 e = (e << mLen) | m
14211 for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
14213 buffer[offset + i - d] |= s * 128
14216 },{}],106:[function(require,module,exports){
14217 if (typeof Object.create === 'function') {
14218 // implementation from standard node.js 'util' module
14219 module.exports = function inherits(ctor, superCtor) {
14220 ctor.super_ = superCtor
14221 ctor.prototype = Object.create(superCtor.prototype, {
14231 // old school shim for old browsers
14232 module.exports = function inherits(ctor, superCtor) {
14233 ctor.super_ = superCtor
14234 var TempCtor = function () {}
14235 TempCtor.prototype = superCtor.prototype
14236 ctor.prototype = new TempCtor()
14237 ctor.prototype.constructor = ctor
14241 },{}],107:[function(require,module,exports){
14243 * Determine if an object is a Buffer
14245 * @author Feross Aboukhadijeh <https://feross.org>
14249 // The _isBuffer check is for Safari 5-7 support, because it's missing
14250 // Object.prototype.constructor. Remove this eventually
14251 module.exports = function (obj) {
14252 return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer)
14255 function isBuffer (obj) {
14256 return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
14259 // For Node v0.10 support. Remove this eventually.
14260 function isSlowBuffer (obj) {
14261 return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0))
14264 },{}],108:[function(require,module,exports){
14265 var toString = {}.toString;
14267 module.exports = Array.isArray || function (arr) {
14268 return toString.call(arr) == '[object Array]';
14271 },{}],109:[function(require,module,exports){
14272 exports.endianness = function () { return 'LE' };
14274 exports.hostname = function () {
14275 if (typeof location !== 'undefined') {
14276 return location.hostname
14281 exports.loadavg = function () { return [] };
14283 exports.uptime = function () { return 0 };
14285 exports.freemem = function () {
14286 return Number.MAX_VALUE;
14289 exports.totalmem = function () {
14290 return Number.MAX_VALUE;
14293 exports.cpus = function () { return [] };
14295 exports.type = function () { return 'Browser' };
14297 exports.release = function () {
14298 if (typeof navigator !== 'undefined') {
14299 return navigator.appVersion;
14304 exports.networkInterfaces
14305 = exports.getNetworkInterfaces
14306 = function () { return {} };
14308 exports.arch = function () { return 'javascript' };
14310 exports.platform = function () { return 'browser' };
14312 exports.tmpdir = exports.tmpDir = function () {
14316 exports.EOL = '\n';
14318 exports.homedir = function () {
14322 },{}],110:[function(require,module,exports){
14323 (function (process){
14324 // .dirname, .basename, and .extname methods are extracted from Node.js v8.11.1,
14325 // backported and transplited with Babel, with backwards-compat fixes
14327 // Copyright Joyent, Inc. and other Node contributors.
14329 // Permission is hereby granted, free of charge, to any person obtaining a
14330 // copy of this software and associated documentation files (the
14331 // "Software"), to deal in the Software without restriction, including
14332 // without limitation the rights to use, copy, modify, merge, publish,
14333 // distribute, sublicense, and/or sell copies of the Software, and to permit
14334 // persons to whom the Software is furnished to do so, subject to the
14335 // following conditions:
14337 // The above copyright notice and this permission notice shall be included
14338 // in all copies or substantial portions of the Software.
14340 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
14341 // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
14342 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
14343 // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
14344 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
14345 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
14346 // USE OR OTHER DEALINGS IN THE SOFTWARE.
14348 // resolves . and .. elements in a path array with directory names there
14349 // must be no slashes, empty elements, or device names (c:\) in the array
14350 // (so also no leading and trailing slashes - it does not distinguish
14351 // relative and absolute paths)
14352 function normalizeArray(parts, allowAboveRoot) {
14353 // if the path tries to go above the root, `up` ends up > 0
14355 for (var i = parts.length - 1; i >= 0; i--) {
14356 var last = parts[i];
14357 if (last === '.') {
14358 parts.splice(i, 1);
14359 } else if (last === '..') {
14360 parts.splice(i, 1);
14363 parts.splice(i, 1);
14368 // if the path is allowed to go above the root, restore leading ..s
14369 if (allowAboveRoot) {
14371 parts.unshift('..');
14378 // path.resolve([from ...], to)
14380 exports.resolve = function() {
14381 var resolvedPath = '',
14382 resolvedAbsolute = false;
14384 for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
14385 var path = (i >= 0) ? arguments[i] : process.cwd();
14387 // Skip empty and invalid entries
14388 if (typeof path !== 'string') {
14389 throw new TypeError('Arguments to path.resolve must be strings');
14390 } else if (!path) {
14394 resolvedPath = path + '/' + resolvedPath;
14395 resolvedAbsolute = path.charAt(0) === '/';
14398 // At this point the path should be resolved to a full absolute path, but
14399 // handle relative paths to be safe (might happen when process.cwd() fails)
14401 // Normalize the path
14402 resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) {
14404 }), !resolvedAbsolute).join('/');
14406 return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
14409 // path.normalize(path)
14411 exports.normalize = function(path) {
14412 var isAbsolute = exports.isAbsolute(path),
14413 trailingSlash = substr(path, -1) === '/';
14415 // Normalize the path
14416 path = normalizeArray(filter(path.split('/'), function(p) {
14418 }), !isAbsolute).join('/');
14420 if (!path && !isAbsolute) {
14423 if (path && trailingSlash) {
14427 return (isAbsolute ? '/' : '') + path;
14431 exports.isAbsolute = function(path) {
14432 return path.charAt(0) === '/';
14436 exports.join = function() {
14437 var paths = Array.prototype.slice.call(arguments, 0);
14438 return exports.normalize(filter(paths, function(p, index) {
14439 if (typeof p !== 'string') {
14440 throw new TypeError('Arguments to path.join must be strings');
14447 // path.relative(from, to)
14449 exports.relative = function(from, to) {
14450 from = exports.resolve(from).substr(1);
14451 to = exports.resolve(to).substr(1);
14453 function trim(arr) {
14455 for (; start < arr.length; start++) {
14456 if (arr[start] !== '') break;
14459 var end = arr.length - 1;
14460 for (; end >= 0; end--) {
14461 if (arr[end] !== '') break;
14464 if (start > end) return [];
14465 return arr.slice(start, end - start + 1);
14468 var fromParts = trim(from.split('/'));
14469 var toParts = trim(to.split('/'));
14471 var length = Math.min(fromParts.length, toParts.length);
14472 var samePartsLength = length;
14473 for (var i = 0; i < length; i++) {
14474 if (fromParts[i] !== toParts[i]) {
14475 samePartsLength = i;
14480 var outputParts = [];
14481 for (var i = samePartsLength; i < fromParts.length; i++) {
14482 outputParts.push('..');
14485 outputParts = outputParts.concat(toParts.slice(samePartsLength));
14487 return outputParts.join('/');
14491 exports.delimiter = ':';
14493 exports.dirname = function (path) {
14494 if (typeof path !== 'string') path = path + '';
14495 if (path.length === 0) return '.';
14496 var code = path.charCodeAt(0);
14497 var hasRoot = code === 47 /*/*/;
14499 var matchedSlash = true;
14500 for (var i = path.length - 1; i >= 1; --i) {
14501 code = path.charCodeAt(i);
14502 if (code === 47 /*/*/) {
14503 if (!matchedSlash) {
14508 // We saw the first non-path separator
14509 matchedSlash = false;
14513 if (end === -1) return hasRoot ? '/' : '.';
14514 if (hasRoot && end === 1) {
14516 // Backwards-compat fix:
14519 return path.slice(0, end);
14522 function basename(path) {
14523 if (typeof path !== 'string') path = path + '';
14527 var matchedSlash = true;
14530 for (i = path.length - 1; i >= 0; --i) {
14531 if (path.charCodeAt(i) === 47 /*/*/) {
14532 // If we reached a path separator that was not part of a set of path
14533 // separators at the end of the string, stop now
14534 if (!matchedSlash) {
14538 } else if (end === -1) {
14539 // We saw the first non-path separator, mark this as the end of our
14541 matchedSlash = false;
14546 if (end === -1) return '';
14547 return path.slice(start, end);
14550 // Uses a mixed approach for backwards-compatibility, as ext behavior changed
14551 // in new Node.js versions, so only basename() above is backported here
14552 exports.basename = function (path, ext) {
14553 var f = basename(path);
14554 if (ext && f.substr(-1 * ext.length) === ext) {
14555 f = f.substr(0, f.length - ext.length);
14560 exports.extname = function (path) {
14561 if (typeof path !== 'string') path = path + '';
14565 var matchedSlash = true;
14566 // Track the state of characters (if any) we see before our first dot and
14567 // after any path separator we find
14568 var preDotState = 0;
14569 for (var i = path.length - 1; i >= 0; --i) {
14570 var code = path.charCodeAt(i);
14571 if (code === 47 /*/*/) {
14572 // If we reached a path separator that was not part of a set of path
14573 // separators at the end of the string, stop now
14574 if (!matchedSlash) {
14581 // We saw the first non-path separator, mark this as the end of our
14583 matchedSlash = false;
14586 if (code === 46 /*.*/) {
14587 // If this is our first dot, mark it as the start of our extension
14588 if (startDot === -1)
14590 else if (preDotState !== 1)
14592 } else if (startDot !== -1) {
14593 // We saw a non-dot and non-path separator before our dot, so we should
14594 // have a good chance at having a non-empty extension
14599 if (startDot === -1 || end === -1 ||
14600 // We saw a non-dot character immediately before the dot
14601 preDotState === 0 ||
14602 // The (right-most) trimmed path component is exactly '..'
14603 preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) {
14606 return path.slice(startDot, end);
14609 function filter (xs, f) {
14610 if (xs.filter) return xs.filter(f);
14612 for (var i = 0; i < xs.length; i++) {
14613 if (f(xs[i], i, xs)) res.push(xs[i]);
14618 // String.prototype.substr - negative index don't work in IE8
14619 var substr = 'ab'.substr(-1) === 'b'
14620 ? function (str, start, len) { return str.substr(start, len) }
14621 : function (str, start, len) {
14622 if (start < 0) start = str.length + start;
14623 return str.substr(start, len);
14627 }).call(this,require('_process'))
14628 },{"_process":112}],111:[function(require,module,exports){
14629 (function (process){
14632 if (!process.version ||
14633 process.version.indexOf('v0.') === 0 ||
14634 process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) {
14635 module.exports = { nextTick: nextTick };
14637 module.exports = process
14640 function nextTick(fn, arg1, arg2, arg3) {
14641 if (typeof fn !== 'function') {
14642 throw new TypeError('"callback" argument must be a function');
14644 var len = arguments.length;
14649 return process.nextTick(fn);
14651 return process.nextTick(function afterTickOne() {
14652 fn.call(null, arg1);
14655 return process.nextTick(function afterTickTwo() {
14656 fn.call(null, arg1, arg2);
14659 return process.nextTick(function afterTickThree() {
14660 fn.call(null, arg1, arg2, arg3);
14663 args = new Array(len - 1);
14665 while (i < args.length) {
14666 args[i++] = arguments[i];
14668 return process.nextTick(function afterTick() {
14669 fn.apply(null, args);
14675 }).call(this,require('_process'))
14676 },{"_process":112}],112:[function(require,module,exports){
14677 // shim for using process in browser
14678 var process = module.exports = {};
14680 // cached from whatever global is present so that test runners that stub it
14681 // don't break things. But we need to wrap it in a try catch in case it is
14682 // wrapped in strict mode code which doesn't define any globals. It's inside a
14683 // function because try/catches deoptimize in certain engines.
14685 var cachedSetTimeout;
14686 var cachedClearTimeout;
14688 function defaultSetTimout() {
14689 throw new Error('setTimeout has not been defined');
14691 function defaultClearTimeout () {
14692 throw new Error('clearTimeout has not been defined');
14696 if (typeof setTimeout === 'function') {
14697 cachedSetTimeout = setTimeout;
14699 cachedSetTimeout = defaultSetTimout;
14702 cachedSetTimeout = defaultSetTimout;
14705 if (typeof clearTimeout === 'function') {
14706 cachedClearTimeout = clearTimeout;
14708 cachedClearTimeout = defaultClearTimeout;
14711 cachedClearTimeout = defaultClearTimeout;
14714 function runTimeout(fun) {
14715 if (cachedSetTimeout === setTimeout) {
14716 //normal enviroments in sane situations
14717 return setTimeout(fun, 0);
14719 // if setTimeout wasn't available but was latter defined
14720 if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
14721 cachedSetTimeout = setTimeout;
14722 return setTimeout(fun, 0);
14725 // when when somebody has screwed with setTimeout but no I.E. maddness
14726 return cachedSetTimeout(fun, 0);
14729 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
14730 return cachedSetTimeout.call(null, fun, 0);
14732 // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
14733 return cachedSetTimeout.call(this, fun, 0);
14739 function runClearTimeout(marker) {
14740 if (cachedClearTimeout === clearTimeout) {
14741 //normal enviroments in sane situations
14742 return clearTimeout(marker);
14744 // if clearTimeout wasn't available but was latter defined
14745 if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
14746 cachedClearTimeout = clearTimeout;
14747 return clearTimeout(marker);
14750 // when when somebody has screwed with setTimeout but no I.E. maddness
14751 return cachedClearTimeout(marker);
14754 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
14755 return cachedClearTimeout.call(null, marker);
14757 // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
14758 // Some versions of I.E. have different rules for clearTimeout vs setTimeout
14759 return cachedClearTimeout.call(this, marker);
14767 var draining = false;
14769 var queueIndex = -1;
14771 function cleanUpNextTick() {
14772 if (!draining || !currentQueue) {
14776 if (currentQueue.length) {
14777 queue = currentQueue.concat(queue);
14781 if (queue.length) {
14786 function drainQueue() {
14790 var timeout = runTimeout(cleanUpNextTick);
14793 var len = queue.length;
14795 currentQueue = queue;
14797 while (++queueIndex < len) {
14798 if (currentQueue) {
14799 currentQueue[queueIndex].run();
14803 len = queue.length;
14805 currentQueue = null;
14807 runClearTimeout(timeout);
14810 process.nextTick = function (fun) {
14811 var args = new Array(arguments.length - 1);
14812 if (arguments.length > 1) {
14813 for (var i = 1; i < arguments.length; i++) {
14814 args[i - 1] = arguments[i];
14817 queue.push(new Item(fun, args));
14818 if (queue.length === 1 && !draining) {
14819 runTimeout(drainQueue);
14823 // v8 likes predictible objects
14824 function Item(fun, array) {
14826 this.array = array;
14828 Item.prototype.run = function () {
14829 this.fun.apply(null, this.array);
14831 process.title = 'browser';
14832 process.browser = true;
14835 process.version = ''; // empty string to avoid regexp issues
14836 process.versions = {};
14841 process.addListener = noop;
14842 process.once = noop;
14843 process.off = noop;
14844 process.removeListener = noop;
14845 process.removeAllListeners = noop;
14846 process.emit = noop;
14847 process.prependListener = noop;
14848 process.prependOnceListener = noop;
14850 process.listeners = function (name) { return [] }
14852 process.binding = function (name) {
14853 throw new Error('process.binding is not supported');
14856 process.cwd = function () { return '/' };
14857 process.chdir = function (dir) {
14858 throw new Error('process.chdir is not supported');
14860 process.umask = function() { return 0; };
14862 },{}],113:[function(require,module,exports){
14863 (function (global){
14864 /*! https://mths.be/punycode v1.4.1 by @mathias */
14867 /** Detect free variables */
14868 var freeExports = typeof exports == 'object' && exports &&
14869 !exports.nodeType && exports;
14870 var freeModule = typeof module == 'object' && module &&
14871 !module.nodeType && module;
14872 var freeGlobal = typeof global == 'object' && global;
14874 freeGlobal.global === freeGlobal ||
14875 freeGlobal.window === freeGlobal ||
14876 freeGlobal.self === freeGlobal
14882 * The `punycode` object.
14888 /** Highest positive signed 32-bit float value */
14889 maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1
14891 /** Bootstring parameters */
14898 initialN = 128, // 0x80
14899 delimiter = '-', // '\x2D'
14901 /** Regular expressions */
14902 regexPunycode = /^xn--/,
14903 regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars
14904 regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators
14906 /** Error messages */
14908 'overflow': 'Overflow: input needs wider integers to process',
14909 'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
14910 'invalid-input': 'Invalid input'
14913 /** Convenience shortcuts */
14914 baseMinusTMin = base - tMin,
14915 floor = Math.floor,
14916 stringFromCharCode = String.fromCharCode,
14918 /** Temporary variable */
14921 /*--------------------------------------------------------------------------*/
14924 * A generic error utility function.
14926 * @param {String} type The error type.
14927 * @returns {Error} Throws a `RangeError` with the applicable error message.
14929 function error(type) {
14930 throw new RangeError(errors[type]);
14934 * A generic `Array#map` utility function.
14936 * @param {Array} array The array to iterate over.
14937 * @param {Function} callback The function that gets called for every array
14939 * @returns {Array} A new array of values returned by the callback function.
14941 function map(array, fn) {
14942 var length = array.length;
14945 result[length] = fn(array[length]);
14951 * A simple `Array#map`-like wrapper to work with domain name strings or email
14954 * @param {String} domain The domain name or email address.
14955 * @param {Function} callback The function that gets called for every
14957 * @returns {Array} A new string of characters returned by the callback
14960 function mapDomain(string, fn) {
14961 var parts = string.split('@');
14963 if (parts.length > 1) {
14964 // In email addresses, only the domain name should be punycoded. Leave
14965 // the local part (i.e. everything up to `@`) intact.
14966 result = parts[0] + '@';
14969 // Avoid `split(regex)` for IE8 compatibility. See #17.
14970 string = string.replace(regexSeparators, '\x2E');
14971 var labels = string.split('.');
14972 var encoded = map(labels, fn).join('.');
14973 return result + encoded;
14977 * Creates an array containing the numeric code points of each Unicode
14978 * character in the string. While JavaScript uses UCS-2 internally,
14979 * this function will convert a pair of surrogate halves (each of which
14980 * UCS-2 exposes as separate characters) into a single code point,
14982 * @see `punycode.ucs2.encode`
14983 * @see <https://mathiasbynens.be/notes/javascript-encoding>
14984 * @memberOf punycode.ucs2
14986 * @param {String} string The Unicode input string (UCS-2).
14987 * @returns {Array} The new array of code points.
14989 function ucs2decode(string) {
14992 length = string.length,
14995 while (counter < length) {
14996 value = string.charCodeAt(counter++);
14997 if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
14998 // high surrogate, and there is a next character
14999 extra = string.charCodeAt(counter++);
15000 if ((extra & 0xFC00) == 0xDC00) { // low surrogate
15001 output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
15003 // unmatched surrogate; only append this code unit, in case the next
15004 // code unit is the high surrogate of a surrogate pair
15005 output.push(value);
15009 output.push(value);
15016 * Creates a string based on an array of numeric code points.
15017 * @see `punycode.ucs2.decode`
15018 * @memberOf punycode.ucs2
15020 * @param {Array} codePoints The array of numeric code points.
15021 * @returns {String} The new Unicode string (UCS-2).
15023 function ucs2encode(array) {
15024 return map(array, function(value) {
15026 if (value > 0xFFFF) {
15028 output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
15029 value = 0xDC00 | value & 0x3FF;
15031 output += stringFromCharCode(value);
15037 * Converts a basic code point into a digit/integer.
15038 * @see `digitToBasic()`
15040 * @param {Number} codePoint The basic numeric code point value.
15041 * @returns {Number} The numeric value of a basic code point (for use in
15042 * representing integers) in the range `0` to `base - 1`, or `base` if
15043 * the code point does not represent a value.
15045 function basicToDigit(codePoint) {
15046 if (codePoint - 48 < 10) {
15047 return codePoint - 22;
15049 if (codePoint - 65 < 26) {
15050 return codePoint - 65;
15052 if (codePoint - 97 < 26) {
15053 return codePoint - 97;
15059 * Converts a digit/integer into a basic code point.
15060 * @see `basicToDigit()`
15062 * @param {Number} digit The numeric value of a basic code point.
15063 * @returns {Number} The basic code point whose value (when used for
15064 * representing integers) is `digit`, which needs to be in the range
15065 * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
15066 * used; else, the lowercase form is used. The behavior is undefined
15067 * if `flag` is non-zero and `digit` has no uppercase form.
15069 function digitToBasic(digit, flag) {
15070 // 0..25 map to ASCII a..z or A..Z
15071 // 26..35 map to ASCII 0..9
15072 return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
15076 * Bias adaptation function as per section 3.4 of RFC 3492.
15077 * https://tools.ietf.org/html/rfc3492#section-3.4
15080 function adapt(delta, numPoints, firstTime) {
15082 delta = firstTime ? floor(delta / damp) : delta >> 1;
15083 delta += floor(delta / numPoints);
15084 for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {
15085 delta = floor(delta / baseMinusTMin);
15087 return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
15091 * Converts a Punycode string of ASCII-only symbols to a string of Unicode
15093 * @memberOf punycode
15094 * @param {String} input The Punycode string of ASCII-only symbols.
15095 * @returns {String} The resulting string of Unicode symbols.
15097 function decode(input) {
15100 inputLength = input.length,
15104 bias = initialBias,
15113 /** Cached calculation results */
15116 // Handle the basic code points: let `basic` be the number of input code
15117 // points before the last delimiter, or `0` if there is none, then copy
15118 // the first basic code points to the output.
15120 basic = input.lastIndexOf(delimiter);
15125 for (j = 0; j < basic; ++j) {
15126 // if it's not a basic code point
15127 if (input.charCodeAt(j) >= 0x80) {
15128 error('not-basic');
15130 output.push(input.charCodeAt(j));
15133 // Main decoding loop: start just after the last delimiter if any basic code
15134 // points were copied; start at the beginning otherwise.
15136 for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) {
15138 // `index` is the index of the next character to be consumed.
15139 // Decode a generalized variable-length integer into `delta`,
15140 // which gets added to `i`. The overflow checking is easier
15141 // if we increase `i` as we go, then subtract off its starting
15142 // value at the end to obtain `delta`.
15143 for (oldi = i, w = 1, k = base; /* no condition */; k += base) {
15145 if (index >= inputLength) {
15146 error('invalid-input');
15149 digit = basicToDigit(input.charCodeAt(index++));
15151 if (digit >= base || digit > floor((maxInt - i) / w)) {
15156 t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
15162 baseMinusT = base - t;
15163 if (w > floor(maxInt / baseMinusT)) {
15171 out = output.length + 1;
15172 bias = adapt(i - oldi, out, oldi == 0);
15174 // `i` was supposed to wrap around from `out` to `0`,
15175 // incrementing `n` each time, so we'll fix that now:
15176 if (floor(i / out) > maxInt - n) {
15180 n += floor(i / out);
15183 // Insert `n` at position `i` of the output
15184 output.splice(i++, 0, n);
15188 return ucs2encode(output);
15192 * Converts a string of Unicode symbols (e.g. a domain name label) to a
15193 * Punycode string of ASCII-only symbols.
15194 * @memberOf punycode
15195 * @param {String} input The string of Unicode symbols.
15196 * @returns {String} The resulting Punycode string of ASCII-only symbols.
15198 function encode(input) {
15211 /** `inputLength` will hold the number of code points in `input`. */
15213 /** Cached calculation results */
15214 handledCPCountPlusOne,
15218 // Convert the input in UCS-2 to Unicode
15219 input = ucs2decode(input);
15221 // Cache the length
15222 inputLength = input.length;
15224 // Initialize the state
15227 bias = initialBias;
15229 // Handle the basic code points
15230 for (j = 0; j < inputLength; ++j) {
15231 currentValue = input[j];
15232 if (currentValue < 0x80) {
15233 output.push(stringFromCharCode(currentValue));
15237 handledCPCount = basicLength = output.length;
15239 // `handledCPCount` is the number of code points that have been handled;
15240 // `basicLength` is the number of basic code points.
15242 // Finish the basic string - if it is not empty - with a delimiter
15244 output.push(delimiter);
15247 // Main encoding loop:
15248 while (handledCPCount < inputLength) {
15250 // All non-basic code points < n have been handled already. Find the next
15252 for (m = maxInt, j = 0; j < inputLength; ++j) {
15253 currentValue = input[j];
15254 if (currentValue >= n && currentValue < m) {
15259 // Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,
15260 // but guard against overflow
15261 handledCPCountPlusOne = handledCPCount + 1;
15262 if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
15266 delta += (m - n) * handledCPCountPlusOne;
15269 for (j = 0; j < inputLength; ++j) {
15270 currentValue = input[j];
15272 if (currentValue < n && ++delta > maxInt) {
15276 if (currentValue == n) {
15277 // Represent delta as a generalized variable-length integer
15278 for (q = delta, k = base; /* no condition */; k += base) {
15279 t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
15284 baseMinusT = base - t;
15286 stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))
15288 q = floor(qMinusT / baseMinusT);
15291 output.push(stringFromCharCode(digitToBasic(q, 0)));
15292 bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
15302 return output.join('');
15306 * Converts a Punycode string representing a domain name or an email address
15307 * to Unicode. Only the Punycoded parts of the input will be converted, i.e.
15308 * it doesn't matter if you call it on a string that has already been
15309 * converted to Unicode.
15310 * @memberOf punycode
15311 * @param {String} input The Punycoded domain name or email address to
15312 * convert to Unicode.
15313 * @returns {String} The Unicode representation of the given Punycode
15316 function toUnicode(input) {
15317 return mapDomain(input, function(string) {
15318 return regexPunycode.test(string)
15319 ? decode(string.slice(4).toLowerCase())
15325 * Converts a Unicode string representing a domain name or an email address to
15326 * Punycode. Only the non-ASCII parts of the domain name will be converted,
15327 * i.e. it doesn't matter if you call it with a domain that's already in
15329 * @memberOf punycode
15330 * @param {String} input The domain name or email address to convert, as a
15332 * @returns {String} The Punycode representation of the given domain name or
15335 function toASCII(input) {
15336 return mapDomain(input, function(string) {
15337 return regexNonASCII.test(string)
15338 ? 'xn--' + encode(string)
15343 /*--------------------------------------------------------------------------*/
15345 /** Define the public API */
15348 * A string representing the current Punycode.js version number.
15349 * @memberOf punycode
15352 'version': '1.4.1',
15354 * An object of methods to convert from JavaScript's internal character
15355 * representation (UCS-2) to Unicode code points, and back.
15356 * @see <https://mathiasbynens.be/notes/javascript-encoding>
15357 * @memberOf punycode
15361 'decode': ucs2decode,
15362 'encode': ucs2encode
15366 'toASCII': toASCII,
15367 'toUnicode': toUnicode
15370 /** Expose `punycode` */
15371 // Some AMD build optimizers, like r.js, check for specific condition patterns
15372 // like the following:
15374 typeof define == 'function' &&
15375 typeof define.amd == 'object' &&
15378 define('punycode', function() {
15381 } else if (freeExports && freeModule) {
15382 if (module.exports == freeExports) {
15383 // in Node.js, io.js, or RingoJS v0.8.0+
15384 freeModule.exports = punycode;
15386 // in Narwhal or RingoJS v0.7.0-
15387 for (key in punycode) {
15388 punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]);
15392 // in Rhino or a web browser
15393 root.punycode = punycode;
15398 }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
15399 },{}],114:[function(require,module,exports){
15400 // Copyright Joyent, Inc. and other Node contributors.
15402 // Permission is hereby granted, free of charge, to any person obtaining a
15403 // copy of this software and associated documentation files (the
15404 // "Software"), to deal in the Software without restriction, including
15405 // without limitation the rights to use, copy, modify, merge, publish,
15406 // distribute, sublicense, and/or sell copies of the Software, and to permit
15407 // persons to whom the Software is furnished to do so, subject to the
15408 // following conditions:
15410 // The above copyright notice and this permission notice shall be included
15411 // in all copies or substantial portions of the Software.
15413 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15414 // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
15415 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
15416 // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
15417 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
15418 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
15419 // USE OR OTHER DEALINGS IN THE SOFTWARE.
15423 // If obj.hasOwnProperty has been overridden, then calling
15424 // obj.hasOwnProperty(prop) will break.
15425 // See: https://github.com/joyent/node/issues/1707
15426 function hasOwnProperty(obj, prop) {
15427 return Object.prototype.hasOwnProperty.call(obj, prop);
15430 module.exports = function(qs, sep, eq, options) {
15435 if (typeof qs !== 'string' || qs.length === 0) {
15439 var regexp = /\+/g;
15440 qs = qs.split(sep);
15442 var maxKeys = 1000;
15443 if (options && typeof options.maxKeys === 'number') {
15444 maxKeys = options.maxKeys;
15447 var len = qs.length;
15448 // maxKeys <= 0 means that we should not limit keys count
15449 if (maxKeys > 0 && len > maxKeys) {
15453 for (var i = 0; i < len; ++i) {
15454 var x = qs[i].replace(regexp, '%20'),
15455 idx = x.indexOf(eq),
15459 kstr = x.substr(0, idx);
15460 vstr = x.substr(idx + 1);
15466 k = decodeURIComponent(kstr);
15467 v = decodeURIComponent(vstr);
15469 if (!hasOwnProperty(obj, k)) {
15471 } else if (isArray(obj[k])) {
15474 obj[k] = [obj[k], v];
15481 var isArray = Array.isArray || function (xs) {
15482 return Object.prototype.toString.call(xs) === '[object Array]';
15485 },{}],115:[function(require,module,exports){
15486 // Copyright Joyent, Inc. and other Node contributors.
15488 // Permission is hereby granted, free of charge, to any person obtaining a
15489 // copy of this software and associated documentation files (the
15490 // "Software"), to deal in the Software without restriction, including
15491 // without limitation the rights to use, copy, modify, merge, publish,
15492 // distribute, sublicense, and/or sell copies of the Software, and to permit
15493 // persons to whom the Software is furnished to do so, subject to the
15494 // following conditions:
15496 // The above copyright notice and this permission notice shall be included
15497 // in all copies or substantial portions of the Software.
15499 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15500 // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
15501 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
15502 // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
15503 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
15504 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
15505 // USE OR OTHER DEALINGS IN THE SOFTWARE.
15509 var stringifyPrimitive = function(v) {
15510 switch (typeof v) {
15515 return v ? 'true' : 'false';
15518 return isFinite(v) ? v : '';
15525 module.exports = function(obj, sep, eq, name) {
15528 if (obj === null) {
15532 if (typeof obj === 'object') {
15533 return map(objectKeys(obj), function(k) {
15534 var ks = encodeURIComponent(stringifyPrimitive(k)) + eq;
15535 if (isArray(obj[k])) {
15536 return map(obj[k], function(v) {
15537 return ks + encodeURIComponent(stringifyPrimitive(v));
15540 return ks + encodeURIComponent(stringifyPrimitive(obj[k]));
15546 if (!name) return '';
15547 return encodeURIComponent(stringifyPrimitive(name)) + eq +
15548 encodeURIComponent(stringifyPrimitive(obj));
15551 var isArray = Array.isArray || function (xs) {
15552 return Object.prototype.toString.call(xs) === '[object Array]';
15555 function map (xs, f) {
15556 if (xs.map) return xs.map(f);
15558 for (var i = 0; i < xs.length; i++) {
15559 res.push(f(xs[i], i));
15564 var objectKeys = Object.keys || function (obj) {
15566 for (var key in obj) {
15567 if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key);
15572 },{}],116:[function(require,module,exports){
15575 exports.decode = exports.parse = require('./decode');
15576 exports.encode = exports.stringify = require('./encode');
15578 },{"./decode":114,"./encode":115}],117:[function(require,module,exports){
15579 // Copyright Joyent, Inc. and other Node contributors.
15581 // Permission is hereby granted, free of charge, to any person obtaining a
15582 // copy of this software and associated documentation files (the
15583 // "Software"), to deal in the Software without restriction, including
15584 // without limitation the rights to use, copy, modify, merge, publish,
15585 // distribute, sublicense, and/or sell copies of the Software, and to permit
15586 // persons to whom the Software is furnished to do so, subject to the
15587 // following conditions:
15589 // The above copyright notice and this permission notice shall be included
15590 // in all copies or substantial portions of the Software.
15592 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15593 // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
15594 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
15595 // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
15596 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
15597 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
15598 // USE OR OTHER DEALINGS IN THE SOFTWARE.
15600 // a duplex stream is just a stream that is both readable and writable.
15601 // Since JS doesn't have multiple prototypal inheritance, this class
15602 // prototypally inherits from Readable, and then parasitically from
15609 var pna = require('process-nextick-args');
15613 var objectKeys = Object.keys || function (obj) {
15615 for (var key in obj) {
15621 module.exports = Duplex;
15624 var util = require('core-util-is');
15625 util.inherits = require('inherits');
15628 var Readable = require('./_stream_readable');
15629 var Writable = require('./_stream_writable');
15631 util.inherits(Duplex, Readable);
15634 // avoid scope creep, the keys array can then be collected
15635 var keys = objectKeys(Writable.prototype);
15636 for (var v = 0; v < keys.length; v++) {
15637 var method = keys[v];
15638 if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
15642 function Duplex(options) {
15643 if (!(this instanceof Duplex)) return new Duplex(options);
15645 Readable.call(this, options);
15646 Writable.call(this, options);
15648 if (options && options.readable === false) this.readable = false;
15650 if (options && options.writable === false) this.writable = false;
15652 this.allowHalfOpen = true;
15653 if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;
15655 this.once('end', onend);
15658 Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', {
15659 // making it explicit this property is not enumerable
15660 // because otherwise some prototype manipulation in
15661 // userland will fail
15664 return this._writableState.highWaterMark;
15668 // the no-half-open enforcer
15670 // if we allow half-open state, or if the writable side ended,
15672 if (this.allowHalfOpen || this._writableState.ended) return;
15674 // no more data can be written.
15675 // But allow more writes to happen in this tick.
15676 pna.nextTick(onEndNT, this);
15679 function onEndNT(self) {
15683 Object.defineProperty(Duplex.prototype, 'destroyed', {
15685 if (this._readableState === undefined || this._writableState === undefined) {
15688 return this._readableState.destroyed && this._writableState.destroyed;
15690 set: function (value) {
15691 // we ignore the value if the stream
15692 // has not been initialized yet
15693 if (this._readableState === undefined || this._writableState === undefined) {
15697 // backward compatibility, the user is explicitly
15698 // managing destroyed
15699 this._readableState.destroyed = value;
15700 this._writableState.destroyed = value;
15704 Duplex.prototype._destroy = function (err, cb) {
15708 pna.nextTick(cb, err);
15710 },{"./_stream_readable":119,"./_stream_writable":121,"core-util-is":101,"inherits":106,"process-nextick-args":111}],118:[function(require,module,exports){
15711 // Copyright Joyent, Inc. and other Node contributors.
15713 // Permission is hereby granted, free of charge, to any person obtaining a
15714 // copy of this software and associated documentation files (the
15715 // "Software"), to deal in the Software without restriction, including
15716 // without limitation the rights to use, copy, modify, merge, publish,
15717 // distribute, sublicense, and/or sell copies of the Software, and to permit
15718 // persons to whom the Software is furnished to do so, subject to the
15719 // following conditions:
15721 // The above copyright notice and this permission notice shall be included
15722 // in all copies or substantial portions of the Software.
15724 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15725 // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
15726 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
15727 // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
15728 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
15729 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
15730 // USE OR OTHER DEALINGS IN THE SOFTWARE.
15732 // a passthrough stream.
15733 // basically just the most minimal sort of Transform stream.
15734 // Every written chunk gets output as-is.
15738 module.exports = PassThrough;
15740 var Transform = require('./_stream_transform');
15743 var util = require('core-util-is');
15744 util.inherits = require('inherits');
15747 util.inherits(PassThrough, Transform);
15749 function PassThrough(options) {
15750 if (!(this instanceof PassThrough)) return new PassThrough(options);
15752 Transform.call(this, options);
15755 PassThrough.prototype._transform = function (chunk, encoding, cb) {
15758 },{"./_stream_transform":120,"core-util-is":101,"inherits":106}],119:[function(require,module,exports){
15759 (function (process,global){
15760 // Copyright Joyent, Inc. and other Node contributors.
15762 // Permission is hereby granted, free of charge, to any person obtaining a
15763 // copy of this software and associated documentation files (the
15764 // "Software"), to deal in the Software without restriction, including
15765 // without limitation the rights to use, copy, modify, merge, publish,
15766 // distribute, sublicense, and/or sell copies of the Software, and to permit
15767 // persons to whom the Software is furnished to do so, subject to the
15768 // following conditions:
15770 // The above copyright notice and this permission notice shall be included
15771 // in all copies or substantial portions of the Software.
15773 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15774 // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
15775 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
15776 // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
15777 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
15778 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
15779 // USE OR OTHER DEALINGS IN THE SOFTWARE.
15785 var pna = require('process-nextick-args');
15788 module.exports = Readable;
15791 var isArray = require('isarray');
15798 Readable.ReadableState = ReadableState;
15801 var EE = require('events').EventEmitter;
15803 var EElistenerCount = function (emitter, type) {
15804 return emitter.listeners(type).length;
15809 var Stream = require('./internal/streams/stream');
15814 var Buffer = require('safe-buffer').Buffer;
15815 var OurUint8Array = global.Uint8Array || function () {};
15816 function _uint8ArrayToBuffer(chunk) {
15817 return Buffer.from(chunk);
15819 function _isUint8Array(obj) {
15820 return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
15826 var util = require('core-util-is');
15827 util.inherits = require('inherits');
15831 var debugUtil = require('util');
15832 var debug = void 0;
15833 if (debugUtil && debugUtil.debuglog) {
15834 debug = debugUtil.debuglog('stream');
15836 debug = function () {};
15840 var BufferList = require('./internal/streams/BufferList');
15841 var destroyImpl = require('./internal/streams/destroy');
15844 util.inherits(Readable, Stream);
15846 var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];
15848 function prependListener(emitter, event, fn) {
15849 // Sadly this is not cacheable as some libraries bundle their own
15850 // event emitter implementation with them.
15851 if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn);
15853 // This is a hack to make sure that our error handler is attached before any
15854 // userland ones. NEVER DO THIS. This is here only because this code needs
15855 // to continue to work with older versions of Node.js that do not include
15856 // the prependListener() method. The goal is to eventually remove this hack.
15857 if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]];
15860 function ReadableState(options, stream) {
15861 Duplex = Duplex || require('./_stream_duplex');
15863 options = options || {};
15865 // Duplex streams are both readable and writable, but share
15866 // the same options object.
15867 // However, some cases require setting options to different
15868 // values for the readable and the writable sides of the duplex stream.
15869 // These options can be provided separately as readableXXX and writableXXX.
15870 var isDuplex = stream instanceof Duplex;
15872 // object stream flag. Used to make read(n) ignore n and to
15873 // make all the buffer merging and length checks go away
15874 this.objectMode = !!options.objectMode;
15876 if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode;
15878 // the point at which it stops calling _read() to fill the buffer
15879 // Note: 0 is a valid value, means "don't call _read preemptively ever"
15880 var hwm = options.highWaterMark;
15881 var readableHwm = options.readableHighWaterMark;
15882 var defaultHwm = this.objectMode ? 16 : 16 * 1024;
15884 if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm;
15887 this.highWaterMark = Math.floor(this.highWaterMark);
15889 // A linked list is used to store data chunks instead of an array because the
15890 // linked list can remove elements from the beginning faster than
15892 this.buffer = new BufferList();
15895 this.pipesCount = 0;
15896 this.flowing = null;
15897 this.ended = false;
15898 this.endEmitted = false;
15899 this.reading = false;
15901 // a flag to be able to tell if the event 'readable'/'data' is emitted
15902 // immediately, or on a later tick. We set this to true at first, because
15903 // any actions that shouldn't happen until "later" should generally also
15904 // not happen before the first read call.
15907 // whenever we return null, then we set a flag to say
15908 // that we're awaiting a 'readable' event emission.
15909 this.needReadable = false;
15910 this.emittedReadable = false;
15911 this.readableListening = false;
15912 this.resumeScheduled = false;
15914 // has it been destroyed
15915 this.destroyed = false;
15917 // Crypto is kind of old and crusty. Historically, its default string
15918 // encoding is 'binary' so we have to make this configurable.
15919 // Everything else in the universe uses 'utf8', though.
15920 this.defaultEncoding = options.defaultEncoding || 'utf8';
15922 // the number of writers that are awaiting a drain event in .pipe()s
15923 this.awaitDrain = 0;
15925 // if true, a maybeReadMore has been scheduled
15926 this.readingMore = false;
15928 this.decoder = null;
15929 this.encoding = null;
15930 if (options.encoding) {
15931 if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
15932 this.decoder = new StringDecoder(options.encoding);
15933 this.encoding = options.encoding;
15937 function Readable(options) {
15938 Duplex = Duplex || require('./_stream_duplex');
15940 if (!(this instanceof Readable)) return new Readable(options);
15942 this._readableState = new ReadableState(options, this);
15945 this.readable = true;
15948 if (typeof options.read === 'function') this._read = options.read;
15950 if (typeof options.destroy === 'function') this._destroy = options.destroy;
15956 Object.defineProperty(Readable.prototype, 'destroyed', {
15958 if (this._readableState === undefined) {
15961 return this._readableState.destroyed;
15963 set: function (value) {
15964 // we ignore the value if the stream
15965 // has not been initialized yet
15966 if (!this._readableState) {
15970 // backward compatibility, the user is explicitly
15971 // managing destroyed
15972 this._readableState.destroyed = value;
15976 Readable.prototype.destroy = destroyImpl.destroy;
15977 Readable.prototype._undestroy = destroyImpl.undestroy;
15978 Readable.prototype._destroy = function (err, cb) {
15983 // Manually shove something into the read() buffer.
15984 // This returns true if the highWaterMark has not been hit yet,
15985 // similar to how Writable.write() returns true if you should
15986 // write() some more.
15987 Readable.prototype.push = function (chunk, encoding) {
15988 var state = this._readableState;
15989 var skipChunkCheck;
15991 if (!state.objectMode) {
15992 if (typeof chunk === 'string') {
15993 encoding = encoding || state.defaultEncoding;
15994 if (encoding !== state.encoding) {
15995 chunk = Buffer.from(chunk, encoding);
15998 skipChunkCheck = true;
16001 skipChunkCheck = true;
16004 return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);
16007 // Unshift should *always* be something directly out of read()
16008 Readable.prototype.unshift = function (chunk) {
16009 return readableAddChunk(this, chunk, null, true, false);
16012 function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {
16013 var state = stream._readableState;
16014 if (chunk === null) {
16015 state.reading = false;
16016 onEofChunk(stream, state);
16019 if (!skipChunkCheck) er = chunkInvalid(state, chunk);
16021 stream.emit('error', er);
16022 } else if (state.objectMode || chunk && chunk.length > 0) {
16023 if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {
16024 chunk = _uint8ArrayToBuffer(chunk);
16028 if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true);
16029 } else if (state.ended) {
16030 stream.emit('error', new Error('stream.push() after EOF'));
16032 state.reading = false;
16033 if (state.decoder && !encoding) {
16034 chunk = state.decoder.write(chunk);
16035 if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);
16037 addChunk(stream, state, chunk, false);
16040 } else if (!addToFront) {
16041 state.reading = false;
16045 return needMoreData(state);
16048 function addChunk(stream, state, chunk, addToFront) {
16049 if (state.flowing && state.length === 0 && !state.sync) {
16050 stream.emit('data', chunk);
16053 // update the buffer info.
16054 state.length += state.objectMode ? 1 : chunk.length;
16055 if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
16057 if (state.needReadable) emitReadable(stream);
16059 maybeReadMore(stream, state);
16062 function chunkInvalid(state, chunk) {
16064 if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
16065 er = new TypeError('Invalid non-string/buffer chunk');
16070 // if it's past the high water mark, we can push in some more.
16071 // Also, if we have no data yet, we can stand some
16072 // more bytes. This is to work around cases where hwm=0,
16073 // such as the repl. Also, if the push() triggered a
16074 // readable event, and the user called read(largeNumber) such that
16075 // needReadable was set, then we ought to push more, so that another
16076 // 'readable' event will be triggered.
16077 function needMoreData(state) {
16078 return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0);
16081 Readable.prototype.isPaused = function () {
16082 return this._readableState.flowing === false;
16085 // backwards compatibility.
16086 Readable.prototype.setEncoding = function (enc) {
16087 if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
16088 this._readableState.decoder = new StringDecoder(enc);
16089 this._readableState.encoding = enc;
16093 // Don't raise the hwm > 8MB
16094 var MAX_HWM = 0x800000;
16095 function computeNewHighWaterMark(n) {
16096 if (n >= MAX_HWM) {
16099 // Get the next highest power of 2 to prevent increasing hwm excessively in
16112 // This function is designed to be inlinable, so please take care when making
16113 // changes to the function body.
16114 function howMuchToRead(n, state) {
16115 if (n <= 0 || state.length === 0 && state.ended) return 0;
16116 if (state.objectMode) return 1;
16118 // Only flow one buffer at a time
16119 if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
16121 // If we're asking for more than the current hwm, then raise the hwm.
16122 if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
16123 if (n <= state.length) return n;
16124 // Don't have enough
16125 if (!state.ended) {
16126 state.needReadable = true;
16129 return state.length;
16132 // you can override either this method, or the async _read(n) below.
16133 Readable.prototype.read = function (n) {
16135 n = parseInt(n, 10);
16136 var state = this._readableState;
16139 if (n !== 0) state.emittedReadable = false;
16141 // if we're doing read(0) to trigger a readable event, but we
16142 // already have a bunch of data in the buffer, then just trigger
16143 // the 'readable' event and move on.
16144 if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) {
16145 debug('read: emitReadable', state.length, state.ended);
16146 if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
16150 n = howMuchToRead(n, state);
16152 // if we've ended, and we're now clear, then finish it up.
16153 if (n === 0 && state.ended) {
16154 if (state.length === 0) endReadable(this);
16158 // All the actual chunk generation logic needs to be
16159 // *below* the call to _read. The reason is that in certain
16160 // synthetic stream cases, such as passthrough streams, _read
16161 // may be a completely synchronous operation which may change
16162 // the state of the read buffer, providing enough data when
16163 // before there was *not* enough.
16165 // So, the steps are:
16166 // 1. Figure out what the state of things will be after we do
16167 // a read from the buffer.
16169 // 2. If that resulting state will trigger a _read, then call _read.
16170 // Note that this may be asynchronous, or synchronous. Yes, it is
16171 // deeply ugly to write APIs this way, but that still doesn't mean
16172 // that the Readable class should behave improperly, as streams are
16173 // designed to be sync/async agnostic.
16174 // Take note if the _read call is sync or async (ie, if the read call
16175 // has returned yet), so that we know whether or not it's safe to emit
16178 // 3. Actually pull the requested chunks out of the buffer and return.
16180 // if we need a readable event, then we need to do some reading.
16181 var doRead = state.needReadable;
16182 debug('need readable', doRead);
16184 // if we currently have less than the highWaterMark, then also read some
16185 if (state.length === 0 || state.length - n < state.highWaterMark) {
16187 debug('length less than watermark', doRead);
16190 // however, if we've ended, then there's no point, and if we're already
16191 // reading, then it's unnecessary.
16192 if (state.ended || state.reading) {
16194 debug('reading or ended', doRead);
16195 } else if (doRead) {
16197 state.reading = true;
16199 // if the length is currently zero, then we *need* a readable event.
16200 if (state.length === 0) state.needReadable = true;
16201 // call internal read method
16202 this._read(state.highWaterMark);
16203 state.sync = false;
16204 // If _read pushed data synchronously, then `reading` will be false,
16205 // and we need to re-evaluate how much data we can return to the user.
16206 if (!state.reading) n = howMuchToRead(nOrig, state);
16210 if (n > 0) ret = fromList(n, state);else ret = null;
16212 if (ret === null) {
16213 state.needReadable = true;
16219 if (state.length === 0) {
16220 // If we have nothing in the buffer, then we want to know
16221 // as soon as we *do* get something into the buffer.
16222 if (!state.ended) state.needReadable = true;
16224 // If we tried to read() past the EOF, then emit end on the next tick.
16225 if (nOrig !== n && state.ended) endReadable(this);
16228 if (ret !== null) this.emit('data', ret);
16233 function onEofChunk(stream, state) {
16234 if (state.ended) return;
16235 if (state.decoder) {
16236 var chunk = state.decoder.end();
16237 if (chunk && chunk.length) {
16238 state.buffer.push(chunk);
16239 state.length += state.objectMode ? 1 : chunk.length;
16242 state.ended = true;
16244 // emit 'readable' now to make sure it gets picked up.
16245 emitReadable(stream);
16248 // Don't emit readable right away in sync mode, because this can trigger
16249 // another read() call => stack overflow. This way, it might trigger
16250 // a nextTick recursion warning, but that's not so bad.
16251 function emitReadable(stream) {
16252 var state = stream._readableState;
16253 state.needReadable = false;
16254 if (!state.emittedReadable) {
16255 debug('emitReadable', state.flowing);
16256 state.emittedReadable = true;
16257 if (state.sync) pna.nextTick(emitReadable_, stream);else emitReadable_(stream);
16261 function emitReadable_(stream) {
16262 debug('emit readable');
16263 stream.emit('readable');
16267 // at this point, the user has presumably seen the 'readable' event,
16268 // and called read() to consume some data. that may have triggered
16269 // in turn another _read(n) call, in which case reading = true if
16270 // it's in progress.
16271 // However, if we're not ended, or reading, and the length < hwm,
16272 // then go ahead and try to read some more preemptively.
16273 function maybeReadMore(stream, state) {
16274 if (!state.readingMore) {
16275 state.readingMore = true;
16276 pna.nextTick(maybeReadMore_, stream, state);
16280 function maybeReadMore_(stream, state) {
16281 var len = state.length;
16282 while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) {
16283 debug('maybeReadMore read 0');
16285 if (len === state.length)
16286 // didn't get any data, stop spinning.
16287 break;else len = state.length;
16289 state.readingMore = false;
16292 // abstract method. to be overridden in specific implementation classes.
16293 // call cb(er, data) where data is <= n in length.
16294 // for virtual (non-string, non-buffer) streams, "length" is somewhat
16295 // arbitrary, and perhaps not very meaningful.
16296 Readable.prototype._read = function (n) {
16297 this.emit('error', new Error('_read() is not implemented'));
16300 Readable.prototype.pipe = function (dest, pipeOpts) {
16302 var state = this._readableState;
16304 switch (state.pipesCount) {
16306 state.pipes = dest;
16309 state.pipes = [state.pipes, dest];
16312 state.pipes.push(dest);
16315 state.pipesCount += 1;
16316 debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
16318 var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
16320 var endFn = doEnd ? onend : unpipe;
16321 if (state.endEmitted) pna.nextTick(endFn);else src.once('end', endFn);
16323 dest.on('unpipe', onunpipe);
16324 function onunpipe(readable, unpipeInfo) {
16326 if (readable === src) {
16327 if (unpipeInfo && unpipeInfo.hasUnpiped === false) {
16328 unpipeInfo.hasUnpiped = true;
16339 // when the dest drains, it reduces the awaitDrain counter
16340 // on the source. This would be more elegant with a .once()
16341 // handler in flow(), but adding and removing repeatedly is
16343 var ondrain = pipeOnDrain(src);
16344 dest.on('drain', ondrain);
16346 var cleanedUp = false;
16347 function cleanup() {
16349 // cleanup event handlers once the pipe is broken
16350 dest.removeListener('close', onclose);
16351 dest.removeListener('finish', onfinish);
16352 dest.removeListener('drain', ondrain);
16353 dest.removeListener('error', onerror);
16354 dest.removeListener('unpipe', onunpipe);
16355 src.removeListener('end', onend);
16356 src.removeListener('end', unpipe);
16357 src.removeListener('data', ondata);
16361 // if the reader is waiting for a drain event from this
16362 // specific writer, then it would cause it to never start
16364 // So, if this is awaiting a drain, then we just call it now.
16365 // If we don't know, then assume that we are waiting for one.
16366 if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
16369 // If the user pushes more data while we're writing to dest then we'll end up
16370 // in ondata again. However, we only want to increase awaitDrain once because
16371 // dest will only emit one 'drain' event for the multiple writes.
16372 // => Introduce a guard on increasing awaitDrain.
16373 var increasedAwaitDrain = false;
16374 src.on('data', ondata);
16375 function ondata(chunk) {
16377 increasedAwaitDrain = false;
16378 var ret = dest.write(chunk);
16379 if (false === ret && !increasedAwaitDrain) {
16380 // If the user unpiped during `dest.write()`, it is possible
16381 // to get stuck in a permanently paused state if that write
16382 // also returned false.
16383 // => Check whether `dest` is still a piping destination.
16384 if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
16385 debug('false write response, pause', src._readableState.awaitDrain);
16386 src._readableState.awaitDrain++;
16387 increasedAwaitDrain = true;
16393 // if the dest has an error, then stop piping into it.
16394 // however, don't suppress the throwing behavior for this.
16395 function onerror(er) {
16396 debug('onerror', er);
16398 dest.removeListener('error', onerror);
16399 if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er);
16402 // Make sure our error handler is attached before userland ones.
16403 prependListener(dest, 'error', onerror);
16405 // Both close and finish should trigger unpipe, but only once.
16406 function onclose() {
16407 dest.removeListener('finish', onfinish);
16410 dest.once('close', onclose);
16411 function onfinish() {
16413 dest.removeListener('close', onclose);
16416 dest.once('finish', onfinish);
16418 function unpipe() {
16423 // tell the dest that it's being piped to
16424 dest.emit('pipe', src);
16426 // start the flow if it hasn't been started already.
16427 if (!state.flowing) {
16428 debug('pipe resume');
16435 function pipeOnDrain(src) {
16436 return function () {
16437 var state = src._readableState;
16438 debug('pipeOnDrain', state.awaitDrain);
16439 if (state.awaitDrain) state.awaitDrain--;
16440 if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
16441 state.flowing = true;
16447 Readable.prototype.unpipe = function (dest) {
16448 var state = this._readableState;
16449 var unpipeInfo = { hasUnpiped: false };
16451 // if we're not piping anywhere, then do nothing.
16452 if (state.pipesCount === 0) return this;
16454 // just one destination. most common case.
16455 if (state.pipesCount === 1) {
16456 // passed in one, but it's not the right one.
16457 if (dest && dest !== state.pipes) return this;
16459 if (!dest) dest = state.pipes;
16462 state.pipes = null;
16463 state.pipesCount = 0;
16464 state.flowing = false;
16465 if (dest) dest.emit('unpipe', this, unpipeInfo);
16469 // slow case. multiple pipe destinations.
16473 var dests = state.pipes;
16474 var len = state.pipesCount;
16475 state.pipes = null;
16476 state.pipesCount = 0;
16477 state.flowing = false;
16479 for (var i = 0; i < len; i++) {
16480 dests[i].emit('unpipe', this, unpipeInfo);
16484 // try to find the right one.
16485 var index = indexOf(state.pipes, dest);
16486 if (index === -1) return this;
16488 state.pipes.splice(index, 1);
16489 state.pipesCount -= 1;
16490 if (state.pipesCount === 1) state.pipes = state.pipes[0];
16492 dest.emit('unpipe', this, unpipeInfo);
16497 // set up data events if they are asked for
16498 // Ensure readable listeners eventually get something
16499 Readable.prototype.on = function (ev, fn) {
16500 var res = Stream.prototype.on.call(this, ev, fn);
16502 if (ev === 'data') {
16503 // Start flowing on next tick if stream isn't explicitly paused
16504 if (this._readableState.flowing !== false) this.resume();
16505 } else if (ev === 'readable') {
16506 var state = this._readableState;
16507 if (!state.endEmitted && !state.readableListening) {
16508 state.readableListening = state.needReadable = true;
16509 state.emittedReadable = false;
16510 if (!state.reading) {
16511 pna.nextTick(nReadingNextTick, this);
16512 } else if (state.length) {
16513 emitReadable(this);
16520 Readable.prototype.addListener = Readable.prototype.on;
16522 function nReadingNextTick(self) {
16523 debug('readable nexttick read 0');
16527 // pause() and resume() are remnants of the legacy readable stream API
16528 // If the user uses them, then switch into old mode.
16529 Readable.prototype.resume = function () {
16530 var state = this._readableState;
16531 if (!state.flowing) {
16533 state.flowing = true;
16534 resume(this, state);
16539 function resume(stream, state) {
16540 if (!state.resumeScheduled) {
16541 state.resumeScheduled = true;
16542 pna.nextTick(resume_, stream, state);
16546 function resume_(stream, state) {
16547 if (!state.reading) {
16548 debug('resume read 0');
16552 state.resumeScheduled = false;
16553 state.awaitDrain = 0;
16554 stream.emit('resume');
16556 if (state.flowing && !state.reading) stream.read(0);
16559 Readable.prototype.pause = function () {
16560 debug('call pause flowing=%j', this._readableState.flowing);
16561 if (false !== this._readableState.flowing) {
16563 this._readableState.flowing = false;
16564 this.emit('pause');
16569 function flow(stream) {
16570 var state = stream._readableState;
16571 debug('flow', state.flowing);
16572 while (state.flowing && stream.read() !== null) {}
16575 // wrap an old-style stream as the async data source.
16576 // This is *not* part of the readable stream interface.
16577 // It is an ugly unfortunate mess of history.
16578 Readable.prototype.wrap = function (stream) {
16581 var state = this._readableState;
16582 var paused = false;
16584 stream.on('end', function () {
16585 debug('wrapped end');
16586 if (state.decoder && !state.ended) {
16587 var chunk = state.decoder.end();
16588 if (chunk && chunk.length) _this.push(chunk);
16594 stream.on('data', function (chunk) {
16595 debug('wrapped data');
16596 if (state.decoder) chunk = state.decoder.write(chunk);
16598 // don't skip over falsy values in objectMode
16599 if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
16601 var ret = _this.push(chunk);
16608 // proxy all the other methods.
16609 // important when wrapping filters and duplexes.
16610 for (var i in stream) {
16611 if (this[i] === undefined && typeof stream[i] === 'function') {
16612 this[i] = function (method) {
16613 return function () {
16614 return stream[method].apply(stream, arguments);
16620 // proxy certain important events.
16621 for (var n = 0; n < kProxyEvents.length; n++) {
16622 stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));
16625 // when we try to consume some more bytes, simply unpause the
16626 // underlying stream.
16627 this._read = function (n) {
16628 debug('wrapped _read', n);
16638 Object.defineProperty(Readable.prototype, 'readableHighWaterMark', {
16639 // making it explicit this property is not enumerable
16640 // because otherwise some prototype manipulation in
16641 // userland will fail
16644 return this._readableState.highWaterMark;
16648 // exposed for testing purposes only.
16649 Readable._fromList = fromList;
16651 // Pluck off n bytes from an array of buffers.
16652 // Length is the combined lengths of all the buffers in the list.
16653 // This function is designed to be inlinable, so please take care when making
16654 // changes to the function body.
16655 function fromList(n, state) {
16656 // nothing buffered
16657 if (state.length === 0) return null;
16660 if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
16661 // read it all, truncate the list
16662 if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length);
16663 state.buffer.clear();
16665 // read part of list
16666 ret = fromListPartial(n, state.buffer, state.decoder);
16672 // Extracts only enough buffered data to satisfy the amount requested.
16673 // This function is designed to be inlinable, so please take care when making
16674 // changes to the function body.
16675 function fromListPartial(n, list, hasStrings) {
16677 if (n < list.head.data.length) {
16678 // slice is the same for buffers and strings
16679 ret = list.head.data.slice(0, n);
16680 list.head.data = list.head.data.slice(n);
16681 } else if (n === list.head.data.length) {
16682 // first chunk is a perfect match
16683 ret = list.shift();
16685 // result spans more than one buffer
16686 ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list);
16691 // Copies a specified amount of characters from the list of buffered data
16693 // This function is designed to be inlinable, so please take care when making
16694 // changes to the function body.
16695 function copyFromBufferString(n, list) {
16700 while (p = p.next) {
16702 var nb = n > str.length ? str.length : n;
16703 if (nb === str.length) ret += str;else ret += str.slice(0, n);
16706 if (nb === str.length) {
16708 if (p.next) list.head = p.next;else list.head = list.tail = null;
16711 p.data = str.slice(nb);
16721 // Copies a specified amount of bytes from the list of buffered data chunks.
16722 // This function is designed to be inlinable, so please take care when making
16723 // changes to the function body.
16724 function copyFromBuffer(n, list) {
16725 var ret = Buffer.allocUnsafe(n);
16729 n -= p.data.length;
16730 while (p = p.next) {
16732 var nb = n > buf.length ? buf.length : n;
16733 buf.copy(ret, ret.length - n, 0, nb);
16736 if (nb === buf.length) {
16738 if (p.next) list.head = p.next;else list.head = list.tail = null;
16741 p.data = buf.slice(nb);
16751 function endReadable(stream) {
16752 var state = stream._readableState;
16754 // If we get here before consuming all the bytes, then that is a
16755 // bug in node. Should never happen.
16756 if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream');
16758 if (!state.endEmitted) {
16759 state.ended = true;
16760 pna.nextTick(endReadableNT, state, stream);
16764 function endReadableNT(state, stream) {
16765 // Check that we didn't get one last unshift.
16766 if (!state.endEmitted && state.length === 0) {
16767 state.endEmitted = true;
16768 stream.readable = false;
16769 stream.emit('end');
16773 function indexOf(xs, x) {
16774 for (var i = 0, l = xs.length; i < l; i++) {
16775 if (xs[i] === x) return i;
16779 }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
16780 },{"./_stream_duplex":117,"./internal/streams/BufferList":122,"./internal/streams/destroy":123,"./internal/streams/stream":124,"_process":112,"core-util-is":101,"events":102,"inherits":106,"isarray":108,"process-nextick-args":111,"safe-buffer":143,"string_decoder/":159,"util":2}],120:[function(require,module,exports){
16781 // Copyright Joyent, Inc. and other Node contributors.
16783 // Permission is hereby granted, free of charge, to any person obtaining a
16784 // copy of this software and associated documentation files (the
16785 // "Software"), to deal in the Software without restriction, including
16786 // without limitation the rights to use, copy, modify, merge, publish,
16787 // distribute, sublicense, and/or sell copies of the Software, and to permit
16788 // persons to whom the Software is furnished to do so, subject to the
16789 // following conditions:
16791 // The above copyright notice and this permission notice shall be included
16792 // in all copies or substantial portions of the Software.
16794 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
16795 // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16796 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
16797 // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
16798 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
16799 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
16800 // USE OR OTHER DEALINGS IN THE SOFTWARE.
16802 // a transform stream is a readable/writable stream where you do
16803 // something with the data. Sometimes it's called a "filter",
16804 // but that's not a great name for it, since that implies a thing where
16805 // some bits pass through, and others are simply ignored. (That would
16806 // be a valid example of a transform, of course.)
16808 // While the output is causally related to the input, it's not a
16809 // necessarily symmetric or synchronous transformation. For example,
16810 // a zlib stream might take multiple plain-text writes(), and then
16811 // emit a single compressed chunk some time in the future.
16813 // Here's how this works:
16815 // The Transform stream has all the aspects of the readable and writable
16816 // stream classes. When you write(chunk), that calls _write(chunk,cb)
16817 // internally, and returns false if there's a lot of pending writes
16818 // buffered up. When you call read(), that calls _read(n) until
16819 // there's enough pending readable data buffered up.
16821 // In a transform stream, the written data is placed in a buffer. When
16822 // _read(n) is called, it transforms the queued up data, calling the
16823 // buffered _write cb's as it consumes chunks. If consuming a single
16824 // written chunk would result in multiple output chunks, then the first
16825 // outputted bit calls the readcb, and subsequent chunks just go into
16826 // the read buffer, and will cause it to emit 'readable' if necessary.
16828 // This way, back-pressure is actually determined by the reading side,
16829 // since _read has to be called to start processing a new chunk. However,
16830 // a pathological inflate type of transform can cause excessive buffering
16831 // here. For example, imagine a stream where every byte of input is
16832 // interpreted as an integer from 0-255, and then results in that many
16833 // bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
16834 // 1kb of data being output. In this case, you could write a very small
16835 // amount of input, and end up with a very large amount of output. In
16836 // such a pathological inflating mechanism, there'd be no way to tell
16837 // the system to stop doing the transform. A single 4MB write could
16838 // cause the system to run out of memory.
16840 // However, even in such a pathological case, only a single written chunk
16841 // would be consumed, and then the rest would wait (un-transformed) until
16842 // the results of the previous transformed chunk were consumed.
16846 module.exports = Transform;
16848 var Duplex = require('./_stream_duplex');
16851 var util = require('core-util-is');
16852 util.inherits = require('inherits');
16855 util.inherits(Transform, Duplex);
16857 function afterTransform(er, data) {
16858 var ts = this._transformState;
16859 ts.transforming = false;
16861 var cb = ts.writecb;
16864 return this.emit('error', new Error('write callback called multiple times'));
16867 ts.writechunk = null;
16870 if (data != null) // single equals check for both `null` and `undefined`
16875 var rs = this._readableState;
16876 rs.reading = false;
16877 if (rs.needReadable || rs.length < rs.highWaterMark) {
16878 this._read(rs.highWaterMark);
16882 function Transform(options) {
16883 if (!(this instanceof Transform)) return new Transform(options);
16885 Duplex.call(this, options);
16887 this._transformState = {
16888 afterTransform: afterTransform.bind(this),
16889 needTransform: false,
16890 transforming: false,
16893 writeencoding: null
16896 // start out asking for a readable event once data is transformed.
16897 this._readableState.needReadable = true;
16899 // we have implemented the _read method, and done the other things
16900 // that Readable wants before the first _read call, so unset the
16901 // sync guard flag.
16902 this._readableState.sync = false;
16905 if (typeof options.transform === 'function') this._transform = options.transform;
16907 if (typeof options.flush === 'function') this._flush = options.flush;
16910 // When the writable side finishes, then flush out anything remaining.
16911 this.on('prefinish', prefinish);
16914 function prefinish() {
16917 if (typeof this._flush === 'function') {
16918 this._flush(function (er, data) {
16919 done(_this, er, data);
16922 done(this, null, null);
16926 Transform.prototype.push = function (chunk, encoding) {
16927 this._transformState.needTransform = false;
16928 return Duplex.prototype.push.call(this, chunk, encoding);
16931 // This is the part where you do stuff!
16932 // override this function in implementation classes.
16933 // 'chunk' is an input chunk.
16935 // Call `push(newChunk)` to pass along transformed output
16936 // to the readable side. You may call 'push' zero or more times.
16938 // Call `cb(err)` when you are done with this chunk. If you pass
16939 // an error, then that'll put the hurt on the whole operation. If you
16940 // never call cb(), then you'll never get another chunk.
16941 Transform.prototype._transform = function (chunk, encoding, cb) {
16942 throw new Error('_transform() is not implemented');
16945 Transform.prototype._write = function (chunk, encoding, cb) {
16946 var ts = this._transformState;
16948 ts.writechunk = chunk;
16949 ts.writeencoding = encoding;
16950 if (!ts.transforming) {
16951 var rs = this._readableState;
16952 if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
16956 // Doesn't matter what the args are here.
16957 // _transform does all the work.
16958 // That we got here means that the readable side wants more data.
16959 Transform.prototype._read = function (n) {
16960 var ts = this._transformState;
16962 if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
16963 ts.transforming = true;
16964 this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
16966 // mark that we need a transform, so that any data that comes in
16967 // will get processed, now that we've asked for it.
16968 ts.needTransform = true;
16972 Transform.prototype._destroy = function (err, cb) {
16975 Duplex.prototype._destroy.call(this, err, function (err2) {
16977 _this2.emit('close');
16981 function done(stream, er, data) {
16982 if (er) return stream.emit('error', er);
16984 if (data != null) // single equals check for both `null` and `undefined`
16987 // if there's nothing in the write buffer, then that means
16988 // that nothing more will ever be provided
16989 if (stream._writableState.length) throw new Error('Calling transform done when ws.length != 0');
16991 if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming');
16993 return stream.push(null);
16995 },{"./_stream_duplex":117,"core-util-is":101,"inherits":106}],121:[function(require,module,exports){
16996 (function (process,global,setImmediate){
16997 // Copyright Joyent, Inc. and other Node contributors.
16999 // Permission is hereby granted, free of charge, to any person obtaining a
17000 // copy of this software and associated documentation files (the
17001 // "Software"), to deal in the Software without restriction, including
17002 // without limitation the rights to use, copy, modify, merge, publish,
17003 // distribute, sublicense, and/or sell copies of the Software, and to permit
17004 // persons to whom the Software is furnished to do so, subject to the
17005 // following conditions:
17007 // The above copyright notice and this permission notice shall be included
17008 // in all copies or substantial portions of the Software.
17010 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
17011 // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17012 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17013 // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
17014 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
17015 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
17016 // USE OR OTHER DEALINGS IN THE SOFTWARE.
17018 // A bit simpler than readable streams.
17019 // Implement an async ._write(chunk, encoding, cb), and it'll handle all
17020 // the drain event emission and buffering.
17026 var pna = require('process-nextick-args');
17029 module.exports = Writable;
17031 /* <replacement> */
17032 function WriteReq(chunk, encoding, cb) {
17033 this.chunk = chunk;
17034 this.encoding = encoding;
17035 this.callback = cb;
17039 // It seems a linked list but it is not
17040 // there will be only 2 of these for each stream
17041 function CorkedRequest(state) {
17046 this.finish = function () {
17047 onCorkedFinish(_this, state);
17050 /* </replacement> */
17053 var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick;
17060 Writable.WritableState = WritableState;
17063 var util = require('core-util-is');
17064 util.inherits = require('inherits');
17068 var internalUtil = {
17069 deprecate: require('util-deprecate')
17074 var Stream = require('./internal/streams/stream');
17079 var Buffer = require('safe-buffer').Buffer;
17080 var OurUint8Array = global.Uint8Array || function () {};
17081 function _uint8ArrayToBuffer(chunk) {
17082 return Buffer.from(chunk);
17084 function _isUint8Array(obj) {
17085 return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
17090 var destroyImpl = require('./internal/streams/destroy');
17092 util.inherits(Writable, Stream);
17096 function WritableState(options, stream) {
17097 Duplex = Duplex || require('./_stream_duplex');
17099 options = options || {};
17101 // Duplex streams are both readable and writable, but share
17102 // the same options object.
17103 // However, some cases require setting options to different
17104 // values for the readable and the writable sides of the duplex stream.
17105 // These options can be provided separately as readableXXX and writableXXX.
17106 var isDuplex = stream instanceof Duplex;
17108 // object stream flag to indicate whether or not this stream
17109 // contains buffers or objects.
17110 this.objectMode = !!options.objectMode;
17112 if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode;
17114 // the point at which write() starts returning false
17115 // Note: 0 is a valid value, means that we always return false if
17116 // the entire buffer is not flushed immediately on write()
17117 var hwm = options.highWaterMark;
17118 var writableHwm = options.writableHighWaterMark;
17119 var defaultHwm = this.objectMode ? 16 : 16 * 1024;
17121 if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = defaultHwm;
17124 this.highWaterMark = Math.floor(this.highWaterMark);
17126 // if _final has been called
17127 this.finalCalled = false;
17129 // drain event flag.
17130 this.needDrain = false;
17131 // at the start of calling end()
17132 this.ending = false;
17133 // when end() has been called, and returned
17134 this.ended = false;
17135 // when 'finish' is emitted
17136 this.finished = false;
17138 // has it been destroyed
17139 this.destroyed = false;
17141 // should we decode strings into buffers before passing to _write?
17142 // this is here so that some node-core streams can optimize string
17143 // handling at a lower level.
17144 var noDecode = options.decodeStrings === false;
17145 this.decodeStrings = !noDecode;
17147 // Crypto is kind of old and crusty. Historically, its default string
17148 // encoding is 'binary' so we have to make this configurable.
17149 // Everything else in the universe uses 'utf8', though.
17150 this.defaultEncoding = options.defaultEncoding || 'utf8';
17152 // not an actual buffer we keep track of, but a measurement
17153 // of how much we're waiting to get pushed to some underlying
17157 // a flag to see when we're in the middle of a write.
17158 this.writing = false;
17160 // when true all writes will be buffered until .uncork() call
17163 // a flag to be able to tell if the onwrite cb is called immediately,
17164 // or on a later tick. We set this to true at first, because any
17165 // actions that shouldn't happen until "later" should generally also
17166 // not happen before the first write call.
17169 // a flag to know if we're processing previously buffered items, which
17170 // may call the _write() callback in the same tick, so that we don't
17171 // end up in an overlapped onwrite situation.
17172 this.bufferProcessing = false;
17174 // the callback that's passed to _write(chunk,cb)
17175 this.onwrite = function (er) {
17176 onwrite(stream, er);
17179 // the callback that the user supplies to write(chunk,encoding,cb)
17180 this.writecb = null;
17182 // the amount that is being written when _write is called.
17185 this.bufferedRequest = null;
17186 this.lastBufferedRequest = null;
17188 // number of pending user-supplied write callbacks
17189 // this must be 0 before 'finish' can be emitted
17190 this.pendingcb = 0;
17192 // emit prefinish if the only thing we're waiting for is _write cbs
17193 // This is relevant for synchronous Transform streams
17194 this.prefinished = false;
17196 // True if the error was already emitted and should not be thrown again
17197 this.errorEmitted = false;
17199 // count buffered requests
17200 this.bufferedRequestCount = 0;
17202 // allocate the first CorkedRequest, there is always
17203 // one allocated and free to use, and we maintain at most two
17204 this.corkedRequestsFree = new CorkedRequest(this);
17207 WritableState.prototype.getBuffer = function getBuffer() {
17208 var current = this.bufferedRequest;
17212 current = current.next;
17219 Object.defineProperty(WritableState.prototype, 'buffer', {
17220 get: internalUtil.deprecate(function () {
17221 return this.getBuffer();
17222 }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')
17227 // Test _writableState for inheritance to account for Duplex streams,
17228 // whose prototype chain only points to Readable.
17229 var realHasInstance;
17230 if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {
17231 realHasInstance = Function.prototype[Symbol.hasInstance];
17232 Object.defineProperty(Writable, Symbol.hasInstance, {
17233 value: function (object) {
17234 if (realHasInstance.call(this, object)) return true;
17235 if (this !== Writable) return false;
17237 return object && object._writableState instanceof WritableState;
17241 realHasInstance = function (object) {
17242 return object instanceof this;
17246 function Writable(options) {
17247 Duplex = Duplex || require('./_stream_duplex');
17249 // Writable ctor is applied to Duplexes, too.
17250 // `realHasInstance` is necessary because using plain `instanceof`
17251 // would return false, as no `_writableState` property is attached.
17253 // Trying to use the custom `instanceof` for Writable here will also break the
17254 // Node.js LazyTransform implementation, which has a non-trivial getter for
17255 // `_writableState` that would lead to infinite recursion.
17256 if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) {
17257 return new Writable(options);
17260 this._writableState = new WritableState(options, this);
17263 this.writable = true;
17266 if (typeof options.write === 'function') this._write = options.write;
17268 if (typeof options.writev === 'function') this._writev = options.writev;
17270 if (typeof options.destroy === 'function') this._destroy = options.destroy;
17272 if (typeof options.final === 'function') this._final = options.final;
17278 // Otherwise people can pipe Writable streams, which is just wrong.
17279 Writable.prototype.pipe = function () {
17280 this.emit('error', new Error('Cannot pipe, not readable'));
17283 function writeAfterEnd(stream, cb) {
17284 var er = new Error('write after end');
17285 // TODO: defer error events consistently everywhere, not just the cb
17286 stream.emit('error', er);
17287 pna.nextTick(cb, er);
17290 // Checks that a user-supplied chunk is valid, especially for the particular
17291 // mode the stream is in. Currently this means that `null` is never accepted
17292 // and undefined/non-string values are only allowed in object mode.
17293 function validChunk(stream, state, chunk, cb) {
17297 if (chunk === null) {
17298 er = new TypeError('May not write null values to stream');
17299 } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
17300 er = new TypeError('Invalid non-string/buffer chunk');
17303 stream.emit('error', er);
17304 pna.nextTick(cb, er);
17310 Writable.prototype.write = function (chunk, encoding, cb) {
17311 var state = this._writableState;
17313 var isBuf = !state.objectMode && _isUint8Array(chunk);
17315 if (isBuf && !Buffer.isBuffer(chunk)) {
17316 chunk = _uint8ArrayToBuffer(chunk);
17319 if (typeof encoding === 'function') {
17324 if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
17326 if (typeof cb !== 'function') cb = nop;
17328 if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {
17330 ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
17336 Writable.prototype.cork = function () {
17337 var state = this._writableState;
17342 Writable.prototype.uncork = function () {
17343 var state = this._writableState;
17345 if (state.corked) {
17348 if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
17352 Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
17353 // node::ParseEncoding() requires lower case.
17354 if (typeof encoding === 'string') encoding = encoding.toLowerCase();
17355 if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding);
17356 this._writableState.defaultEncoding = encoding;
17360 function decodeChunk(state, chunk, encoding) {
17361 if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
17362 chunk = Buffer.from(chunk, encoding);
17367 Object.defineProperty(Writable.prototype, 'writableHighWaterMark', {
17368 // making it explicit this property is not enumerable
17369 // because otherwise some prototype manipulation in
17370 // userland will fail
17373 return this._writableState.highWaterMark;
17377 // if we're already writing something, then just put this
17378 // in the queue, and wait our turn. Otherwise, call _write
17379 // If we return false, then we need a drain event, so set that flag.
17380 function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
17382 var newChunk = decodeChunk(state, chunk, encoding);
17383 if (chunk !== newChunk) {
17385 encoding = 'buffer';
17389 var len = state.objectMode ? 1 : chunk.length;
17391 state.length += len;
17393 var ret = state.length < state.highWaterMark;
17394 // we must ensure that previous needDrain will not be reset to false.
17395 if (!ret) state.needDrain = true;
17397 if (state.writing || state.corked) {
17398 var last = state.lastBufferedRequest;
17399 state.lastBufferedRequest = {
17401 encoding: encoding,
17407 last.next = state.lastBufferedRequest;
17409 state.bufferedRequest = state.lastBufferedRequest;
17411 state.bufferedRequestCount += 1;
17413 doWrite(stream, state, false, len, chunk, encoding, cb);
17419 function doWrite(stream, state, writev, len, chunk, encoding, cb) {
17420 state.writelen = len;
17421 state.writecb = cb;
17422 state.writing = true;
17424 if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
17425 state.sync = false;
17428 function onwriteError(stream, state, sync, er, cb) {
17432 // defer the callback if we are being called synchronously
17433 // to avoid piling up things on the stack
17434 pna.nextTick(cb, er);
17435 // this can emit finish, and it will always happen
17437 pna.nextTick(finishMaybe, stream, state);
17438 stream._writableState.errorEmitted = true;
17439 stream.emit('error', er);
17441 // the caller expect this to happen before if
17444 stream._writableState.errorEmitted = true;
17445 stream.emit('error', er);
17446 // this can emit finish, but finish must
17447 // always follow error
17448 finishMaybe(stream, state);
17452 function onwriteStateUpdate(state) {
17453 state.writing = false;
17454 state.writecb = null;
17455 state.length -= state.writelen;
17456 state.writelen = 0;
17459 function onwrite(stream, er) {
17460 var state = stream._writableState;
17461 var sync = state.sync;
17462 var cb = state.writecb;
17464 onwriteStateUpdate(state);
17466 if (er) onwriteError(stream, state, sync, er, cb);else {
17467 // Check if we're actually ready to finish, but don't emit yet
17468 var finished = needFinish(state);
17470 if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
17471 clearBuffer(stream, state);
17476 asyncWrite(afterWrite, stream, state, finished, cb);
17479 afterWrite(stream, state, finished, cb);
17484 function afterWrite(stream, state, finished, cb) {
17485 if (!finished) onwriteDrain(stream, state);
17488 finishMaybe(stream, state);
17491 // Must force callback to be called on nextTick, so that we don't
17492 // emit 'drain' before the write() consumer gets the 'false' return
17493 // value, and has a chance to attach a 'drain' listener.
17494 function onwriteDrain(stream, state) {
17495 if (state.length === 0 && state.needDrain) {
17496 state.needDrain = false;
17497 stream.emit('drain');
17501 // if there's something in the buffer waiting, then process it
17502 function clearBuffer(stream, state) {
17503 state.bufferProcessing = true;
17504 var entry = state.bufferedRequest;
17506 if (stream._writev && entry && entry.next) {
17507 // Fast case, write everything using _writev()
17508 var l = state.bufferedRequestCount;
17509 var buffer = new Array(l);
17510 var holder = state.corkedRequestsFree;
17511 holder.entry = entry;
17514 var allBuffers = true;
17516 buffer[count] = entry;
17517 if (!entry.isBuf) allBuffers = false;
17518 entry = entry.next;
17521 buffer.allBuffers = allBuffers;
17523 doWrite(stream, state, true, state.length, buffer, '', holder.finish);
17525 // doWrite is almost always async, defer these to save a bit of time
17526 // as the hot path ends with doWrite
17528 state.lastBufferedRequest = null;
17530 state.corkedRequestsFree = holder.next;
17531 holder.next = null;
17533 state.corkedRequestsFree = new CorkedRequest(state);
17535 state.bufferedRequestCount = 0;
17537 // Slow case, write chunks one-by-one
17539 var chunk = entry.chunk;
17540 var encoding = entry.encoding;
17541 var cb = entry.callback;
17542 var len = state.objectMode ? 1 : chunk.length;
17544 doWrite(stream, state, false, len, chunk, encoding, cb);
17545 entry = entry.next;
17546 state.bufferedRequestCount--;
17547 // if we didn't call the onwrite immediately, then
17548 // it means that we need to wait until it does.
17549 // also, that means that the chunk and cb are currently
17550 // being processed, so move the buffer counter past them.
17551 if (state.writing) {
17556 if (entry === null) state.lastBufferedRequest = null;
17559 state.bufferedRequest = entry;
17560 state.bufferProcessing = false;
17563 Writable.prototype._write = function (chunk, encoding, cb) {
17564 cb(new Error('_write() is not implemented'));
17567 Writable.prototype._writev = null;
17569 Writable.prototype.end = function (chunk, encoding, cb) {
17570 var state = this._writableState;
17572 if (typeof chunk === 'function') {
17576 } else if (typeof encoding === 'function') {
17581 if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);
17583 // .end() fully uncorks
17584 if (state.corked) {
17589 // ignore unnecessary end() calls.
17590 if (!state.ending && !state.finished) endWritable(this, state, cb);
17593 function needFinish(state) {
17594 return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
17596 function callFinal(stream, state) {
17597 stream._final(function (err) {
17600 stream.emit('error', err);
17602 state.prefinished = true;
17603 stream.emit('prefinish');
17604 finishMaybe(stream, state);
17607 function prefinish(stream, state) {
17608 if (!state.prefinished && !state.finalCalled) {
17609 if (typeof stream._final === 'function') {
17611 state.finalCalled = true;
17612 pna.nextTick(callFinal, stream, state);
17614 state.prefinished = true;
17615 stream.emit('prefinish');
17620 function finishMaybe(stream, state) {
17621 var need = needFinish(state);
17623 prefinish(stream, state);
17624 if (state.pendingcb === 0) {
17625 state.finished = true;
17626 stream.emit('finish');
17632 function endWritable(stream, state, cb) {
17633 state.ending = true;
17634 finishMaybe(stream, state);
17636 if (state.finished) pna.nextTick(cb);else stream.once('finish', cb);
17638 state.ended = true;
17639 stream.writable = false;
17642 function onCorkedFinish(corkReq, state, err) {
17643 var entry = corkReq.entry;
17644 corkReq.entry = null;
17646 var cb = entry.callback;
17649 entry = entry.next;
17651 if (state.corkedRequestsFree) {
17652 state.corkedRequestsFree.next = corkReq;
17654 state.corkedRequestsFree = corkReq;
17658 Object.defineProperty(Writable.prototype, 'destroyed', {
17660 if (this._writableState === undefined) {
17663 return this._writableState.destroyed;
17665 set: function (value) {
17666 // we ignore the value if the stream
17667 // has not been initialized yet
17668 if (!this._writableState) {
17672 // backward compatibility, the user is explicitly
17673 // managing destroyed
17674 this._writableState.destroyed = value;
17678 Writable.prototype.destroy = destroyImpl.destroy;
17679 Writable.prototype._undestroy = destroyImpl.undestroy;
17680 Writable.prototype._destroy = function (err, cb) {
17684 }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("timers").setImmediate)
17685 },{"./_stream_duplex":117,"./internal/streams/destroy":123,"./internal/streams/stream":124,"_process":112,"core-util-is":101,"inherits":106,"process-nextick-args":111,"safe-buffer":143,"timers":160,"util-deprecate":164}],122:[function(require,module,exports){
17688 function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
17690 var Buffer = require('safe-buffer').Buffer;
17691 var util = require('util');
17693 function copyBuffer(src, target, offset) {
17694 src.copy(target, offset);
17697 module.exports = function () {
17698 function BufferList() {
17699 _classCallCheck(this, BufferList);
17706 BufferList.prototype.push = function push(v) {
17707 var entry = { data: v, next: null };
17708 if (this.length > 0) this.tail.next = entry;else this.head = entry;
17713 BufferList.prototype.unshift = function unshift(v) {
17714 var entry = { data: v, next: this.head };
17715 if (this.length === 0) this.tail = entry;
17720 BufferList.prototype.shift = function shift() {
17721 if (this.length === 0) return;
17722 var ret = this.head.data;
17723 if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
17728 BufferList.prototype.clear = function clear() {
17729 this.head = this.tail = null;
17733 BufferList.prototype.join = function join(s) {
17734 if (this.length === 0) return '';
17736 var ret = '' + p.data;
17737 while (p = p.next) {
17742 BufferList.prototype.concat = function concat(n) {
17743 if (this.length === 0) return Buffer.alloc(0);
17744 if (this.length === 1) return this.head.data;
17745 var ret = Buffer.allocUnsafe(n >>> 0);
17749 copyBuffer(p.data, ret, i);
17750 i += p.data.length;
17759 if (util && util.inspect && util.inspect.custom) {
17760 module.exports.prototype[util.inspect.custom] = function () {
17761 var obj = util.inspect({ length: this.length });
17762 return this.constructor.name + ' ' + obj;
17765 },{"safe-buffer":143,"util":2}],123:[function(require,module,exports){
17770 var pna = require('process-nextick-args');
17773 // undocumented cb() API, needed for core, not for public API
17774 function destroy(err, cb) {
17777 var readableDestroyed = this._readableState && this._readableState.destroyed;
17778 var writableDestroyed = this._writableState && this._writableState.destroyed;
17780 if (readableDestroyed || writableDestroyed) {
17783 } else if (err && (!this._writableState || !this._writableState.errorEmitted)) {
17784 pna.nextTick(emitErrorNT, this, err);
17789 // we set destroyed to true before firing error callbacks in order
17790 // to make it re-entrance safe in case destroy() is called within callbacks
17792 if (this._readableState) {
17793 this._readableState.destroyed = true;
17796 // if this is a duplex stream mark the writable part as destroyed as well
17797 if (this._writableState) {
17798 this._writableState.destroyed = true;
17801 this._destroy(err || null, function (err) {
17803 pna.nextTick(emitErrorNT, _this, err);
17804 if (_this._writableState) {
17805 _this._writableState.errorEmitted = true;
17815 function undestroy() {
17816 if (this._readableState) {
17817 this._readableState.destroyed = false;
17818 this._readableState.reading = false;
17819 this._readableState.ended = false;
17820 this._readableState.endEmitted = false;
17823 if (this._writableState) {
17824 this._writableState.destroyed = false;
17825 this._writableState.ended = false;
17826 this._writableState.ending = false;
17827 this._writableState.finished = false;
17828 this._writableState.errorEmitted = false;
17832 function emitErrorNT(self, err) {
17833 self.emit('error', err);
17838 undestroy: undestroy
17840 },{"process-nextick-args":111}],124:[function(require,module,exports){
17841 module.exports = require('events').EventEmitter;
17843 },{"events":102}],125:[function(require,module,exports){
17844 exports = module.exports = require('./lib/_stream_readable.js');
17845 exports.Stream = exports;
17846 exports.Readable = exports;
17847 exports.Writable = require('./lib/_stream_writable.js');
17848 exports.Duplex = require('./lib/_stream_duplex.js');
17849 exports.Transform = require('./lib/_stream_transform.js');
17850 exports.PassThrough = require('./lib/_stream_passthrough.js');
17852 },{"./lib/_stream_duplex.js":117,"./lib/_stream_passthrough.js":118,"./lib/_stream_readable.js":119,"./lib/_stream_transform.js":120,"./lib/_stream_writable.js":121}],126:[function(require,module,exports){
17858 ABSOLUTE: "absolute",
17859 PATH_RELATIVE: "pathRelative",
17860 ROOT_RELATIVE: "rootRelative",
17861 SHORTEST: "shortest"
17864 },{}],127:[function(require,module,exports){
17867 var constants = require("./constants");
17871 function formatAuth(urlObj, options)
17873 if (urlObj.auth && !options.removeAuth && (urlObj.extra.relation.maximumHost || options.output===constants.ABSOLUTE))
17875 return urlObj.auth + "@";
17883 function formatHash(urlObj, options)
17885 return urlObj.hash ? urlObj.hash : "";
17890 function formatHost(urlObj, options)
17892 if (urlObj.host.full && (urlObj.extra.relation.maximumAuth || options.output===constants.ABSOLUTE))
17894 return urlObj.host.full;
17902 function formatPath(urlObj, options)
17906 var absolutePath = urlObj.path.absolute.string;
17907 var relativePath = urlObj.path.relative.string;
17908 var resource = showResource(urlObj, options);
17910 if (urlObj.extra.relation.maximumHost || options.output===constants.ABSOLUTE || options.output===constants.ROOT_RELATIVE)
17912 str = absolutePath;
17914 else if (relativePath.length<=absolutePath.length && options.output===constants.SHORTEST || options.output===constants.PATH_RELATIVE)
17916 str = relativePath;
17920 var query = showQuery(urlObj,options) && !!getQuery(urlObj,options);
17922 if (urlObj.extra.relation.maximumPath && !resource)
17926 else if (urlObj.extra.relation.overridesQuery && !resource && !query)
17934 str = absolutePath;
17937 if ( str==="/" && !resource && options.removeRootTrailingSlash && (!urlObj.extra.relation.minimumPort || options.output===constants.ABSOLUTE) )
17947 function formatPort(urlObj, options)
17949 if (urlObj.port && !urlObj.extra.portIsDefault && urlObj.extra.relation.maximumHost)
17951 return ":" + urlObj.port;
17959 function formatQuery(urlObj, options)
17961 return showQuery(urlObj,options) ? getQuery(urlObj, options) : "";
17966 function formatResource(urlObj, options)
17968 return showResource(urlObj,options) ? urlObj.resource : "";
17973 function formatScheme(urlObj, options)
17977 if (urlObj.extra.relation.maximumHost || options.output===constants.ABSOLUTE)
17979 if (!urlObj.extra.relation.minimumScheme || !options.schemeRelative || options.output===constants.ABSOLUTE)
17981 str += urlObj.scheme + "://";
17994 function formatUrl(urlObj, options)
17998 url += formatScheme(urlObj, options);
17999 url += formatAuth(urlObj, options);
18000 url += formatHost(urlObj, options);
18001 url += formatPort(urlObj, options);
18002 url += formatPath(urlObj, options);
18003 url += formatResource(urlObj, options);
18004 url += formatQuery(urlObj, options);
18005 url += formatHash(urlObj, options);
18012 function getQuery(urlObj, options)
18014 var stripQuery = options.removeEmptyQueries && urlObj.extra.relation.minimumPort;
18016 return urlObj.query.string[ stripQuery ? "stripped" : "full" ];
18021 function showQuery(urlObj, options)
18023 return !urlObj.extra.relation.minimumQuery || options.output===constants.ABSOLUTE || options.output===constants.ROOT_RELATIVE;
18028 function showResource(urlObj, options)
18030 var removeIndex = options.removeDirectoryIndexes && urlObj.extra.resourceIsIndex;
18031 var removeMatchingResource = urlObj.extra.relation.minimumResource && options.output!==constants.ABSOLUTE && options.output!==constants.ROOT_RELATIVE;
18033 return !!urlObj.resource && !removeMatchingResource && !removeIndex;
18038 module.exports = formatUrl;
18040 },{"./constants":126}],128:[function(require,module,exports){
18043 var constants = require("./constants");
18044 var formatUrl = require("./format");
18045 var getOptions = require("./options");
18046 var objUtils = require("./util/object");
18047 var parseUrl = require("./parse");
18048 var relateUrl = require("./relate");
18052 function RelateUrl(from, options)
18054 this.options = getOptions(options,
18056 defaultPorts: {ftp:21, http:80, https:443},
18057 directoryIndexes: ["index.html"],
18059 output: RelateUrl.SHORTEST,
18060 rejectedSchemes: ["data","javascript","mailto"],
18062 removeDirectoryIndexes: true,
18063 removeEmptyQueries: false,
18064 removeRootTrailingSlash: true,
18065 schemeRelative: true,
18067 slashesDenoteHost: true
18070 this.from = parseUrl.from(from, this.options, null);
18076 Usage: instance=new RelateUrl(); instance.relate();
18078 RelateUrl.prototype.relate = function(from, to, options)
18080 // relate(to,options)
18081 if ( objUtils.isPlainObject(to) )
18094 options = getOptions(options, this.options);
18095 from = from || options.site;
18096 from = parseUrl.from(from, options, this.from);
18098 if (!from || !from.href)
18100 throw new Error("from value not defined.");
18102 else if (from.extra.hrefInfo.minimumPathOnly)
18104 throw new Error("from value supplied is not absolute: "+from.href);
18107 to = parseUrl.to(to, options);
18109 if (to.valid===false) return to.href;
18111 to = relateUrl(from, to, options);
18112 to = formatUrl(to, options);
18120 Usage: RelateUrl.relate();
18122 RelateUrl.relate = function(from, to, options)
18124 return new RelateUrl().relate(from, to, options);
18129 // Make constants accessible from API
18130 objUtils.shallowMerge(RelateUrl, constants);
18134 module.exports = RelateUrl;
18136 },{"./constants":126,"./format":127,"./options":129,"./parse":132,"./relate":139,"./util/object":141}],129:[function(require,module,exports){
18139 var objUtils = require("./util/object");
18143 function getOptions(options, defaults)
18145 if ( objUtils.isPlainObject(options) )
18147 var newOptions = {};
18149 for (var i in defaults)
18151 if ( defaults.hasOwnProperty(i) )
18153 if (options[i] !== undefined)
18155 newOptions[i] = mergeOption(options[i], defaults[i]);
18159 newOptions[i] = defaults[i];
18174 function mergeOption(newValues, defaultValues)
18176 if (defaultValues instanceof Object && newValues instanceof Object)
18178 if (defaultValues instanceof Array && newValues instanceof Array)
18180 return defaultValues.concat(newValues);
18184 return objUtils.shallowMerge(newValues, defaultValues);
18193 module.exports = getOptions;
18195 },{"./util/object":141}],130:[function(require,module,exports){
18198 function parseHost(urlObj, options)
18200 // TWEAK :: condition only for speed optimization
18201 if (options.ignore_www)
18203 var host = urlObj.host.full;
18207 var stripped = host;
18209 if (host.indexOf("www.") === 0)
18211 stripped = host.substr(4);
18214 urlObj.host.stripped = stripped;
18221 module.exports = parseHost;
18223 },{}],131:[function(require,module,exports){
18226 function hrefInfo(urlObj)
18228 var minimumPathOnly = (!urlObj.scheme && !urlObj.auth && !urlObj.host.full && !urlObj.port);
18229 var minimumResourceOnly = (minimumPathOnly && !urlObj.path.absolute.string);
18230 var minimumQueryOnly = (minimumResourceOnly && !urlObj.resource);
18231 var minimumHashOnly = (minimumQueryOnly && !urlObj.query.string.full.length);
18232 var empty = (minimumHashOnly && !urlObj.hash);
18234 urlObj.extra.hrefInfo.minimumPathOnly = minimumPathOnly;
18235 urlObj.extra.hrefInfo.minimumResourceOnly = minimumResourceOnly;
18236 urlObj.extra.hrefInfo.minimumQueryOnly = minimumQueryOnly;
18237 urlObj.extra.hrefInfo.minimumHashOnly = minimumHashOnly;
18238 urlObj.extra.hrefInfo.empty = empty;
18243 module.exports = hrefInfo;
18245 },{}],132:[function(require,module,exports){
18248 var hrefInfo = require("./hrefInfo");
18249 var parseHost = require("./host");
18250 var parsePath = require("./path");
18251 var parsePort = require("./port");
18252 var parseQuery = require("./query");
18253 var parseUrlString = require("./urlstring");
18254 var pathUtils = require("../util/path");
18258 function parseFromUrl(url, options, fallback)
18262 var urlObj = parseUrl(url, options);
18264 // Because the following occurs in the relate stage for "to" URLs,
18265 // such had to be mostly duplicated here
18267 var pathArray = pathUtils.resolveDotSegments(urlObj.path.absolute.array);
18269 urlObj.path.absolute.array = pathArray;
18270 urlObj.path.absolute.string = "/" + pathUtils.join(pathArray);
18282 function parseUrl(url, options)
18284 var urlObj = parseUrlString(url, options);
18286 if (urlObj.valid===false) return urlObj;
18288 parseHost(urlObj, options);
18289 parsePort(urlObj, options);
18290 parsePath(urlObj, options);
18291 parseQuery(urlObj, options);
18301 from: parseFromUrl,
18305 },{"../util/path":142,"./host":130,"./hrefInfo":131,"./path":133,"./port":134,"./query":135,"./urlstring":136}],133:[function(require,module,exports){
18308 function isDirectoryIndex(resource, options)
18310 var verdict = false;
18312 options.directoryIndexes.every( function(index)
18314 if (index === resource)
18328 function parsePath(urlObj, options)
18330 var path = urlObj.path.absolute.string;
18334 var lastSlash = path.lastIndexOf("/");
18336 if (lastSlash > -1)
18338 if (++lastSlash < path.length)
18340 var resource = path.substr(lastSlash);
18342 if (resource!=="." && resource!=="..")
18344 urlObj.resource = resource;
18345 path = path.substr(0, lastSlash);
18353 urlObj.path.absolute.string = path;
18354 urlObj.path.absolute.array = splitPath(path);
18356 else if (path==="." || path==="..")
18358 // "..?var", "..#anchor", etc ... not "..index.html"
18361 urlObj.path.absolute.string = path;
18362 urlObj.path.absolute.array = splitPath(path);
18367 urlObj.resource = path;
18368 urlObj.path.absolute.string = null;
18371 urlObj.extra.resourceIsIndex = isDirectoryIndex(urlObj.resource, options);
18373 // Else: query/hash-only or empty
18378 function splitPath(path)
18380 // TWEAK :: condition only for speed optimization
18385 path.split("/").forEach( function(dir)
18387 // Cleanup -- splitting "/dir/" becomes ["","dir",""]
18398 // Faster to skip the above block and just create an array
18405 module.exports = parsePath;
18407 },{}],134:[function(require,module,exports){
18410 function parsePort(urlObj, options)
18412 var defaultPort = -1;
18414 for (var i in options.defaultPorts)
18416 if ( i===urlObj.scheme && options.defaultPorts.hasOwnProperty(i) )
18418 defaultPort = options.defaultPorts[i];
18423 if (defaultPort > -1)
18425 // Force same type as urlObj.port
18426 defaultPort = defaultPort.toString();
18428 if (urlObj.port === null)
18430 urlObj.port = defaultPort;
18433 urlObj.extra.portIsDefault = (urlObj.port === defaultPort);
18439 module.exports = parsePort;
18441 },{}],135:[function(require,module,exports){
18443 var hasOwnProperty = Object.prototype.hasOwnProperty;
18447 function parseQuery(urlObj, options)
18449 urlObj.query.string.full = stringify(urlObj.query.object, false);
18451 // TWEAK :: condition only for speed optimization
18452 if (options.removeEmptyQueries)
18454 urlObj.query.string.stripped = stringify(urlObj.query.object, true);
18460 function stringify(queryObj, removeEmptyQueries)
18465 for (var i in queryObj)
18467 if ( i!=="" && hasOwnProperty.call(queryObj, i)===true )
18469 var value = queryObj[i];
18471 if (value !== "" || !removeEmptyQueries)
18473 str += (++count===1) ? "?" : "&";
18475 i = encodeURIComponent(i);
18479 str += i +"="+ encodeURIComponent(value).replace(/%20/g,"+");
18494 module.exports = parseQuery;
18496 },{}],136:[function(require,module,exports){
18499 var _parseUrl = require("url").parse;
18504 Customize the URL object that Node generates
18507 * necessary data for later
18508 * urlObj.host is useless
18509 * urlObj.hostname is too long
18510 * urlObj.path is useless
18511 * urlObj.pathname is too long
18512 * urlObj.protocol is inaccurate; should be called "scheme"
18513 * urlObj.search is mostly useless
18515 function clean(urlObj)
18517 var scheme = urlObj.protocol;
18521 // Remove ":" suffix
18522 if (scheme.indexOf(":") === scheme.length-1)
18524 scheme = scheme.substr(0, scheme.length-1);
18530 // TODO :: unescape(encodeURIComponent(s)) ? ... http://ecmanaut.blogspot.ca/2006/07/encoding-decoding-utf8-in-javascript.html
18531 full: urlObj.hostname,
18540 string: urlObj.pathname
18551 object: urlObj.query,
18563 minimumPathOnly: null,
18564 minimumResourceOnly: null,
18565 minimumQueryOnly: null,
18566 minimumHashOnly: null,
18569 separatorOnlyQuery: urlObj.search==="?"
18571 portIsDefault: null,
18574 maximumScheme: null,
18579 maximumResource: null,
18580 maximumQuery: null,
18583 minimumScheme: null,
18588 minimumResource: null,
18589 minimumQuery: null,
18592 overridesQuery: null
18594 resourceIsIndex: null,
18595 slashes: urlObj.slashes
18598 urlObj.resource = null;
18599 urlObj.scheme = scheme;
18600 delete urlObj.hostname;
18601 delete urlObj.pathname;
18602 delete urlObj.protocol;
18603 delete urlObj.search;
18604 delete urlObj.slashes;
18611 function validScheme(url, options)
18615 options.rejectedSchemes.every( function(rejectedScheme)
18617 valid = !(url.indexOf(rejectedScheme+":") === 0);
18628 function parseUrlString(url, options)
18630 if ( validScheme(url,options) )
18632 return clean( _parseUrl(url, true, options.slashesDenoteHost) );
18636 return {href:url, valid:false};
18642 module.exports = parseUrlString;
18644 },{"url":162}],137:[function(require,module,exports){
18647 var findRelation = require("./findRelation");
18648 var objUtils = require("../util/object");
18649 var pathUtils = require("../util/path");
18653 function absolutize(urlObj, siteUrlObj, options)
18655 findRelation.upToPath(urlObj, siteUrlObj, options);
18657 // Fill in relative URLs
18658 if (urlObj.extra.relation.minimumScheme) urlObj.scheme = siteUrlObj.scheme;
18659 if (urlObj.extra.relation.minimumAuth) urlObj.auth = siteUrlObj.auth;
18660 if (urlObj.extra.relation.minimumHost) urlObj.host = objUtils.clone(siteUrlObj.host);
18661 if (urlObj.extra.relation.minimumPort) copyPort(urlObj, siteUrlObj);
18662 if (urlObj.extra.relation.minimumScheme) copyPath(urlObj, siteUrlObj);
18664 // Check remaining relativeness now that path has been copied and/or resolved
18665 findRelation.pathOn(urlObj, siteUrlObj, options);
18667 // Fill in relative URLs
18668 if (urlObj.extra.relation.minimumResource) copyResource(urlObj, siteUrlObj);
18669 if (urlObj.extra.relation.minimumQuery) urlObj.query = objUtils.clone(siteUrlObj.query);
18670 if (urlObj.extra.relation.minimumHash) urlObj.hash = siteUrlObj.hash;
18676 Get an absolute path that's relative to site url.
18678 function copyPath(urlObj, siteUrlObj)
18680 if (urlObj.extra.relation.maximumHost || !urlObj.extra.hrefInfo.minimumResourceOnly)
18682 var pathArray = urlObj.path.absolute.array;
18683 var pathString = "/";
18685 // If not erroneous URL
18688 // If is relative path
18689 if (urlObj.extra.hrefInfo.minimumPathOnly && urlObj.path.absolute.string.indexOf("/")!==0)
18691 // Append path to site path
18692 pathArray = siteUrlObj.path.absolute.array.concat(pathArray);
18695 pathArray = pathUtils.resolveDotSegments(pathArray);
18696 pathString += pathUtils.join(pathArray);
18703 urlObj.path.absolute.array = pathArray;
18704 urlObj.path.absolute.string = pathString;
18708 // Resource-, query- or hash-only or empty
18709 urlObj.path = objUtils.clone(siteUrlObj.path);
18715 function copyPort(urlObj, siteUrlObj)
18717 urlObj.port = siteUrlObj.port;
18719 urlObj.extra.portIsDefault = siteUrlObj.extra.portIsDefault;
18724 function copyResource(urlObj, siteUrlObj)
18726 urlObj.resource = siteUrlObj.resource;
18728 urlObj.extra.resourceIsIndex = siteUrlObj.extra.resourceIsIndex;
18733 module.exports = absolutize;
18735 },{"../util/object":141,"../util/path":142,"./findRelation":138}],138:[function(require,module,exports){
18738 function findRelation_upToPath(urlObj, siteUrlObj, options)
18740 // Path- or root-relative URL
18741 var pathOnly = urlObj.extra.hrefInfo.minimumPathOnly;
18743 // Matching scheme, scheme-relative or path-only
18744 var minimumScheme = (urlObj.scheme===siteUrlObj.scheme || !urlObj.scheme);
18746 // Matching auth, ignoring auth or path-only
18747 var minimumAuth = minimumScheme && (urlObj.auth===siteUrlObj.auth || options.removeAuth || pathOnly);
18749 // Matching host or path-only
18750 var www = options.ignore_www ? "stripped" : "full";
18751 var minimumHost = minimumAuth && (urlObj.host[www]===siteUrlObj.host[www] || pathOnly);
18753 // Matching port or path-only
18754 var minimumPort = minimumHost && (urlObj.port===siteUrlObj.port || pathOnly);
18756 urlObj.extra.relation.minimumScheme = minimumScheme;
18757 urlObj.extra.relation.minimumAuth = minimumAuth;
18758 urlObj.extra.relation.minimumHost = minimumHost;
18759 urlObj.extra.relation.minimumPort = minimumPort;
18761 urlObj.extra.relation.maximumScheme = !minimumScheme || minimumScheme && !minimumAuth;
18762 urlObj.extra.relation.maximumAuth = !minimumScheme || minimumScheme && !minimumHost;
18763 urlObj.extra.relation.maximumHost = !minimumScheme || minimumScheme && !minimumPort;
18768 function findRelation_pathOn(urlObj, siteUrlObj, options)
18770 var queryOnly = urlObj.extra.hrefInfo.minimumQueryOnly;
18771 var hashOnly = urlObj.extra.hrefInfo.minimumHashOnly;
18772 var empty = urlObj.extra.hrefInfo.empty; // not required, but self-documenting
18775 var minimumPort = urlObj.extra.relation.minimumPort;
18776 var minimumScheme = urlObj.extra.relation.minimumScheme;
18778 // Matching port and path
18779 var minimumPath = minimumPort && urlObj.path.absolute.string===siteUrlObj.path.absolute.string;
18781 // Matching resource or query/hash-only or empty
18782 var matchingResource = (urlObj.resource===siteUrlObj.resource || !urlObj.resource && siteUrlObj.extra.resourceIsIndex) || (options.removeDirectoryIndexes && urlObj.extra.resourceIsIndex && !siteUrlObj.resource);
18783 var minimumResource = minimumPath && (matchingResource || queryOnly || hashOnly || empty);
18785 // Matching query or hash-only/empty
18786 var query = options.removeEmptyQueries ? "stripped" : "full";
18787 var urlQuery = urlObj.query.string[query];
18788 var siteUrlQuery = siteUrlObj.query.string[query];
18789 var minimumQuery = (minimumResource && !!urlQuery && urlQuery===siteUrlQuery) || ((hashOnly || empty) && !urlObj.extra.hrefInfo.separatorOnlyQuery);
18791 var minimumHash = minimumQuery && urlObj.hash===siteUrlObj.hash;
18793 urlObj.extra.relation.minimumPath = minimumPath;
18794 urlObj.extra.relation.minimumResource = minimumResource;
18795 urlObj.extra.relation.minimumQuery = minimumQuery;
18796 urlObj.extra.relation.minimumHash = minimumHash;
18798 urlObj.extra.relation.maximumPort = !minimumScheme || minimumScheme && !minimumPath;
18799 urlObj.extra.relation.maximumPath = !minimumScheme || minimumScheme && !minimumResource;
18800 urlObj.extra.relation.maximumResource = !minimumScheme || minimumScheme && !minimumQuery;
18801 urlObj.extra.relation.maximumQuery = !minimumScheme || minimumScheme && !minimumHash;
18802 urlObj.extra.relation.maximumHash = !minimumScheme || minimumScheme && !minimumHash; // there's nothing after hash, so it's the same as maximumQuery
18804 // Matching path and/or resource with existing but non-matching site query
18805 urlObj.extra.relation.overridesQuery = minimumPath && urlObj.extra.relation.maximumResource && !minimumQuery && !!siteUrlQuery;
18812 pathOn: findRelation_pathOn,
18813 upToPath: findRelation_upToPath
18816 },{}],139:[function(require,module,exports){
18819 var absolutize = require("./absolutize");
18820 var relativize = require("./relativize");
18824 function relateUrl(siteUrlObj, urlObj, options)
18826 absolutize(urlObj, siteUrlObj, options);
18827 relativize(urlObj, siteUrlObj, options);
18834 module.exports = relateUrl;
18836 },{"./absolutize":137,"./relativize":140}],140:[function(require,module,exports){
18839 var pathUtils = require("../util/path");
18844 Get a path relative to the site path.
18846 function relatePath(absolutePath, siteAbsolutePath)
18848 var relativePath = [];
18850 // At this point, it's related to the host/port
18851 var related = true;
18852 var parentIndex = -1;
18855 siteAbsolutePath.forEach( function(siteAbsoluteDir, i)
18859 if (absolutePath[i] !== siteAbsoluteDir)
18872 relativePath.push("..");
18877 absolutePath.forEach( function(dir, i)
18879 if (i > parentIndex)
18881 relativePath.push(dir);
18885 return relativePath;
18890 function relativize(urlObj, siteUrlObj, options)
18892 if (urlObj.extra.relation.minimumScheme)
18894 var pathArray = relatePath(urlObj.path.absolute.array, siteUrlObj.path.absolute.array);
18896 urlObj.path.relative.array = pathArray;
18897 urlObj.path.relative.string = pathUtils.join(pathArray);
18903 module.exports = relativize;
18905 },{"../util/path":142}],141:[function(require,module,exports){
18909 Deep-clone an object.
18911 function clone(obj)
18913 if (obj instanceof Object)
18915 var clonedObj = (obj instanceof Array) ? [] : {};
18919 if ( obj.hasOwnProperty(i) )
18921 clonedObj[i] = clone( obj[i] );
18934 https://github.com/jonschlinkert/is-plain-object
18936 function isPlainObject(obj)
18938 return !!obj && typeof obj==="object" && obj.constructor===Object;
18944 Shallow-merge two objects.
18946 function shallowMerge(target, source)
18948 if (target instanceof Object && source instanceof Object)
18950 for (var i in source)
18952 if ( source.hasOwnProperty(i) )
18954 target[i] = source[i];
18967 isPlainObject: isPlainObject,
18968 shallowMerge: shallowMerge
18971 },{}],142:[function(require,module,exports){
18974 function joinPath(pathArray)
18976 if (pathArray.length > 0)
18978 return pathArray.join("/") + "/";
18988 function resolveDotSegments(pathArray)
18990 var pathAbsolute = [];
18992 pathArray.forEach( function(dir)
18998 pathAbsolute.push(dir);
19004 if (pathAbsolute.length > 0)
19006 pathAbsolute.splice(pathAbsolute.length-1, 1);
19011 return pathAbsolute;
19019 resolveDotSegments: resolveDotSegments
19022 },{}],143:[function(require,module,exports){
19023 /* eslint-disable node/no-deprecated-api */
19024 var buffer = require('buffer')
19025 var Buffer = buffer.Buffer
19027 // alternative to using Object.keys for old browsers
19028 function copyProps (src, dst) {
19029 for (var key in src) {
19030 dst[key] = src[key]
19033 if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
19034 module.exports = buffer
19036 // Copy properties from require('buffer')
19037 copyProps(buffer, exports)
19038 exports.Buffer = SafeBuffer
19041 function SafeBuffer (arg, encodingOrOffset, length) {
19042 return Buffer(arg, encodingOrOffset, length)
19045 // Copy static methods from Buffer
19046 copyProps(Buffer, SafeBuffer)
19048 SafeBuffer.from = function (arg, encodingOrOffset, length) {
19049 if (typeof arg === 'number') {
19050 throw new TypeError('Argument must not be a number')
19052 return Buffer(arg, encodingOrOffset, length)
19055 SafeBuffer.alloc = function (size, fill, encoding) {
19056 if (typeof size !== 'number') {
19057 throw new TypeError('Argument must be a number')
19059 var buf = Buffer(size)
19060 if (fill !== undefined) {
19061 if (typeof encoding === 'string') {
19062 buf.fill(fill, encoding)
19072 SafeBuffer.allocUnsafe = function (size) {
19073 if (typeof size !== 'number') {
19074 throw new TypeError('Argument must be a number')
19076 return Buffer(size)
19079 SafeBuffer.allocUnsafeSlow = function (size) {
19080 if (typeof size !== 'number') {
19081 throw new TypeError('Argument must be a number')
19083 return buffer.SlowBuffer(size)
19086 },{"buffer":4}],144:[function(require,module,exports){
19087 /* -*- Mode: js; js-indent-level: 2; -*- */
19089 * Copyright 2011 Mozilla Foundation and contributors
19090 * Licensed under the New BSD license. See LICENSE or:
19091 * http://opensource.org/licenses/BSD-3-Clause
19094 var util = require('./util');
19095 var has = Object.prototype.hasOwnProperty;
19096 var hasNativeMap = typeof Map !== "undefined";
19099 * A data structure which is a combination of an array and a set. Adding a new
19100 * member is O(1), testing for membership is O(1), and finding the index of an
19101 * element is O(1). Removing elements from the set is not supported. Only
19102 * strings are supported for membership.
19104 function ArraySet() {
19106 this._set = hasNativeMap ? new Map() : Object.create(null);
19110 * Static method for creating ArraySet instances from an existing array.
19112 ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) {
19113 var set = new ArraySet();
19114 for (var i = 0, len = aArray.length; i < len; i++) {
19115 set.add(aArray[i], aAllowDuplicates);
19121 * Return how many unique items are in this ArraySet. If duplicates have been
19122 * added, than those do not count towards the size.
19126 ArraySet.prototype.size = function ArraySet_size() {
19127 return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length;
19131 * Add the given string to this set.
19133 * @param String aStr
19135 ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {
19136 var sStr = hasNativeMap ? aStr : util.toSetString(aStr);
19137 var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr);
19138 var idx = this._array.length;
19139 if (!isDuplicate || aAllowDuplicates) {
19140 this._array.push(aStr);
19142 if (!isDuplicate) {
19143 if (hasNativeMap) {
19144 this._set.set(aStr, idx);
19146 this._set[sStr] = idx;
19152 * Is the given string a member of this set?
19154 * @param String aStr
19156 ArraySet.prototype.has = function ArraySet_has(aStr) {
19157 if (hasNativeMap) {
19158 return this._set.has(aStr);
19160 var sStr = util.toSetString(aStr);
19161 return has.call(this._set, sStr);
19166 * What is the index of the given string in the array?
19168 * @param String aStr
19170 ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) {
19171 if (hasNativeMap) {
19172 var idx = this._set.get(aStr);
19177 var sStr = util.toSetString(aStr);
19178 if (has.call(this._set, sStr)) {
19179 return this._set[sStr];
19183 throw new Error('"' + aStr + '" is not in the set.');
19187 * What is the element at the given index?
19189 * @param Number aIdx
19191 ArraySet.prototype.at = function ArraySet_at(aIdx) {
19192 if (aIdx >= 0 && aIdx < this._array.length) {
19193 return this._array[aIdx];
19195 throw new Error('No element indexed by ' + aIdx);
19199 * Returns the array representation of this set (which has the proper indices
19200 * indicated by indexOf). Note that this is a copy of the internal array used
19201 * for storing the members so that no one can mess with internal state.
19203 ArraySet.prototype.toArray = function ArraySet_toArray() {
19204 return this._array.slice();
19207 exports.ArraySet = ArraySet;
19209 },{"./util":153}],145:[function(require,module,exports){
19210 /* -*- Mode: js; js-indent-level: 2; -*- */
19212 * Copyright 2011 Mozilla Foundation and contributors
19213 * Licensed under the New BSD license. See LICENSE or:
19214 * http://opensource.org/licenses/BSD-3-Clause
19216 * Based on the Base 64 VLQ implementation in Closure Compiler:
19217 * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java
19219 * Copyright 2011 The Closure Compiler Authors. All rights reserved.
19220 * Redistribution and use in source and binary forms, with or without
19221 * modification, are permitted provided that the following conditions are
19224 * * Redistributions of source code must retain the above copyright
19225 * notice, this list of conditions and the following disclaimer.
19226 * * Redistributions in binary form must reproduce the above
19227 * copyright notice, this list of conditions and the following
19228 * disclaimer in the documentation and/or other materials provided
19229 * with the distribution.
19230 * * Neither the name of Google Inc. nor the names of its
19231 * contributors may be used to endorse or promote products derived
19232 * from this software without specific prior written permission.
19234 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19235 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19236 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19237 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
19238 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
19239 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
19240 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
19241 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
19242 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
19243 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
19244 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
19247 var base64 = require('./base64');
19249 // A single base 64 digit can contain 6 bits of data. For the base 64 variable
19250 // length quantities we use in the source map spec, the first bit is the sign,
19251 // the next four bits are the actual value, and the 6th bit is the
19252 // continuation bit. The continuation bit tells us whether there are more
19253 // digits in this value following this digit.
19261 var VLQ_BASE_SHIFT = 5;
19264 var VLQ_BASE = 1 << VLQ_BASE_SHIFT;
19267 var VLQ_BASE_MASK = VLQ_BASE - 1;
19270 var VLQ_CONTINUATION_BIT = VLQ_BASE;
19273 * Converts from a two-complement value to a value where the sign bit is
19274 * placed in the least significant bit. For example, as decimals:
19275 * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary)
19276 * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary)
19278 function toVLQSigned(aValue) {
19280 ? ((-aValue) << 1) + 1
19281 : (aValue << 1) + 0;
19285 * Converts to a two-complement value from a value where the sign bit is
19286 * placed in the least significant bit. For example, as decimals:
19287 * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1
19288 * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2
19290 function fromVLQSigned(aValue) {
19291 var isNegative = (aValue & 1) === 1;
19292 var shifted = aValue >> 1;
19299 * Returns the base 64 VLQ encoded value.
19301 exports.encode = function base64VLQ_encode(aValue) {
19305 var vlq = toVLQSigned(aValue);
19308 digit = vlq & VLQ_BASE_MASK;
19309 vlq >>>= VLQ_BASE_SHIFT;
19311 // There are still more digits in this value, so we must make sure the
19312 // continuation bit is marked.
19313 digit |= VLQ_CONTINUATION_BIT;
19315 encoded += base64.encode(digit);
19322 * Decodes the next base 64 VLQ value from the given string and returns the
19323 * value and the rest of the string via the out parameter.
19325 exports.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) {
19326 var strLen = aStr.length;
19329 var continuation, digit;
19332 if (aIndex >= strLen) {
19333 throw new Error("Expected more digits in base 64 VLQ value.");
19336 digit = base64.decode(aStr.charCodeAt(aIndex++));
19337 if (digit === -1) {
19338 throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1));
19341 continuation = !!(digit & VLQ_CONTINUATION_BIT);
19342 digit &= VLQ_BASE_MASK;
19343 result = result + (digit << shift);
19344 shift += VLQ_BASE_SHIFT;
19345 } while (continuation);
19347 aOutParam.value = fromVLQSigned(result);
19348 aOutParam.rest = aIndex;
19351 },{"./base64":146}],146:[function(require,module,exports){
19352 /* -*- Mode: js; js-indent-level: 2; -*- */
19354 * Copyright 2011 Mozilla Foundation and contributors
19355 * Licensed under the New BSD license. See LICENSE or:
19356 * http://opensource.org/licenses/BSD-3-Clause
19359 var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('');
19362 * Encode an integer in the range of 0 to 63 to a single base 64 digit.
19364 exports.encode = function (number) {
19365 if (0 <= number && number < intToCharMap.length) {
19366 return intToCharMap[number];
19368 throw new TypeError("Must be between 0 and 63: " + number);
19372 * Decode a single base 64 character code digit to an integer. Returns -1 on
19375 exports.decode = function (charCode) {
19376 var bigA = 65; // 'A'
19377 var bigZ = 90; // 'Z'
19379 var littleA = 97; // 'a'
19380 var littleZ = 122; // 'z'
19382 var zero = 48; // '0'
19383 var nine = 57; // '9'
19385 var plus = 43; // '+'
19386 var slash = 47; // '/'
19388 var littleOffset = 26;
19389 var numberOffset = 52;
19391 // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ
19392 if (bigA <= charCode && charCode <= bigZ) {
19393 return (charCode - bigA);
19396 // 26 - 51: abcdefghijklmnopqrstuvwxyz
19397 if (littleA <= charCode && charCode <= littleZ) {
19398 return (charCode - littleA + littleOffset);
19401 // 52 - 61: 0123456789
19402 if (zero <= charCode && charCode <= nine) {
19403 return (charCode - zero + numberOffset);
19407 if (charCode == plus) {
19412 if (charCode == slash) {
19416 // Invalid base64 digit.
19420 },{}],147:[function(require,module,exports){
19421 /* -*- Mode: js; js-indent-level: 2; -*- */
19423 * Copyright 2011 Mozilla Foundation and contributors
19424 * Licensed under the New BSD license. See LICENSE or:
19425 * http://opensource.org/licenses/BSD-3-Clause
19428 exports.GREATEST_LOWER_BOUND = 1;
19429 exports.LEAST_UPPER_BOUND = 2;
19432 * Recursive implementation of binary search.
19434 * @param aLow Indices here and lower do not contain the needle.
19435 * @param aHigh Indices here and higher do not contain the needle.
19436 * @param aNeedle The element being searched for.
19437 * @param aHaystack The non-empty array being searched.
19438 * @param aCompare Function which takes two elements and returns -1, 0, or 1.
19439 * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
19440 * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
19441 * closest element that is smaller than or greater than the one we are
19442 * searching for, respectively, if the exact element cannot be found.
19444 function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) {
19445 // This function terminates when one of the following is true:
19447 // 1. We find the exact element we are looking for.
19449 // 2. We did not find the exact element, but we can return the index of
19450 // the next-closest element.
19452 // 3. We did not find the exact element, and there is no next-closest
19453 // element than the one we are searching for, so we return -1.
19454 var mid = Math.floor((aHigh - aLow) / 2) + aLow;
19455 var cmp = aCompare(aNeedle, aHaystack[mid], true);
19457 // Found the element we are looking for.
19460 else if (cmp > 0) {
19461 // Our needle is greater than aHaystack[mid].
19462 if (aHigh - mid > 1) {
19463 // The element is in the upper half.
19464 return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias);
19467 // The exact needle element was not found in this haystack. Determine if
19468 // we are in termination case (3) or (2) and return the appropriate thing.
19469 if (aBias == exports.LEAST_UPPER_BOUND) {
19470 return aHigh < aHaystack.length ? aHigh : -1;
19476 // Our needle is less than aHaystack[mid].
19477 if (mid - aLow > 1) {
19478 // The element is in the lower half.
19479 return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias);
19482 // we are in termination case (3) or (2) and return the appropriate thing.
19483 if (aBias == exports.LEAST_UPPER_BOUND) {
19486 return aLow < 0 ? -1 : aLow;
19492 * This is an implementation of binary search which will always try and return
19493 * the index of the closest element if there is no exact hit. This is because
19494 * mappings between original and generated line/col pairs are single points,
19495 * and there is an implicit region between each of them, so a miss just means
19496 * that you aren't on the very start of a region.
19498 * @param aNeedle The element you are looking for.
19499 * @param aHaystack The array that is being searched.
19500 * @param aCompare A function which takes the needle and an element in the
19501 * array and returns -1, 0, or 1 depending on whether the needle is less
19502 * than, equal to, or greater than the element, respectively.
19503 * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
19504 * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
19505 * closest element that is smaller than or greater than the one we are
19506 * searching for, respectively, if the exact element cannot be found.
19507 * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'.
19509 exports.search = function search(aNeedle, aHaystack, aCompare, aBias) {
19510 if (aHaystack.length === 0) {
19514 var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack,
19515 aCompare, aBias || exports.GREATEST_LOWER_BOUND);
19520 // We have found either the exact element, or the next-closest element than
19521 // the one we are searching for. However, there may be more than one such
19522 // element. Make sure we always return the smallest of these.
19523 while (index - 1 >= 0) {
19524 if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) {
19533 },{}],148:[function(require,module,exports){
19534 /* -*- Mode: js; js-indent-level: 2; -*- */
19536 * Copyright 2014 Mozilla Foundation and contributors
19537 * Licensed under the New BSD license. See LICENSE or:
19538 * http://opensource.org/licenses/BSD-3-Clause
19541 var util = require('./util');
19544 * Determine whether mappingB is after mappingA with respect to generated
19547 function generatedPositionAfter(mappingA, mappingB) {
19548 // Optimized for most common case
19549 var lineA = mappingA.generatedLine;
19550 var lineB = mappingB.generatedLine;
19551 var columnA = mappingA.generatedColumn;
19552 var columnB = mappingB.generatedColumn;
19553 return lineB > lineA || lineB == lineA && columnB >= columnA ||
19554 util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0;
19558 * A data structure to provide a sorted view of accumulated mappings in a
19559 * performance conscious manner. It trades a neglibable overhead in general
19560 * case for a large speedup in case of mappings being added in order.
19562 function MappingList() {
19564 this._sorted = true;
19565 // Serves as infimum
19566 this._last = {generatedLine: -1, generatedColumn: 0};
19570 * Iterate through internal items. This method takes the same arguments that
19571 * `Array.prototype.forEach` takes.
19573 * NOTE: The order of the mappings is NOT guaranteed.
19575 MappingList.prototype.unsortedForEach =
19576 function MappingList_forEach(aCallback, aThisArg) {
19577 this._array.forEach(aCallback, aThisArg);
19581 * Add the given source mapping.
19583 * @param Object aMapping
19585 MappingList.prototype.add = function MappingList_add(aMapping) {
19586 if (generatedPositionAfter(this._last, aMapping)) {
19587 this._last = aMapping;
19588 this._array.push(aMapping);
19590 this._sorted = false;
19591 this._array.push(aMapping);
19596 * Returns the flat, sorted array of mappings. The mappings are sorted by
19597 * generated position.
19599 * WARNING: This method returns internal data without copying, for
19600 * performance. The return value must NOT be mutated, and should be treated as
19601 * an immutable borrow. If you want to take ownership, you must make your own
19604 MappingList.prototype.toArray = function MappingList_toArray() {
19605 if (!this._sorted) {
19606 this._array.sort(util.compareByGeneratedPositionsInflated);
19607 this._sorted = true;
19609 return this._array;
19612 exports.MappingList = MappingList;
19614 },{"./util":153}],149:[function(require,module,exports){
19615 /* -*- Mode: js; js-indent-level: 2; -*- */
19617 * Copyright 2011 Mozilla Foundation and contributors
19618 * Licensed under the New BSD license. See LICENSE or:
19619 * http://opensource.org/licenses/BSD-3-Clause
19622 // It turns out that some (most?) JavaScript engines don't self-host
19623 // `Array.prototype.sort`. This makes sense because C++ will likely remain
19624 // faster than JS when doing raw CPU-intensive sorting. However, when using a
19625 // custom comparator function, calling back and forth between the VM's C++ and
19626 // JIT'd JS is rather slow *and* loses JIT type information, resulting in
19627 // worse generated code for the comparator function than would be optimal. In
19628 // fact, when sorting with a comparator, these costs outweigh the benefits of
19629 // sorting in C++. By using our own JS-implemented Quick Sort (below), we get
19630 // a ~3500ms mean speed-up in `bench/bench.html`.
19633 * Swap the elements indexed by `x` and `y` in the array `ary`.
19635 * @param {Array} ary
19637 * @param {Number} x
19638 * The index of the first item.
19639 * @param {Number} y
19640 * The index of the second item.
19642 function swap(ary, x, y) {
19649 * Returns a random integer within the range `low .. high` inclusive.
19651 * @param {Number} low
19652 * The lower bound on the range.
19653 * @param {Number} high
19654 * The upper bound on the range.
19656 function randomIntInRange(low, high) {
19657 return Math.round(low + (Math.random() * (high - low)));
19661 * The Quick Sort algorithm.
19663 * @param {Array} ary
19664 * An array to sort.
19665 * @param {function} comparator
19666 * Function to use to compare two items.
19667 * @param {Number} p
19668 * Start index of the array
19669 * @param {Number} r
19670 * End index of the array
19672 function doQuickSort(ary, comparator, p, r) {
19673 // If our lower bound is less than our upper bound, we (1) partition the
19674 // array into two pieces and (2) recurse on each half. If it is not, this is
19675 // the empty array and our base case.
19678 // (1) Partitioning.
19680 // The partitioning chooses a pivot between `p` and `r` and moves all
19681 // elements that are less than or equal to the pivot to the before it, and
19682 // all the elements that are greater than it after it. The effect is that
19683 // once partition is done, the pivot is in the exact place it will be when
19684 // the array is put in sorted order, and it will not need to be moved
19685 // again. This runs in O(n) time.
19687 // Always choose a random pivot so that an input array which is reverse
19688 // sorted does not cause O(n^2) running time.
19689 var pivotIndex = randomIntInRange(p, r);
19692 swap(ary, pivotIndex, r);
19693 var pivot = ary[r];
19695 // Immediately after `j` is incremented in this loop, the following hold
19698 // * Every element in `ary[p .. i]` is less than or equal to the pivot.
19700 // * Every element in `ary[i+1 .. j-1]` is greater than the pivot.
19701 for (var j = p; j < r; j++) {
19702 if (comparator(ary[j], pivot) <= 0) {
19708 swap(ary, i + 1, j);
19711 // (2) Recurse on each half.
19713 doQuickSort(ary, comparator, p, q - 1);
19714 doQuickSort(ary, comparator, q + 1, r);
19719 * Sort the given array in-place with the given comparator function.
19721 * @param {Array} ary
19722 * An array to sort.
19723 * @param {function} comparator
19724 * Function to use to compare two items.
19726 exports.quickSort = function (ary, comparator) {
19727 doQuickSort(ary, comparator, 0, ary.length - 1);
19730 },{}],150:[function(require,module,exports){
19731 /* -*- Mode: js; js-indent-level: 2; -*- */
19733 * Copyright 2011 Mozilla Foundation and contributors
19734 * Licensed under the New BSD license. See LICENSE or:
19735 * http://opensource.org/licenses/BSD-3-Clause
19738 var util = require('./util');
19739 var binarySearch = require('./binary-search');
19740 var ArraySet = require('./array-set').ArraySet;
19741 var base64VLQ = require('./base64-vlq');
19742 var quickSort = require('./quick-sort').quickSort;
19744 function SourceMapConsumer(aSourceMap, aSourceMapURL) {
19745 var sourceMap = aSourceMap;
19746 if (typeof aSourceMap === 'string') {
19747 sourceMap = util.parseSourceMapInput(aSourceMap);
19750 return sourceMap.sections != null
19751 ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL)
19752 : new BasicSourceMapConsumer(sourceMap, aSourceMapURL);
19755 SourceMapConsumer.fromSourceMap = function(aSourceMap, aSourceMapURL) {
19756 return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL);
19760 * The version of the source mapping spec that we are consuming.
19762 SourceMapConsumer.prototype._version = 3;
19764 // `__generatedMappings` and `__originalMappings` are arrays that hold the
19765 // parsed mapping coordinates from the source map's "mappings" attribute. They
19766 // are lazily instantiated, accessed via the `_generatedMappings` and
19767 // `_originalMappings` getters respectively, and we only parse the mappings
19768 // and create these arrays once queried for a source location. We jump through
19769 // these hoops because there can be many thousands of mappings, and parsing
19770 // them is expensive, so we only want to do it if we must.
19772 // Each object in the arrays is of the form:
19775 // generatedLine: The line number in the generated code,
19776 // generatedColumn: The column number in the generated code,
19777 // source: The path to the original source file that generated this
19779 // originalLine: The line number in the original source that
19780 // corresponds to this chunk of generated code,
19781 // originalColumn: The column number in the original source that
19782 // corresponds to this chunk of generated code,
19783 // name: The name of the original symbol which generated this chunk of
19787 // All properties except for `generatedLine` and `generatedColumn` can be
19790 // `_generatedMappings` is ordered by the generated positions.
19792 // `_originalMappings` is ordered by the original positions.
19794 SourceMapConsumer.prototype.__generatedMappings = null;
19795 Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', {
19796 configurable: true,
19799 if (!this.__generatedMappings) {
19800 this._parseMappings(this._mappings, this.sourceRoot);
19803 return this.__generatedMappings;
19807 SourceMapConsumer.prototype.__originalMappings = null;
19808 Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', {
19809 configurable: true,
19812 if (!this.__originalMappings) {
19813 this._parseMappings(this._mappings, this.sourceRoot);
19816 return this.__originalMappings;
19820 SourceMapConsumer.prototype._charIsMappingSeparator =
19821 function SourceMapConsumer_charIsMappingSeparator(aStr, index) {
19822 var c = aStr.charAt(index);
19823 return c === ";" || c === ",";
19827 * Parse the mappings in a string in to a data structure which we can easily
19828 * query (the ordered arrays in the `this.__generatedMappings` and
19829 * `this.__originalMappings` properties).
19831 SourceMapConsumer.prototype._parseMappings =
19832 function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
19833 throw new Error("Subclasses must implement _parseMappings");
19836 SourceMapConsumer.GENERATED_ORDER = 1;
19837 SourceMapConsumer.ORIGINAL_ORDER = 2;
19839 SourceMapConsumer.GREATEST_LOWER_BOUND = 1;
19840 SourceMapConsumer.LEAST_UPPER_BOUND = 2;
19843 * Iterate over each mapping between an original source/line/column and a
19844 * generated line/column in this source map.
19846 * @param Function aCallback
19847 * The function that is called with each mapping.
19848 * @param Object aContext
19849 * Optional. If specified, this object will be the value of `this` every
19850 * time that `aCallback` is called.
19852 * Either `SourceMapConsumer.GENERATED_ORDER` or
19853 * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to
19854 * iterate over the mappings sorted by the generated file's line/column
19855 * order or the original's source/line/column order, respectively. Defaults to
19856 * `SourceMapConsumer.GENERATED_ORDER`.
19858 SourceMapConsumer.prototype.eachMapping =
19859 function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) {
19860 var context = aContext || null;
19861 var order = aOrder || SourceMapConsumer.GENERATED_ORDER;
19865 case SourceMapConsumer.GENERATED_ORDER:
19866 mappings = this._generatedMappings;
19868 case SourceMapConsumer.ORIGINAL_ORDER:
19869 mappings = this._originalMappings;
19872 throw new Error("Unknown order of iteration.");
19875 var sourceRoot = this.sourceRoot;
19876 mappings.map(function (mapping) {
19877 var source = mapping.source === null ? null : this._sources.at(mapping.source);
19878 source = util.computeSourceURL(sourceRoot, source, this._sourceMapURL);
19881 generatedLine: mapping.generatedLine,
19882 generatedColumn: mapping.generatedColumn,
19883 originalLine: mapping.originalLine,
19884 originalColumn: mapping.originalColumn,
19885 name: mapping.name === null ? null : this._names.at(mapping.name)
19887 }, this).forEach(aCallback, context);
19891 * Returns all generated line and column information for the original source,
19892 * line, and column provided. If no column is provided, returns all mappings
19893 * corresponding to a either the line we are searching for or the next
19894 * closest line that has any mappings. Otherwise, returns all mappings
19895 * corresponding to the given line and either the column we are searching for
19896 * or the next closest column that has any offsets.
19898 * The only argument is an object with the following properties:
19900 * - source: The filename of the original source.
19901 * - line: The line number in the original source. The line number is 1-based.
19902 * - column: Optional. the column number in the original source.
19903 * The column number is 0-based.
19905 * and an array of objects is returned, each with the following properties:
19907 * - line: The line number in the generated source, or null. The
19908 * line number is 1-based.
19909 * - column: The column number in the generated source, or null.
19910 * The column number is 0-based.
19912 SourceMapConsumer.prototype.allGeneratedPositionsFor =
19913 function SourceMapConsumer_allGeneratedPositionsFor(aArgs) {
19914 var line = util.getArg(aArgs, 'line');
19916 // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping
19917 // returns the index of the closest mapping less than the needle. By
19918 // setting needle.originalColumn to 0, we thus find the last mapping for
19919 // the given line, provided such a mapping exists.
19921 source: util.getArg(aArgs, 'source'),
19922 originalLine: line,
19923 originalColumn: util.getArg(aArgs, 'column', 0)
19926 needle.source = this._findSourceIndex(needle.source);
19927 if (needle.source < 0) {
19933 var index = this._findMapping(needle,
19934 this._originalMappings,
19937 util.compareByOriginalPositions,
19938 binarySearch.LEAST_UPPER_BOUND);
19940 var mapping = this._originalMappings[index];
19942 if (aArgs.column === undefined) {
19943 var originalLine = mapping.originalLine;
19945 // Iterate until either we run out of mappings, or we run into
19946 // a mapping for a different line than the one we found. Since
19947 // mappings are sorted, this is guaranteed to find all mappings for
19948 // the line we found.
19949 while (mapping && mapping.originalLine === originalLine) {
19951 line: util.getArg(mapping, 'generatedLine', null),
19952 column: util.getArg(mapping, 'generatedColumn', null),
19953 lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
19956 mapping = this._originalMappings[++index];
19959 var originalColumn = mapping.originalColumn;
19961 // Iterate until either we run out of mappings, or we run into
19962 // a mapping for a different line than the one we were searching for.
19963 // Since mappings are sorted, this is guaranteed to find all mappings for
19964 // the line we are searching for.
19966 mapping.originalLine === line &&
19967 mapping.originalColumn == originalColumn) {
19969 line: util.getArg(mapping, 'generatedLine', null),
19970 column: util.getArg(mapping, 'generatedColumn', null),
19971 lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
19974 mapping = this._originalMappings[++index];
19982 exports.SourceMapConsumer = SourceMapConsumer;
19985 * A BasicSourceMapConsumer instance represents a parsed source map which we can
19986 * query for information about the original file positions by giving it a file
19987 * position in the generated source.
19989 * The first parameter is the raw source map (either as a JSON string, or
19990 * already parsed to an object). According to the spec, source maps have the
19991 * following attributes:
19993 * - version: Which version of the source map spec this map is following.
19994 * - sources: An array of URLs to the original source files.
19995 * - names: An array of identifiers which can be referrenced by individual mappings.
19996 * - sourceRoot: Optional. The URL root from which all sources are relative.
19997 * - sourcesContent: Optional. An array of contents of the original source files.
19998 * - mappings: A string of base64 VLQs which contain the actual mappings.
19999 * - file: Optional. The generated file this source map is associated with.
20001 * Here is an example source map, taken from the source map spec[0]:
20007 * sources: ["foo.js", "bar.js"],
20008 * names: ["src", "maps", "are", "fun"],
20009 * mappings: "AA,AB;;ABCDE;"
20012 * The second parameter, if given, is a string whose value is the URL
20013 * at which the source map was found. This URL is used to compute the
20016 * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1#
20018 function BasicSourceMapConsumer(aSourceMap, aSourceMapURL) {
20019 var sourceMap = aSourceMap;
20020 if (typeof aSourceMap === 'string') {
20021 sourceMap = util.parseSourceMapInput(aSourceMap);
20024 var version = util.getArg(sourceMap, 'version');
20025 var sources = util.getArg(sourceMap, 'sources');
20026 // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which
20027 // requires the array) to play nice here.
20028 var names = util.getArg(sourceMap, 'names', []);
20029 var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null);
20030 var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null);
20031 var mappings = util.getArg(sourceMap, 'mappings');
20032 var file = util.getArg(sourceMap, 'file', null);
20034 // Once again, Sass deviates from the spec and supplies the version as a
20035 // string rather than a number, so we use loose equality checking here.
20036 if (version != this._version) {
20037 throw new Error('Unsupported version: ' + version);
20041 sourceRoot = util.normalize(sourceRoot);
20046 // Some source maps produce relative source paths like "./foo.js" instead of
20047 // "foo.js". Normalize these first so that future comparisons will succeed.
20048 // See bugzil.la/1090768.
20049 .map(util.normalize)
20050 // Always ensure that absolute sources are internally stored relative to
20051 // the source root, if the source root is absolute. Not doing this would
20052 // be particularly problematic when the source root is a prefix of the
20053 // source (valid, but why??). See github issue #199 and bugzil.la/1188982.
20054 .map(function (source) {
20055 return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source)
20056 ? util.relative(sourceRoot, source)
20060 // Pass `true` below to allow duplicate names and sources. While source maps
20061 // are intended to be compressed and deduplicated, the TypeScript compiler
20062 // sometimes generates source maps with duplicates in them. See Github issue
20063 // #72 and bugzil.la/889492.
20064 this._names = ArraySet.fromArray(names.map(String), true);
20065 this._sources = ArraySet.fromArray(sources, true);
20067 this._absoluteSources = this._sources.toArray().map(function (s) {
20068 return util.computeSourceURL(sourceRoot, s, aSourceMapURL);
20071 this.sourceRoot = sourceRoot;
20072 this.sourcesContent = sourcesContent;
20073 this._mappings = mappings;
20074 this._sourceMapURL = aSourceMapURL;
20078 BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);
20079 BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer;
20082 * Utility function to find the index of a source. Returns -1 if not
20085 BasicSourceMapConsumer.prototype._findSourceIndex = function(aSource) {
20086 var relativeSource = aSource;
20087 if (this.sourceRoot != null) {
20088 relativeSource = util.relative(this.sourceRoot, relativeSource);
20091 if (this._sources.has(relativeSource)) {
20092 return this._sources.indexOf(relativeSource);
20095 // Maybe aSource is an absolute URL as returned by |sources|. In
20096 // this case we can't simply undo the transform.
20098 for (i = 0; i < this._absoluteSources.length; ++i) {
20099 if (this._absoluteSources[i] == aSource) {
20108 * Create a BasicSourceMapConsumer from a SourceMapGenerator.
20110 * @param SourceMapGenerator aSourceMap
20111 * The source map that will be consumed.
20112 * @param String aSourceMapURL
20113 * The URL at which the source map can be found (optional)
20114 * @returns BasicSourceMapConsumer
20116 BasicSourceMapConsumer.fromSourceMap =
20117 function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) {
20118 var smc = Object.create(BasicSourceMapConsumer.prototype);
20120 var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true);
20121 var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true);
20122 smc.sourceRoot = aSourceMap._sourceRoot;
20123 smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(),
20125 smc.file = aSourceMap._file;
20126 smc._sourceMapURL = aSourceMapURL;
20127 smc._absoluteSources = smc._sources.toArray().map(function (s) {
20128 return util.computeSourceURL(smc.sourceRoot, s, aSourceMapURL);
20131 // Because we are modifying the entries (by converting string sources and
20132 // names to indices into the sources and names ArraySets), we have to make
20133 // a copy of the entry or else bad things happen. Shared mutable state
20134 // strikes again! See github issue #191.
20136 var generatedMappings = aSourceMap._mappings.toArray().slice();
20137 var destGeneratedMappings = smc.__generatedMappings = [];
20138 var destOriginalMappings = smc.__originalMappings = [];
20140 for (var i = 0, length = generatedMappings.length; i < length; i++) {
20141 var srcMapping = generatedMappings[i];
20142 var destMapping = new Mapping;
20143 destMapping.generatedLine = srcMapping.generatedLine;
20144 destMapping.generatedColumn = srcMapping.generatedColumn;
20146 if (srcMapping.source) {
20147 destMapping.source = sources.indexOf(srcMapping.source);
20148 destMapping.originalLine = srcMapping.originalLine;
20149 destMapping.originalColumn = srcMapping.originalColumn;
20151 if (srcMapping.name) {
20152 destMapping.name = names.indexOf(srcMapping.name);
20155 destOriginalMappings.push(destMapping);
20158 destGeneratedMappings.push(destMapping);
20161 quickSort(smc.__originalMappings, util.compareByOriginalPositions);
20167 * The version of the source mapping spec that we are consuming.
20169 BasicSourceMapConsumer.prototype._version = 3;
20172 * The list of original sources.
20174 Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', {
20176 return this._absoluteSources.slice();
20181 * Provide the JIT with a nice shape / hidden class.
20183 function Mapping() {
20184 this.generatedLine = 0;
20185 this.generatedColumn = 0;
20186 this.source = null;
20187 this.originalLine = null;
20188 this.originalColumn = null;
20193 * Parse the mappings in a string in to a data structure which we can easily
20194 * query (the ordered arrays in the `this.__generatedMappings` and
20195 * `this.__originalMappings` properties).
20197 BasicSourceMapConsumer.prototype._parseMappings =
20198 function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
20199 var generatedLine = 1;
20200 var previousGeneratedColumn = 0;
20201 var previousOriginalLine = 0;
20202 var previousOriginalColumn = 0;
20203 var previousSource = 0;
20204 var previousName = 0;
20205 var length = aStr.length;
20207 var cachedSegments = {};
20209 var originalMappings = [];
20210 var generatedMappings = [];
20211 var mapping, str, segment, end, value;
20213 while (index < length) {
20214 if (aStr.charAt(index) === ';') {
20217 previousGeneratedColumn = 0;
20219 else if (aStr.charAt(index) === ',') {
20223 mapping = new Mapping();
20224 mapping.generatedLine = generatedLine;
20226 // Because each offset is encoded relative to the previous one,
20227 // many segments often have the same encoding. We can exploit this
20228 // fact by caching the parsed variable length fields of each segment,
20229 // allowing us to avoid a second parse if we encounter the same
20231 for (end = index; end < length; end++) {
20232 if (this._charIsMappingSeparator(aStr, end)) {
20236 str = aStr.slice(index, end);
20238 segment = cachedSegments[str];
20240 index += str.length;
20243 while (index < end) {
20244 base64VLQ.decode(aStr, index, temp);
20245 value = temp.value;
20247 segment.push(value);
20250 if (segment.length === 2) {
20251 throw new Error('Found a source, but no line and column');
20254 if (segment.length === 3) {
20255 throw new Error('Found a source and line, but no column');
20258 cachedSegments[str] = segment;
20261 // Generated column.
20262 mapping.generatedColumn = previousGeneratedColumn + segment[0];
20263 previousGeneratedColumn = mapping.generatedColumn;
20265 if (segment.length > 1) {
20266 // Original source.
20267 mapping.source = previousSource + segment[1];
20268 previousSource += segment[1];
20271 mapping.originalLine = previousOriginalLine + segment[2];
20272 previousOriginalLine = mapping.originalLine;
20273 // Lines are stored 0-based
20274 mapping.originalLine += 1;
20276 // Original column.
20277 mapping.originalColumn = previousOriginalColumn + segment[3];
20278 previousOriginalColumn = mapping.originalColumn;
20280 if (segment.length > 4) {
20282 mapping.name = previousName + segment[4];
20283 previousName += segment[4];
20287 generatedMappings.push(mapping);
20288 if (typeof mapping.originalLine === 'number') {
20289 originalMappings.push(mapping);
20294 quickSort(generatedMappings, util.compareByGeneratedPositionsDeflated);
20295 this.__generatedMappings = generatedMappings;
20297 quickSort(originalMappings, util.compareByOriginalPositions);
20298 this.__originalMappings = originalMappings;
20302 * Find the mapping that best matches the hypothetical "needle" mapping that
20303 * we are searching for in the given "haystack" of mappings.
20305 BasicSourceMapConsumer.prototype._findMapping =
20306 function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName,
20307 aColumnName, aComparator, aBias) {
20308 // To return the position we are searching for, we must first find the
20309 // mapping for the given position and then return the opposite position it
20310 // points to. Because the mappings are sorted, we can use binary search to
20311 // find the best mapping.
20313 if (aNeedle[aLineName] <= 0) {
20314 throw new TypeError('Line must be greater than or equal to 1, got '
20315 + aNeedle[aLineName]);
20317 if (aNeedle[aColumnName] < 0) {
20318 throw new TypeError('Column must be greater than or equal to 0, got '
20319 + aNeedle[aColumnName]);
20322 return binarySearch.search(aNeedle, aMappings, aComparator, aBias);
20326 * Compute the last column for each generated mapping. The last column is
20329 BasicSourceMapConsumer.prototype.computeColumnSpans =
20330 function SourceMapConsumer_computeColumnSpans() {
20331 for (var index = 0; index < this._generatedMappings.length; ++index) {
20332 var mapping = this._generatedMappings[index];
20334 // Mappings do not contain a field for the last generated columnt. We
20335 // can come up with an optimistic estimate, however, by assuming that
20336 // mappings are contiguous (i.e. given two consecutive mappings, the
20337 // first mapping ends where the second one starts).
20338 if (index + 1 < this._generatedMappings.length) {
20339 var nextMapping = this._generatedMappings[index + 1];
20341 if (mapping.generatedLine === nextMapping.generatedLine) {
20342 mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1;
20347 // The last mapping for each line spans the entire line.
20348 mapping.lastGeneratedColumn = Infinity;
20353 * Returns the original source, line, and column information for the generated
20354 * source's line and column positions provided. The only argument is an object
20355 * with the following properties:
20357 * - line: The line number in the generated source. The line number
20359 * - column: The column number in the generated source. The column
20360 * number is 0-based.
20361 * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
20362 * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
20363 * closest element that is smaller than or greater than the one we are
20364 * searching for, respectively, if the exact element cannot be found.
20365 * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
20367 * and an object is returned with the following properties:
20369 * - source: The original source file, or null.
20370 * - line: The line number in the original source, or null. The
20371 * line number is 1-based.
20372 * - column: The column number in the original source, or null. The
20373 * column number is 0-based.
20374 * - name: The original identifier, or null.
20376 BasicSourceMapConsumer.prototype.originalPositionFor =
20377 function SourceMapConsumer_originalPositionFor(aArgs) {
20379 generatedLine: util.getArg(aArgs, 'line'),
20380 generatedColumn: util.getArg(aArgs, 'column')
20383 var index = this._findMapping(
20385 this._generatedMappings,
20388 util.compareByGeneratedPositionsDeflated,
20389 util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)
20393 var mapping = this._generatedMappings[index];
20395 if (mapping.generatedLine === needle.generatedLine) {
20396 var source = util.getArg(mapping, 'source', null);
20397 if (source !== null) {
20398 source = this._sources.at(source);
20399 source = util.computeSourceURL(this.sourceRoot, source, this._sourceMapURL);
20401 var name = util.getArg(mapping, 'name', null);
20402 if (name !== null) {
20403 name = this._names.at(name);
20407 line: util.getArg(mapping, 'originalLine', null),
20408 column: util.getArg(mapping, 'originalColumn', null),
20423 * Return true if we have the source content for every source in the source
20424 * map, false otherwise.
20426 BasicSourceMapConsumer.prototype.hasContentsOfAllSources =
20427 function BasicSourceMapConsumer_hasContentsOfAllSources() {
20428 if (!this.sourcesContent) {
20431 return this.sourcesContent.length >= this._sources.size() &&
20432 !this.sourcesContent.some(function (sc) { return sc == null; });
20436 * Returns the original source content. The only argument is the url of the
20437 * original source file. Returns null if no original source content is
20440 BasicSourceMapConsumer.prototype.sourceContentFor =
20441 function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
20442 if (!this.sourcesContent) {
20446 var index = this._findSourceIndex(aSource);
20448 return this.sourcesContent[index];
20451 var relativeSource = aSource;
20452 if (this.sourceRoot != null) {
20453 relativeSource = util.relative(this.sourceRoot, relativeSource);
20457 if (this.sourceRoot != null
20458 && (url = util.urlParse(this.sourceRoot))) {
20459 // XXX: file:// URIs and absolute paths lead to unexpected behavior for
20460 // many users. We can help them out when they expect file:// URIs to
20461 // behave like it would if they were running a local HTTP server. See
20462 // https://bugzilla.mozilla.org/show_bug.cgi?id=885597.
20463 var fileUriAbsPath = relativeSource.replace(/^file:\/\//, "");
20464 if (url.scheme == "file"
20465 && this._sources.has(fileUriAbsPath)) {
20466 return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]
20469 if ((!url.path || url.path == "/")
20470 && this._sources.has("/" + relativeSource)) {
20471 return this.sourcesContent[this._sources.indexOf("/" + relativeSource)];
20475 // This function is used recursively from
20476 // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we
20477 // don't want to throw if we can't find the source - we just want to
20478 // return null, so we provide a flag to exit gracefully.
20479 if (nullOnMissing) {
20483 throw new Error('"' + relativeSource + '" is not in the SourceMap.');
20488 * Returns the generated line and column information for the original source,
20489 * line, and column positions provided. The only argument is an object with
20490 * the following properties:
20492 * - source: The filename of the original source.
20493 * - line: The line number in the original source. The line number
20495 * - column: The column number in the original source. The column
20496 * number is 0-based.
20497 * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
20498 * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
20499 * closest element that is smaller than or greater than the one we are
20500 * searching for, respectively, if the exact element cannot be found.
20501 * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
20503 * and an object is returned with the following properties:
20505 * - line: The line number in the generated source, or null. The
20506 * line number is 1-based.
20507 * - column: The column number in the generated source, or null.
20508 * The column number is 0-based.
20510 BasicSourceMapConsumer.prototype.generatedPositionFor =
20511 function SourceMapConsumer_generatedPositionFor(aArgs) {
20512 var source = util.getArg(aArgs, 'source');
20513 source = this._findSourceIndex(source);
20524 originalLine: util.getArg(aArgs, 'line'),
20525 originalColumn: util.getArg(aArgs, 'column')
20528 var index = this._findMapping(
20530 this._originalMappings,
20533 util.compareByOriginalPositions,
20534 util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)
20538 var mapping = this._originalMappings[index];
20540 if (mapping.source === needle.source) {
20542 line: util.getArg(mapping, 'generatedLine', null),
20543 column: util.getArg(mapping, 'generatedColumn', null),
20544 lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
20556 exports.BasicSourceMapConsumer = BasicSourceMapConsumer;
20559 * An IndexedSourceMapConsumer instance represents a parsed source map which
20560 * we can query for information. It differs from BasicSourceMapConsumer in
20561 * that it takes "indexed" source maps (i.e. ones with a "sections" field) as
20564 * The first parameter is a raw source map (either as a JSON string, or already
20565 * parsed to an object). According to the spec for indexed source maps, they
20566 * have the following attributes:
20568 * - version: Which version of the source map spec this map is following.
20569 * - file: Optional. The generated file this source map is associated with.
20570 * - sections: A list of section definitions.
20572 * Each value under the "sections" field has two fields:
20573 * - offset: The offset into the original specified at which this section
20574 * begins to apply, defined as an object with a "line" and "column"
20576 * - map: A source map definition. This source map could also be indexed,
20577 * but doesn't have to be.
20579 * Instead of the "map" field, it's also possible to have a "url" field
20580 * specifying a URL to retrieve a source map from, but that's currently
20583 * Here's an example source map, taken from the source map spec[0], but
20584 * modified to omit a section which uses the "url" field.
20590 * offset: {line:100, column:10},
20593 * file: "section.js",
20594 * sources: ["foo.js", "bar.js"],
20595 * names: ["src", "maps", "are", "fun"],
20596 * mappings: "AAAA,E;;ABCDE;"
20601 * The second parameter, if given, is a string whose value is the URL
20602 * at which the source map was found. This URL is used to compute the
20605 * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt
20607 function IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) {
20608 var sourceMap = aSourceMap;
20609 if (typeof aSourceMap === 'string') {
20610 sourceMap = util.parseSourceMapInput(aSourceMap);
20613 var version = util.getArg(sourceMap, 'version');
20614 var sections = util.getArg(sourceMap, 'sections');
20616 if (version != this._version) {
20617 throw new Error('Unsupported version: ' + version);
20620 this._sources = new ArraySet();
20621 this._names = new ArraySet();
20627 this._sections = sections.map(function (s) {
20629 // The url field will require support for asynchronicity.
20630 // See https://github.com/mozilla/source-map/issues/16
20631 throw new Error('Support for url field in sections not implemented.');
20633 var offset = util.getArg(s, 'offset');
20634 var offsetLine = util.getArg(offset, 'line');
20635 var offsetColumn = util.getArg(offset, 'column');
20637 if (offsetLine < lastOffset.line ||
20638 (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) {
20639 throw new Error('Section offsets must be ordered and non-overlapping.');
20641 lastOffset = offset;
20645 // The offset fields are 0-based, but we use 1-based indices when
20646 // encoding/decoding from VLQ.
20647 generatedLine: offsetLine + 1,
20648 generatedColumn: offsetColumn + 1
20650 consumer: new SourceMapConsumer(util.getArg(s, 'map'), aSourceMapURL)
20655 IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);
20656 IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer;
20659 * The version of the source mapping spec that we are consuming.
20661 IndexedSourceMapConsumer.prototype._version = 3;
20664 * The list of original sources.
20666 Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', {
20669 for (var i = 0; i < this._sections.length; i++) {
20670 for (var j = 0; j < this._sections[i].consumer.sources.length; j++) {
20671 sources.push(this._sections[i].consumer.sources[j]);
20679 * Returns the original source, line, and column information for the generated
20680 * source's line and column positions provided. The only argument is an object
20681 * with the following properties:
20683 * - line: The line number in the generated source. The line number
20685 * - column: The column number in the generated source. The column
20686 * number is 0-based.
20688 * and an object is returned with the following properties:
20690 * - source: The original source file, or null.
20691 * - line: The line number in the original source, or null. The
20692 * line number is 1-based.
20693 * - column: The column number in the original source, or null. The
20694 * column number is 0-based.
20695 * - name: The original identifier, or null.
20697 IndexedSourceMapConsumer.prototype.originalPositionFor =
20698 function IndexedSourceMapConsumer_originalPositionFor(aArgs) {
20700 generatedLine: util.getArg(aArgs, 'line'),
20701 generatedColumn: util.getArg(aArgs, 'column')
20704 // Find the section containing the generated position we're trying to map
20705 // to an original position.
20706 var sectionIndex = binarySearch.search(needle, this._sections,
20707 function(needle, section) {
20708 var cmp = needle.generatedLine - section.generatedOffset.generatedLine;
20713 return (needle.generatedColumn -
20714 section.generatedOffset.generatedColumn);
20716 var section = this._sections[sectionIndex];
20727 return section.consumer.originalPositionFor({
20728 line: needle.generatedLine -
20729 (section.generatedOffset.generatedLine - 1),
20730 column: needle.generatedColumn -
20731 (section.generatedOffset.generatedLine === needle.generatedLine
20732 ? section.generatedOffset.generatedColumn - 1
20739 * Return true if we have the source content for every source in the source
20740 * map, false otherwise.
20742 IndexedSourceMapConsumer.prototype.hasContentsOfAllSources =
20743 function IndexedSourceMapConsumer_hasContentsOfAllSources() {
20744 return this._sections.every(function (s) {
20745 return s.consumer.hasContentsOfAllSources();
20750 * Returns the original source content. The only argument is the url of the
20751 * original source file. Returns null if no original source content is
20754 IndexedSourceMapConsumer.prototype.sourceContentFor =
20755 function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
20756 for (var i = 0; i < this._sections.length; i++) {
20757 var section = this._sections[i];
20759 var content = section.consumer.sourceContentFor(aSource, true);
20764 if (nullOnMissing) {
20768 throw new Error('"' + aSource + '" is not in the SourceMap.');
20773 * Returns the generated line and column information for the original source,
20774 * line, and column positions provided. The only argument is an object with
20775 * the following properties:
20777 * - source: The filename of the original source.
20778 * - line: The line number in the original source. The line number
20780 * - column: The column number in the original source. The column
20781 * number is 0-based.
20783 * and an object is returned with the following properties:
20785 * - line: The line number in the generated source, or null. The
20786 * line number is 1-based.
20787 * - column: The column number in the generated source, or null.
20788 * The column number is 0-based.
20790 IndexedSourceMapConsumer.prototype.generatedPositionFor =
20791 function IndexedSourceMapConsumer_generatedPositionFor(aArgs) {
20792 for (var i = 0; i < this._sections.length; i++) {
20793 var section = this._sections[i];
20795 // Only consider this section if the requested source is in the list of
20796 // sources of the consumer.
20797 if (section.consumer._findSourceIndex(util.getArg(aArgs, 'source')) === -1) {
20800 var generatedPosition = section.consumer.generatedPositionFor(aArgs);
20801 if (generatedPosition) {
20803 line: generatedPosition.line +
20804 (section.generatedOffset.generatedLine - 1),
20805 column: generatedPosition.column +
20806 (section.generatedOffset.generatedLine === generatedPosition.line
20807 ? section.generatedOffset.generatedColumn - 1
20821 * Parse the mappings in a string in to a data structure which we can easily
20822 * query (the ordered arrays in the `this.__generatedMappings` and
20823 * `this.__originalMappings` properties).
20825 IndexedSourceMapConsumer.prototype._parseMappings =
20826 function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) {
20827 this.__generatedMappings = [];
20828 this.__originalMappings = [];
20829 for (var i = 0; i < this._sections.length; i++) {
20830 var section = this._sections[i];
20831 var sectionMappings = section.consumer._generatedMappings;
20832 for (var j = 0; j < sectionMappings.length; j++) {
20833 var mapping = sectionMappings[j];
20835 var source = section.consumer._sources.at(mapping.source);
20836 source = util.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL);
20837 this._sources.add(source);
20838 source = this._sources.indexOf(source);
20841 if (mapping.name) {
20842 name = section.consumer._names.at(mapping.name);
20843 this._names.add(name);
20844 name = this._names.indexOf(name);
20847 // The mappings coming from the consumer for the section have
20848 // generated positions relative to the start of the section, so we
20849 // need to offset them to be relative to the start of the concatenated
20851 var adjustedMapping = {
20853 generatedLine: mapping.generatedLine +
20854 (section.generatedOffset.generatedLine - 1),
20855 generatedColumn: mapping.generatedColumn +
20856 (section.generatedOffset.generatedLine === mapping.generatedLine
20857 ? section.generatedOffset.generatedColumn - 1
20859 originalLine: mapping.originalLine,
20860 originalColumn: mapping.originalColumn,
20864 this.__generatedMappings.push(adjustedMapping);
20865 if (typeof adjustedMapping.originalLine === 'number') {
20866 this.__originalMappings.push(adjustedMapping);
20871 quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated);
20872 quickSort(this.__originalMappings, util.compareByOriginalPositions);
20875 exports.IndexedSourceMapConsumer = IndexedSourceMapConsumer;
20877 },{"./array-set":144,"./base64-vlq":145,"./binary-search":147,"./quick-sort":149,"./util":153}],151:[function(require,module,exports){
20878 /* -*- Mode: js; js-indent-level: 2; -*- */
20880 * Copyright 2011 Mozilla Foundation and contributors
20881 * Licensed under the New BSD license. See LICENSE or:
20882 * http://opensource.org/licenses/BSD-3-Clause
20885 var base64VLQ = require('./base64-vlq');
20886 var util = require('./util');
20887 var ArraySet = require('./array-set').ArraySet;
20888 var MappingList = require('./mapping-list').MappingList;
20891 * An instance of the SourceMapGenerator represents a source map which is
20892 * being built incrementally. You may pass an object with the following
20895 * - file: The filename of the generated source.
20896 * - sourceRoot: A root for all relative URLs in this source map.
20898 function SourceMapGenerator(aArgs) {
20902 this._file = util.getArg(aArgs, 'file', null);
20903 this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null);
20904 this._skipValidation = util.getArg(aArgs, 'skipValidation', false);
20905 this._sources = new ArraySet();
20906 this._names = new ArraySet();
20907 this._mappings = new MappingList();
20908 this._sourcesContents = null;
20911 SourceMapGenerator.prototype._version = 3;
20914 * Creates a new SourceMapGenerator based on a SourceMapConsumer
20916 * @param aSourceMapConsumer The SourceMap.
20918 SourceMapGenerator.fromSourceMap =
20919 function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) {
20920 var sourceRoot = aSourceMapConsumer.sourceRoot;
20921 var generator = new SourceMapGenerator({
20922 file: aSourceMapConsumer.file,
20923 sourceRoot: sourceRoot
20925 aSourceMapConsumer.eachMapping(function (mapping) {
20928 line: mapping.generatedLine,
20929 column: mapping.generatedColumn
20933 if (mapping.source != null) {
20934 newMapping.source = mapping.source;
20935 if (sourceRoot != null) {
20936 newMapping.source = util.relative(sourceRoot, newMapping.source);
20939 newMapping.original = {
20940 line: mapping.originalLine,
20941 column: mapping.originalColumn
20944 if (mapping.name != null) {
20945 newMapping.name = mapping.name;
20949 generator.addMapping(newMapping);
20951 aSourceMapConsumer.sources.forEach(function (sourceFile) {
20952 var sourceRelative = sourceFile;
20953 if (sourceRoot !== null) {
20954 sourceRelative = util.relative(sourceRoot, sourceFile);
20957 if (!generator._sources.has(sourceRelative)) {
20958 generator._sources.add(sourceRelative);
20961 var content = aSourceMapConsumer.sourceContentFor(sourceFile);
20962 if (content != null) {
20963 generator.setSourceContent(sourceFile, content);
20970 * Add a single mapping from original source line and column to the generated
20971 * source's line and column for this source map being created. The mapping
20972 * object should have the following properties:
20974 * - generated: An object with the generated line and column positions.
20975 * - original: An object with the original line and column positions.
20976 * - source: The original source file (relative to the sourceRoot).
20977 * - name: An optional original token name for this mapping.
20979 SourceMapGenerator.prototype.addMapping =
20980 function SourceMapGenerator_addMapping(aArgs) {
20981 var generated = util.getArg(aArgs, 'generated');
20982 var original = util.getArg(aArgs, 'original', null);
20983 var source = util.getArg(aArgs, 'source', null);
20984 var name = util.getArg(aArgs, 'name', null);
20986 if (!this._skipValidation) {
20987 this._validateMapping(generated, original, source, name);
20990 if (source != null) {
20991 source = String(source);
20992 if (!this._sources.has(source)) {
20993 this._sources.add(source);
20997 if (name != null) {
20998 name = String(name);
20999 if (!this._names.has(name)) {
21000 this._names.add(name);
21004 this._mappings.add({
21005 generatedLine: generated.line,
21006 generatedColumn: generated.column,
21007 originalLine: original != null && original.line,
21008 originalColumn: original != null && original.column,
21015 * Set the source content for a source file.
21017 SourceMapGenerator.prototype.setSourceContent =
21018 function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) {
21019 var source = aSourceFile;
21020 if (this._sourceRoot != null) {
21021 source = util.relative(this._sourceRoot, source);
21024 if (aSourceContent != null) {
21025 // Add the source content to the _sourcesContents map.
21026 // Create a new _sourcesContents map if the property is null.
21027 if (!this._sourcesContents) {
21028 this._sourcesContents = Object.create(null);
21030 this._sourcesContents[util.toSetString(source)] = aSourceContent;
21031 } else if (this._sourcesContents) {
21032 // Remove the source file from the _sourcesContents map.
21033 // If the _sourcesContents map is empty, set the property to null.
21034 delete this._sourcesContents[util.toSetString(source)];
21035 if (Object.keys(this._sourcesContents).length === 0) {
21036 this._sourcesContents = null;
21042 * Applies the mappings of a sub-source-map for a specific source file to the
21043 * source map being generated. Each mapping to the supplied source file is
21044 * rewritten using the supplied source map. Note: The resolution for the
21045 * resulting mappings is the minimium of this map and the supplied map.
21047 * @param aSourceMapConsumer The source map to be applied.
21048 * @param aSourceFile Optional. The filename of the source file.
21049 * If omitted, SourceMapConsumer's file property will be used.
21050 * @param aSourceMapPath Optional. The dirname of the path to the source map
21051 * to be applied. If relative, it is relative to the SourceMapConsumer.
21052 * This parameter is needed when the two source maps aren't in the same
21053 * directory, and the source map to be applied contains relative source
21054 * paths. If so, those relative source paths need to be rewritten
21055 * relative to the SourceMapGenerator.
21057 SourceMapGenerator.prototype.applySourceMap =
21058 function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) {
21059 var sourceFile = aSourceFile;
21060 // If aSourceFile is omitted, we will use the file property of the SourceMap
21061 if (aSourceFile == null) {
21062 if (aSourceMapConsumer.file == null) {
21064 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' +
21065 'or the source map\'s "file" property. Both were omitted.'
21068 sourceFile = aSourceMapConsumer.file;
21070 var sourceRoot = this._sourceRoot;
21071 // Make "sourceFile" relative if an absolute Url is passed.
21072 if (sourceRoot != null) {
21073 sourceFile = util.relative(sourceRoot, sourceFile);
21075 // Applying the SourceMap can add and remove items from the sources and
21076 // the names array.
21077 var newSources = new ArraySet();
21078 var newNames = new ArraySet();
21080 // Find mappings for the "sourceFile"
21081 this._mappings.unsortedForEach(function (mapping) {
21082 if (mapping.source === sourceFile && mapping.originalLine != null) {
21083 // Check if it can be mapped by the source map, then update the mapping.
21084 var original = aSourceMapConsumer.originalPositionFor({
21085 line: mapping.originalLine,
21086 column: mapping.originalColumn
21088 if (original.source != null) {
21090 mapping.source = original.source;
21091 if (aSourceMapPath != null) {
21092 mapping.source = util.join(aSourceMapPath, mapping.source)
21094 if (sourceRoot != null) {
21095 mapping.source = util.relative(sourceRoot, mapping.source);
21097 mapping.originalLine = original.line;
21098 mapping.originalColumn = original.column;
21099 if (original.name != null) {
21100 mapping.name = original.name;
21105 var source = mapping.source;
21106 if (source != null && !newSources.has(source)) {
21107 newSources.add(source);
21110 var name = mapping.name;
21111 if (name != null && !newNames.has(name)) {
21112 newNames.add(name);
21116 this._sources = newSources;
21117 this._names = newNames;
21119 // Copy sourcesContents of applied map.
21120 aSourceMapConsumer.sources.forEach(function (sourceFile) {
21121 var content = aSourceMapConsumer.sourceContentFor(sourceFile);
21122 if (content != null) {
21123 if (aSourceMapPath != null) {
21124 sourceFile = util.join(aSourceMapPath, sourceFile);
21126 if (sourceRoot != null) {
21127 sourceFile = util.relative(sourceRoot, sourceFile);
21129 this.setSourceContent(sourceFile, content);
21135 * A mapping can have one of the three levels of data:
21137 * 1. Just the generated position.
21138 * 2. The Generated position, original position, and original source.
21139 * 3. Generated and original position, original source, as well as a name
21142 * To maintain consistency, we validate that any new mapping being added falls
21143 * in to one of these categories.
21145 SourceMapGenerator.prototype._validateMapping =
21146 function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource,
21148 // When aOriginal is truthy but has empty values for .line and .column,
21149 // it is most likely a programmer error. In this case we throw a very
21150 // specific error message to try to guide them the right way.
21151 // For example: https://github.com/Polymer/polymer-bundler/pull/519
21152 if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') {
21154 'original.line and original.column are not numbers -- you probably meant to omit ' +
21155 'the original mapping entirely and only map the generated position. If so, pass ' +
21156 'null for the original mapping instead of an object with empty or null values.'
21160 if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
21161 && aGenerated.line > 0 && aGenerated.column >= 0
21162 && !aOriginal && !aSource && !aName) {
21166 else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
21167 && aOriginal && 'line' in aOriginal && 'column' in aOriginal
21168 && aGenerated.line > 0 && aGenerated.column >= 0
21169 && aOriginal.line > 0 && aOriginal.column >= 0
21175 throw new Error('Invalid mapping: ' + JSON.stringify({
21176 generated: aGenerated,
21178 original: aOriginal,
21185 * Serialize the accumulated mappings in to the stream of base 64 VLQs
21186 * specified by the source map format.
21188 SourceMapGenerator.prototype._serializeMappings =
21189 function SourceMapGenerator_serializeMappings() {
21190 var previousGeneratedColumn = 0;
21191 var previousGeneratedLine = 1;
21192 var previousOriginalColumn = 0;
21193 var previousOriginalLine = 0;
21194 var previousName = 0;
21195 var previousSource = 0;
21202 var mappings = this._mappings.toArray();
21203 for (var i = 0, len = mappings.length; i < len; i++) {
21204 mapping = mappings[i];
21207 if (mapping.generatedLine !== previousGeneratedLine) {
21208 previousGeneratedColumn = 0;
21209 while (mapping.generatedLine !== previousGeneratedLine) {
21211 previousGeneratedLine++;
21216 if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) {
21223 next += base64VLQ.encode(mapping.generatedColumn
21224 - previousGeneratedColumn);
21225 previousGeneratedColumn = mapping.generatedColumn;
21227 if (mapping.source != null) {
21228 sourceIdx = this._sources.indexOf(mapping.source);
21229 next += base64VLQ.encode(sourceIdx - previousSource);
21230 previousSource = sourceIdx;
21232 // lines are stored 0-based in SourceMap spec version 3
21233 next += base64VLQ.encode(mapping.originalLine - 1
21234 - previousOriginalLine);
21235 previousOriginalLine = mapping.originalLine - 1;
21237 next += base64VLQ.encode(mapping.originalColumn
21238 - previousOriginalColumn);
21239 previousOriginalColumn = mapping.originalColumn;
21241 if (mapping.name != null) {
21242 nameIdx = this._names.indexOf(mapping.name);
21243 next += base64VLQ.encode(nameIdx - previousName);
21244 previousName = nameIdx;
21254 SourceMapGenerator.prototype._generateSourcesContent =
21255 function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) {
21256 return aSources.map(function (source) {
21257 if (!this._sourcesContents) {
21260 if (aSourceRoot != null) {
21261 source = util.relative(aSourceRoot, source);
21263 var key = util.toSetString(source);
21264 return Object.prototype.hasOwnProperty.call(this._sourcesContents, key)
21265 ? this._sourcesContents[key]
21271 * Externalize the source map.
21273 SourceMapGenerator.prototype.toJSON =
21274 function SourceMapGenerator_toJSON() {
21276 version: this._version,
21277 sources: this._sources.toArray(),
21278 names: this._names.toArray(),
21279 mappings: this._serializeMappings()
21281 if (this._file != null) {
21282 map.file = this._file;
21284 if (this._sourceRoot != null) {
21285 map.sourceRoot = this._sourceRoot;
21287 if (this._sourcesContents) {
21288 map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot);
21295 * Render the source map being generated to a string.
21297 SourceMapGenerator.prototype.toString =
21298 function SourceMapGenerator_toString() {
21299 return JSON.stringify(this.toJSON());
21302 exports.SourceMapGenerator = SourceMapGenerator;
21304 },{"./array-set":144,"./base64-vlq":145,"./mapping-list":148,"./util":153}],152:[function(require,module,exports){
21305 /* -*- Mode: js; js-indent-level: 2; -*- */
21307 * Copyright 2011 Mozilla Foundation and contributors
21308 * Licensed under the New BSD license. See LICENSE or:
21309 * http://opensource.org/licenses/BSD-3-Clause
21312 var SourceMapGenerator = require('./source-map-generator').SourceMapGenerator;
21313 var util = require('./util');
21315 // Matches a Windows-style `\r\n` newline or a `\n` newline used by all other
21316 // operating systems these days (capturing the result).
21317 var REGEX_NEWLINE = /(\r?\n)/;
21319 // Newline character code for charCodeAt() comparisons
21320 var NEWLINE_CODE = 10;
21322 // Private symbol for identifying `SourceNode`s when multiple versions of
21323 // the source-map library are loaded. This MUST NOT CHANGE across
21325 var isSourceNode = "$$$isSourceNode$$$";
21328 * SourceNodes provide a way to abstract over interpolating/concatenating
21329 * snippets of generated JavaScript source code while maintaining the line and
21330 * column information associated with the original source code.
21332 * @param aLine The original line number.
21333 * @param aColumn The original column number.
21334 * @param aSource The original source's filename.
21335 * @param aChunks Optional. An array of strings which are snippets of
21336 * generated JS, or other SourceNodes.
21337 * @param aName The original identifier.
21339 function SourceNode(aLine, aColumn, aSource, aChunks, aName) {
21340 this.children = [];
21341 this.sourceContents = {};
21342 this.line = aLine == null ? null : aLine;
21343 this.column = aColumn == null ? null : aColumn;
21344 this.source = aSource == null ? null : aSource;
21345 this.name = aName == null ? null : aName;
21346 this[isSourceNode] = true;
21347 if (aChunks != null) this.add(aChunks);
21351 * Creates a SourceNode from generated code and a SourceMapConsumer.
21353 * @param aGeneratedCode The generated code
21354 * @param aSourceMapConsumer The SourceMap for the generated code
21355 * @param aRelativePath Optional. The path that relative sources in the
21356 * SourceMapConsumer should be relative to.
21358 SourceNode.fromStringWithSourceMap =
21359 function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) {
21360 // The SourceNode we want to fill with the generated code
21361 // and the SourceMap
21362 var node = new SourceNode();
21364 // All even indices of this array are one line of the generated code,
21365 // while all odd indices are the newlines between two adjacent lines
21366 // (since `REGEX_NEWLINE` captures its match).
21367 // Processed fragments are accessed by calling `shiftNextLine`.
21368 var remainingLines = aGeneratedCode.split(REGEX_NEWLINE);
21369 var remainingLinesIndex = 0;
21370 var shiftNextLine = function() {
21371 var lineContents = getNextLine();
21372 // The last line of a file might not have a newline.
21373 var newLine = getNextLine() || "";
21374 return lineContents + newLine;
21376 function getNextLine() {
21377 return remainingLinesIndex < remainingLines.length ?
21378 remainingLines[remainingLinesIndex++] : undefined;
21382 // We need to remember the position of "remainingLines"
21383 var lastGeneratedLine = 1, lastGeneratedColumn = 0;
21385 // The generate SourceNodes we need a code range.
21386 // To extract it current and last mapping is used.
21387 // Here we store the last mapping.
21388 var lastMapping = null;
21390 aSourceMapConsumer.eachMapping(function (mapping) {
21391 if (lastMapping !== null) {
21392 // We add the code from "lastMapping" to "mapping":
21393 // First check if there is a new line in between.
21394 if (lastGeneratedLine < mapping.generatedLine) {
21395 // Associate first line with "lastMapping"
21396 addMappingWithCode(lastMapping, shiftNextLine());
21397 lastGeneratedLine++;
21398 lastGeneratedColumn = 0;
21399 // The remaining code is added without mapping
21401 // There is no new line in between.
21402 // Associate the code between "lastGeneratedColumn" and
21403 // "mapping.generatedColumn" with "lastMapping"
21404 var nextLine = remainingLines[remainingLinesIndex] || '';
21405 var code = nextLine.substr(0, mapping.generatedColumn -
21406 lastGeneratedColumn);
21407 remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn -
21408 lastGeneratedColumn);
21409 lastGeneratedColumn = mapping.generatedColumn;
21410 addMappingWithCode(lastMapping, code);
21411 // No more remaining code, continue
21412 lastMapping = mapping;
21416 // We add the generated code until the first mapping
21417 // to the SourceNode without any mapping.
21418 // Each line is added as separate string.
21419 while (lastGeneratedLine < mapping.generatedLine) {
21420 node.add(shiftNextLine());
21421 lastGeneratedLine++;
21423 if (lastGeneratedColumn < mapping.generatedColumn) {
21424 var nextLine = remainingLines[remainingLinesIndex] || '';
21425 node.add(nextLine.substr(0, mapping.generatedColumn));
21426 remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn);
21427 lastGeneratedColumn = mapping.generatedColumn;
21429 lastMapping = mapping;
21431 // We have processed all mappings.
21432 if (remainingLinesIndex < remainingLines.length) {
21434 // Associate the remaining code in the current line with "lastMapping"
21435 addMappingWithCode(lastMapping, shiftNextLine());
21437 // and add the remaining lines without any mapping
21438 node.add(remainingLines.splice(remainingLinesIndex).join(""));
21441 // Copy sourcesContent into SourceNode
21442 aSourceMapConsumer.sources.forEach(function (sourceFile) {
21443 var content = aSourceMapConsumer.sourceContentFor(sourceFile);
21444 if (content != null) {
21445 if (aRelativePath != null) {
21446 sourceFile = util.join(aRelativePath, sourceFile);
21448 node.setSourceContent(sourceFile, content);
21454 function addMappingWithCode(mapping, code) {
21455 if (mapping === null || mapping.source === undefined) {
21458 var source = aRelativePath
21459 ? util.join(aRelativePath, mapping.source)
21461 node.add(new SourceNode(mapping.originalLine,
21462 mapping.originalColumn,
21471 * Add a chunk of generated JS to this source node.
21473 * @param aChunk A string snippet of generated JS code, another instance of
21474 * SourceNode, or an array where each member is one of those things.
21476 SourceNode.prototype.add = function SourceNode_add(aChunk) {
21477 if (Array.isArray(aChunk)) {
21478 aChunk.forEach(function (chunk) {
21482 else if (aChunk[isSourceNode] || typeof aChunk === "string") {
21484 this.children.push(aChunk);
21488 throw new TypeError(
21489 "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
21496 * Add a chunk of generated JS to the beginning of this source node.
21498 * @param aChunk A string snippet of generated JS code, another instance of
21499 * SourceNode, or an array where each member is one of those things.
21501 SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) {
21502 if (Array.isArray(aChunk)) {
21503 for (var i = aChunk.length-1; i >= 0; i--) {
21504 this.prepend(aChunk[i]);
21507 else if (aChunk[isSourceNode] || typeof aChunk === "string") {
21508 this.children.unshift(aChunk);
21511 throw new TypeError(
21512 "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
21519 * Walk over the tree of JS snippets in this node and its children. The
21520 * walking function is called once for each snippet of JS and is passed that
21521 * snippet and the its original associated source's line/column location.
21523 * @param aFn The traversal function.
21525 SourceNode.prototype.walk = function SourceNode_walk(aFn) {
21527 for (var i = 0, len = this.children.length; i < len; i++) {
21528 chunk = this.children[i];
21529 if (chunk[isSourceNode]) {
21533 if (chunk !== '') {
21534 aFn(chunk, { source: this.source,
21536 column: this.column,
21537 name: this.name });
21544 * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between
21545 * each of `this.children`.
21547 * @param aSep The separator.
21549 SourceNode.prototype.join = function SourceNode_join(aSep) {
21552 var len = this.children.length;
21555 for (i = 0; i < len-1; i++) {
21556 newChildren.push(this.children[i]);
21557 newChildren.push(aSep);
21559 newChildren.push(this.children[i]);
21560 this.children = newChildren;
21566 * Call String.prototype.replace on the very right-most source snippet. Useful
21567 * for trimming whitespace from the end of a source node, etc.
21569 * @param aPattern The pattern to replace.
21570 * @param aReplacement The thing to replace the pattern with.
21572 SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) {
21573 var lastChild = this.children[this.children.length - 1];
21574 if (lastChild[isSourceNode]) {
21575 lastChild.replaceRight(aPattern, aReplacement);
21577 else if (typeof lastChild === 'string') {
21578 this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement);
21581 this.children.push(''.replace(aPattern, aReplacement));
21587 * Set the source content for a source file. This will be added to the SourceMapGenerator
21588 * in the sourcesContent field.
21590 * @param aSourceFile The filename of the source file
21591 * @param aSourceContent The content of the source file
21593 SourceNode.prototype.setSourceContent =
21594 function SourceNode_setSourceContent(aSourceFile, aSourceContent) {
21595 this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent;
21599 * Walk over the tree of SourceNodes. The walking function is called for each
21600 * source file content and is passed the filename and source content.
21602 * @param aFn The traversal function.
21604 SourceNode.prototype.walkSourceContents =
21605 function SourceNode_walkSourceContents(aFn) {
21606 for (var i = 0, len = this.children.length; i < len; i++) {
21607 if (this.children[i][isSourceNode]) {
21608 this.children[i].walkSourceContents(aFn);
21612 var sources = Object.keys(this.sourceContents);
21613 for (var i = 0, len = sources.length; i < len; i++) {
21614 aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]);
21619 * Return the string representation of this source node. Walks over the tree
21620 * and concatenates all the various snippets together to one string.
21622 SourceNode.prototype.toString = function SourceNode_toString() {
21624 this.walk(function (chunk) {
21631 * Returns the string representation of this source node along with a source
21634 SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) {
21640 var map = new SourceMapGenerator(aArgs);
21641 var sourceMappingActive = false;
21642 var lastOriginalSource = null;
21643 var lastOriginalLine = null;
21644 var lastOriginalColumn = null;
21645 var lastOriginalName = null;
21646 this.walk(function (chunk, original) {
21647 generated.code += chunk;
21648 if (original.source !== null
21649 && original.line !== null
21650 && original.column !== null) {
21651 if(lastOriginalSource !== original.source
21652 || lastOriginalLine !== original.line
21653 || lastOriginalColumn !== original.column
21654 || lastOriginalName !== original.name) {
21656 source: original.source,
21658 line: original.line,
21659 column: original.column
21662 line: generated.line,
21663 column: generated.column
21665 name: original.name
21668 lastOriginalSource = original.source;
21669 lastOriginalLine = original.line;
21670 lastOriginalColumn = original.column;
21671 lastOriginalName = original.name;
21672 sourceMappingActive = true;
21673 } else if (sourceMappingActive) {
21676 line: generated.line,
21677 column: generated.column
21680 lastOriginalSource = null;
21681 sourceMappingActive = false;
21683 for (var idx = 0, length = chunk.length; idx < length; idx++) {
21684 if (chunk.charCodeAt(idx) === NEWLINE_CODE) {
21686 generated.column = 0;
21687 // Mappings end at eol
21688 if (idx + 1 === length) {
21689 lastOriginalSource = null;
21690 sourceMappingActive = false;
21691 } else if (sourceMappingActive) {
21693 source: original.source,
21695 line: original.line,
21696 column: original.column
21699 line: generated.line,
21700 column: generated.column
21702 name: original.name
21706 generated.column++;
21710 this.walkSourceContents(function (sourceFile, sourceContent) {
21711 map.setSourceContent(sourceFile, sourceContent);
21714 return { code: generated.code, map: map };
21717 exports.SourceNode = SourceNode;
21719 },{"./source-map-generator":151,"./util":153}],153:[function(require,module,exports){
21720 /* -*- Mode: js; js-indent-level: 2; -*- */
21722 * Copyright 2011 Mozilla Foundation and contributors
21723 * Licensed under the New BSD license. See LICENSE or:
21724 * http://opensource.org/licenses/BSD-3-Clause
21728 * This is a helper function for getting values from parameter/options
21731 * @param args The object we are extracting values from
21732 * @param name The name of the property we are getting.
21733 * @param defaultValue An optional value to return if the property is missing
21734 * from the object. If this is not specified and the property is missing, an
21735 * error will be thrown.
21737 function getArg(aArgs, aName, aDefaultValue) {
21738 if (aName in aArgs) {
21739 return aArgs[aName];
21740 } else if (arguments.length === 3) {
21741 return aDefaultValue;
21743 throw new Error('"' + aName + '" is a required argument.');
21746 exports.getArg = getArg;
21748 var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/;
21749 var dataUrlRegexp = /^data:.+\,.+$/;
21751 function urlParse(aUrl) {
21752 var match = aUrl.match(urlRegexp);
21764 exports.urlParse = urlParse;
21766 function urlGenerate(aParsedUrl) {
21768 if (aParsedUrl.scheme) {
21769 url += aParsedUrl.scheme + ':';
21772 if (aParsedUrl.auth) {
21773 url += aParsedUrl.auth + '@';
21775 if (aParsedUrl.host) {
21776 url += aParsedUrl.host;
21778 if (aParsedUrl.port) {
21779 url += ":" + aParsedUrl.port
21781 if (aParsedUrl.path) {
21782 url += aParsedUrl.path;
21786 exports.urlGenerate = urlGenerate;
21789 * Normalizes a path, or the path portion of a URL:
21791 * - Replaces consecutive slashes with one slash.
21792 * - Removes unnecessary '.' parts.
21793 * - Removes unnecessary '<dir>/..' parts.
21795 * Based on code in the Node.js 'path' core module.
21797 * @param aPath The path or url to normalize.
21799 function normalize(aPath) {
21801 var url = urlParse(aPath);
21808 var isAbsolute = exports.isAbsolute(path);
21810 var parts = path.split(/\/+/);
21811 for (var part, up = 0, i = parts.length - 1; i >= 0; i--) {
21813 if (part === '.') {
21814 parts.splice(i, 1);
21815 } else if (part === '..') {
21817 } else if (up > 0) {
21819 // The first part is blank if the path is absolute. Trying to go
21820 // above the root is a no-op. Therefore we can remove all '..' parts
21821 // directly after the root.
21822 parts.splice(i + 1, up);
21825 parts.splice(i, 2);
21830 path = parts.join('/');
21833 path = isAbsolute ? '/' : '.';
21838 return urlGenerate(url);
21842 exports.normalize = normalize;
21845 * Joins two paths/URLs.
21847 * @param aRoot The root path or URL.
21848 * @param aPath The path or URL to be joined with the root.
21850 * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a
21851 * scheme-relative URL: Then the scheme of aRoot, if any, is prepended
21853 * - Otherwise aPath is a path. If aRoot is a URL, then its path portion
21854 * is updated with the result and aRoot is returned. Otherwise the result
21856 * - If aPath is absolute, the result is aPath.
21857 * - Otherwise the two paths are joined with a slash.
21858 * - Joining for example 'http://' and 'www.example.com' is also supported.
21860 function join(aRoot, aPath) {
21861 if (aRoot === "") {
21864 if (aPath === "") {
21867 var aPathUrl = urlParse(aPath);
21868 var aRootUrl = urlParse(aRoot);
21870 aRoot = aRootUrl.path || '/';
21873 // `join(foo, '//www.example.org')`
21874 if (aPathUrl && !aPathUrl.scheme) {
21876 aPathUrl.scheme = aRootUrl.scheme;
21878 return urlGenerate(aPathUrl);
21881 if (aPathUrl || aPath.match(dataUrlRegexp)) {
21885 // `join('http://', 'www.example.com')`
21886 if (aRootUrl && !aRootUrl.host && !aRootUrl.path) {
21887 aRootUrl.host = aPath;
21888 return urlGenerate(aRootUrl);
21891 var joined = aPath.charAt(0) === '/'
21893 : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath);
21896 aRootUrl.path = joined;
21897 return urlGenerate(aRootUrl);
21901 exports.join = join;
21903 exports.isAbsolute = function (aPath) {
21904 return aPath.charAt(0) === '/' || urlRegexp.test(aPath);
21908 * Make a path relative to a URL or another path.
21910 * @param aRoot The root path or URL.
21911 * @param aPath The path or URL to be made relative to aRoot.
21913 function relative(aRoot, aPath) {
21914 if (aRoot === "") {
21918 aRoot = aRoot.replace(/\/$/, '');
21920 // It is possible for the path to be above the root. In this case, simply
21921 // checking whether the root is a prefix of the path won't work. Instead, we
21922 // need to remove components from the root one by one, until either we find
21923 // a prefix that fits, or we run out of components to remove.
21925 while (aPath.indexOf(aRoot + '/') !== 0) {
21926 var index = aRoot.lastIndexOf("/");
21931 // If the only part of the root that is left is the scheme (i.e. http://,
21932 // file:///, etc.), one or more slashes (/), or simply nothing at all, we
21933 // have exhausted all components, so the path is not relative to the root.
21934 aRoot = aRoot.slice(0, index);
21935 if (aRoot.match(/^([^\/]+:\/)?\/*$/)) {
21942 // Make sure we add a "../" for each component we removed from the root.
21943 return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1);
21945 exports.relative = relative;
21947 var supportsNullProto = (function () {
21948 var obj = Object.create(null);
21949 return !('__proto__' in obj);
21952 function identity (s) {
21957 * Because behavior goes wacky when you set `__proto__` on objects, we
21958 * have to prefix all the strings in our set with an arbitrary character.
21960 * See https://github.com/mozilla/source-map/pull/31 and
21961 * https://github.com/mozilla/source-map/issues/30
21963 * @param String aStr
21965 function toSetString(aStr) {
21966 if (isProtoString(aStr)) {
21972 exports.toSetString = supportsNullProto ? identity : toSetString;
21974 function fromSetString(aStr) {
21975 if (isProtoString(aStr)) {
21976 return aStr.slice(1);
21981 exports.fromSetString = supportsNullProto ? identity : fromSetString;
21983 function isProtoString(s) {
21988 var length = s.length;
21990 if (length < 9 /* "__proto__".length */) {
21994 if (s.charCodeAt(length - 1) !== 95 /* '_' */ ||
21995 s.charCodeAt(length - 2) !== 95 /* '_' */ ||
21996 s.charCodeAt(length - 3) !== 111 /* 'o' */ ||
21997 s.charCodeAt(length - 4) !== 116 /* 't' */ ||
21998 s.charCodeAt(length - 5) !== 111 /* 'o' */ ||
21999 s.charCodeAt(length - 6) !== 114 /* 'r' */ ||
22000 s.charCodeAt(length - 7) !== 112 /* 'p' */ ||
22001 s.charCodeAt(length - 8) !== 95 /* '_' */ ||
22002 s.charCodeAt(length - 9) !== 95 /* '_' */) {
22006 for (var i = length - 10; i >= 0; i--) {
22007 if (s.charCodeAt(i) !== 36 /* '$' */) {
22016 * Comparator between two mappings where the original positions are compared.
22018 * Optionally pass in `true` as `onlyCompareGenerated` to consider two
22019 * mappings with the same original source/line/column, but different generated
22020 * line and column the same. Useful when searching for a mapping with a
22021 * stubbed out mapping.
22023 function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {
22024 var cmp = strcmp(mappingA.source, mappingB.source);
22029 cmp = mappingA.originalLine - mappingB.originalLine;
22034 cmp = mappingA.originalColumn - mappingB.originalColumn;
22035 if (cmp !== 0 || onlyCompareOriginal) {
22039 cmp = mappingA.generatedColumn - mappingB.generatedColumn;
22044 cmp = mappingA.generatedLine - mappingB.generatedLine;
22049 return strcmp(mappingA.name, mappingB.name);
22051 exports.compareByOriginalPositions = compareByOriginalPositions;
22054 * Comparator between two mappings with deflated source and name indices where
22055 * the generated positions are compared.
22057 * Optionally pass in `true` as `onlyCompareGenerated` to consider two
22058 * mappings with the same generated line and column, but different
22059 * source/name/original line and column the same. Useful when searching for a
22060 * mapping with a stubbed out mapping.
22062 function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) {
22063 var cmp = mappingA.generatedLine - mappingB.generatedLine;
22068 cmp = mappingA.generatedColumn - mappingB.generatedColumn;
22069 if (cmp !== 0 || onlyCompareGenerated) {
22073 cmp = strcmp(mappingA.source, mappingB.source);
22078 cmp = mappingA.originalLine - mappingB.originalLine;
22083 cmp = mappingA.originalColumn - mappingB.originalColumn;
22088 return strcmp(mappingA.name, mappingB.name);
22090 exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated;
22092 function strcmp(aStr1, aStr2) {
22093 if (aStr1 === aStr2) {
22097 if (aStr1 === null) {
22098 return 1; // aStr2 !== null
22101 if (aStr2 === null) {
22102 return -1; // aStr1 !== null
22105 if (aStr1 > aStr2) {
22113 * Comparator between two mappings with inflated source and name strings where
22114 * the generated positions are compared.
22116 function compareByGeneratedPositionsInflated(mappingA, mappingB) {
22117 var cmp = mappingA.generatedLine - mappingB.generatedLine;
22122 cmp = mappingA.generatedColumn - mappingB.generatedColumn;
22127 cmp = strcmp(mappingA.source, mappingB.source);
22132 cmp = mappingA.originalLine - mappingB.originalLine;
22137 cmp = mappingA.originalColumn - mappingB.originalColumn;
22142 return strcmp(mappingA.name, mappingB.name);
22144 exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated;
22147 * Strip any JSON XSSI avoidance prefix from the string (as documented
22148 * in the source maps specification), and then parse the string as
22151 function parseSourceMapInput(str) {
22152 return JSON.parse(str.replace(/^\)]}'[^\n]*\n/, ''));
22154 exports.parseSourceMapInput = parseSourceMapInput;
22157 * Compute the URL of a source given the the source root, the source's
22158 * URL, and the source map's URL.
22160 function computeSourceURL(sourceRoot, sourceURL, sourceMapURL) {
22161 sourceURL = sourceURL || '';
22164 // This follows what Chrome does.
22165 if (sourceRoot[sourceRoot.length - 1] !== '/' && sourceURL[0] !== '/') {
22169 // Line 4: An optional source root, useful for relocating source
22170 // files on a server or removing repeated values in the
22171 // “sources” entry. This value is prepended to the individual
22172 // entries in the “source” field.
22173 sourceURL = sourceRoot + sourceURL;
22176 // Historically, SourceMapConsumer did not take the sourceMapURL as
22177 // a parameter. This mode is still somewhat supported, which is why
22178 // this code block is conditional. However, it's preferable to pass
22179 // the source map URL to SourceMapConsumer, so that this function
22180 // can implement the source URL resolution algorithm as outlined in
22181 // the spec. This block is basically the equivalent of:
22182 // new URL(sourceURL, sourceMapURL).toString()
22183 // ... except it avoids using URL, which wasn't available in the
22184 // older releases of node still supported by this library.
22187 // If the sources are not absolute URLs after prepending of the
22188 // “sourceRoot”, the sources are resolved relative to the
22189 // SourceMap (like resolving script src in a html document).
22190 if (sourceMapURL) {
22191 var parsed = urlParse(sourceMapURL);
22193 throw new Error("sourceMapURL could not be parsed");
22196 // Strip the last path component, but keep the "/".
22197 var index = parsed.path.lastIndexOf('/');
22199 parsed.path = parsed.path.substring(0, index + 1);
22202 sourceURL = join(urlGenerate(parsed), sourceURL);
22205 return normalize(sourceURL);
22207 exports.computeSourceURL = computeSourceURL;
22209 },{}],154:[function(require,module,exports){
22211 * Copyright 2009-2011 Mozilla Foundation and contributors
22212 * Licensed under the New BSD license. See LICENSE.txt or:
22213 * http://opensource.org/licenses/BSD-3-Clause
22215 exports.SourceMapGenerator = require('./lib/source-map-generator').SourceMapGenerator;
22216 exports.SourceMapConsumer = require('./lib/source-map-consumer').SourceMapConsumer;
22217 exports.SourceNode = require('./lib/source-node').SourceNode;
22219 },{"./lib/source-map-consumer":150,"./lib/source-map-generator":151,"./lib/source-node":152}],155:[function(require,module,exports){
22220 (function (global){
22221 var ClientRequest = require('./lib/request')
22222 var response = require('./lib/response')
22223 var extend = require('xtend')
22224 var statusCodes = require('builtin-status-codes')
22225 var url = require('url')
22229 http.request = function (opts, cb) {
22230 if (typeof opts === 'string')
22231 opts = url.parse(opts)
22233 opts = extend(opts)
22235 // Normally, the page is loaded from http or https, so not specifying a protocol
22236 // will result in a (valid) protocol-relative url. However, this won't work if
22237 // the protocol is something else, like 'file:'
22238 var defaultProtocol = global.location.protocol.search(/^https?:$/) === -1 ? 'http:' : ''
22240 var protocol = opts.protocol || defaultProtocol
22241 var host = opts.hostname || opts.host
22242 var port = opts.port
22243 var path = opts.path || '/'
22245 // Necessary for IPv6 addresses
22246 if (host && host.indexOf(':') !== -1)
22247 host = '[' + host + ']'
22249 // This may be a relative url. The browser should always be able to interpret it correctly.
22250 opts.url = (host ? (protocol + '//' + host) : '') + (port ? ':' + port : '') + path
22251 opts.method = (opts.method || 'GET').toUpperCase()
22252 opts.headers = opts.headers || {}
22254 // Also valid opts.auth, opts.mode
22256 var req = new ClientRequest(opts)
22258 req.on('response', cb)
22262 http.get = function get (opts, cb) {
22263 var req = http.request(opts, cb)
22268 http.ClientRequest = ClientRequest
22269 http.IncomingMessage = response.IncomingMessage
22271 http.Agent = function () {}
22272 http.Agent.defaultMaxSockets = 4
22274 http.globalAgent = new http.Agent()
22276 http.STATUS_CODES = statusCodes
22306 }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
22307 },{"./lib/request":157,"./lib/response":158,"builtin-status-codes":5,"url":162,"xtend":165}],156:[function(require,module,exports){
22308 (function (global){
22309 exports.fetch = isFunction(global.fetch) && isFunction(global.ReadableStream)
22311 exports.writableStream = isFunction(global.WritableStream)
22313 exports.abortController = isFunction(global.AbortController)
22315 exports.blobConstructor = false
22317 new Blob([new ArrayBuffer(1)])
22318 exports.blobConstructor = true
22321 // The xhr request to example.com may violate some restrictive CSP configurations,
22322 // so if we're running in a browser that supports `fetch`, avoid calling getXHR()
22323 // and assume support for certain features below.
22325 function getXHR () {
22326 // Cache the xhr value
22327 if (xhr !== undefined) return xhr
22329 if (global.XMLHttpRequest) {
22330 xhr = new global.XMLHttpRequest()
22331 // If XDomainRequest is available (ie only, where xhr might not work
22332 // cross domain), use the page location. Otherwise use example.com
22333 // Note: this doesn't actually make an http request.
22335 xhr.open('GET', global.XDomainRequest ? '/' : 'https://example.com')
22340 // Service workers don't have XHR
22346 function checkTypeSupport (type) {
22348 if (!xhr) return false
22350 xhr.responseType = type
22351 return xhr.responseType === type
22356 // For some strange reason, Safari 7.0 reports typeof global.ArrayBuffer === 'object'.
22357 // Safari 7.1 appears to have fixed this bug.
22358 var haveArrayBuffer = typeof global.ArrayBuffer !== 'undefined'
22359 var haveSlice = haveArrayBuffer && isFunction(global.ArrayBuffer.prototype.slice)
22361 // If fetch is supported, then arraybuffer will be supported too. Skip calling
22362 // checkTypeSupport(), since that calls getXHR().
22363 exports.arraybuffer = exports.fetch || (haveArrayBuffer && checkTypeSupport('arraybuffer'))
22365 // These next two tests unavoidably show warnings in Chrome. Since fetch will always
22366 // be used if it's available, just return false for these to avoid the warnings.
22367 exports.msstream = !exports.fetch && haveSlice && checkTypeSupport('ms-stream')
22368 exports.mozchunkedarraybuffer = !exports.fetch && haveArrayBuffer &&
22369 checkTypeSupport('moz-chunked-arraybuffer')
22371 // If fetch is supported, then overrideMimeType will be supported too. Skip calling
22373 exports.overrideMimeType = exports.fetch || (getXHR() ? isFunction(getXHR().overrideMimeType) : false)
22375 exports.vbArray = isFunction(global.VBArray)
22377 function isFunction (value) {
22378 return typeof value === 'function'
22381 xhr = null // Help gc
22383 }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
22384 },{}],157:[function(require,module,exports){
22385 (function (process,global,Buffer){
22386 var capability = require('./capability')
22387 var inherits = require('inherits')
22388 var response = require('./response')
22389 var stream = require('readable-stream')
22390 var toArrayBuffer = require('to-arraybuffer')
22392 var IncomingMessage = response.IncomingMessage
22393 var rStates = response.readyStates
22395 function decideMode (preferBinary, useFetch) {
22396 if (capability.fetch && useFetch) {
22398 } else if (capability.mozchunkedarraybuffer) {
22399 return 'moz-chunked-arraybuffer'
22400 } else if (capability.msstream) {
22402 } else if (capability.arraybuffer && preferBinary) {
22403 return 'arraybuffer'
22404 } else if (capability.vbArray && preferBinary) {
22405 return 'text:vbarray'
22411 var ClientRequest = module.exports = function (opts) {
22413 stream.Writable.call(self)
22419 self.setHeader('Authorization', 'Basic ' + new Buffer(opts.auth).toString('base64'))
22420 Object.keys(opts.headers).forEach(function (name) {
22421 self.setHeader(name, opts.headers[name])
22425 var useFetch = true
22426 if (opts.mode === 'disable-fetch' || ('requestTimeout' in opts && !capability.abortController)) {
22427 // If the use of XHR should be preferred. Not typically needed.
22429 preferBinary = true
22430 } else if (opts.mode === 'prefer-streaming') {
22431 // If streaming is a high priority but binary compatibility and
22432 // the accuracy of the 'content-type' header aren't
22433 preferBinary = false
22434 } else if (opts.mode === 'allow-wrong-content-type') {
22435 // If streaming is more important than preserving the 'content-type' header
22436 preferBinary = !capability.overrideMimeType
22437 } else if (!opts.mode || opts.mode === 'default' || opts.mode === 'prefer-fast') {
22438 // Use binary if text streaming may corrupt data or the content-type header, or for speed
22439 preferBinary = true
22441 throw new Error('Invalid value for opts.mode')
22443 self._mode = decideMode(preferBinary, useFetch)
22444 self._fetchTimer = null
22446 self.on('finish', function () {
22451 inherits(ClientRequest, stream.Writable)
22453 ClientRequest.prototype.setHeader = function (name, value) {
22455 var lowerName = name.toLowerCase()
22456 // This check is not necessary, but it prevents warnings from browsers about setting unsafe
22457 // headers. To be honest I'm not entirely sure hiding these warnings is a good thing, but
22458 // http-browserify did it, so I will too.
22459 if (unsafeHeaders.indexOf(lowerName) !== -1)
22462 self._headers[lowerName] = {
22468 ClientRequest.prototype.getHeader = function (name) {
22469 var header = this._headers[name.toLowerCase()]
22471 return header.value
22475 ClientRequest.prototype.removeHeader = function (name) {
22477 delete self._headers[name.toLowerCase()]
22480 ClientRequest.prototype._onFinish = function () {
22483 if (self._destroyed)
22485 var opts = self._opts
22487 var headersObj = self._headers
22489 if (opts.method !== 'GET' && opts.method !== 'HEAD') {
22490 if (capability.arraybuffer) {
22491 body = toArrayBuffer(Buffer.concat(self._body))
22492 } else if (capability.blobConstructor) {
22493 body = new global.Blob(self._body.map(function (buffer) {
22494 return toArrayBuffer(buffer)
22496 type: (headersObj['content-type'] || {}).value || ''
22500 body = Buffer.concat(self._body).toString()
22504 // create flattened list of headers
22505 var headersList = []
22506 Object.keys(headersObj).forEach(function (keyName) {
22507 var name = headersObj[keyName].name
22508 var value = headersObj[keyName].value
22509 if (Array.isArray(value)) {
22510 value.forEach(function (v) {
22511 headersList.push([name, v])
22514 headersList.push([name, value])
22518 if (self._mode === 'fetch') {
22520 var fetchTimer = null
22521 if (capability.abortController) {
22522 var controller = new AbortController()
22523 signal = controller.signal
22524 self._fetchAbortController = controller
22526 if ('requestTimeout' in opts && opts.requestTimeout !== 0) {
22527 self._fetchTimer = global.setTimeout(function () {
22528 self.emit('requestTimeout')
22529 if (self._fetchAbortController)
22530 self._fetchAbortController.abort()
22531 }, opts.requestTimeout)
22535 global.fetch(self._opts.url, {
22536 method: self._opts.method,
22537 headers: headersList,
22538 body: body || undefined,
22540 credentials: opts.withCredentials ? 'include' : 'same-origin',
22542 }).then(function (response) {
22543 self._fetchResponse = response
22545 }, function (reason) {
22546 global.clearTimeout(self._fetchTimer)
22547 if (!self._destroyed)
22548 self.emit('error', reason)
22551 var xhr = self._xhr = new global.XMLHttpRequest()
22553 xhr.open(self._opts.method, self._opts.url, true)
22555 process.nextTick(function () {
22556 self.emit('error', err)
22561 // Can't set responseType on really old browsers
22562 if ('responseType' in xhr)
22563 xhr.responseType = self._mode.split(':')[0]
22565 if ('withCredentials' in xhr)
22566 xhr.withCredentials = !!opts.withCredentials
22568 if (self._mode === 'text' && 'overrideMimeType' in xhr)
22569 xhr.overrideMimeType('text/plain; charset=x-user-defined')
22571 if ('requestTimeout' in opts) {
22572 xhr.timeout = opts.requestTimeout
22573 xhr.ontimeout = function () {
22574 self.emit('requestTimeout')
22578 headersList.forEach(function (header) {
22579 xhr.setRequestHeader(header[0], header[1])
22582 self._response = null
22583 xhr.onreadystatechange = function () {
22584 switch (xhr.readyState) {
22585 case rStates.LOADING:
22587 self._onXHRProgress()
22591 // Necessary for streaming in Firefox, since xhr.response is ONLY defined
22592 // in onprogress, not in onreadystatechange with xhr.readyState = 3
22593 if (self._mode === 'moz-chunked-arraybuffer') {
22594 xhr.onprogress = function () {
22595 self._onXHRProgress()
22599 xhr.onerror = function () {
22600 if (self._destroyed)
22602 self.emit('error', new Error('XHR error'))
22608 process.nextTick(function () {
22609 self.emit('error', err)
22617 * Checks if xhr.status is readable and non-zero, indicating no error.
22618 * Even though the spec says it should be available in readyState 3,
22619 * accessing it throws an exception in IE8
22621 function statusValid (xhr) {
22623 var status = xhr.status
22624 return (status !== null && status !== 0)
22630 ClientRequest.prototype._onXHRProgress = function () {
22633 if (!statusValid(self._xhr) || self._destroyed)
22636 if (!self._response)
22639 self._response._onXHRProgress()
22642 ClientRequest.prototype._connect = function () {
22645 if (self._destroyed)
22648 self._response = new IncomingMessage(self._xhr, self._fetchResponse, self._mode, self._fetchTimer)
22649 self._response.on('error', function(err) {
22650 self.emit('error', err)
22653 self.emit('response', self._response)
22656 ClientRequest.prototype._write = function (chunk, encoding, cb) {
22659 self._body.push(chunk)
22663 ClientRequest.prototype.abort = ClientRequest.prototype.destroy = function () {
22665 self._destroyed = true
22666 global.clearTimeout(self._fetchTimer)
22667 if (self._response)
22668 self._response._destroyed = true
22671 else if (self._fetchAbortController)
22672 self._fetchAbortController.abort()
22675 ClientRequest.prototype.end = function (data, encoding, cb) {
22677 if (typeof data === 'function') {
22682 stream.Writable.prototype.end.call(self, data, encoding, cb)
22685 ClientRequest.prototype.flushHeaders = function () {}
22686 ClientRequest.prototype.setTimeout = function () {}
22687 ClientRequest.prototype.setNoDelay = function () {}
22688 ClientRequest.prototype.setSocketKeepAlive = function () {}
22690 // Taken from http://www.w3.org/TR/XMLHttpRequest/#the-setrequestheader%28%29-method
22691 var unsafeHeaders = [
22694 'access-control-request-headers',
22695 'access-control-request-method',
22709 'transfer-encoding',
22714 }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer)
22715 },{"./capability":156,"./response":158,"_process":112,"buffer":4,"inherits":106,"readable-stream":125,"to-arraybuffer":161}],158:[function(require,module,exports){
22716 (function (process,global,Buffer){
22717 var capability = require('./capability')
22718 var inherits = require('inherits')
22719 var stream = require('readable-stream')
22721 var rStates = exports.readyStates = {
22724 HEADERS_RECEIVED: 2,
22729 var IncomingMessage = exports.IncomingMessage = function (xhr, response, mode, fetchTimer) {
22731 stream.Readable.call(self)
22735 self.rawHeaders = []
22737 self.rawTrailers = []
22739 // Fake the 'close' event, but only once 'end' fires
22740 self.on('end', function () {
22741 // The nextTick is necessary to prevent the 'request' module from causing an infinite loop
22742 process.nextTick(function () {
22747 if (mode === 'fetch') {
22748 self._fetchResponse = response
22750 self.url = response.url
22751 self.statusCode = response.status
22752 self.statusMessage = response.statusText
22754 response.headers.forEach(function (header, key){
22755 self.headers[key.toLowerCase()] = header
22756 self.rawHeaders.push(key, header)
22759 if (capability.writableStream) {
22760 var writable = new WritableStream({
22761 write: function (chunk) {
22762 return new Promise(function (resolve, reject) {
22763 if (self._destroyed) {
22765 } else if(self.push(new Buffer(chunk))) {
22768 self._resumeFetch = resolve
22772 close: function () {
22773 global.clearTimeout(fetchTimer)
22774 if (!self._destroyed)
22777 abort: function (err) {
22778 if (!self._destroyed)
22779 self.emit('error', err)
22784 response.body.pipeTo(writable).catch(function (err) {
22785 global.clearTimeout(fetchTimer)
22786 if (!self._destroyed)
22787 self.emit('error', err)
22790 } catch (e) {} // pipeTo method isn't defined. Can't find a better way to feature test this
22792 // fallback for when writableStream or pipeTo aren't available
22793 var reader = response.body.getReader()
22795 reader.read().then(function (result) {
22796 if (self._destroyed)
22799 global.clearTimeout(fetchTimer)
22803 self.push(new Buffer(result.value))
22805 }).catch(function (err) {
22806 global.clearTimeout(fetchTimer)
22807 if (!self._destroyed)
22808 self.emit('error', err)
22816 self.url = xhr.responseURL
22817 self.statusCode = xhr.status
22818 self.statusMessage = xhr.statusText
22819 var headers = xhr.getAllResponseHeaders().split(/\r?\n/)
22820 headers.forEach(function (header) {
22821 var matches = header.match(/^([^:]+):\s*(.*)/)
22823 var key = matches[1].toLowerCase()
22824 if (key === 'set-cookie') {
22825 if (self.headers[key] === undefined) {
22826 self.headers[key] = []
22828 self.headers[key].push(matches[2])
22829 } else if (self.headers[key] !== undefined) {
22830 self.headers[key] += ', ' + matches[2]
22832 self.headers[key] = matches[2]
22834 self.rawHeaders.push(matches[1], matches[2])
22838 self._charset = 'x-user-defined'
22839 if (!capability.overrideMimeType) {
22840 var mimeType = self.rawHeaders['mime-type']
22842 var charsetMatch = mimeType.match(/;\s*charset=([^;])(;|$)/)
22843 if (charsetMatch) {
22844 self._charset = charsetMatch[1].toLowerCase()
22847 if (!self._charset)
22848 self._charset = 'utf-8' // best guess
22853 inherits(IncomingMessage, stream.Readable)
22855 IncomingMessage.prototype._read = function () {
22858 var resolve = self._resumeFetch
22860 self._resumeFetch = null
22865 IncomingMessage.prototype._onXHRProgress = function () {
22868 var xhr = self._xhr
22870 var response = null
22871 switch (self._mode) {
22872 case 'text:vbarray': // For IE9
22873 if (xhr.readyState !== rStates.DONE)
22876 // This fails in IE8
22877 response = new global.VBArray(xhr.responseBody).toArray()
22879 if (response !== null) {
22880 self.push(new Buffer(response))
22883 // Falls through in IE8
22885 try { // This will fail when readyState = 3 in IE9. Switch mode and wait for readyState = 4
22886 response = xhr.responseText
22888 self._mode = 'text:vbarray'
22891 if (response.length > self._pos) {
22892 var newData = response.substr(self._pos)
22893 if (self._charset === 'x-user-defined') {
22894 var buffer = new Buffer(newData.length)
22895 for (var i = 0; i < newData.length; i++)
22896 buffer[i] = newData.charCodeAt(i) & 0xff
22900 self.push(newData, self._charset)
22902 self._pos = response.length
22905 case 'arraybuffer':
22906 if (xhr.readyState !== rStates.DONE || !xhr.response)
22908 response = xhr.response
22909 self.push(new Buffer(new Uint8Array(response)))
22911 case 'moz-chunked-arraybuffer': // take whole
22912 response = xhr.response
22913 if (xhr.readyState !== rStates.LOADING || !response)
22915 self.push(new Buffer(new Uint8Array(response)))
22918 response = xhr.response
22919 if (xhr.readyState !== rStates.LOADING)
22921 var reader = new global.MSStreamReader()
22922 reader.onprogress = function () {
22923 if (reader.result.byteLength > self._pos) {
22924 self.push(new Buffer(new Uint8Array(reader.result.slice(self._pos))))
22925 self._pos = reader.result.byteLength
22928 reader.onload = function () {
22931 // reader.onerror = ??? // TODO: this
22932 reader.readAsArrayBuffer(response)
22936 // The ms-stream case handles end separately in reader.onload()
22937 if (self._xhr.readyState === rStates.DONE && self._mode !== 'ms-stream') {
22942 }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer)
22943 },{"./capability":156,"_process":112,"buffer":4,"inherits":106,"readable-stream":125}],159:[function(require,module,exports){
22944 // Copyright Joyent, Inc. and other Node contributors.
22946 // Permission is hereby granted, free of charge, to any person obtaining a
22947 // copy of this software and associated documentation files (the
22948 // "Software"), to deal in the Software without restriction, including
22949 // without limitation the rights to use, copy, modify, merge, publish,
22950 // distribute, sublicense, and/or sell copies of the Software, and to permit
22951 // persons to whom the Software is furnished to do so, subject to the
22952 // following conditions:
22954 // The above copyright notice and this permission notice shall be included
22955 // in all copies or substantial portions of the Software.
22957 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
22958 // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
22959 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
22960 // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
22961 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
22962 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
22963 // USE OR OTHER DEALINGS IN THE SOFTWARE.
22969 var Buffer = require('safe-buffer').Buffer;
22972 var isEncoding = Buffer.isEncoding || function (encoding) {
22973 encoding = '' + encoding;
22974 switch (encoding && encoding.toLowerCase()) {
22975 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':
22982 function _normalizeEncoding(enc) {
22983 if (!enc) return 'utf8';
23003 if (retried) return; // undefined
23004 enc = ('' + enc).toLowerCase();
23010 // Do not cache `Buffer.isEncoding` when checking encoding names as some
23011 // modules monkey-patch it to support additional encodings
23012 function normalizeEncoding(enc) {
23013 var nenc = _normalizeEncoding(enc);
23014 if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);
23015 return nenc || enc;
23018 // StringDecoder provides an interface for efficiently splitting a series of
23019 // buffers into a series of JS strings without breaking apart multi-byte
23021 exports.StringDecoder = StringDecoder;
23022 function StringDecoder(encoding) {
23023 this.encoding = normalizeEncoding(encoding);
23025 switch (this.encoding) {
23027 this.text = utf16Text;
23028 this.end = utf16End;
23032 this.fillLast = utf8FillLast;
23036 this.text = base64Text;
23037 this.end = base64End;
23041 this.write = simpleWrite;
23042 this.end = simpleEnd;
23046 this.lastTotal = 0;
23047 this.lastChar = Buffer.allocUnsafe(nb);
23050 StringDecoder.prototype.write = function (buf) {
23051 if (buf.length === 0) return '';
23054 if (this.lastNeed) {
23055 r = this.fillLast(buf);
23056 if (r === undefined) return '';
23062 if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);
23066 StringDecoder.prototype.end = utf8End;
23068 // Returns only complete characters in a Buffer
23069 StringDecoder.prototype.text = utf8Text;
23071 // Attempts to complete a partial non-UTF-8 character using bytes from a Buffer
23072 StringDecoder.prototype.fillLast = function (buf) {
23073 if (this.lastNeed <= buf.length) {
23074 buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);
23075 return this.lastChar.toString(this.encoding, 0, this.lastTotal);
23077 buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);
23078 this.lastNeed -= buf.length;
23081 // Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a
23082 // continuation byte. If an invalid byte is detected, -2 is returned.
23083 function utf8CheckByte(byte) {
23084 if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4;
23085 return byte >> 6 === 0x02 ? -1 : -2;
23088 // Checks at most 3 bytes at the end of a Buffer in order to detect an
23089 // incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)
23090 // needed to complete the UTF-8 character (if applicable) are returned.
23091 function utf8CheckIncomplete(self, buf, i) {
23092 var j = buf.length - 1;
23093 if (j < i) return 0;
23094 var nb = utf8CheckByte(buf[j]);
23096 if (nb > 0) self.lastNeed = nb - 1;
23099 if (--j < i || nb === -2) return 0;
23100 nb = utf8CheckByte(buf[j]);
23102 if (nb > 0) self.lastNeed = nb - 2;
23105 if (--j < i || nb === -2) return 0;
23106 nb = utf8CheckByte(buf[j]);
23109 if (nb === 2) nb = 0;else self.lastNeed = nb - 3;
23116 // Validates as many continuation bytes for a multi-byte UTF-8 character as
23117 // needed or are available. If we see a non-continuation byte where we expect
23118 // one, we "replace" the validated continuation bytes we've seen so far with
23119 // a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding
23120 // behavior. The continuation byte check is included three times in the case
23121 // where all of the continuation bytes for a character exist in the same buffer.
23122 // It is also done this way as a slight performance increase instead of using a
23124 function utf8CheckExtraBytes(self, buf, p) {
23125 if ((buf[0] & 0xC0) !== 0x80) {
23129 if (self.lastNeed > 1 && buf.length > 1) {
23130 if ((buf[1] & 0xC0) !== 0x80) {
23134 if (self.lastNeed > 2 && buf.length > 2) {
23135 if ((buf[2] & 0xC0) !== 0x80) {
23143 // Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.
23144 function utf8FillLast(buf) {
23145 var p = this.lastTotal - this.lastNeed;
23146 var r = utf8CheckExtraBytes(this, buf, p);
23147 if (r !== undefined) return r;
23148 if (this.lastNeed <= buf.length) {
23149 buf.copy(this.lastChar, p, 0, this.lastNeed);
23150 return this.lastChar.toString(this.encoding, 0, this.lastTotal);
23152 buf.copy(this.lastChar, p, 0, buf.length);
23153 this.lastNeed -= buf.length;
23156 // Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a
23157 // partial character, the character's bytes are buffered until the required
23158 // number of bytes are available.
23159 function utf8Text(buf, i) {
23160 var total = utf8CheckIncomplete(this, buf, i);
23161 if (!this.lastNeed) return buf.toString('utf8', i);
23162 this.lastTotal = total;
23163 var end = buf.length - (total - this.lastNeed);
23164 buf.copy(this.lastChar, 0, end);
23165 return buf.toString('utf8', i, end);
23168 // For UTF-8, a replacement character is added when ending on a partial
23170 function utf8End(buf) {
23171 var r = buf && buf.length ? this.write(buf) : '';
23172 if (this.lastNeed) return r + '\ufffd';
23176 // UTF-16LE typically needs two bytes per character, but even if we have an even
23177 // number of bytes available, we need to check if we end on a leading/high
23178 // surrogate. In that case, we need to wait for the next two bytes in order to
23179 // decode the last character properly.
23180 function utf16Text(buf, i) {
23181 if ((buf.length - i) % 2 === 0) {
23182 var r = buf.toString('utf16le', i);
23184 var c = r.charCodeAt(r.length - 1);
23185 if (c >= 0xD800 && c <= 0xDBFF) {
23187 this.lastTotal = 4;
23188 this.lastChar[0] = buf[buf.length - 2];
23189 this.lastChar[1] = buf[buf.length - 1];
23190 return r.slice(0, -1);
23196 this.lastTotal = 2;
23197 this.lastChar[0] = buf[buf.length - 1];
23198 return buf.toString('utf16le', i, buf.length - 1);
23201 // For UTF-16LE we do not explicitly append special replacement characters if we
23202 // end on a partial character, we simply let v8 handle that.
23203 function utf16End(buf) {
23204 var r = buf && buf.length ? this.write(buf) : '';
23205 if (this.lastNeed) {
23206 var end = this.lastTotal - this.lastNeed;
23207 return r + this.lastChar.toString('utf16le', 0, end);
23212 function base64Text(buf, i) {
23213 var n = (buf.length - i) % 3;
23214 if (n === 0) return buf.toString('base64', i);
23215 this.lastNeed = 3 - n;
23216 this.lastTotal = 3;
23218 this.lastChar[0] = buf[buf.length - 1];
23220 this.lastChar[0] = buf[buf.length - 2];
23221 this.lastChar[1] = buf[buf.length - 1];
23223 return buf.toString('base64', i, buf.length - n);
23226 function base64End(buf) {
23227 var r = buf && buf.length ? this.write(buf) : '';
23228 if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);
23232 // Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)
23233 function simpleWrite(buf) {
23234 return buf.toString(this.encoding);
23237 function simpleEnd(buf) {
23238 return buf && buf.length ? this.write(buf) : '';
23240 },{"safe-buffer":143}],160:[function(require,module,exports){
23241 (function (setImmediate,clearImmediate){
23242 var nextTick = require('process/browser.js').nextTick;
23243 var apply = Function.prototype.apply;
23244 var slice = Array.prototype.slice;
23245 var immediateIds = {};
23246 var nextImmediateId = 0;
23248 // DOM APIs, for completeness
23250 exports.setTimeout = function() {
23251 return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout);
23253 exports.setInterval = function() {
23254 return new Timeout(apply.call(setInterval, window, arguments), clearInterval);
23256 exports.clearTimeout =
23257 exports.clearInterval = function(timeout) { timeout.close(); };
23259 function Timeout(id, clearFn) {
23261 this._clearFn = clearFn;
23263 Timeout.prototype.unref = Timeout.prototype.ref = function() {};
23264 Timeout.prototype.close = function() {
23265 this._clearFn.call(window, this._id);
23268 // Does not start the time, just sets up the members needed.
23269 exports.enroll = function(item, msecs) {
23270 clearTimeout(item._idleTimeoutId);
23271 item._idleTimeout = msecs;
23274 exports.unenroll = function(item) {
23275 clearTimeout(item._idleTimeoutId);
23276 item._idleTimeout = -1;
23279 exports._unrefActive = exports.active = function(item) {
23280 clearTimeout(item._idleTimeoutId);
23282 var msecs = item._idleTimeout;
23284 item._idleTimeoutId = setTimeout(function onTimeout() {
23285 if (item._onTimeout)
23291 // That's not how node.js implements it but the exposed api is the same.
23292 exports.setImmediate = typeof setImmediate === "function" ? setImmediate : function(fn) {
23293 var id = nextImmediateId++;
23294 var args = arguments.length < 2 ? false : slice.call(arguments, 1);
23296 immediateIds[id] = true;
23298 nextTick(function onNextTick() {
23299 if (immediateIds[id]) {
23300 // fn.call() is faster so we optimize for the common use-case
23301 // @see http://jsperf.com/call-apply-segu
23303 fn.apply(null, args);
23307 // Prevent ids from leaking
23308 exports.clearImmediate(id);
23315 exports.clearImmediate = typeof clearImmediate === "function" ? clearImmediate : function(id) {
23316 delete immediateIds[id];
23318 }).call(this,require("timers").setImmediate,require("timers").clearImmediate)
23319 },{"process/browser.js":112,"timers":160}],161:[function(require,module,exports){
23320 var Buffer = require('buffer').Buffer
23322 module.exports = function (buf) {
23323 // If the buffer is backed by a Uint8Array, a faster version will work
23324 if (buf instanceof Uint8Array) {
23325 // If the buffer isn't a subarray, return the underlying ArrayBuffer
23326 if (buf.byteOffset === 0 && buf.byteLength === buf.buffer.byteLength) {
23328 } else if (typeof buf.buffer.slice === 'function') {
23329 // Otherwise we need to get a proper copy
23330 return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength)
23334 if (Buffer.isBuffer(buf)) {
23335 // This is the slow version that will work with any Buffer
23336 // implementation (even in old browsers)
23337 var arrayCopy = new Uint8Array(buf.length)
23338 var len = buf.length
23339 for (var i = 0; i < len; i++) {
23340 arrayCopy[i] = buf[i]
23342 return arrayCopy.buffer
23344 throw new Error('Argument must be a Buffer')
23348 },{"buffer":4}],162:[function(require,module,exports){
23349 // Copyright Joyent, Inc. and other Node contributors.
23351 // Permission is hereby granted, free of charge, to any person obtaining a
23352 // copy of this software and associated documentation files (the
23353 // "Software"), to deal in the Software without restriction, including
23354 // without limitation the rights to use, copy, modify, merge, publish,
23355 // distribute, sublicense, and/or sell copies of the Software, and to permit
23356 // persons to whom the Software is furnished to do so, subject to the
23357 // following conditions:
23359 // The above copyright notice and this permission notice shall be included
23360 // in all copies or substantial portions of the Software.
23362 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
23363 // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
23364 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
23365 // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
23366 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
23367 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
23368 // USE OR OTHER DEALINGS IN THE SOFTWARE.
23372 var punycode = require('punycode');
23373 var util = require('./util');
23375 exports.parse = urlParse;
23376 exports.resolve = urlResolve;
23377 exports.resolveObject = urlResolveObject;
23378 exports.format = urlFormat;
23383 this.protocol = null;
23384 this.slashes = null;
23388 this.hostname = null;
23390 this.search = null;
23392 this.pathname = null;
23397 // Reference: RFC 3986, RFC 1808, RFC 2396
23399 // define these here so at least they only have to be
23400 // compiled once on the first module load.
23401 var protocolPattern = /^([a-z0-9.+-]+:)/i,
23402 portPattern = /:[0-9]*$/,
23404 // Special case for a simple path URL
23405 simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,
23407 // RFC 2396: characters reserved for delimiting URLs.
23408 // We actually just auto-escape these.
23409 delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'],
23411 // RFC 2396: characters not allowed for various reasons.
23412 unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims),
23414 // Allowed by RFCs, but cause of XSS attacks. Always escape these.
23415 autoEscape = ['\''].concat(unwise),
23416 // Characters that are never ever allowed in a hostname.
23417 // Note that any invalid chars are also handled, but these
23418 // are the ones that are *expected* to be seen, so we fast-path
23420 nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape),
23421 hostEndingChars = ['/', '?', '#'],
23422 hostnameMaxLen = 255,
23423 hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/,
23424 hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/,
23425 // protocols that can allow "unsafe" and "unwise" chars.
23427 'javascript': true,
23428 'javascript:': true
23430 // protocols that never have a hostname.
23431 hostlessProtocol = {
23432 'javascript': true,
23433 'javascript:': true
23435 // protocols that always contain a // bit.
23436 slashedProtocol = {
23448 querystring = require('querystring');
23450 function urlParse(url, parseQueryString, slashesDenoteHost) {
23451 if (url && util.isObject(url) && url instanceof Url) return url;
23454 u.parse(url, parseQueryString, slashesDenoteHost);
23458 Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) {
23459 if (!util.isString(url)) {
23460 throw new TypeError("Parameter 'url' must be a string, not " + typeof url);
23463 // Copy chrome, IE, opera backslash-handling behavior.
23464 // Back slashes before the query string get converted to forward slashes
23465 // See: https://code.google.com/p/chromium/issues/detail?id=25916
23466 var queryIndex = url.indexOf('?'),
23468 (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#',
23469 uSplit = url.split(splitter),
23470 slashRegex = /\\/g;
23471 uSplit[0] = uSplit[0].replace(slashRegex, '/');
23472 url = uSplit.join(splitter);
23476 // trim before proceeding.
23477 // This is to support parse stuff like " http://foo.com \n"
23478 rest = rest.trim();
23480 if (!slashesDenoteHost && url.split('#').length === 1) {
23481 // Try fast path regexp
23482 var simplePath = simplePathPattern.exec(rest);
23486 this.pathname = simplePath[1];
23487 if (simplePath[2]) {
23488 this.search = simplePath[2];
23489 if (parseQueryString) {
23490 this.query = querystring.parse(this.search.substr(1));
23492 this.query = this.search.substr(1);
23494 } else if (parseQueryString) {
23502 var proto = protocolPattern.exec(rest);
23505 var lowerProto = proto.toLowerCase();
23506 this.protocol = lowerProto;
23507 rest = rest.substr(proto.length);
23510 // figure out if it's got a host
23511 // user@server is *always* interpreted as a hostname, and url
23512 // resolution will treat //foo/bar as host=foo,path=bar because that's
23513 // how the browser resolves relative URLs.
23514 if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) {
23515 var slashes = rest.substr(0, 2) === '//';
23516 if (slashes && !(proto && hostlessProtocol[proto])) {
23517 rest = rest.substr(2);
23518 this.slashes = true;
23522 if (!hostlessProtocol[proto] &&
23523 (slashes || (proto && !slashedProtocol[proto]))) {
23525 // there's a hostname.
23526 // the first instance of /, ?, ;, or # ends the host.
23528 // If there is an @ in the hostname, then non-host chars *are* allowed
23529 // to the left of the last @ sign, unless some host-ending character
23530 // comes *before* the @-sign.
23531 // URLs are obnoxious.
23534 // http://a@b@c/ => user:a@b host:c
23535 // http://a@b?@c => user:a host:c path:/?@c
23537 // v0.12 TODO(isaacs): This is not quite how Chrome does things.
23538 // Review our test case against browsers more comprehensively.
23540 // find the first instance of any hostEndingChars
23542 for (var i = 0; i < hostEndingChars.length; i++) {
23543 var hec = rest.indexOf(hostEndingChars[i]);
23544 if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
23548 // at this point, either we have an explicit point where the
23549 // auth portion cannot go past, or the last @ char is the decider.
23551 if (hostEnd === -1) {
23552 // atSign can be anywhere.
23553 atSign = rest.lastIndexOf('@');
23555 // atSign must be in auth portion.
23556 // http://a@b/c@d => host:b auth:a path:/c@d
23557 atSign = rest.lastIndexOf('@', hostEnd);
23560 // Now we have a portion which is definitely the auth.
23562 if (atSign !== -1) {
23563 auth = rest.slice(0, atSign);
23564 rest = rest.slice(atSign + 1);
23565 this.auth = decodeURIComponent(auth);
23568 // the host is the remaining to the left of the first non-host char
23570 for (var i = 0; i < nonHostChars.length; i++) {
23571 var hec = rest.indexOf(nonHostChars[i]);
23572 if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
23575 // if we still have not hit it, then the entire thing is a host.
23576 if (hostEnd === -1)
23577 hostEnd = rest.length;
23579 this.host = rest.slice(0, hostEnd);
23580 rest = rest.slice(hostEnd);
23585 // we've indicated that there is a hostname,
23586 // so even if it's empty, it has to be present.
23587 this.hostname = this.hostname || '';
23589 // if hostname begins with [ and ends with ]
23590 // assume that it's an IPv6 address.
23591 var ipv6Hostname = this.hostname[0] === '[' &&
23592 this.hostname[this.hostname.length - 1] === ']';
23594 // validate a little.
23595 if (!ipv6Hostname) {
23596 var hostparts = this.hostname.split(/\./);
23597 for (var i = 0, l = hostparts.length; i < l; i++) {
23598 var part = hostparts[i];
23599 if (!part) continue;
23600 if (!part.match(hostnamePartPattern)) {
23602 for (var j = 0, k = part.length; j < k; j++) {
23603 if (part.charCodeAt(j) > 127) {
23604 // we replace non-ASCII char with a temporary placeholder
23605 // we need this to make sure size of hostname is not
23606 // broken by replacing non-ASCII by nothing
23609 newpart += part[j];
23612 // we test again with ASCII char only
23613 if (!newpart.match(hostnamePartPattern)) {
23614 var validParts = hostparts.slice(0, i);
23615 var notHost = hostparts.slice(i + 1);
23616 var bit = part.match(hostnamePartStart);
23618 validParts.push(bit[1]);
23619 notHost.unshift(bit[2]);
23621 if (notHost.length) {
23622 rest = '/' + notHost.join('.') + rest;
23624 this.hostname = validParts.join('.');
23631 if (this.hostname.length > hostnameMaxLen) {
23632 this.hostname = '';
23634 // hostnames are always lower case.
23635 this.hostname = this.hostname.toLowerCase();
23638 if (!ipv6Hostname) {
23639 // IDNA Support: Returns a punycoded representation of "domain".
23640 // It only converts parts of the domain name that
23641 // have non-ASCII characters, i.e. it doesn't matter if
23642 // you call it with a domain that already is ASCII-only.
23643 this.hostname = punycode.toASCII(this.hostname);
23646 var p = this.port ? ':' + this.port : '';
23647 var h = this.hostname || '';
23649 this.href += this.host;
23651 // strip [ and ] from the hostname
23652 // the host field still retains them, though
23653 if (ipv6Hostname) {
23654 this.hostname = this.hostname.substr(1, this.hostname.length - 2);
23655 if (rest[0] !== '/') {
23661 // now rest is set to the post-host stuff.
23662 // chop off any delim chars.
23663 if (!unsafeProtocol[lowerProto]) {
23665 // First, make 100% sure that any "autoEscape" chars get
23666 // escaped, even if encodeURIComponent doesn't think they
23668 for (var i = 0, l = autoEscape.length; i < l; i++) {
23669 var ae = autoEscape[i];
23670 if (rest.indexOf(ae) === -1)
23672 var esc = encodeURIComponent(ae);
23676 rest = rest.split(ae).join(esc);
23681 // chop off from the tail first.
23682 var hash = rest.indexOf('#');
23684 // got a fragment string.
23685 this.hash = rest.substr(hash);
23686 rest = rest.slice(0, hash);
23688 var qm = rest.indexOf('?');
23690 this.search = rest.substr(qm);
23691 this.query = rest.substr(qm + 1);
23692 if (parseQueryString) {
23693 this.query = querystring.parse(this.query);
23695 rest = rest.slice(0, qm);
23696 } else if (parseQueryString) {
23697 // no query string, but parseQueryString still requested
23701 if (rest) this.pathname = rest;
23702 if (slashedProtocol[lowerProto] &&
23703 this.hostname && !this.pathname) {
23704 this.pathname = '/';
23707 //to support http.request
23708 if (this.pathname || this.search) {
23709 var p = this.pathname || '';
23710 var s = this.search || '';
23714 // finally, reconstruct the href based on what has been validated.
23715 this.href = this.format();
23719 // format a parsed object into a url string
23720 function urlFormat(obj) {
23721 // ensure it's an object, and not a string url.
23722 // If it's an obj, this is a no-op.
23723 // this way, you can call url_format() on strings
23724 // to clean up potentially wonky urls.
23725 if (util.isString(obj)) obj = urlParse(obj);
23726 if (!(obj instanceof Url)) return Url.prototype.format.call(obj);
23727 return obj.format();
23730 Url.prototype.format = function() {
23731 var auth = this.auth || '';
23733 auth = encodeURIComponent(auth);
23734 auth = auth.replace(/%3A/i, ':');
23738 var protocol = this.protocol || '',
23739 pathname = this.pathname || '',
23740 hash = this.hash || '',
23745 host = auth + this.host;
23746 } else if (this.hostname) {
23747 host = auth + (this.hostname.indexOf(':') === -1 ?
23749 '[' + this.hostname + ']');
23751 host += ':' + this.port;
23756 util.isObject(this.query) &&
23757 Object.keys(this.query).length) {
23758 query = querystring.stringify(this.query);
23761 var search = this.search || (query && ('?' + query)) || '';
23763 if (protocol && protocol.substr(-1) !== ':') protocol += ':';
23765 // only the slashedProtocols get the //. Not mailto:, xmpp:, etc.
23766 // unless they had them to begin with.
23767 if (this.slashes ||
23768 (!protocol || slashedProtocol[protocol]) && host !== false) {
23769 host = '//' + (host || '');
23770 if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname;
23771 } else if (!host) {
23775 if (hash && hash.charAt(0) !== '#') hash = '#' + hash;
23776 if (search && search.charAt(0) !== '?') search = '?' + search;
23778 pathname = pathname.replace(/[?#]/g, function(match) {
23779 return encodeURIComponent(match);
23781 search = search.replace('#', '%23');
23783 return protocol + host + pathname + search + hash;
23786 function urlResolve(source, relative) {
23787 return urlParse(source, false, true).resolve(relative);
23790 Url.prototype.resolve = function(relative) {
23791 return this.resolveObject(urlParse(relative, false, true)).format();
23794 function urlResolveObject(source, relative) {
23795 if (!source) return relative;
23796 return urlParse(source, false, true).resolveObject(relative);
23799 Url.prototype.resolveObject = function(relative) {
23800 if (util.isString(relative)) {
23801 var rel = new Url();
23802 rel.parse(relative, false, true);
23806 var result = new Url();
23807 var tkeys = Object.keys(this);
23808 for (var tk = 0; tk < tkeys.length; tk++) {
23809 var tkey = tkeys[tk];
23810 result[tkey] = this[tkey];
23813 // hash is always overridden, no matter what.
23814 // even href="" will remove it.
23815 result.hash = relative.hash;
23817 // if the relative url is empty, then there's nothing left to do here.
23818 if (relative.href === '') {
23819 result.href = result.format();
23823 // hrefs like //foo/bar always cut to the protocol.
23824 if (relative.slashes && !relative.protocol) {
23825 // take everything except the protocol from relative
23826 var rkeys = Object.keys(relative);
23827 for (var rk = 0; rk < rkeys.length; rk++) {
23828 var rkey = rkeys[rk];
23829 if (rkey !== 'protocol')
23830 result[rkey] = relative[rkey];
23833 //urlParse appends trailing / to urls like http://www.example.com
23834 if (slashedProtocol[result.protocol] &&
23835 result.hostname && !result.pathname) {
23836 result.path = result.pathname = '/';
23839 result.href = result.format();
23843 if (relative.protocol && relative.protocol !== result.protocol) {
23844 // if it's a known url protocol, then changing
23845 // the protocol does weird things
23846 // first, if it's not file:, then we MUST have a host,
23847 // and if there was a path
23848 // to begin with, then we MUST have a path.
23849 // if it is file:, then the host is dropped,
23850 // because that's known to be hostless.
23851 // anything else is assumed to be absolute.
23852 if (!slashedProtocol[relative.protocol]) {
23853 var keys = Object.keys(relative);
23854 for (var v = 0; v < keys.length; v++) {
23856 result[k] = relative[k];
23858 result.href = result.format();
23862 result.protocol = relative.protocol;
23863 if (!relative.host && !hostlessProtocol[relative.protocol]) {
23864 var relPath = (relative.pathname || '').split('/');
23865 while (relPath.length && !(relative.host = relPath.shift()));
23866 if (!relative.host) relative.host = '';
23867 if (!relative.hostname) relative.hostname = '';
23868 if (relPath[0] !== '') relPath.unshift('');
23869 if (relPath.length < 2) relPath.unshift('');
23870 result.pathname = relPath.join('/');
23872 result.pathname = relative.pathname;
23874 result.search = relative.search;
23875 result.query = relative.query;
23876 result.host = relative.host || '';
23877 result.auth = relative.auth;
23878 result.hostname = relative.hostname || relative.host;
23879 result.port = relative.port;
23880 // to support http.request
23881 if (result.pathname || result.search) {
23882 var p = result.pathname || '';
23883 var s = result.search || '';
23884 result.path = p + s;
23886 result.slashes = result.slashes || relative.slashes;
23887 result.href = result.format();
23891 var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'),
23894 relative.pathname && relative.pathname.charAt(0) === '/'
23896 mustEndAbs = (isRelAbs || isSourceAbs ||
23897 (result.host && relative.pathname)),
23898 removeAllDots = mustEndAbs,
23899 srcPath = result.pathname && result.pathname.split('/') || [],
23900 relPath = relative.pathname && relative.pathname.split('/') || [],
23901 psychotic = result.protocol && !slashedProtocol[result.protocol];
23903 // if the url is a non-slashed url, then relative
23904 // links like ../.. should be able
23905 // to crawl up to the hostname, as well. This is strange.
23906 // result.protocol has already been set by now.
23907 // Later on, put the first path part into the host field.
23909 result.hostname = '';
23910 result.port = null;
23912 if (srcPath[0] === '') srcPath[0] = result.host;
23913 else srcPath.unshift(result.host);
23916 if (relative.protocol) {
23917 relative.hostname = null;
23918 relative.port = null;
23919 if (relative.host) {
23920 if (relPath[0] === '') relPath[0] = relative.host;
23921 else relPath.unshift(relative.host);
23923 relative.host = null;
23925 mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === '');
23930 result.host = (relative.host || relative.host === '') ?
23931 relative.host : result.host;
23932 result.hostname = (relative.hostname || relative.hostname === '') ?
23933 relative.hostname : result.hostname;
23934 result.search = relative.search;
23935 result.query = relative.query;
23937 // fall through to the dot-handling below.
23938 } else if (relPath.length) {
23940 // throw away the existing file, and take the new path instead.
23941 if (!srcPath) srcPath = [];
23943 srcPath = srcPath.concat(relPath);
23944 result.search = relative.search;
23945 result.query = relative.query;
23946 } else if (!util.isNullOrUndefined(relative.search)) {
23947 // just pull out the search.
23948 // like href='?foo'.
23949 // Put this after the other two cases because it simplifies the booleans
23951 result.hostname = result.host = srcPath.shift();
23952 //occationaly the auth can get stuck only in host
23953 //this especially happens in cases like
23954 //url.resolveObject('mailto:local1@domain1', 'local2@domain2')
23955 var authInHost = result.host && result.host.indexOf('@') > 0 ?
23956 result.host.split('@') : false;
23958 result.auth = authInHost.shift();
23959 result.host = result.hostname = authInHost.shift();
23962 result.search = relative.search;
23963 result.query = relative.query;
23964 //to support http.request
23965 if (!util.isNull(result.pathname) || !util.isNull(result.search)) {
23966 result.path = (result.pathname ? result.pathname : '') +
23967 (result.search ? result.search : '');
23969 result.href = result.format();
23973 if (!srcPath.length) {
23974 // no path at all. easy.
23975 // we've already handled the other stuff above.
23976 result.pathname = null;
23977 //to support http.request
23978 if (result.search) {
23979 result.path = '/' + result.search;
23981 result.path = null;
23983 result.href = result.format();
23987 // if a url ENDs in . or .., then it must get a trailing slash.
23988 // however, if it ends in anything else non-slashy,
23989 // then it must NOT get a trailing slash.
23990 var last = srcPath.slice(-1)[0];
23991 var hasTrailingSlash = (
23992 (result.host || relative.host || srcPath.length > 1) &&
23993 (last === '.' || last === '..') || last === '');
23995 // strip single dots, resolve double dots to parent dir
23996 // if the path tries to go above the root, `up` ends up > 0
23998 for (var i = srcPath.length; i >= 0; i--) {
24000 if (last === '.') {
24001 srcPath.splice(i, 1);
24002 } else if (last === '..') {
24003 srcPath.splice(i, 1);
24006 srcPath.splice(i, 1);
24011 // if the path is allowed to go above the root, restore leading ..s
24012 if (!mustEndAbs && !removeAllDots) {
24014 srcPath.unshift('..');
24018 if (mustEndAbs && srcPath[0] !== '' &&
24019 (!srcPath[0] || srcPath[0].charAt(0) !== '/')) {
24020 srcPath.unshift('');
24023 if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) {
24027 var isAbsolute = srcPath[0] === '' ||
24028 (srcPath[0] && srcPath[0].charAt(0) === '/');
24030 // put the host back
24032 result.hostname = result.host = isAbsolute ? '' :
24033 srcPath.length ? srcPath.shift() : '';
24034 //occationaly the auth can get stuck only in host
24035 //this especially happens in cases like
24036 //url.resolveObject('mailto:local1@domain1', 'local2@domain2')
24037 var authInHost = result.host && result.host.indexOf('@') > 0 ?
24038 result.host.split('@') : false;
24040 result.auth = authInHost.shift();
24041 result.host = result.hostname = authInHost.shift();
24045 mustEndAbs = mustEndAbs || (result.host && srcPath.length);
24047 if (mustEndAbs && !isAbsolute) {
24048 srcPath.unshift('');
24051 if (!srcPath.length) {
24052 result.pathname = null;
24053 result.path = null;
24055 result.pathname = srcPath.join('/');
24058 //to support request.http
24059 if (!util.isNull(result.pathname) || !util.isNull(result.search)) {
24060 result.path = (result.pathname ? result.pathname : '') +
24061 (result.search ? result.search : '');
24063 result.auth = relative.auth || result.auth;
24064 result.slashes = result.slashes || relative.slashes;
24065 result.href = result.format();
24069 Url.prototype.parseHost = function() {
24070 var host = this.host;
24071 var port = portPattern.exec(host);
24074 if (port !== ':') {
24075 this.port = port.substr(1);
24077 host = host.substr(0, host.length - port.length);
24079 if (host) this.hostname = host;
24082 },{"./util":163,"punycode":113,"querystring":116}],163:[function(require,module,exports){
24086 isString: function(arg) {
24087 return typeof(arg) === 'string';
24089 isObject: function(arg) {
24090 return typeof(arg) === 'object' && arg !== null;
24092 isNull: function(arg) {
24093 return arg === null;
24095 isNullOrUndefined: function(arg) {
24096 return arg == null;
24100 },{}],164:[function(require,module,exports){
24101 (function (global){
24107 module.exports = deprecate;
24110 * Mark that a method should not be used.
24111 * Returns a modified function which warns once by default.
24113 * If `localStorage.noDeprecation = true` is set, then it is a no-op.
24115 * If `localStorage.throwDeprecation = true` is set, then deprecated functions
24116 * will throw an Error when invoked.
24118 * If `localStorage.traceDeprecation = true` is set, then deprecated functions
24119 * will invoke `console.trace()` instead of `console.error()`.
24121 * @param {Function} fn - the function to deprecate
24122 * @param {String} msg - the string to print to the console when `fn` is invoked
24123 * @returns {Function} a new "deprecated" version of `fn`
24127 function deprecate (fn, msg) {
24128 if (config('noDeprecation')) {
24132 var warned = false;
24133 function deprecated() {
24135 if (config('throwDeprecation')) {
24136 throw new Error(msg);
24137 } else if (config('traceDeprecation')) {
24138 console.trace(msg);
24144 return fn.apply(this, arguments);
24151 * Checks `localStorage` for boolean values for the given `name`.
24153 * @param {String} name
24154 * @returns {Boolean}
24158 function config (name) {
24159 // accessing global.localStorage can trigger a DOMException in sandboxed iframes
24161 if (!global.localStorage) return false;
24165 var val = global.localStorage[name];
24166 if (null == val) return false;
24167 return String(val).toLowerCase() === 'true';
24170 }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
24171 },{}],165:[function(require,module,exports){
24172 module.exports = extend
24174 var hasOwnProperty = Object.prototype.hasOwnProperty;
24176 function extend() {
24179 for (var i = 0; i < arguments.length; i++) {
24180 var source = arguments[i]
24182 for (var key in source) {
24183 if (hasOwnProperty.call(source, key)) {
24184 target[key] = source[key]
24192 },{}],166:[function(require,module,exports){
24194 * HTML Parser By John Resig (ejohn.org)
24195 * Modified by Juriy "kangax" Zaytsev
24196 * Original code by Erik Arvidsson, Mozilla Public License
24197 * http://erik.eae.net/simplehtmlparser/simplehtmlparser.js
24202 * HTMLParser(htmlString, {
24203 * start: function(tag, attrs, unary) {},
24204 * end: function(tag) {},
24205 * chars: function(text) {},
24206 * comment: function(text) {}
24209 * // or to get an XML string:
24210 * HTMLtoXML(htmlString);
24212 * // or to get an XML DOM Document
24213 * HTMLtoDOM(htmlString);
24215 * // or to inject into an existing document/DOM node
24216 * HTMLtoDOM(htmlString, document);
24217 * HTMLtoDOM(htmlString, document.body);
24221 /* global ActiveXObject, DOMDocument */
24225 var createMapFromString = require('./utils').createMapFromString;
24227 function makeMap(values) {
24228 return createMapFromString(values, true);
24231 // Regular Expressions for parsing tags and attributes
24232 var singleAttrIdentifier = /([^\s"'<>/=]+)/,
24233 singleAttrAssigns = [/=/],
24234 singleAttrValues = [
24235 // attr value double quotes
24236 /"([^"]*)"+/.source,
24237 // attr value, single quotes
24238 /'([^']*)'+/.source,
24239 // attr value, no quotes
24240 /([^ \t\n\f\r"'`=<>]+)/.source
24242 // https://www.w3.org/TR/1999/REC-xml-names-19990114/#NT-QName
24243 qnameCapture = (function() {
24244 // based on https://www.npmjs.com/package/ncname
24245 var combiningChar = '\\u0300-\\u0345\\u0360\\u0361\\u0483-\\u0486\\u0591-\\u05A1\\u05A3-\\u05B9\\u05BB-\\u05BD\\u05BF\\u05C1\\u05C2\\u05C4\\u064B-\\u0652\\u0670\\u06D6-\\u06E4\\u06E7\\u06E8\\u06EA-\\u06ED\\u0901-\\u0903\\u093C\\u093E-\\u094D\\u0951-\\u0954\\u0962\\u0963\\u0981-\\u0983\\u09BC\\u09BE-\\u09C4\\u09C7\\u09C8\\u09CB-\\u09CD\\u09D7\\u09E2\\u09E3\\u0A02\\u0A3C\\u0A3E-\\u0A42\\u0A47\\u0A48\\u0A4B-\\u0A4D\\u0A70\\u0A71\\u0A81-\\u0A83\\u0ABC\\u0ABE-\\u0AC5\\u0AC7-\\u0AC9\\u0ACB-\\u0ACD\\u0B01-\\u0B03\\u0B3C\\u0B3E-\\u0B43\\u0B47\\u0B48\\u0B4B-\\u0B4D\\u0B56\\u0B57\\u0B82\\u0B83\\u0BBE-\\u0BC2\\u0BC6-\\u0BC8\\u0BCA-\\u0BCD\\u0BD7\\u0C01-\\u0C03\\u0C3E-\\u0C44\\u0C46-\\u0C48\\u0C4A-\\u0C4D\\u0C55\\u0C56\\u0C82\\u0C83\\u0CBE-\\u0CC4\\u0CC6-\\u0CC8\\u0CCA-\\u0CCD\\u0CD5\\u0CD6\\u0D02\\u0D03\\u0D3E-\\u0D43\\u0D46-\\u0D48\\u0D4A-\\u0D4D\\u0D57\\u0E31\\u0E34-\\u0E3A\\u0E47-\\u0E4E\\u0EB1\\u0EB4-\\u0EB9\\u0EBB\\u0EBC\\u0EC8-\\u0ECD\\u0F18\\u0F19\\u0F35\\u0F37\\u0F39\\u0F3E\\u0F3F\\u0F71-\\u0F84\\u0F86-\\u0F8B\\u0F90-\\u0F95\\u0F97\\u0F99-\\u0FAD\\u0FB1-\\u0FB7\\u0FB9\\u20D0-\\u20DC\\u20E1\\u302A-\\u302F\\u3099\\u309A';
24246 var digit = '0-9\\u0660-\\u0669\\u06F0-\\u06F9\\u0966-\\u096F\\u09E6-\\u09EF\\u0A66-\\u0A6F\\u0AE6-\\u0AEF\\u0B66-\\u0B6F\\u0BE7-\\u0BEF\\u0C66-\\u0C6F\\u0CE6-\\u0CEF\\u0D66-\\u0D6F\\u0E50-\\u0E59\\u0ED0-\\u0ED9\\u0F20-\\u0F29';
24247 var extender = '\\xB7\\u02D0\\u02D1\\u0387\\u0640\\u0E46\\u0EC6\\u3005\\u3031-\\u3035\\u309D\\u309E\\u30FC-\\u30FE';
24248 var letter = 'A-Za-z\\xC0-\\xD6\\xD8-\\xF6\\xF8-\\u0131\\u0134-\\u013E\\u0141-\\u0148\\u014A-\\u017E\\u0180-\\u01C3\\u01CD-\\u01F0\\u01F4\\u01F5\\u01FA-\\u0217\\u0250-\\u02A8\\u02BB-\\u02C1\\u0386\\u0388-\\u038A\\u038C\\u038E-\\u03A1\\u03A3-\\u03CE\\u03D0-\\u03D6\\u03DA\\u03DC\\u03DE\\u03E0\\u03E2-\\u03F3\\u0401-\\u040C\\u040E-\\u044F\\u0451-\\u045C\\u045E-\\u0481\\u0490-\\u04C4\\u04C7\\u04C8\\u04CB\\u04CC\\u04D0-\\u04EB\\u04EE-\\u04F5\\u04F8\\u04F9\\u0531-\\u0556\\u0559\\u0561-\\u0586\\u05D0-\\u05EA\\u05F0-\\u05F2\\u0621-\\u063A\\u0641-\\u064A\\u0671-\\u06B7\\u06BA-\\u06BE\\u06C0-\\u06CE\\u06D0-\\u06D3\\u06D5\\u06E5\\u06E6\\u0905-\\u0939\\u093D\\u0958-\\u0961\\u0985-\\u098C\\u098F\\u0990\\u0993-\\u09A8\\u09AA-\\u09B0\\u09B2\\u09B6-\\u09B9\\u09DC\\u09DD\\u09DF-\\u09E1\\u09F0\\u09F1\\u0A05-\\u0A0A\\u0A0F\\u0A10\\u0A13-\\u0A28\\u0A2A-\\u0A30\\u0A32\\u0A33\\u0A35\\u0A36\\u0A38\\u0A39\\u0A59-\\u0A5C\\u0A5E\\u0A72-\\u0A74\\u0A85-\\u0A8B\\u0A8D\\u0A8F-\\u0A91\\u0A93-\\u0AA8\\u0AAA-\\u0AB0\\u0AB2\\u0AB3\\u0AB5-\\u0AB9\\u0ABD\\u0AE0\\u0B05-\\u0B0C\\u0B0F\\u0B10\\u0B13-\\u0B28\\u0B2A-\\u0B30\\u0B32\\u0B33\\u0B36-\\u0B39\\u0B3D\\u0B5C\\u0B5D\\u0B5F-\\u0B61\\u0B85-\\u0B8A\\u0B8E-\\u0B90\\u0B92-\\u0B95\\u0B99\\u0B9A\\u0B9C\\u0B9E\\u0B9F\\u0BA3\\u0BA4\\u0BA8-\\u0BAA\\u0BAE-\\u0BB5\\u0BB7-\\u0BB9\\u0C05-\\u0C0C\\u0C0E-\\u0C10\\u0C12-\\u0C28\\u0C2A-\\u0C33\\u0C35-\\u0C39\\u0C60\\u0C61\\u0C85-\\u0C8C\\u0C8E-\\u0C90\\u0C92-\\u0CA8\\u0CAA-\\u0CB3\\u0CB5-\\u0CB9\\u0CDE\\u0CE0\\u0CE1\\u0D05-\\u0D0C\\u0D0E-\\u0D10\\u0D12-\\u0D28\\u0D2A-\\u0D39\\u0D60\\u0D61\\u0E01-\\u0E2E\\u0E30\\u0E32\\u0E33\\u0E40-\\u0E45\\u0E81\\u0E82\\u0E84\\u0E87\\u0E88\\u0E8A\\u0E8D\\u0E94-\\u0E97\\u0E99-\\u0E9F\\u0EA1-\\u0EA3\\u0EA5\\u0EA7\\u0EAA\\u0EAB\\u0EAD\\u0EAE\\u0EB0\\u0EB2\\u0EB3\\u0EBD\\u0EC0-\\u0EC4\\u0F40-\\u0F47\\u0F49-\\u0F69\\u10A0-\\u10C5\\u10D0-\\u10F6\\u1100\\u1102\\u1103\\u1105-\\u1107\\u1109\\u110B\\u110C\\u110E-\\u1112\\u113C\\u113E\\u1140\\u114C\\u114E\\u1150\\u1154\\u1155\\u1159\\u115F-\\u1161\\u1163\\u1165\\u1167\\u1169\\u116D\\u116E\\u1172\\u1173\\u1175\\u119E\\u11A8\\u11AB\\u11AE\\u11AF\\u11B7\\u11B8\\u11BA\\u11BC-\\u11C2\\u11EB\\u11F0\\u11F9\\u1E00-\\u1E9B\\u1EA0-\\u1EF9\\u1F00-\\u1F15\\u1F18-\\u1F1D\\u1F20-\\u1F45\\u1F48-\\u1F4D\\u1F50-\\u1F57\\u1F59\\u1F5B\\u1F5D\\u1F5F-\\u1F7D\\u1F80-\\u1FB4\\u1FB6-\\u1FBC\\u1FBE\\u1FC2-\\u1FC4\\u1FC6-\\u1FCC\\u1FD0-\\u1FD3\\u1FD6-\\u1FDB\\u1FE0-\\u1FEC\\u1FF2-\\u1FF4\\u1FF6-\\u1FFC\\u2126\\u212A\\u212B\\u212E\\u2180-\\u2182\\u3007\\u3021-\\u3029\\u3041-\\u3094\\u30A1-\\u30FA\\u3105-\\u312C\\u4E00-\\u9FA5\\uAC00-\\uD7A3';
24249 var ncname = '[' + letter + '_][' + letter + digit + '\\.\\-_' + combiningChar + extender + ']*';
24250 return '((?:' + ncname + '\\:)?' + ncname + ')';
24252 startTagOpen = new RegExp('^<' + qnameCapture),
24253 startTagClose = /^\s*(\/?)>/,
24254 endTag = new RegExp('^<\\/' + qnameCapture + '[^>]*>'),
24255 doctype = /^<!DOCTYPE\s?[^>]+>/i;
24257 var IS_REGEX_CAPTURING_BROKEN = false;
24258 'x'.replace(/x(.)?/g, function(m, g) {
24259 IS_REGEX_CAPTURING_BROKEN = g === '';
24263 var empty = makeMap('area,base,basefont,br,col,embed,frame,hr,img,input,isindex,keygen,link,meta,param,source,track,wbr');
24266 var inline = makeMap('a,abbr,acronym,applet,b,basefont,bdo,big,br,button,cite,code,del,dfn,em,font,i,iframe,img,input,ins,kbd,label,map,noscript,object,q,s,samp,script,select,small,span,strike,strong,sub,sup,svg,textarea,tt,u,var');
24268 // Elements that you can, intentionally, leave open
24269 // (and which close themselves)
24270 var closeSelf = makeMap('colgroup,dd,dt,li,option,p,td,tfoot,th,thead,tr,source');
24272 // Attributes that have their values filled in disabled='disabled'
24273 var fillAttrs = makeMap('checked,compact,declare,defer,disabled,ismap,multiple,nohref,noresize,noshade,nowrap,readonly,selected');
24275 // Special Elements (can contain anything)
24276 var special = makeMap('script,style');
24278 // HTML5 tags https://html.spec.whatwg.org/multipage/indices.html#elements-3
24279 // Phrasing Content https://html.spec.whatwg.org/multipage/dom.html#phrasing-content
24280 var nonPhrasing = makeMap('address,article,aside,base,blockquote,body,caption,col,colgroup,dd,details,dialog,div,dl,dt,fieldset,figcaption,figure,footer,form,h1,h2,h3,h4,h5,h6,head,header,hgroup,hr,html,legend,li,menuitem,meta,ol,optgroup,option,param,rp,rt,source,style,summary,tbody,td,tfoot,th,thead,title,tr,track,ul');
24284 function attrForHandler(handler) {
24285 var pattern = singleAttrIdentifier.source +
24286 '(?:\\s*(' + joinSingleAttrAssigns(handler) + ')' +
24287 '[ \\t\\n\\f\\r]*(?:' + singleAttrValues.join('|') + '))?';
24288 if (handler.customAttrSurround) {
24289 var attrClauses = [];
24290 for (var i = handler.customAttrSurround.length - 1; i >= 0; i--) {
24291 attrClauses[i] = '(?:' +
24292 '(' + handler.customAttrSurround[i][0].source + ')\\s*' +
24294 '\\s*(' + handler.customAttrSurround[i][1].source + ')' +
24297 attrClauses.push('(?:' + pattern + ')');
24298 pattern = '(?:' + attrClauses.join('|') + ')';
24300 return new RegExp('^\\s*' + pattern);
24303 function joinSingleAttrAssigns(handler) {
24304 return singleAttrAssigns.concat(
24305 handler.customAttrAssign || []
24306 ).map(function(assign) {
24307 return '(?:' + assign.source + ')';
24311 function HTMLParser(html, handler) {
24312 var stack = [], lastTag;
24313 var attribute = attrForHandler(handler);
24314 var last, prevTag, nextTag;
24317 // Make sure we're not in a script or style element
24318 if (!lastTag || !special(lastTag)) {
24319 var textEnd = html.indexOf('<');
24320 if (textEnd === 0) {
24322 if (/^<!--/.test(html)) {
24323 var commentEnd = html.indexOf('-->');
24325 if (commentEnd >= 0) {
24326 if (handler.comment) {
24327 handler.comment(html.substring(4, commentEnd));
24329 html = html.substring(commentEnd + 3);
24335 // https://en.wikipedia.org/wiki/Conditional_comment#Downlevel-revealed_conditional_comment
24336 if (/^<!\[/.test(html)) {
24337 var conditionalEnd = html.indexOf(']>');
24339 if (conditionalEnd >= 0) {
24340 if (handler.comment) {
24341 handler.comment(html.substring(2, conditionalEnd + 1), true /* non-standard */);
24343 html = html.substring(conditionalEnd + 2);
24350 var doctypeMatch = html.match(doctype);
24351 if (doctypeMatch) {
24352 if (handler.doctype) {
24353 handler.doctype(doctypeMatch[0]);
24355 html = html.substring(doctypeMatch[0].length);
24361 var endTagMatch = html.match(endTag);
24363 html = html.substring(endTagMatch[0].length);
24364 endTagMatch[0].replace(endTag, parseEndTag);
24365 prevTag = '/' + endTagMatch[1].toLowerCase();
24370 var startTagMatch = parseStartTag(html);
24371 if (startTagMatch) {
24372 html = startTagMatch.rest;
24373 handleStartTag(startTagMatch);
24374 prevTag = startTagMatch.tagName.toLowerCase();
24380 if (textEnd >= 0) {
24381 text = html.substring(0, textEnd);
24382 html = html.substring(textEnd);
24390 var nextTagMatch = parseStartTag(html);
24391 if (nextTagMatch) {
24392 nextTag = nextTagMatch.tagName;
24395 nextTagMatch = html.match(endTag);
24396 if (nextTagMatch) {
24397 nextTag = '/' + nextTagMatch[1];
24404 if (handler.chars) {
24405 handler.chars(text, prevTag, nextTag);
24411 var stackedTag = lastTag.toLowerCase();
24412 var reStackedTag = reCache[stackedTag] || (reCache[stackedTag] = new RegExp('([\\s\\S]*?)</' + stackedTag + '[^>]*>', 'i'));
24414 html = html.replace(reStackedTag, function(all, text) {
24415 if (stackedTag !== 'script' && stackedTag !== 'style' && stackedTag !== 'noscript') {
24417 .replace(/<!--([\s\S]*?)-->/g, '$1')
24418 .replace(/<!\[CDATA\[([\s\S]*?)]]>/g, '$1');
24421 if (handler.chars) {
24422 handler.chars(text);
24428 parseEndTag('</' + stackedTag + '>', stackedTag);
24431 if (html === last) {
24432 throw new Error('Parse Error: ' + html);
24436 if (!handler.partialMarkup) {
24437 // Clean up any remaining tags
24441 function parseStartTag(input) {
24442 var start = input.match(startTagOpen);
24448 input = input.slice(start[0].length);
24450 while (!(end = input.match(startTagClose)) && (attr = input.match(attribute))) {
24451 input = input.slice(attr[0].length);
24452 match.attrs.push(attr);
24455 match.unarySlash = end[1];
24456 match.rest = input.slice(end[0].length);
24462 function closeIfFound(tagName) {
24463 if (findTag(tagName) >= 0) {
24464 parseEndTag('', tagName);
24469 function handleStartTag(match) {
24470 var tagName = match.tagName;
24471 var unarySlash = match.unarySlash;
24473 if (handler.html5) {
24474 if (lastTag === 'p' && nonPhrasing(tagName)) {
24475 parseEndTag('', lastTag);
24477 else if (tagName === 'tbody') {
24478 closeIfFound('thead');
24480 else if (tagName === 'tfoot') {
24481 if (!closeIfFound('tbody')) {
24482 closeIfFound('thead');
24485 if (tagName === 'col' && findTag('colgroup') < 0) {
24486 lastTag = 'colgroup';
24487 stack.push({ tag: lastTag, attrs: [] });
24488 if (handler.start) {
24489 handler.start(lastTag, [], false, '');
24494 if (!handler.html5 && !inline(tagName)) {
24495 while (lastTag && inline(lastTag)) {
24496 parseEndTag('', lastTag);
24500 if (closeSelf(tagName) && lastTag === tagName) {
24501 parseEndTag('', tagName);
24504 var unary = empty(tagName) || tagName === 'html' && lastTag === 'head' || !!unarySlash;
24506 var attrs = match.attrs.map(function(args) {
24507 var name, value, customOpen, customClose, customAssign, quote;
24508 var ncp = 7; // number of captured parts, scalar
24510 // hackish work around FF bug https://bugzilla.mozilla.org/show_bug.cgi?id=369778
24511 if (IS_REGEX_CAPTURING_BROKEN && args[0].indexOf('""') === -1) {
24512 if (args[3] === '') { delete args[3]; }
24513 if (args[4] === '') { delete args[4]; }
24514 if (args[5] === '') { delete args[5]; }
24517 function populate(index) {
24518 customAssign = args[index];
24519 value = args[index + 1];
24520 if (typeof value !== 'undefined') {
24523 value = args[index + 2];
24524 if (typeof value !== 'undefined') {
24527 value = args[index + 3];
24528 if (typeof value === 'undefined' && fillAttrs(name)) {
24535 if (handler.customAttrSurround) {
24536 for (var i = 0, l = handler.customAttrSurround.length; i < l; i++, j += ncp) {
24537 name = args[j + 1];
24539 quote = populate(j + 2);
24540 customOpen = args[j];
24541 customClose = args[j + 6];
24547 if (!name && (name = args[j])) {
24548 quote = populate(j + 1);
24554 customAssign: customAssign || '=',
24555 customOpen: customOpen || '',
24556 customClose: customClose || '',
24562 stack.push({ tag: tagName, attrs: attrs });
24567 if (handler.start) {
24568 handler.start(tagName, attrs, unary, unarySlash);
24572 function findTag(tagName) {
24574 var needle = tagName.toLowerCase();
24575 for (pos = stack.length - 1; pos >= 0; pos--) {
24576 if (stack[pos].tag.toLowerCase() === needle) {
24583 function parseEndTag(tag, tagName) {
24586 // Find the closest opened tag of the same type
24588 pos = findTag(tagName);
24590 // If no tag name is provided, clean shop
24596 // Close all the open elements, up the stack
24597 for (var i = stack.length - 1; i >= pos; i--) {
24599 handler.end(stack[i].tag, stack[i].attrs, i > pos || !tag);
24603 // Remove the open elements from the stack
24604 stack.length = pos;
24605 lastTag = pos && stack[pos - 1].tag;
24607 else if (tagName.toLowerCase() === 'br') {
24608 if (handler.start) {
24609 handler.start(tagName, [], true, '');
24612 else if (tagName.toLowerCase() === 'p') {
24613 if (handler.start) {
24614 handler.start(tagName, [], false, '', true);
24617 handler.end(tagName, []);
24623 exports.HTMLParser = HTMLParser;
24624 exports.HTMLtoXML = function(html) {
24627 new HTMLParser(html, {
24628 start: function(tag, attrs, unary) {
24629 results += '<' + tag;
24631 for (var i = 0, len = attrs.length; i < len; i++) {
24632 results += ' ' + attrs[i].name + '="' + (attrs[i].value || '').replace(/"/g, '"') + '"';
24635 results += (unary ? '/' : '') + '>';
24637 end: function(tag) {
24638 results += '</' + tag + '>';
24640 chars: function(text) {
24643 comment: function(text) {
24644 results += '<!--' + text + '-->';
24646 ignore: function(text) {
24654 exports.HTMLtoDOM = function(html, doc) {
24655 // There can be only one of these elements
24663 // Enforce a structure for the document
24670 doc = doc.ownerDocument || doc.getOwnerDocument && doc.getOwnerDocument() || doc;
24672 else if (typeof DOMDocument !== 'undefined') {
24673 doc = new DOMDocument();
24675 else if (typeof document !== 'undefined' && document.implementation && document.implementation.createDocument) {
24676 doc = document.implementation.createDocument('', '', null);
24678 else if (typeof ActiveX !== 'undefined') {
24679 doc = new ActiveXObject('Msxml.DOMDocument');
24683 documentElement = doc.documentElement ||
24684 doc.getDocumentElement && doc.getDocumentElement();
24686 // If we're dealing with an empty document then we
24687 // need to pre-populate it with the HTML document structure
24688 if (!documentElement && doc.createElement) {
24690 var html = doc.createElement('html');
24691 var head = doc.createElement('head');
24692 head.appendChild(doc.createElement('title'));
24693 html.appendChild(head);
24694 html.appendChild(doc.createElement('body'));
24695 doc.appendChild(html);
24699 // Find all the unique elements
24700 if (doc.getElementsByTagName) {
24701 for (var i in one) {
24702 one[i] = doc.getElementsByTagName(i)[0];
24706 // If we're working with a document, inject contents into
24707 // the body element
24708 var curParentNode = one.body;
24710 new HTMLParser(html, {
24711 start: function(tagName, attrs, unary) {
24712 // If it's a pre-built element, then we can ignore
24713 // its construction
24714 if (one[tagName]) {
24715 curParentNode = one[tagName];
24719 var elem = doc.createElement(tagName);
24721 for (var attr in attrs) {
24722 elem.setAttribute(attrs[attr].name, attrs[attr].value);
24725 if (structure[tagName] && typeof one[structure[tagName]] !== 'boolean') {
24726 one[structure[tagName]].appendChild(elem);
24728 else if (curParentNode && curParentNode.appendChild) {
24729 curParentNode.appendChild(elem);
24734 curParentNode = elem;
24737 end: function(/* tag */) {
24740 // Init the new parentNode
24741 curParentNode = elems[elems.length - 1];
24743 chars: function(text) {
24744 curParentNode.appendChild(doc.createTextNode(text));
24746 comment: function(/* text */) {
24747 // create comment node
24749 ignore: function(/* text */) {
24750 // What to do here?
24757 },{"./utils":168}],167:[function(require,module,exports){
24760 function Sorter() {
24763 Sorter.prototype.sort = function(tokens, fromIndex) {
24764 fromIndex = fromIndex || 0;
24765 for (var i = 0, len = this.keys.length; i < len; i++) {
24766 var key = this.keys[i];
24767 var token = key.slice(1);
24768 var index = tokens.indexOf(token, fromIndex);
24769 if (index !== -1) {
24771 if (index !== fromIndex) {
24772 tokens.splice(index, 1);
24773 tokens.splice(fromIndex, 0, token);
24776 } while ((index = tokens.indexOf(token, fromIndex)) !== -1);
24777 return this[key].sort(tokens, fromIndex);
24783 function TokenChain() {
24786 TokenChain.prototype = {
24787 add: function(tokens) {
24789 tokens.forEach(function(token) {
24790 var key = '$' + token;
24793 self[key].processed = 0;
24795 self[key].push(tokens);
24798 createSorter: function() {
24800 var sorter = new Sorter();
24801 sorter.keys = Object.keys(self).sort(function(j, k) {
24802 var m = self[j].length;
24803 var n = self[k].length;
24804 return m < n ? 1 : m > n ? -1 : j < k ? -1 : j > k ? 1 : 0;
24805 }).filter(function(key) {
24806 if (self[key].processed < self[key].length) {
24807 var token = key.slice(1);
24808 var chain = new TokenChain();
24809 self[key].forEach(function(tokens) {
24811 while ((index = tokens.indexOf(token)) !== -1) {
24812 tokens.splice(index, 1);
24814 tokens.forEach(function(token) {
24815 self['$' + token].processed++;
24817 chain.add(tokens.slice(0));
24819 sorter[key] = chain.createSorter();
24828 module.exports = TokenChain;
24830 },{}],168:[function(require,module,exports){
24833 function createMap(values, ignoreCase) {
24835 values.forEach(function(value) {
24838 return ignoreCase ? function(value) {
24839 return map[value.toLowerCase()] === 1;
24840 } : function(value) {
24841 return map[value] === 1;
24845 exports.createMap = createMap;
24846 exports.createMapFromString = function(values, ignoreCase) {
24847 return createMap(values.split(/,/), ignoreCase);
24850 },{}],"html-minifier":[function(require,module,exports){
24853 var CleanCSS = require('clean-css');
24854 var decode = require('he').decode;
24855 var HTMLParser = require('./htmlparser').HTMLParser;
24856 var RelateUrl = require('relateurl');
24857 var TokenChain = require('./tokenchain');
24858 var UglifyJS = require('uglify-js');
24859 var utils = require('./utils');
24861 function trimWhitespace(str) {
24862 return str && str.replace(/^[ \n\r\t\f]+/, '').replace(/[ \n\r\t\f]+$/, '');
24865 function collapseWhitespaceAll(str) {
24866 // Non-breaking space is specifically handled inside the replacer function here:
24867 return str && str.replace(/[ \n\r\t\f\xA0]+/g, function(spaces) {
24868 return spaces === '\t' ? '\t' : spaces.replace(/(^|\xA0+)[^\xA0]+/g, '$1 ');
24872 function collapseWhitespace(str, options, trimLeft, trimRight, collapseAll) {
24873 var lineBreakBefore = '', lineBreakAfter = '';
24875 if (options.preserveLineBreaks) {
24876 str = str.replace(/^[ \n\r\t\f]*?[\n\r][ \n\r\t\f]*/, function() {
24877 lineBreakBefore = '\n';
24879 }).replace(/[ \n\r\t\f]*?[\n\r][ \n\r\t\f]*$/, function() {
24880 lineBreakAfter = '\n';
24886 // Non-breaking space is specifically handled inside the replacer function here:
24887 str = str.replace(/^[ \n\r\t\f\xA0]+/, function(spaces) {
24888 var conservative = !lineBreakBefore && options.conservativeCollapse;
24889 if (conservative && spaces === '\t') {
24892 return spaces.replace(/^[^\xA0]+/, '').replace(/(\xA0+)[^\xA0]+/g, '$1 ') || (conservative ? ' ' : '');
24897 // Non-breaking space is specifically handled inside the replacer function here:
24898 str = str.replace(/[ \n\r\t\f\xA0]+$/, function(spaces) {
24899 var conservative = !lineBreakAfter && options.conservativeCollapse;
24900 if (conservative && spaces === '\t') {
24903 return spaces.replace(/[^\xA0]+(\xA0+)/g, ' $1').replace(/[^\xA0]+$/, '') || (conservative ? ' ' : '');
24908 // strip non space whitespace then compress spaces to one
24909 str = collapseWhitespaceAll(str);
24912 return lineBreakBefore + str + lineBreakAfter;
24915 var createMapFromString = utils.createMapFromString;
24916 // non-empty tags that will maintain whitespace around them
24917 var inlineTags = createMapFromString('a,abbr,acronym,b,bdi,bdo,big,button,cite,code,del,dfn,em,font,i,ins,kbd,label,mark,math,nobr,object,q,rp,rt,rtc,ruby,s,samp,select,small,span,strike,strong,sub,sup,svg,textarea,time,tt,u,var');
24918 // non-empty tags that will maintain whitespace within them
24919 var inlineTextTags = createMapFromString('a,abbr,acronym,b,big,del,em,font,i,ins,kbd,mark,nobr,rp,s,samp,small,span,strike,strong,sub,sup,time,tt,u,var');
24920 // self-closing tags that will maintain whitespace around them
24921 var selfClosingInlineTags = createMapFromString('comment,img,input,wbr');
24923 function collapseWhitespaceSmart(str, prevTag, nextTag, options) {
24924 var trimLeft = prevTag && !selfClosingInlineTags(prevTag);
24925 if (trimLeft && !options.collapseInlineTagWhitespace) {
24926 trimLeft = prevTag.charAt(0) === '/' ? !inlineTags(prevTag.slice(1)) : !inlineTextTags(prevTag);
24928 var trimRight = nextTag && !selfClosingInlineTags(nextTag);
24929 if (trimRight && !options.collapseInlineTagWhitespace) {
24930 trimRight = nextTag.charAt(0) === '/' ? !inlineTextTags(nextTag.slice(1)) : !inlineTags(nextTag);
24932 return collapseWhitespace(str, options, trimLeft, trimRight, prevTag && nextTag);
24935 function isConditionalComment(text) {
24936 return /^\[if\s[^\]]+]|\[endif]$/.test(text);
24939 function isIgnoredComment(text, options) {
24940 for (var i = 0, len = options.ignoreCustomComments.length; i < len; i++) {
24941 if (options.ignoreCustomComments[i].test(text)) {
24948 function isEventAttribute(attrName, options) {
24949 var patterns = options.customEventAttributes;
24951 for (var i = patterns.length; i--;) {
24952 if (patterns[i].test(attrName)) {
24958 return /^on[a-z]{3,}$/.test(attrName);
24961 function canRemoveAttributeQuotes(value) {
24962 // https://mathiasbynens.be/notes/unquoted-attribute-values
24963 return /^[^ \t\n\f\r"'`=<>]+$/.test(value);
24966 function attributesInclude(attributes, attribute) {
24967 for (var i = attributes.length; i--;) {
24968 if (attributes[i].name.toLowerCase() === attribute) {
24975 function isAttributeRedundant(tag, attrName, attrValue, attrs) {
24976 attrValue = attrValue ? trimWhitespace(attrValue.toLowerCase()) : '';
24979 tag === 'script' &&
24980 attrName === 'language' &&
24981 attrValue === 'javascript' ||
24984 attrName === 'method' &&
24985 attrValue === 'get' ||
24988 attrName === 'type' &&
24989 attrValue === 'text' ||
24991 tag === 'script' &&
24992 attrName === 'charset' &&
24993 !attributesInclude(attrs, 'src') ||
24996 attrName === 'name' &&
24997 attributesInclude(attrs, 'id') ||
25000 attrName === 'shape' &&
25001 attrValue === 'rect'
25005 // https://mathiasbynens.be/demo/javascript-mime-type
25006 // https://developer.mozilla.org/en/docs/Web/HTML/Element/script#attr-type
25007 var executableScriptsMimetypes = utils.createMap([
25011 'application/javascript',
25012 'application/x-javascript',
25013 'application/ecmascript'
25016 function isScriptTypeAttribute(attrValue) {
25017 attrValue = trimWhitespace(attrValue.split(/;/, 2)[0]).toLowerCase();
25018 return attrValue === '' || executableScriptsMimetypes(attrValue);
25021 function isExecutableScript(tag, attrs) {
25022 if (tag !== 'script') {
25025 for (var i = 0, len = attrs.length; i < len; i++) {
25026 var attrName = attrs[i].name.toLowerCase();
25027 if (attrName === 'type') {
25028 return isScriptTypeAttribute(attrs[i].value);
25034 function isStyleLinkTypeAttribute(attrValue) {
25035 attrValue = trimWhitespace(attrValue).toLowerCase();
25036 return attrValue === '' || attrValue === 'text/css';
25039 function isStyleSheet(tag, attrs) {
25040 if (tag !== 'style') {
25043 for (var i = 0, len = attrs.length; i < len; i++) {
25044 var attrName = attrs[i].name.toLowerCase();
25045 if (attrName === 'type') {
25046 return isStyleLinkTypeAttribute(attrs[i].value);
25052 var isSimpleBoolean = createMapFromString('allowfullscreen,async,autofocus,autoplay,checked,compact,controls,declare,default,defaultchecked,defaultmuted,defaultselected,defer,disabled,enabled,formnovalidate,hidden,indeterminate,inert,ismap,itemscope,loop,multiple,muted,nohref,noresize,noshade,novalidate,nowrap,open,pauseonexit,readonly,required,reversed,scoped,seamless,selected,sortable,truespeed,typemustmatch,visible');
25053 var isBooleanValue = createMapFromString('true,false');
25055 function isBooleanAttribute(attrName, attrValue) {
25056 return isSimpleBoolean(attrName) || attrName === 'draggable' && !isBooleanValue(attrValue);
25059 function isUriTypeAttribute(attrName, tag) {
25061 /^(?:a|area|link|base)$/.test(tag) && attrName === 'href' ||
25062 tag === 'img' && /^(?:src|longdesc|usemap)$/.test(attrName) ||
25063 tag === 'object' && /^(?:classid|codebase|data|usemap)$/.test(attrName) ||
25064 tag === 'q' && attrName === 'cite' ||
25065 tag === 'blockquote' && attrName === 'cite' ||
25066 (tag === 'ins' || tag === 'del') && attrName === 'cite' ||
25067 tag === 'form' && attrName === 'action' ||
25068 tag === 'input' && (attrName === 'src' || attrName === 'usemap') ||
25069 tag === 'head' && attrName === 'profile' ||
25070 tag === 'script' && (attrName === 'src' || attrName === 'for')
25074 function isNumberTypeAttribute(attrName, tag) {
25076 /^(?:a|area|object|button)$/.test(tag) && attrName === 'tabindex' ||
25077 tag === 'input' && (attrName === 'maxlength' || attrName === 'tabindex') ||
25078 tag === 'select' && (attrName === 'size' || attrName === 'tabindex') ||
25079 tag === 'textarea' && /^(?:rows|cols|tabindex)$/.test(attrName) ||
25080 tag === 'colgroup' && attrName === 'span' ||
25081 tag === 'col' && attrName === 'span' ||
25082 (tag === 'th' || tag === 'td') && (attrName === 'rowspan' || attrName === 'colspan')
25086 function isLinkType(tag, attrs, value) {
25087 if (tag !== 'link') {
25090 for (var i = 0, len = attrs.length; i < len; i++) {
25091 if (attrs[i].name === 'rel' && attrs[i].value === value) {
25097 function isMediaQuery(tag, attrs, attrName) {
25098 return attrName === 'media' && (isLinkType(tag, attrs, 'stylesheet') || isStyleSheet(tag, attrs));
25101 var srcsetTags = createMapFromString('img,source');
25103 function isSrcset(attrName, tag) {
25104 return attrName === 'srcset' && srcsetTags(tag);
25107 function cleanAttributeValue(tag, attrName, attrValue, options, attrs) {
25108 if (isEventAttribute(attrName, options)) {
25109 attrValue = trimWhitespace(attrValue).replace(/^javascript:\s*/i, '');
25110 return options.minifyJS(attrValue, true);
25112 else if (attrName === 'class') {
25113 attrValue = trimWhitespace(attrValue);
25114 if (options.sortClassName) {
25115 attrValue = options.sortClassName(attrValue);
25118 attrValue = collapseWhitespaceAll(attrValue);
25122 else if (isUriTypeAttribute(attrName, tag)) {
25123 attrValue = trimWhitespace(attrValue);
25124 return isLinkType(tag, attrs, 'canonical') ? attrValue : options.minifyURLs(attrValue);
25126 else if (isNumberTypeAttribute(attrName, tag)) {
25127 return trimWhitespace(attrValue);
25129 else if (attrName === 'style') {
25130 attrValue = trimWhitespace(attrValue);
25132 if (/;$/.test(attrValue) && !/&#?[0-9a-zA-Z]+;$/.test(attrValue)) {
25133 attrValue = attrValue.replace(/\s*;$/, ';');
25135 attrValue = options.minifyCSS(attrValue, 'inline');
25139 else if (isSrcset(attrName, tag)) {
25140 // https://html.spec.whatwg.org/multipage/embedded-content.html#attr-img-srcset
25141 attrValue = trimWhitespace(attrValue).split(/\s+,\s*|\s*,\s+/).map(function(candidate) {
25142 var url = candidate;
25143 var descriptor = '';
25144 var match = candidate.match(/\s+([1-9][0-9]*w|[0-9]+(?:\.[0-9]+)?x)$/);
25146 url = url.slice(0, -match[0].length);
25147 var num = +match[1].slice(0, -1);
25148 var suffix = match[1].slice(-1);
25149 if (num !== 1 || suffix !== 'x') {
25150 descriptor = ' ' + num + suffix;
25153 return options.minifyURLs(url) + descriptor;
25156 else if (isMetaViewport(tag, attrs) && attrName === 'content') {
25157 attrValue = attrValue.replace(/\s+/g, '').replace(/[0-9]+\.[0-9]+/g, function(numString) {
25158 // "0.90000" -> "0.9"
25160 // "1.0001" -> "1.0001" (unchanged)
25161 return (+numString).toString();
25164 else if (options.customAttrCollapse && options.customAttrCollapse.test(attrName)) {
25165 attrValue = attrValue.replace(/\n+|\r+|\s{2,}/g, '');
25167 else if (tag === 'script' && attrName === 'type') {
25168 attrValue = trimWhitespace(attrValue.replace(/\s*;\s*/g, ';'));
25170 else if (isMediaQuery(tag, attrs, attrName)) {
25171 attrValue = trimWhitespace(attrValue);
25172 return options.minifyCSS(attrValue, 'media');
25177 function isMetaViewport(tag, attrs) {
25178 if (tag !== 'meta') {
25181 for (var i = 0, len = attrs.length; i < len; i++) {
25182 if (attrs[i].name === 'name' && attrs[i].value === 'viewport') {
25188 function ignoreCSS(id) {
25189 return '/* clean-css ignore:start */' + id + '/* clean-css ignore:end */';
25192 // Wrap CSS declarations for CleanCSS > 3.x
25193 // See https://github.com/jakubpawlowicz/clean-css/issues/418
25194 function wrapCSS(text, type) {
25197 return '*{' + text + '}';
25199 return '@media ' + text + '{a{top:0}}';
25205 function unwrapCSS(text, type) {
25209 matches = text.match(/^\*\{([\s\S]*)\}$/);
25212 matches = text.match(/^@media ([\s\S]*?)\s*{[\s\S]*}$/);
25215 return matches ? matches[1] : text;
25218 function cleanConditionalComment(comment, options) {
25219 return options.processConditionalComments ? comment.replace(/^(\[if\s[^\]]+]>)([\s\S]*?)(<!\[endif])$/, function(match, prefix, text, suffix) {
25220 return prefix + minify(text, options, true) + suffix;
25224 function processScript(text, options, currentAttrs) {
25225 for (var i = 0, len = currentAttrs.length; i < len; i++) {
25226 if (currentAttrs[i].name.toLowerCase() === 'type' &&
25227 options.processScripts.indexOf(currentAttrs[i].value) > -1) {
25228 return minify(text, options);
25234 // Tag omission rules from https://html.spec.whatwg.org/multipage/syntax.html#optional-tags
25235 // with the following deviations:
25236 // - retain <body> if followed by <noscript>
25237 // - </rb>, </rt>, </rtc>, </rp> & </tfoot> follow https://www.w3.org/TR/html5/syntax.html#optional-tags
25238 // - retain all tags which are adjacent to non-standard HTML tags
25239 var optionalStartTags = createMapFromString('html,head,body,colgroup,tbody');
25240 var optionalEndTags = createMapFromString('html,head,body,li,dt,dd,p,rb,rt,rtc,rp,optgroup,option,colgroup,caption,thead,tbody,tfoot,tr,td,th');
25241 var headerTags = createMapFromString('meta,link,script,style,template,noscript');
25242 var descriptionTags = createMapFromString('dt,dd');
25243 var pBlockTags = createMapFromString('address,article,aside,blockquote,details,div,dl,fieldset,figcaption,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,main,menu,nav,ol,p,pre,section,table,ul');
25244 var pInlineTags = createMapFromString('a,audio,del,ins,map,noscript,video');
25245 var rubyTags = createMapFromString('rb,rt,rtc,rp');
25246 var rtcTag = createMapFromString('rb,rtc,rp');
25247 var optionTag = createMapFromString('option,optgroup');
25248 var tableContentTags = createMapFromString('tbody,tfoot');
25249 var tableSectionTags = createMapFromString('thead,tbody,tfoot');
25250 var cellTags = createMapFromString('td,th');
25251 var topLevelTags = createMapFromString('html,head,body');
25252 var compactTags = createMapFromString('html,body');
25253 var looseTags = createMapFromString('head,colgroup,caption');
25254 var trailingTags = createMapFromString('dt,thead');
25255 var htmlTags = createMapFromString('a,abbr,acronym,address,applet,area,article,aside,audio,b,base,basefont,bdi,bdo,bgsound,big,blink,blockquote,body,br,button,canvas,caption,center,cite,code,col,colgroup,command,content,data,datalist,dd,del,details,dfn,dialog,dir,div,dl,dt,element,em,embed,fieldset,figcaption,figure,font,footer,form,frame,frameset,h1,h2,h3,h4,h5,h6,head,header,hgroup,hr,html,i,iframe,image,img,input,ins,isindex,kbd,keygen,label,legend,li,link,listing,main,map,mark,marquee,menu,menuitem,meta,meter,multicol,nav,nobr,noembed,noframes,noscript,object,ol,optgroup,option,output,p,param,picture,plaintext,pre,progress,q,rb,rp,rt,rtc,ruby,s,samp,script,section,select,shadow,small,source,spacer,span,strike,strong,style,sub,summary,sup,table,tbody,td,template,textarea,tfoot,th,thead,time,title,tr,track,tt,u,ul,var,video,wbr,xmp');
25257 function canRemoveParentTag(optionalStartTag, tag) {
25258 switch (optionalStartTag) {
25263 return !headerTags(tag);
25265 return tag === 'col';
25267 return tag === 'tr';
25272 function isStartTagMandatory(optionalEndTag, tag) {
25275 return optionalEndTag === 'colgroup';
25277 return tableSectionTags(optionalEndTag);
25282 function canRemovePrecedingTag(optionalEndTag, tag) {
25283 switch (optionalEndTag) {
25293 return tag === optionalEndTag;
25296 return descriptionTags(tag);
25298 return pBlockTags(tag);
25302 return rubyTags(tag);
25304 return rtcTag(tag);
25306 return optionTag(tag);
25309 return tableContentTags(tag);
25311 return tag === 'tbody';
25314 return cellTags(tag);
25319 var reEmptyAttribute = new RegExp(
25320 '^(?:class|id|style|title|lang|dir|on(?:focus|blur|change|click|dblclick|mouse(' +
25321 '?:down|up|over|move|out)|key(?:press|down|up)))$');
25323 function canDeleteEmptyAttribute(tag, attrName, attrValue, options) {
25324 var isValueEmpty = !attrValue || /^\s*$/.test(attrValue);
25325 if (!isValueEmpty) {
25328 if (typeof options.removeEmptyAttributes === 'function') {
25329 return options.removeEmptyAttributes(attrName, tag);
25331 return tag === 'input' && attrName === 'value' || reEmptyAttribute.test(attrName);
25334 function hasAttrName(name, attrs) {
25335 for (var i = attrs.length - 1; i >= 0; i--) {
25336 if (attrs[i].name === name) {
25343 function canRemoveElement(tag, attrs) {
25350 if (hasAttrName('src', attrs)) {
25355 if (hasAttrName('src', attrs) || hasAttrName('srcdoc', attrs)) {
25360 if (hasAttrName('data', attrs)) {
25365 if (hasAttrName('code', attrs)) {
25373 function canCollapseWhitespace(tag) {
25374 return !/^(?:script|style|pre|textarea)$/.test(tag);
25377 function canTrimWhitespace(tag) {
25378 return !/^(?:pre|textarea)$/.test(tag);
25381 function normalizeAttr(attr, attrs, tag, options) {
25382 var attrName = options.name(attr.name),
25383 attrValue = attr.value;
25385 if (options.decodeEntities && attrValue) {
25386 attrValue = decode(attrValue, { isAttributeValue: true });
25389 if (options.removeRedundantAttributes &&
25390 isAttributeRedundant(tag, attrName, attrValue, attrs) ||
25391 options.removeScriptTypeAttributes && tag === 'script' &&
25392 attrName === 'type' && isScriptTypeAttribute(attrValue) ||
25393 options.removeStyleLinkTypeAttributes && (tag === 'style' || tag === 'link') &&
25394 attrName === 'type' && isStyleLinkTypeAttribute(attrValue)) {
25399 attrValue = cleanAttributeValue(tag, attrName, attrValue, options, attrs);
25402 if (options.removeEmptyAttributes &&
25403 canDeleteEmptyAttribute(tag, attrName, attrValue, options)) {
25407 if (options.decodeEntities && attrValue) {
25408 attrValue = attrValue.replace(/&(#?[0-9a-zA-Z]+;)/g, '&$1');
25418 function buildAttr(normalized, hasUnarySlash, options, isLast, uidAttr) {
25419 var attrName = normalized.name,
25420 attrValue = normalized.value,
25421 attr = normalized.attr,
25422 attrQuote = attr.quote,
25426 if (typeof attrValue !== 'undefined' && (!options.removeAttributeQuotes ||
25427 ~attrValue.indexOf(uidAttr) || !canRemoveAttributeQuotes(attrValue))) {
25428 if (!options.preventAttributesEscaping) {
25429 if (typeof options.quoteCharacter === 'undefined') {
25430 var apos = (attrValue.match(/'/g) || []).length;
25431 var quot = (attrValue.match(/"/g) || []).length;
25432 attrQuote = apos < quot ? '\'' : '"';
25435 attrQuote = options.quoteCharacter === '\'' ? '\'' : '"';
25437 if (attrQuote === '"') {
25438 attrValue = attrValue.replace(/"/g, '"');
25441 attrValue = attrValue.replace(/'/g, ''');
25444 emittedAttrValue = attrQuote + attrValue + attrQuote;
25445 if (!isLast && !options.removeTagWhitespace) {
25446 emittedAttrValue += ' ';
25449 // make sure trailing slash is not interpreted as HTML self-closing tag
25450 else if (isLast && !hasUnarySlash && !/\/$/.test(attrValue)) {
25451 emittedAttrValue = attrValue;
25454 emittedAttrValue = attrValue + ' ';
25457 if (typeof attrValue === 'undefined' || options.collapseBooleanAttributes &&
25458 isBooleanAttribute(attrName.toLowerCase(), attrValue.toLowerCase())) {
25459 attrFragment = attrName;
25461 attrFragment += ' ';
25465 attrFragment = attrName + attr.customAssign + emittedAttrValue;
25468 return attr.customOpen + attrFragment + attr.customClose;
25471 function identity(value) {
25475 function processOptions(values) {
25477 name: function(name) {
25478 return name.toLowerCase();
25480 canCollapseWhitespace: canCollapseWhitespace,
25481 canTrimWhitespace: canTrimWhitespace,
25483 ignoreCustomComments: [/^!/],
25484 ignoreCustomFragments: [
25488 includeAutoGeneratedTags: true,
25490 minifyCSS: identity,
25491 minifyJS: identity,
25492 minifyURLs: identity
25494 Object.keys(values).forEach(function(key) {
25495 var value = values[key];
25496 if (key === 'caseSensitive') {
25498 options.name = identity;
25501 else if (key === 'log') {
25502 if (typeof value === 'function') {
25503 options.log = value;
25506 else if (key === 'minifyCSS' && typeof value !== 'function') {
25510 if (typeof value !== 'object') {
25513 options.minifyCSS = function(text, type) {
25514 text = text.replace(/(url\s*\(\s*)("|'|)(.*?)\2(\s*\))/ig, function(match, prefix, quote, url, suffix) {
25515 return prefix + quote + options.minifyURLs(url) + quote + suffix;
25517 var cleanCssOutput = new CleanCSS(value).minify(wrapCSS(text, type));
25518 if (cleanCssOutput.errors.length > 0) {
25519 cleanCssOutput.errors.forEach(options.log);
25522 return unwrapCSS(cleanCssOutput.styles, type);
25525 else if (key === 'minifyJS' && typeof value !== 'function') {
25529 if (typeof value !== 'object') {
25532 (value.parse || (value.parse = {})).bare_returns = false;
25533 options.minifyJS = function(text, inline) {
25534 var start = text.match(/^\s*<!--.*/);
25535 var code = start ? text.slice(start[0].length).replace(/\n\s*-->\s*$/, '') : text;
25536 value.parse.bare_returns = inline;
25537 var result = UglifyJS.minify(code, value);
25538 if (result.error) {
25539 options.log(result.error);
25542 return result.code.replace(/;$/, '');
25545 else if (key === 'minifyURLs' && typeof value !== 'function') {
25549 if (typeof value === 'string') {
25550 value = { site: value };
25552 else if (typeof value !== 'object') {
25555 options.minifyURLs = function(text) {
25557 return RelateUrl.relate(text, value);
25566 options[key] = value;
25572 function uniqueId(value) {
25575 id = Math.random().toString(36).replace(/^0\.[0-9]*/, '');
25576 } while (~value.indexOf(id));
25580 var specialContentTags = createMapFromString('script,style');
25582 function createSortFns(value, options, uidIgnore, uidAttr) {
25583 var attrChains = options.sortAttributes && Object.create(null);
25584 var classChain = options.sortClassName && new TokenChain();
25586 function attrNames(attrs) {
25587 return attrs.map(function(attr) {
25588 return options.name(attr.name);
25592 function shouldSkipUID(token, uid) {
25593 return !uid || token.indexOf(uid) === -1;
25596 function shouldSkipUIDs(token) {
25597 return shouldSkipUID(token, uidIgnore) && shouldSkipUID(token, uidAttr);
25600 function scan(input) {
25601 var currentTag, currentType;
25602 new HTMLParser(input, {
25603 start: function(tag, attrs) {
25605 if (!attrChains[tag]) {
25606 attrChains[tag] = new TokenChain();
25608 attrChains[tag].add(attrNames(attrs).filter(shouldSkipUIDs));
25610 for (var i = 0, len = attrs.length; i < len; i++) {
25611 var attr = attrs[i];
25612 if (classChain && attr.value && options.name(attr.name) === 'class') {
25613 classChain.add(trimWhitespace(attr.value).split(/[ \t\n\f\r]+/).filter(shouldSkipUIDs));
25615 else if (options.processScripts && attr.name.toLowerCase() === 'type') {
25617 currentType = attr.value;
25624 chars: function(text) {
25625 if (options.processScripts && specialContentTags(currentTag) &&
25626 options.processScripts.indexOf(currentType) > -1) {
25633 var log = options.log;
25634 options.log = identity;
25635 options.sortAttributes = false;
25636 options.sortClassName = false;
25637 scan(minify(value, options));
25640 var attrSorters = Object.create(null);
25641 for (var tag in attrChains) {
25642 attrSorters[tag] = attrChains[tag].createSorter();
25644 options.sortAttributes = function(tag, attrs) {
25645 var sorter = attrSorters[tag];
25647 var attrMap = Object.create(null);
25648 var names = attrNames(attrs);
25649 names.forEach(function(name, index) {
25650 (attrMap[name] || (attrMap[name] = [])).push(attrs[index]);
25652 sorter.sort(names).forEach(function(name, index) {
25653 attrs[index] = attrMap[name].shift();
25659 var sorter = classChain.createSorter();
25660 options.sortClassName = function(value) {
25661 return sorter.sort(value.split(/[ \n\f\r]+/)).join(' ');
25666 function minify(value, options, partialMarkup) {
25667 if (options.collapseWhitespace) {
25668 value = collapseWhitespace(value, options, true, true);
25677 stackNoTrimWhitespace = [],
25678 stackNoCollapseWhitespace = [],
25679 optionalStartTag = '',
25680 optionalEndTag = '',
25681 ignoredMarkupChunks = [],
25682 ignoredCustomMarkupChunks = [],
25687 // temporarily replace ignored chunks with comments,
25688 // so that we don't have to worry what's there.
25689 // for all we care there might be
25690 // completely-horribly-broken-alien-non-html-emoj-cthulhu-filled content
25691 value = value.replace(/<!-- htmlmin:ignore -->([\s\S]*?)<!-- htmlmin:ignore -->/g, function(match, group1) {
25693 uidIgnore = uniqueId(value);
25694 var pattern = new RegExp('^' + uidIgnore + '([0-9]+)$');
25695 if (options.ignoreCustomComments) {
25696 options.ignoreCustomComments = options.ignoreCustomComments.slice();
25699 options.ignoreCustomComments = [];
25701 options.ignoreCustomComments.push(pattern);
25703 var token = '<!--' + uidIgnore + ignoredMarkupChunks.length + '-->';
25704 ignoredMarkupChunks.push(group1);
25708 var customFragments = options.ignoreCustomFragments.map(function(re) {
25711 if (customFragments.length) {
25712 var reCustomIgnore = new RegExp('\\s*(?:' + customFragments.join('|') + ')+\\s*', 'g');
25713 // temporarily replace custom ignored fragments with unique attributes
25714 value = value.replace(reCustomIgnore, function(match) {
25716 uidAttr = uniqueId(value);
25717 uidPattern = new RegExp('(\\s*)' + uidAttr + '([0-9]+)(\\s*)', 'g');
25718 if (options.minifyCSS) {
25719 options.minifyCSS = (function(fn) {
25720 return function(text, type) {
25721 text = text.replace(uidPattern, function(match, prefix, index) {
25722 var chunks = ignoredCustomMarkupChunks[+index];
25723 return chunks[1] + uidAttr + index + chunks[2];
25726 new CleanCSS().minify(wrapCSS(text, type)).warnings.forEach(function(warning) {
25727 var match = uidPattern.exec(warning);
25729 var id = uidAttr + match[2];
25730 text = text.replace(id, ignoreCSS(id));
25734 text = fn(text, type);
25735 ids.forEach(function(id) {
25736 text = text.replace(ignoreCSS(id), id);
25740 })(options.minifyCSS);
25742 if (options.minifyJS) {
25743 options.minifyJS = (function(fn) {
25744 return function(text, type) {
25745 return fn(text.replace(uidPattern, function(match, prefix, index) {
25746 var chunks = ignoredCustomMarkupChunks[+index];
25747 return chunks[1] + uidAttr + index + chunks[2];
25750 })(options.minifyJS);
25753 var token = uidAttr + ignoredCustomMarkupChunks.length;
25754 ignoredCustomMarkupChunks.push(/^(\s*)[\s\S]*?(\s*)$/.exec(match));
25755 return '\t' + token + '\t';
25759 if (options.sortAttributes && typeof options.sortAttributes !== 'function' ||
25760 options.sortClassName && typeof options.sortClassName !== 'function') {
25761 createSortFns(value, options, uidIgnore, uidAttr);
25764 function _canCollapseWhitespace(tag, attrs) {
25765 return options.canCollapseWhitespace(tag, attrs, canCollapseWhitespace);
25768 function _canTrimWhitespace(tag, attrs) {
25769 return options.canTrimWhitespace(tag, attrs, canTrimWhitespace);
25772 function removeStartTag() {
25773 var index = buffer.length - 1;
25774 while (index > 0 && !/^<[^/!]/.test(buffer[index])) {
25777 buffer.length = Math.max(0, index);
25780 function removeEndTag() {
25781 var index = buffer.length - 1;
25782 while (index > 0 && !/^<\//.test(buffer[index])) {
25785 buffer.length = Math.max(0, index);
25788 // look for trailing whitespaces, bypass any inline tags
25789 function trimTrailingWhitespace(index, nextTag) {
25790 for (var endTag = null; index >= 0 && _canTrimWhitespace(endTag); index--) {
25791 var str = buffer[index];
25792 var match = str.match(/^<\/([\w:-]+)>$/);
25796 else if (/>$/.test(str) || (buffer[index] = collapseWhitespaceSmart(str, null, nextTag, options))) {
25802 // look for trailing whitespaces from previously processed text
25803 // which may not be trimmed due to a following comment or an empty
25804 // element which has now been removed
25805 function squashTrailingWhitespace(nextTag) {
25806 var charsIndex = buffer.length - 1;
25807 if (buffer.length > 1) {
25808 var item = buffer[buffer.length - 1];
25809 if (/^(?:<!|$)/.test(item) && item.indexOf(uidIgnore) === -1) {
25813 trimTrailingWhitespace(charsIndex, nextTag);
25816 new HTMLParser(value, {
25817 partialMarkup: partialMarkup,
25818 html5: options.html5,
25820 start: function(tag, attrs, unary, unarySlash, autoGenerated) {
25821 if (tag.toLowerCase() === 'svg') {
25822 options = Object.create(options);
25823 options.caseSensitive = true;
25824 options.keepClosingSlash = true;
25825 options.name = identity;
25827 tag = options.name(tag);
25829 charsPrevTag = tag;
25830 if (!inlineTextTags(tag)) {
25834 currentAttrs = attrs;
25836 var optional = options.removeOptionalTags;
25838 var htmlTag = htmlTags(tag);
25839 // <html> may be omitted if first thing inside is not comment
25840 // <head> may be omitted if first thing inside is an element
25841 // <body> may be omitted if first thing inside is not space, comment, <meta>, <link>, <script>, <style> or <template>
25842 // <colgroup> may be omitted if first thing inside is <col>
25843 // <tbody> may be omitted if first thing inside is <tr>
25844 if (htmlTag && canRemoveParentTag(optionalStartTag, tag)) {
25847 optionalStartTag = '';
25848 // end-tag-followed-by-start-tag omission rules
25849 if (htmlTag && canRemovePrecedingTag(optionalEndTag, tag)) {
25851 // <colgroup> cannot be omitted if preceding </colgroup> is omitted
25852 // <tbody> cannot be omitted if preceding </tbody>, </thead> or </tfoot> is omitted
25853 optional = !isStartTagMandatory(optionalEndTag, tag);
25855 optionalEndTag = '';
25858 // set whitespace flags for nested tags (eg. <code> within a <pre>)
25859 if (options.collapseWhitespace) {
25860 if (!stackNoTrimWhitespace.length) {
25861 squashTrailingWhitespace(tag);
25864 if (!_canTrimWhitespace(tag, attrs) || stackNoTrimWhitespace.length) {
25865 stackNoTrimWhitespace.push(tag);
25867 if (!_canCollapseWhitespace(tag, attrs) || stackNoCollapseWhitespace.length) {
25868 stackNoCollapseWhitespace.push(tag);
25873 var openTag = '<' + tag;
25874 var hasUnarySlash = unarySlash && options.keepClosingSlash;
25876 buffer.push(openTag);
25878 if (options.sortAttributes) {
25879 options.sortAttributes(tag, attrs);
25883 for (var i = attrs.length, isLast = true; --i >= 0;) {
25884 var normalized = normalizeAttr(attrs[i], attrs, tag, options);
25886 parts.unshift(buildAttr(normalized, hasUnarySlash, options, isLast, uidAttr));
25890 if (parts.length > 0) {
25892 buffer.push.apply(buffer, parts);
25894 // start tag must never be omitted if it has any attributes
25895 else if (optional && optionalStartTags(tag)) {
25896 optionalStartTag = tag;
25899 buffer.push(buffer.pop() + (hasUnarySlash ? '/' : '') + '>');
25901 if (autoGenerated && !options.includeAutoGeneratedTags) {
25903 optionalStartTag = '';
25906 end: function(tag, attrs, autoGenerated) {
25907 if (tag.toLowerCase() === 'svg') {
25908 options = Object.getPrototypeOf(options);
25910 tag = options.name(tag);
25912 // check if current tag is in a whitespace stack
25913 if (options.collapseWhitespace) {
25914 if (stackNoTrimWhitespace.length) {
25915 if (tag === stackNoTrimWhitespace[stackNoTrimWhitespace.length - 1]) {
25916 stackNoTrimWhitespace.pop();
25920 squashTrailingWhitespace('/' + tag);
25922 if (stackNoCollapseWhitespace.length &&
25923 tag === stackNoCollapseWhitespace[stackNoCollapseWhitespace.length - 1]) {
25924 stackNoCollapseWhitespace.pop();
25928 var isElementEmpty = false;
25929 if (tag === currentTag) {
25931 isElementEmpty = !hasChars;
25934 if (options.removeOptionalTags) {
25935 // <html>, <head> or <body> may be omitted if the element is empty
25936 if (isElementEmpty && topLevelTags(optionalStartTag)) {
25939 optionalStartTag = '';
25940 // </html> or </body> may be omitted if not followed by comment
25941 // </head> may be omitted if not followed by space or comment
25942 // </p> may be omitted if no more content in non-</a> parent
25943 // except for </dt> or </thead>, end tags may be omitted if no more content in parent element
25944 if (htmlTags(tag) && optionalEndTag && !trailingTags(optionalEndTag) && (optionalEndTag !== 'p' || !pInlineTags(tag))) {
25947 optionalEndTag = optionalEndTags(tag) ? tag : '';
25950 if (options.removeEmptyElements && isElementEmpty && canRemoveElement(tag, attrs)) {
25951 // remove last "element" from buffer
25953 optionalStartTag = '';
25954 optionalEndTag = '';
25957 if (autoGenerated && !options.includeAutoGeneratedTags) {
25958 optionalEndTag = '';
25961 buffer.push('</' + tag + '>');
25963 charsPrevTag = '/' + tag;
25964 if (!inlineTags(tag)) {
25967 else if (isElementEmpty) {
25968 currentChars += '|';
25972 chars: function(text, prevTag, nextTag) {
25973 prevTag = prevTag === '' ? 'comment' : prevTag;
25974 nextTag = nextTag === '' ? 'comment' : nextTag;
25975 if (options.decodeEntities && text && !specialContentTags(currentTag)) {
25976 text = decode(text);
25978 if (options.collapseWhitespace) {
25979 if (!stackNoTrimWhitespace.length) {
25980 if (prevTag === 'comment') {
25981 var prevComment = buffer[buffer.length - 1];
25982 if (prevComment.indexOf(uidIgnore) === -1) {
25983 if (!prevComment) {
25984 prevTag = charsPrevTag;
25986 if (buffer.length > 1 && (!prevComment || !options.conservativeCollapse && / $/.test(currentChars))) {
25987 var charsIndex = buffer.length - 2;
25988 buffer[charsIndex] = buffer[charsIndex].replace(/\s+$/, function(trailingSpaces) {
25989 text = trailingSpaces + text;
25996 if (prevTag === '/nobr' || prevTag === 'wbr') {
25997 if (/^\s/.test(text)) {
25998 var tagIndex = buffer.length - 1;
25999 while (tagIndex > 0 && buffer[tagIndex].lastIndexOf('<' + prevTag) !== 0) {
26002 trimTrailingWhitespace(tagIndex - 1, 'br');
26005 else if (inlineTextTags(prevTag.charAt(0) === '/' ? prevTag.slice(1) : prevTag)) {
26006 text = collapseWhitespace(text, options, /(?:^|\s)$/.test(currentChars));
26009 if (prevTag || nextTag) {
26010 text = collapseWhitespaceSmart(text, prevTag, nextTag, options);
26013 text = collapseWhitespace(text, options, true, true);
26015 if (!text && /\s$/.test(currentChars) && prevTag && prevTag.charAt(0) === '/') {
26016 trimTrailingWhitespace(buffer.length - 1, nextTag);
26019 if (!stackNoCollapseWhitespace.length && nextTag !== 'html' && !(prevTag && nextTag)) {
26020 text = collapseWhitespace(text, options, false, false, true);
26023 if (options.processScripts && specialContentTags(currentTag)) {
26024 text = processScript(text, options, currentAttrs);
26026 if (isExecutableScript(currentTag, currentAttrs)) {
26027 text = options.minifyJS(text);
26029 if (isStyleSheet(currentTag, currentAttrs)) {
26030 text = options.minifyCSS(text);
26032 if (options.removeOptionalTags && text) {
26033 // <html> may be omitted if first thing inside is not comment
26034 // <body> may be omitted if first thing inside is not space, comment, <meta>, <link>, <script>, <style> or <template>
26035 if (optionalStartTag === 'html' || optionalStartTag === 'body' && !/^\s/.test(text)) {
26038 optionalStartTag = '';
26039 // </html> or </body> may be omitted if not followed by comment
26040 // </head>, </colgroup> or </caption> may be omitted if not followed by space or comment
26041 if (compactTags(optionalEndTag) || looseTags(optionalEndTag) && !/^\s/.test(text)) {
26044 optionalEndTag = '';
26046 charsPrevTag = /^\s*$/.test(text) ? prevTag : 'comment';
26047 if (options.decodeEntities && text && !specialContentTags(currentTag)) {
26048 // Escape any `&` symbols that start either:
26049 // 1) a legacy named character reference (i.e. one that doesn't end with `;`)
26050 // 2) or any other character reference (i.e. one that does end with `;`)
26051 // Note that `&` can be escaped as `&`, without the semi-colon.
26052 // https://mathiasbynens.be/notes/ambiguous-ampersands
26053 text = text.replace(/&((?:Iacute|aacute|uacute|plusmn|Otilde|otilde|agrave|Agrave|Yacute|yacute|Oslash|oslash|atilde|Atilde|brvbar|ccedil|Ccedil|Ograve|curren|divide|eacute|Eacute|ograve|Oacute|egrave|Egrave|Ugrave|frac12|frac14|frac34|ugrave|oacute|iacute|Ntilde|ntilde|Uacute|middot|igrave|Igrave|iquest|Aacute|cedil|laquo|micro|iexcl|Icirc|icirc|acirc|Ucirc|Ecirc|ocirc|Ocirc|ecirc|ucirc|Aring|aring|AElig|aelig|acute|pound|raquo|Acirc|times|THORN|szlig|thorn|COPY|auml|ordf|ordm|Uuml|macr|uuml|Auml|ouml|Ouml|para|nbsp|euml|quot|QUOT|Euml|yuml|cent|sect|copy|sup1|sup2|sup3|iuml|Iuml|ETH|shy|reg|not|yen|amp|AMP|REG|uml|eth|deg|gt|GT|LT|lt)(?!;)|(?:#?[0-9a-zA-Z]+;))/g, '&$1').replace(/</g, '<');
26055 if (uidPattern && options.collapseWhitespace && stackNoTrimWhitespace.length) {
26056 text = text.replace(uidPattern, function(match, prefix, index) {
26057 return ignoredCustomMarkupChunks[+index][0];
26060 currentChars += text;
26066 comment: function(text, nonStandard) {
26067 var prefix = nonStandard ? '<!' : '<!--';
26068 var suffix = nonStandard ? '>' : '-->';
26069 if (isConditionalComment(text)) {
26070 text = prefix + cleanConditionalComment(text, options) + suffix;
26072 else if (options.removeComments) {
26073 if (isIgnoredComment(text, options)) {
26074 text = '<!--' + text + '-->';
26081 text = prefix + text + suffix;
26083 if (options.removeOptionalTags && text) {
26084 // preceding comments suppress tag omissions
26085 optionalStartTag = '';
26086 optionalEndTag = '';
26090 doctype: function(doctype) {
26091 buffer.push(options.useShortDoctype ? '<!doctype' +
26092 (options.removeTagWhitespace ? '' : ' ') + 'html>' :
26093 collapseWhitespaceAll(doctype));
26095 customAttrAssign: options.customAttrAssign,
26096 customAttrSurround: options.customAttrSurround
26099 if (options.removeOptionalTags) {
26100 // <html> may be omitted if first thing inside is not comment
26101 // <head> or <body> may be omitted if empty
26102 if (topLevelTags(optionalStartTag)) {
26105 // except for </dt> or </thead>, end tags may be omitted if no more content in parent element
26106 if (optionalEndTag && !trailingTags(optionalEndTag)) {
26110 if (options.collapseWhitespace) {
26111 squashTrailingWhitespace('br');
26114 return joinResultSegments(buffer, options, uidPattern ? function(str) {
26115 return str.replace(uidPattern, function(match, prefix, index, suffix) {
26116 var chunk = ignoredCustomMarkupChunks[+index][0];
26117 if (options.collapseWhitespace) {
26118 if (prefix !== '\t') {
26119 chunk = prefix + chunk;
26121 if (suffix !== '\t') {
26124 return collapseWhitespace(chunk, {
26125 preserveLineBreaks: options.preserveLineBreaks,
26126 conservativeCollapse: !options.trimCustomFragments
26127 }, /^[ \n\r\t\f]/.test(chunk), /[ \n\r\t\f]$/.test(chunk));
26131 } : identity, uidIgnore ? function(str) {
26132 return str.replace(new RegExp('<!--' + uidIgnore + '([0-9]+)-->', 'g'), function(match, index) {
26133 return ignoredMarkupChunks[+index];
26138 function joinResultSegments(results, options, restoreCustom, restoreIgnore) {
26140 var maxLineLength = options.maxLineLength;
26141 if (maxLineLength) {
26142 var line = '', lines = [];
26143 while (results.length) {
26144 var len = line.length;
26145 var end = results[0].indexOf('\n');
26147 line += restoreIgnore(restoreCustom(results.shift()));
26150 line += restoreIgnore(restoreCustom(results[0].slice(0, end)));
26151 results[0] = results[0].slice(end + 1);
26153 if (len > 0 && line.length > maxLineLength) {
26154 lines.push(line.slice(0, len));
26155 line = line.slice(len);
26157 else if (end >= 0) {
26165 str = lines.join('\n');
26168 str = restoreIgnore(restoreCustom(results.join('')));
26170 return options.collapseWhitespace ? collapseWhitespace(str, options, true, true) : str;
26173 exports.minify = function(value, options) {
26174 var start = Date.now();
26175 options = processOptions(options || {});
26176 var result = minify(value, options);
26177 options.log('minified in: ' + (Date.now() - start) + 'ms');
26181 },{"./htmlparser":166,"./tokenchain":167,"./utils":168,"clean-css":6,"he":103,"relateurl":128,"uglify-js":"uglify-js"}],"uglify-js":[function(require,module,exports){
26182 (function (Buffer){
26183 (function(exports){"use strict";function characters(str){return str.split("")}function member(name,array){return array.indexOf(name)>=0}function find_if(func,array){for(var i=array.length;--i>=0;)if(func(array[i]))return array[i]}function repeat_string(str,i){if(i<=0)return"";if(i==1)return str;var d=repeat_string(str,i>>1);d+=d;return i&1?d+str:d}function configure_error_stack(fn){Object.defineProperty(fn.prototype,"stack",{get:function(){var err=new Error(this.message);err.name=this.name;try{throw err}catch(e){return e.stack}}})}function DefaultsError(msg,defs){this.message=msg;this.defs=defs}DefaultsError.prototype=Object.create(Error.prototype);DefaultsError.prototype.constructor=DefaultsError;DefaultsError.prototype.name="DefaultsError";configure_error_stack(DefaultsError);function defaults(args,defs,croak){if(args===true)args={};var ret=args||{};if(croak)for(var i in ret)if(HOP(ret,i)&&!HOP(defs,i)){throw new DefaultsError("`"+i+"` is not a supported option",defs)}for(var i in defs)if(HOP(defs,i)){ret[i]=args&&HOP(args,i)?args[i]:defs[i]}return ret}function merge(obj,ext){var count=0;for(var i in ext)if(HOP(ext,i)){obj[i]=ext[i];count++}return count}function noop(){}function return_false(){return false}function return_true(){return true}function return_this(){return this}function return_null(){return null}var MAP=function(){function MAP(a,f,backwards){var ret=[],top=[],i;function doit(){var val=f(a[i],i);var is_last=val instanceof Last;if(is_last)val=val.v;if(val instanceof AtTop){val=val.v;if(val instanceof Splice){top.push.apply(top,backwards?val.v.slice().reverse():val.v)}else{top.push(val)}}else if(val!==skip){if(val instanceof Splice){ret.push.apply(ret,backwards?val.v.slice().reverse():val.v)}else{ret.push(val)}}return is_last}if(Array.isArray(a)){if(backwards){for(i=a.length;--i>=0;)if(doit())break;ret.reverse();top.reverse()}else{for(i=0;i<a.length;++i)if(doit())break}}else{for(i in a)if(HOP(a,i))if(doit())break}return top.concat(ret)}MAP.at_top=function(val){return new AtTop(val)};MAP.splice=function(val){return new Splice(val)};MAP.last=function(val){return new Last(val)};var skip=MAP.skip={};function AtTop(val){this.v=val}function Splice(val){this.v=val}function Last(val){this.v=val}return MAP}();function push_uniq(array,el){if(array.indexOf(el)<0)return array.push(el)}function string_template(text,props){return text.replace(/\{(.+?)\}/g,function(str,p){return props&&props[p]})}function remove(array,el){var index=array.indexOf(el);if(index>=0)array.splice(index,1)}function makePredicate(words){if(!Array.isArray(words))words=words.split(" ");var map=Object.create(null);words.forEach(function(word){map[word]=true});return map}function all(array,predicate){for(var i=array.length;--i>=0;)if(!predicate(array[i]))return false;return true}function Dictionary(){this._values=Object.create(null);this._size=0}Dictionary.prototype={set:function(key,val){if(!this.has(key))++this._size;this._values["$"+key]=val;return this},add:function(key,val){if(this.has(key)){this.get(key).push(val)}else{this.set(key,[val])}return this},get:function(key){return this._values["$"+key]},del:function(key){if(this.has(key)){--this._size;delete this._values["$"+key]}return this},has:function(key){return"$"+key in this._values},each:function(f){for(var i in this._values)f(this._values[i],i.substr(1))},size:function(){return this._size},map:function(f){var ret=[];for(var i in this._values)ret.push(f(this._values[i],i.substr(1)));return ret},clone:function(){var ret=new Dictionary;for(var i in this._values)ret._values[i]=this._values[i];ret._size=this._size;return ret},toObject:function(){return this._values}};Dictionary.fromObject=function(obj){var dict=new Dictionary;dict._size=merge(dict._values,obj);return dict};function HOP(obj,prop){return Object.prototype.hasOwnProperty.call(obj,prop)}function first_in_statement(stack){var node=stack.parent(-1);for(var i=0,p;p=stack.parent(i++);node=p){if(p.TYPE=="Call"){if(p.expression===node)continue}else if(p instanceof AST_Binary){if(p.left===node)continue}else if(p instanceof AST_Conditional){if(p.condition===node)continue}else if(p instanceof AST_PropAccess){if(p.expression===node)continue}else if(p instanceof AST_Sequence){if(p.expressions[0]===node)continue}else if(p instanceof AST_Statement){return p.body===node}else if(p instanceof AST_UnaryPostfix){if(p.expression===node)continue}return false}}"use strict";function DEFNODE(type,props,methods,base){if(typeof base==="undefined")base=AST_Node;props=props?props.split(/\s+/):[];var self_props=props;if(base&&base.PROPS)props=props.concat(base.PROPS);var code=["return function AST_",type,"(props){","if(props){"];props.forEach(function(prop){code.push("this.",prop,"=props.",prop,";")});var proto=base&&new base;if(proto&&proto.initialize||methods&&methods.initialize)code.push("this.initialize();");code.push("}}");var ctor=new Function(code.join(""))();if(proto){ctor.prototype=proto;ctor.BASE=base}if(base)base.SUBCLASSES.push(ctor);ctor.prototype.CTOR=ctor;ctor.PROPS=props||null;ctor.SELF_PROPS=self_props;ctor.SUBCLASSES=[];if(type){ctor.prototype.TYPE=ctor.TYPE=type}if(methods)for(var name in methods)if(HOP(methods,name)){if(/^\$/.test(name)){ctor[name.substr(1)]=methods[name]}else{ctor.prototype[name]=methods[name]}}ctor.DEFMETHOD=function(name,method){this.prototype[name]=method};if(typeof exports!=="undefined"){exports["AST_"+type]=ctor}return ctor}var AST_Token=DEFNODE("Token","type value line col pos endline endcol endpos nlb comments_before comments_after file raw",{},null);var AST_Node=DEFNODE("Node","start end",{_clone:function(deep){if(deep){var self=this.clone();return self.transform(new TreeTransformer(function(node){if(node!==self){return node.clone(true)}}))}return new this.CTOR(this)},clone:function(deep){return this._clone(deep)},$documentation:"Base class of all AST nodes",$propdoc:{start:"[AST_Token] The first token of this node",end:"[AST_Token] The last token of this node"},_walk:function(visitor){return visitor._visit(this)},walk:function(visitor){return this._walk(visitor)}},null);AST_Node.warn=function(txt,props){if(AST_Node.warn_function)AST_Node.warn_function(string_template(txt,props))};var AST_Statement=DEFNODE("Statement",null,{$documentation:"Base class of all statements"});var AST_Debugger=DEFNODE("Debugger",null,{$documentation:"Represents a debugger statement"},AST_Statement);var AST_Directive=DEFNODE("Directive","value quote",{$documentation:'Represents a directive, like "use strict";',$propdoc:{value:"[string] The value of this directive as a plain string (it's not an AST_String!)",quote:"[string] the original quote character"}},AST_Statement);var AST_SimpleStatement=DEFNODE("SimpleStatement","body",{$documentation:"A statement consisting of an expression, i.e. a = 1 + 2",$propdoc:{body:"[AST_Node] an expression node (should not be instanceof AST_Statement)"},_walk:function(visitor){return visitor._visit(this,function(){this.body._walk(visitor)})}},AST_Statement);function walk_body(node,visitor){var body=node.body;if(body instanceof AST_Statement){body._walk(visitor)}else body.forEach(function(node){node._walk(visitor)})}var AST_Block=DEFNODE("Block","body",{$documentation:"A body of statements (usually braced)",$propdoc:{body:"[AST_Statement*] an array of statements"},_walk:function(visitor){return visitor._visit(this,function(){walk_body(this,visitor)})}},AST_Statement);var AST_BlockStatement=DEFNODE("BlockStatement",null,{$documentation:"A block statement"},AST_Block);var AST_EmptyStatement=DEFNODE("EmptyStatement",null,{$documentation:"The empty statement (empty block or simply a semicolon)"},AST_Statement);var AST_StatementWithBody=DEFNODE("StatementWithBody","body",{$documentation:"Base class for all statements that contain one nested body: `For`, `ForIn`, `Do`, `While`, `With`",$propdoc:{body:"[AST_Statement] the body; this should always be present, even if it's an AST_EmptyStatement"}},AST_Statement);var AST_LabeledStatement=DEFNODE("LabeledStatement","label",{$documentation:"Statement with a label",$propdoc:{label:"[AST_Label] a label definition"},_walk:function(visitor){return visitor._visit(this,function(){this.label._walk(visitor);this.body._walk(visitor)})},clone:function(deep){var node=this._clone(deep);if(deep){var label=node.label;var def=this.label;node.walk(new TreeWalker(function(node){if(node instanceof AST_LoopControl&&node.label&&node.label.thedef===def){node.label.thedef=label;label.references.push(node)}}))}return node}},AST_StatementWithBody);var AST_IterationStatement=DEFNODE("IterationStatement",null,{$documentation:"Internal class. All loops inherit from it."},AST_StatementWithBody);var AST_DWLoop=DEFNODE("DWLoop","condition",{$documentation:"Base class for do/while statements",$propdoc:{condition:"[AST_Node] the loop condition. Should not be instanceof AST_Statement"}},AST_IterationStatement);var AST_Do=DEFNODE("Do",null,{$documentation:"A `do` statement",_walk:function(visitor){return visitor._visit(this,function(){this.body._walk(visitor);this.condition._walk(visitor)})}},AST_DWLoop);var AST_While=DEFNODE("While",null,{$documentation:"A `while` statement",_walk:function(visitor){return visitor._visit(this,function(){this.condition._walk(visitor);this.body._walk(visitor)})}},AST_DWLoop);var AST_For=DEFNODE("For","init condition step",{$documentation:"A `for` statement",$propdoc:{init:"[AST_Node?] the `for` initialization code, or null if empty",condition:"[AST_Node?] the `for` termination clause, or null if empty",step:"[AST_Node?] the `for` update clause, or null if empty"},_walk:function(visitor){return visitor._visit(this,function(){if(this.init)this.init._walk(visitor);if(this.condition)this.condition._walk(visitor);if(this.step)this.step._walk(visitor);this.body._walk(visitor)})}},AST_IterationStatement);var AST_ForIn=DEFNODE("ForIn","init object",{$documentation:"A `for ... in` statement",$propdoc:{init:"[AST_Node] the `for/in` initialization code",object:"[AST_Node] the object that we're looping through"},_walk:function(visitor){return visitor._visit(this,function(){this.init._walk(visitor);this.object._walk(visitor);this.body._walk(visitor)})}},AST_IterationStatement);var AST_With=DEFNODE("With","expression",{$documentation:"A `with` statement",$propdoc:{expression:"[AST_Node] the `with` expression"},_walk:function(visitor){return visitor._visit(this,function(){this.expression._walk(visitor);this.body._walk(visitor)})}},AST_StatementWithBody);var AST_Scope=DEFNODE("Scope","variables functions uses_with uses_eval parent_scope enclosed cname",{$documentation:"Base class for all statements introducing a lexical scope",$propdoc:{variables:"[Object/S] a map of name -> SymbolDef for all variables/functions defined in this scope",functions:"[Object/S] like `variables`, but only lists function declarations",uses_with:"[boolean/S] tells whether this scope uses the `with` statement",uses_eval:"[boolean/S] tells whether this scope contains a direct call to the global `eval`",parent_scope:"[AST_Scope?/S] link to the parent scope",enclosed:"[SymbolDef*/S] a list of all symbol definitions that are accessed from this scope or any subscopes",cname:"[integer/S] current index for mangling variables (used internally by the mangler)"},clone:function(deep){var node=this._clone(deep);if(this.variables)node.variables=this.variables.clone();if(this.functions)node.functions=this.functions.clone();if(this.enclosed)node.enclosed=this.enclosed.slice();return node},pinned:function(){return this.uses_eval||this.uses_with}},AST_Block);var AST_Toplevel=DEFNODE("Toplevel","globals",{$documentation:"The toplevel scope",$propdoc:{globals:"[Object/S] a map of name -> SymbolDef for all undeclared names"},wrap_commonjs:function(name){var body=this.body;var wrapped_tl="(function(exports){'$ORIG';})(typeof "+name+"=='undefined'?("+name+"={}):"+name+");";wrapped_tl=parse(wrapped_tl);wrapped_tl=wrapped_tl.transform(new TreeTransformer(function(node){if(node instanceof AST_Directive&&node.value=="$ORIG"){return MAP.splice(body)}}));return wrapped_tl},wrap_enclose:function(args_values){if(typeof args_values!="string")args_values="";var index=args_values.indexOf(":");if(index<0)index=args_values.length;var body=this.body;return parse(["(function(",args_values.slice(0,index),'){"$ORIG"})(',args_values.slice(index+1),")"].join("")).transform(new TreeTransformer(function(node){if(node instanceof AST_Directive&&node.value=="$ORIG"){return MAP.splice(body)}}))}},AST_Scope);var AST_Lambda=DEFNODE("Lambda","name argnames uses_arguments",{$documentation:"Base class for functions",$propdoc:{name:"[AST_SymbolDeclaration?] the name of this function",argnames:"[AST_SymbolFunarg*] array of function arguments",uses_arguments:"[boolean/S] tells whether this function accesses the arguments array"},_walk:function(visitor){return visitor._visit(this,function(){if(this.name)this.name._walk(visitor);this.argnames.forEach(function(argname){argname._walk(visitor)});walk_body(this,visitor)})}},AST_Scope);var AST_Accessor=DEFNODE("Accessor",null,{$documentation:"A setter/getter function. The `name` property is always null."},AST_Lambda);var AST_Function=DEFNODE("Function","inlined",{$documentation:"A function expression"},AST_Lambda);var AST_Defun=DEFNODE("Defun","inlined",{$documentation:"A function definition"},AST_Lambda);var AST_Jump=DEFNODE("Jump",null,{$documentation:"Base class for “jumps” (for now that's `return`, `throw`, `break` and `continue`)"},AST_Statement);var AST_Exit=DEFNODE("Exit","value",{$documentation:"Base class for “exits” (`return` and `throw`)",$propdoc:{value:"[AST_Node?] the value returned or thrown by this statement; could be null for AST_Return"},_walk:function(visitor){return visitor._visit(this,this.value&&function(){this.value._walk(visitor)})}},AST_Jump);var AST_Return=DEFNODE("Return",null,{$documentation:"A `return` statement"},AST_Exit);var AST_Throw=DEFNODE("Throw",null,{$documentation:"A `throw` statement"},AST_Exit);var AST_LoopControl=DEFNODE("LoopControl","label",{$documentation:"Base class for loop control statements (`break` and `continue`)",$propdoc:{label:"[AST_LabelRef?] the label, or null if none"},_walk:function(visitor){return visitor._visit(this,this.label&&function(){this.label._walk(visitor)})}},AST_Jump);var AST_Break=DEFNODE("Break",null,{$documentation:"A `break` statement"},AST_LoopControl);var AST_Continue=DEFNODE("Continue",null,{$documentation:"A `continue` statement"},AST_LoopControl);var AST_If=DEFNODE("If","condition alternative",{$documentation:"A `if` statement",$propdoc:{condition:"[AST_Node] the `if` condition",alternative:"[AST_Statement?] the `else` part, or null if not present"},_walk:function(visitor){return visitor._visit(this,function(){this.condition._walk(visitor);this.body._walk(visitor);if(this.alternative)this.alternative._walk(visitor)})}},AST_StatementWithBody);var AST_Switch=DEFNODE("Switch","expression",{$documentation:"A `switch` statement",$propdoc:{expression:"[AST_Node] the `switch` “discriminant”"},_walk:function(visitor){return visitor._visit(this,function(){this.expression._walk(visitor);walk_body(this,visitor)})}},AST_Block);var AST_SwitchBranch=DEFNODE("SwitchBranch",null,{$documentation:"Base class for `switch` branches"},AST_Block);var AST_Default=DEFNODE("Default",null,{$documentation:"A `default` switch branch"},AST_SwitchBranch);var AST_Case=DEFNODE("Case","expression",{$documentation:"A `case` switch branch",$propdoc:{expression:"[AST_Node] the `case` expression"},_walk:function(visitor){return visitor._visit(this,function(){this.expression._walk(visitor);walk_body(this,visitor)})}},AST_SwitchBranch);var AST_Try=DEFNODE("Try","bcatch bfinally",{$documentation:"A `try` statement",$propdoc:{bcatch:"[AST_Catch?] the catch block, or null if not present",bfinally:"[AST_Finally?] the finally block, or null if not present"},_walk:function(visitor){return visitor._visit(this,function(){walk_body(this,visitor);if(this.bcatch)this.bcatch._walk(visitor);if(this.bfinally)this.bfinally._walk(visitor)})}},AST_Block);var AST_Catch=DEFNODE("Catch","argname",{$documentation:"A `catch` node; only makes sense as part of a `try` statement",$propdoc:{argname:"[AST_SymbolCatch] symbol for the exception"},_walk:function(visitor){return visitor._visit(this,function(){this.argname._walk(visitor);walk_body(this,visitor)})}},AST_Block);var AST_Finally=DEFNODE("Finally",null,{$documentation:"A `finally` node; only makes sense as part of a `try` statement"},AST_Block);var AST_Definitions=DEFNODE("Definitions","definitions",{$documentation:"Base class for `var` nodes (variable declarations/initializations)",$propdoc:{definitions:"[AST_VarDef*] array of variable definitions"},_walk:function(visitor){return visitor._visit(this,function(){this.definitions.forEach(function(defn){defn._walk(visitor)})})}},AST_Statement);var AST_Var=DEFNODE("Var",null,{$documentation:"A `var` statement"},AST_Definitions);var AST_VarDef=DEFNODE("VarDef","name value",{$documentation:"A variable declaration; only appears in a AST_Definitions node",$propdoc:{name:"[AST_SymbolVar] name of the variable",value:"[AST_Node?] initializer, or null of there's no initializer"},_walk:function(visitor){return visitor._visit(this,function(){this.name._walk(visitor);if(this.value)this.value._walk(visitor)})}});var AST_Call=DEFNODE("Call","expression args",{$documentation:"A function call expression",$propdoc:{expression:"[AST_Node] expression to invoke as function",args:"[AST_Node*] array of arguments"},_walk:function(visitor){return visitor._visit(this,function(){this.expression._walk(visitor);this.args.forEach(function(node){node._walk(visitor)})})}});var AST_New=DEFNODE("New",null,{$documentation:"An object instantiation. Derives from a function call since it has exactly the same properties"},AST_Call);var AST_Sequence=DEFNODE("Sequence","expressions",{$documentation:"A sequence expression (comma-separated expressions)",$propdoc:{expressions:"[AST_Node*] array of expressions (at least two)"},_walk:function(visitor){return visitor._visit(this,function(){this.expressions.forEach(function(node){node._walk(visitor)})})}});var AST_PropAccess=DEFNODE("PropAccess","expression property",{$documentation:'Base class for property access expressions, i.e. `a.foo` or `a["foo"]`',$propdoc:{expression:"[AST_Node] the “container” expression",property:"[AST_Node|string] the property to access. For AST_Dot this is always a plain string, while for AST_Sub it's an arbitrary AST_Node"}});var AST_Dot=DEFNODE("Dot",null,{$documentation:"A dotted property access expression",_walk:function(visitor){return visitor._visit(this,function(){this.expression._walk(visitor)})}},AST_PropAccess);var AST_Sub=DEFNODE("Sub",null,{$documentation:'Index-style property access, i.e. `a["foo"]`',_walk:function(visitor){return visitor._visit(this,function(){this.expression._walk(visitor);this.property._walk(visitor)})}},AST_PropAccess);var AST_Unary=DEFNODE("Unary","operator expression",{$documentation:"Base class for unary expressions",$propdoc:{operator:"[string] the operator",expression:"[AST_Node] expression that this unary operator applies to"},_walk:function(visitor){return visitor._visit(this,function(){this.expression._walk(visitor)})}});var AST_UnaryPrefix=DEFNODE("UnaryPrefix",null,{$documentation:"Unary prefix expression, i.e. `typeof i` or `++i`"},AST_Unary);var AST_UnaryPostfix=DEFNODE("UnaryPostfix",null,{$documentation:"Unary postfix expression, i.e. `i++`"},AST_Unary);var AST_Binary=DEFNODE("Binary","operator left right",{$documentation:"Binary expression, i.e. `a + b`",$propdoc:{left:"[AST_Node] left-hand side expression",operator:"[string] the operator",right:"[AST_Node] right-hand side expression"},_walk:function(visitor){return visitor._visit(this,function(){this.left._walk(visitor);this.right._walk(visitor)})}});var AST_Conditional=DEFNODE("Conditional","condition consequent alternative",{$documentation:"Conditional expression using the ternary operator, i.e. `a ? b : c`",$propdoc:{condition:"[AST_Node]",consequent:"[AST_Node]",alternative:"[AST_Node]"},_walk:function(visitor){return visitor._visit(this,function(){this.condition._walk(visitor);this.consequent._walk(visitor);this.alternative._walk(visitor)})}});var AST_Assign=DEFNODE("Assign",null,{$documentation:"An assignment expression — `a = b + 5`"},AST_Binary);var AST_Array=DEFNODE("Array","elements",{$documentation:"An array literal",$propdoc:{elements:"[AST_Node*] array of elements"},_walk:function(visitor){return visitor._visit(this,function(){this.elements.forEach(function(element){element._walk(visitor)})})}});var AST_Object=DEFNODE("Object","properties",{$documentation:"An object literal",$propdoc:{properties:"[AST_ObjectProperty*] array of properties"},_walk:function(visitor){return visitor._visit(this,function(){this.properties.forEach(function(prop){prop._walk(visitor)})})}});var AST_ObjectProperty=DEFNODE("ObjectProperty","key value",{$documentation:"Base class for literal object properties",$propdoc:{key:"[string|AST_SymbolAccessor] property name. For ObjectKeyVal this is a string. For getters and setters this is an AST_SymbolAccessor.",value:"[AST_Node] property value. For getters and setters this is an AST_Accessor."},_walk:function(visitor){return visitor._visit(this,function(){this.value._walk(visitor)})}});var AST_ObjectKeyVal=DEFNODE("ObjectKeyVal","quote",{$documentation:"A key: value object property",$propdoc:{quote:"[string] the original quote character"}},AST_ObjectProperty);var AST_ObjectSetter=DEFNODE("ObjectSetter",null,{$documentation:"An object setter property"},AST_ObjectProperty);var AST_ObjectGetter=DEFNODE("ObjectGetter",null,{$documentation:"An object getter property"},AST_ObjectProperty);var AST_Symbol=DEFNODE("Symbol","scope name thedef",{$propdoc:{name:"[string] name of this symbol",scope:"[AST_Scope/S] the current scope (not necessarily the definition scope)",thedef:"[SymbolDef/S] the definition of this symbol"},$documentation:"Base class for all symbols"});var AST_SymbolAccessor=DEFNODE("SymbolAccessor",null,{$documentation:"The name of a property accessor (setter/getter function)"},AST_Symbol);var AST_SymbolDeclaration=DEFNODE("SymbolDeclaration","init",{$documentation:"A declaration symbol (symbol in var, function name or argument, symbol in catch)"},AST_Symbol);var AST_SymbolVar=DEFNODE("SymbolVar",null,{$documentation:"Symbol defining a variable"},AST_SymbolDeclaration);var AST_SymbolFunarg=DEFNODE("SymbolFunarg",null,{$documentation:"Symbol naming a function argument"},AST_SymbolVar);var AST_SymbolDefun=DEFNODE("SymbolDefun",null,{$documentation:"Symbol defining a function"},AST_SymbolDeclaration);var AST_SymbolLambda=DEFNODE("SymbolLambda",null,{$documentation:"Symbol naming a function expression"},AST_SymbolDeclaration);var AST_SymbolCatch=DEFNODE("SymbolCatch",null,{$documentation:"Symbol naming the exception in catch"},AST_SymbolDeclaration);var AST_Label=DEFNODE("Label","references",{$documentation:"Symbol naming a label (declaration)",$propdoc:{references:"[AST_LoopControl*] a list of nodes referring to this label"},initialize:function(){this.references=[];this.thedef=this}},AST_Symbol);var AST_SymbolRef=DEFNODE("SymbolRef",null,{$documentation:"Reference to some symbol (not definition/declaration)"},AST_Symbol);var AST_LabelRef=DEFNODE("LabelRef",null,{$documentation:"Reference to a label symbol"},AST_Symbol);var AST_This=DEFNODE("This",null,{$documentation:"The `this` symbol"},AST_Symbol);var AST_Constant=DEFNODE("Constant",null,{$documentation:"Base class for all constants",getValue:function(){return this.value}});var AST_String=DEFNODE("String","value quote",{$documentation:"A string literal",$propdoc:{value:"[string] the contents of this string",quote:"[string] the original quote character"}},AST_Constant);var AST_Number=DEFNODE("Number","value literal",{$documentation:"A number literal",$propdoc:{value:"[number] the numeric value",literal:"[string] numeric value as string (optional)"}},AST_Constant);var AST_RegExp=DEFNODE("RegExp","value",{$documentation:"A regexp literal",$propdoc:{value:"[RegExp] the actual regexp"}},AST_Constant);var AST_Atom=DEFNODE("Atom",null,{$documentation:"Base class for atoms"},AST_Constant);var AST_Null=DEFNODE("Null",null,{$documentation:"The `null` atom",value:null},AST_Atom);var AST_NaN=DEFNODE("NaN",null,{$documentation:"The impossible value",value:0/0},AST_Atom);var AST_Undefined=DEFNODE("Undefined",null,{$documentation:"The `undefined` value",value:function(){}()},AST_Atom);var AST_Hole=DEFNODE("Hole",null,{$documentation:"A hole in an array",value:function(){}()},AST_Atom);var AST_Infinity=DEFNODE("Infinity",null,{$documentation:"The `Infinity` value",value:1/0},AST_Atom);var AST_Boolean=DEFNODE("Boolean",null,{$documentation:"Base class for booleans"},AST_Atom);var AST_False=DEFNODE("False",null,{$documentation:"The `false` atom",value:false},AST_Boolean);var AST_True=DEFNODE("True",null,{$documentation:"The `true` atom",value:true},AST_Boolean);function TreeWalker(callback){this.visit=callback;this.stack=[];this.directives=Object.create(null)}TreeWalker.prototype={_visit:function(node,descend){this.push(node);var ret=this.visit(node,descend?function(){descend.call(node)}:noop);if(!ret&&descend){descend.call(node)}this.pop();return ret},parent:function(n){return this.stack[this.stack.length-2-(n||0)]},push:function(node){if(node instanceof AST_Lambda){this.directives=Object.create(this.directives)}else if(node instanceof AST_Directive&&!this.directives[node.value]){this.directives[node.value]=node}this.stack.push(node)},pop:function(){if(this.stack.pop()instanceof AST_Lambda){this.directives=Object.getPrototypeOf(this.directives)}},self:function(){return this.stack[this.stack.length-1]},find_parent:function(type){var stack=this.stack;for(var i=stack.length;--i>=0;){var x=stack[i];if(x instanceof type)return x}},has_directive:function(type){var dir=this.directives[type];if(dir)return dir;var node=this.stack[this.stack.length-1];if(node instanceof AST_Scope){for(var i=0;i<node.body.length;++i){var st=node.body[i];if(!(st instanceof AST_Directive))break;if(st.value==type)return st}}},loopcontrol_target:function(node){var stack=this.stack;if(node.label)for(var i=stack.length;--i>=0;){var x=stack[i];if(x instanceof AST_LabeledStatement&&x.label.name==node.label.name)return x.body}else for(var i=stack.length;--i>=0;){var x=stack[i];if(x instanceof AST_IterationStatement||node instanceof AST_Break&&x instanceof AST_Switch)return x}},in_boolean_context:function(){var self=this.self();for(var i=0,p;p=this.parent(i);i++){if(p instanceof AST_SimpleStatement||p instanceof AST_Conditional&&p.condition===self||p instanceof AST_DWLoop&&p.condition===self||p instanceof AST_For&&p.condition===self||p instanceof AST_If&&p.condition===self||p instanceof AST_UnaryPrefix&&p.operator=="!"&&p.expression===self){return true}if(p instanceof AST_Binary&&(p.operator=="&&"||p.operator=="||")||p instanceof AST_Conditional||p.tail_node()===self){self=p}else{return false}}}};"use strict";var KEYWORDS="break case catch const continue debugger default delete do else finally for function if in instanceof new return switch throw try typeof var void while with";var KEYWORDS_ATOM="false null true";var RESERVED_WORDS="abstract boolean byte char class double enum export extends final float goto implements import int interface let long native package private protected public short static super synchronized this throws transient volatile yield"+" "+KEYWORDS_ATOM+" "+KEYWORDS;var KEYWORDS_BEFORE_EXPRESSION="return new delete throw else case";KEYWORDS=makePredicate(KEYWORDS);RESERVED_WORDS=makePredicate(RESERVED_WORDS);KEYWORDS_BEFORE_EXPRESSION=makePredicate(KEYWORDS_BEFORE_EXPRESSION);KEYWORDS_ATOM=makePredicate(KEYWORDS_ATOM);var OPERATOR_CHARS=makePredicate(characters("+-*&%=<>!?|~^"));var RE_HEX_NUMBER=/^0x[0-9a-f]+$/i;var RE_OCT_NUMBER=/^0[0-7]+$/;var OPERATORS=makePredicate(["in","instanceof","typeof","new","void","delete","++","--","+","-","!","~","&","|","^","*","/","%",">>","<<",">>>","<",">","<=",">=","==","===","!=","!==","?","=","+=","-=","/=","*=","%=",">>=","<<=",">>>=","|=","^=","&=","&&","||"]);var WHITESPACE_CHARS=makePredicate(characters(" \n\r\t\f\v \u2028\u2029 \ufeff"));var NEWLINE_CHARS=makePredicate(characters("\n\r\u2028\u2029"));var PUNC_BEFORE_EXPRESSION=makePredicate(characters("[{(,;:"));var PUNC_CHARS=makePredicate(characters("[]{}(),;:"));var UNICODE={letter:new RegExp("[\\u0041-\\u005A\\u0061-\\u007A\\u00AA\\u00B5\\u00BA\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02C1\\u02C6-\\u02D1\\u02E0-\\u02E4\\u02EC\\u02EE\\u0370-\\u0374\\u0376\\u0377\\u037A-\\u037D\\u037F\\u0386\\u0388-\\u038A\\u038C\\u038E-\\u03A1\\u03A3-\\u03F5\\u03F7-\\u0481\\u048A-\\u052F\\u0531-\\u0556\\u0559\\u0561-\\u0587\\u05D0-\\u05EA\\u05F0-\\u05F2\\u0620-\\u064A\\u066E\\u066F\\u0671-\\u06D3\\u06D5\\u06E5\\u06E6\\u06EE\\u06EF\\u06FA-\\u06FC\\u06FF\\u0710\\u0712-\\u072F\\u074D-\\u07A5\\u07B1\\u07CA-\\u07EA\\u07F4\\u07F5\\u07FA\\u0800-\\u0815\\u081A\\u0824\\u0828\\u0840-\\u0858\\u08A0-\\u08B2\\u0904-\\u0939\\u093D\\u0950\\u0958-\\u0961\\u0971-\\u0980\\u0985-\\u098C\\u098F\\u0990\\u0993-\\u09A8\\u09AA-\\u09B0\\u09B2\\u09B6-\\u09B9\\u09BD\\u09CE\\u09DC\\u09DD\\u09DF-\\u09E1\\u09F0\\u09F1\\u0A05-\\u0A0A\\u0A0F\\u0A10\\u0A13-\\u0A28\\u0A2A-\\u0A30\\u0A32\\u0A33\\u0A35\\u0A36\\u0A38\\u0A39\\u0A59-\\u0A5C\\u0A5E\\u0A72-\\u0A74\\u0A85-\\u0A8D\\u0A8F-\\u0A91\\u0A93-\\u0AA8\\u0AAA-\\u0AB0\\u0AB2\\u0AB3\\u0AB5-\\u0AB9\\u0ABD\\u0AD0\\u0AE0\\u0AE1\\u0B05-\\u0B0C\\u0B0F\\u0B10\\u0B13-\\u0B28\\u0B2A-\\u0B30\\u0B32\\u0B33\\u0B35-\\u0B39\\u0B3D\\u0B5C\\u0B5D\\u0B5F-\\u0B61\\u0B71\\u0B83\\u0B85-\\u0B8A\\u0B8E-\\u0B90\\u0B92-\\u0B95\\u0B99\\u0B9A\\u0B9C\\u0B9E\\u0B9F\\u0BA3\\u0BA4\\u0BA8-\\u0BAA\\u0BAE-\\u0BB9\\u0BD0\\u0C05-\\u0C0C\\u0C0E-\\u0C10\\u0C12-\\u0C28\\u0C2A-\\u0C39\\u0C3D\\u0C58\\u0C59\\u0C60\\u0C61\\u0C85-\\u0C8C\\u0C8E-\\u0C90\\u0C92-\\u0CA8\\u0CAA-\\u0CB3\\u0CB5-\\u0CB9\\u0CBD\\u0CDE\\u0CE0\\u0CE1\\u0CF1\\u0CF2\\u0D05-\\u0D0C\\u0D0E-\\u0D10\\u0D12-\\u0D3A\\u0D3D\\u0D4E\\u0D60\\u0D61\\u0D7A-\\u0D7F\\u0D85-\\u0D96\\u0D9A-\\u0DB1\\u0DB3-\\u0DBB\\u0DBD\\u0DC0-\\u0DC6\\u0E01-\\u0E30\\u0E32\\u0E33\\u0E40-\\u0E46\\u0E81\\u0E82\\u0E84\\u0E87\\u0E88\\u0E8A\\u0E8D\\u0E94-\\u0E97\\u0E99-\\u0E9F\\u0EA1-\\u0EA3\\u0EA5\\u0EA7\\u0EAA\\u0EAB\\u0EAD-\\u0EB0\\u0EB2\\u0EB3\\u0EBD\\u0EC0-\\u0EC4\\u0EC6\\u0EDC-\\u0EDF\\u0F00\\u0F40-\\u0F47\\u0F49-\\u0F6C\\u0F88-\\u0F8C\\u1000-\\u102A\\u103F\\u1050-\\u1055\\u105A-\\u105D\\u1061\\u1065\\u1066\\u106E-\\u1070\\u1075-\\u1081\\u108E\\u10A0-\\u10C5\\u10C7\\u10CD\\u10D0-\\u10FA\\u10FC-\\u1248\\u124A-\\u124D\\u1250-\\u1256\\u1258\\u125A-\\u125D\\u1260-\\u1288\\u128A-\\u128D\\u1290-\\u12B0\\u12B2-\\u12B5\\u12B8-\\u12BE\\u12C0\\u12C2-\\u12C5\\u12C8-\\u12D6\\u12D8-\\u1310\\u1312-\\u1315\\u1318-\\u135A\\u1380-\\u138F\\u13A0-\\u13F4\\u1401-\\u166C\\u166F-\\u167F\\u1681-\\u169A\\u16A0-\\u16EA\\u16EE-\\u16F8\\u1700-\\u170C\\u170E-\\u1711\\u1720-\\u1731\\u1740-\\u1751\\u1760-\\u176C\\u176E-\\u1770\\u1780-\\u17B3\\u17D7\\u17DC\\u1820-\\u1877\\u1880-\\u18A8\\u18AA\\u18B0-\\u18F5\\u1900-\\u191E\\u1950-\\u196D\\u1970-\\u1974\\u1980-\\u19AB\\u19C1-\\u19C7\\u1A00-\\u1A16\\u1A20-\\u1A54\\u1AA7\\u1B05-\\u1B33\\u1B45-\\u1B4B\\u1B83-\\u1BA0\\u1BAE\\u1BAF\\u1BBA-\\u1BE5\\u1C00-\\u1C23\\u1C4D-\\u1C4F\\u1C5A-\\u1C7D\\u1CE9-\\u1CEC\\u1CEE-\\u1CF1\\u1CF5\\u1CF6\\u1D00-\\u1DBF\\u1E00-\\u1F15\\u1F18-\\u1F1D\\u1F20-\\u1F45\\u1F48-\\u1F4D\\u1F50-\\u1F57\\u1F59\\u1F5B\\u1F5D\\u1F5F-\\u1F7D\\u1F80-\\u1FB4\\u1FB6-\\u1FBC\\u1FBE\\u1FC2-\\u1FC4\\u1FC6-\\u1FCC\\u1FD0-\\u1FD3\\u1FD6-\\u1FDB\\u1FE0-\\u1FEC\\u1FF2-\\u1FF4\\u1FF6-\\u1FFC\\u2071\\u207F\\u2090-\\u209C\\u2102\\u2107\\u210A-\\u2113\\u2115\\u2119-\\u211D\\u2124\\u2126\\u2128\\u212A-\\u212D\\u212F-\\u2139\\u213C-\\u213F\\u2145-\\u2149\\u214E\\u2160-\\u2188\\u2C00-\\u2C2E\\u2C30-\\u2C5E\\u2C60-\\u2CE4\\u2CEB-\\u2CEE\\u2CF2\\u2CF3\\u2D00-\\u2D25\\u2D27\\u2D2D\\u2D30-\\u2D67\\u2D6F\\u2D80-\\u2D96\\u2DA0-\\u2DA6\\u2DA8-\\u2DAE\\u2DB0-\\u2DB6\\u2DB8-\\u2DBE\\u2DC0-\\u2DC6\\u2DC8-\\u2DCE\\u2DD0-\\u2DD6\\u2DD8-\\u2DDE\\u2E2F\\u3005-\\u3007\\u3021-\\u3029\\u3031-\\u3035\\u3038-\\u303C\\u3041-\\u3096\\u309D-\\u309F\\u30A1-\\u30FA\\u30FC-\\u30FF\\u3105-\\u312D\\u3131-\\u318E\\u31A0-\\u31BA\\u31F0-\\u31FF\\u3400-\\u4DB5\\u4E00-\\u9FCC\\uA000-\\uA48C\\uA4D0-\\uA4FD\\uA500-\\uA60C\\uA610-\\uA61F\\uA62A\\uA62B\\uA640-\\uA66E\\uA67F-\\uA69D\\uA6A0-\\uA6EF\\uA717-\\uA71F\\uA722-\\uA788\\uA78B-\\uA78E\\uA790-\\uA7AD\\uA7B0\\uA7B1\\uA7F7-\\uA801\\uA803-\\uA805\\uA807-\\uA80A\\uA80C-\\uA822\\uA840-\\uA873\\uA882-\\uA8B3\\uA8F2-\\uA8F7\\uA8FB\\uA90A-\\uA925\\uA930-\\uA946\\uA960-\\uA97C\\uA984-\\uA9B2\\uA9CF\\uA9E0-\\uA9E4\\uA9E6-\\uA9EF\\uA9FA-\\uA9FE\\uAA00-\\uAA28\\uAA40-\\uAA42\\uAA44-\\uAA4B\\uAA60-\\uAA76\\uAA7A\\uAA7E-\\uAAAF\\uAAB1\\uAAB5\\uAAB6\\uAAB9-\\uAABD\\uAAC0\\uAAC2\\uAADB-\\uAADD\\uAAE0-\\uAAEA\\uAAF2-\\uAAF4\\uAB01-\\uAB06\\uAB09-\\uAB0E\\uAB11-\\uAB16\\uAB20-\\uAB26\\uAB28-\\uAB2E\\uAB30-\\uAB5A\\uAB5C-\\uAB5F\\uAB64\\uAB65\\uABC0-\\uABE2\\uAC00-\\uD7A3\\uD7B0-\\uD7C6\\uD7CB-\\uD7FB\\uF900-\\uFA6D\\uFA70-\\uFAD9\\uFB00-\\uFB06\\uFB13-\\uFB17\\uFB1D\\uFB1F-\\uFB28\\uFB2A-\\uFB36\\uFB38-\\uFB3C\\uFB3E\\uFB40\\uFB41\\uFB43\\uFB44\\uFB46-\\uFBB1\\uFBD3-\\uFD3D\\uFD50-\\uFD8F\\uFD92-\\uFDC7\\uFDF0-\\uFDFB\\uFE70-\\uFE74\\uFE76-\\uFEFC\\uFF21-\\uFF3A\\uFF41-\\uFF5A\\uFF66-\\uFFBE\\uFFC2-\\uFFC7\\uFFCA-\\uFFCF\\uFFD2-\\uFFD7\\uFFDA-\\uFFDC]"),digit:new RegExp("[\\u0030-\\u0039\\u0660-\\u0669\\u06F0-\\u06F9\\u07C0-\\u07C9\\u0966-\\u096F\\u09E6-\\u09EF\\u0A66-\\u0A6F\\u0AE6-\\u0AEF\\u0B66-\\u0B6F\\u0BE6-\\u0BEF\\u0C66-\\u0C6F\\u0CE6-\\u0CEF\\u0D66-\\u0D6F\\u0DE6-\\u0DEF\\u0E50-\\u0E59\\u0ED0-\\u0ED9\\u0F20-\\u0F29\\u1040-\\u1049\\u1090-\\u1099\\u17E0-\\u17E9\\u1810-\\u1819\\u1946-\\u194F\\u19D0-\\u19D9\\u1A80-\\u1A89\\u1A90-\\u1A99\\u1B50-\\u1B59\\u1BB0-\\u1BB9\\u1C40-\\u1C49\\u1C50-\\u1C59\\uA620-\\uA629\\uA8D0-\\uA8D9\\uA900-\\uA909\\uA9D0-\\uA9D9\\uA9F0-\\uA9F9\\uAA50-\\uAA59\\uABF0-\\uABF9\\uFF10-\\uFF19]"),non_spacing_mark:new RegExp("[\\u0300-\\u036F\\u0483-\\u0487\\u0591-\\u05BD\\u05BF\\u05C1\\u05C2\\u05C4\\u05C5\\u05C7\\u0610-\\u061A\\u064B-\\u065E\\u0670\\u06D6-\\u06DC\\u06DF-\\u06E4\\u06E7\\u06E8\\u06EA-\\u06ED\\u0711\\u0730-\\u074A\\u07A6-\\u07B0\\u07EB-\\u07F3\\u0816-\\u0819\\u081B-\\u0823\\u0825-\\u0827\\u0829-\\u082D\\u0900-\\u0902\\u093C\\u0941-\\u0948\\u094D\\u0951-\\u0955\\u0962\\u0963\\u0981\\u09BC\\u09C1-\\u09C4\\u09CD\\u09E2\\u09E3\\u0A01\\u0A02\\u0A3C\\u0A41\\u0A42\\u0A47\\u0A48\\u0A4B-\\u0A4D\\u0A51\\u0A70\\u0A71\\u0A75\\u0A81\\u0A82\\u0ABC\\u0AC1-\\u0AC5\\u0AC7\\u0AC8\\u0ACD\\u0AE2\\u0AE3\\u0B01\\u0B3C\\u0B3F\\u0B41-\\u0B44\\u0B4D\\u0B56\\u0B62\\u0B63\\u0B82\\u0BC0\\u0BCD\\u0C3E-\\u0C40\\u0C46-\\u0C48\\u0C4A-\\u0C4D\\u0C55\\u0C56\\u0C62\\u0C63\\u0CBC\\u0CBF\\u0CC6\\u0CCC\\u0CCD\\u0CE2\\u0CE3\\u0D41-\\u0D44\\u0D4D\\u0D62\\u0D63\\u0DCA\\u0DD2-\\u0DD4\\u0DD6\\u0E31\\u0E34-\\u0E3A\\u0E47-\\u0E4E\\u0EB1\\u0EB4-\\u0EB9\\u0EBB\\u0EBC\\u0EC8-\\u0ECD\\u0F18\\u0F19\\u0F35\\u0F37\\u0F39\\u0F71-\\u0F7E\\u0F80-\\u0F84\\u0F86\\u0F87\\u0F90-\\u0F97\\u0F99-\\u0FBC\\u0FC6\\u102D-\\u1030\\u1032-\\u1037\\u1039\\u103A\\u103D\\u103E\\u1058\\u1059\\u105E-\\u1060\\u1071-\\u1074\\u1082\\u1085\\u1086\\u108D\\u109D\\u135F\\u1712-\\u1714\\u1732-\\u1734\\u1752\\u1753\\u1772\\u1773\\u17B7-\\u17BD\\u17C6\\u17C9-\\u17D3\\u17DD\\u180B-\\u180D\\u18A9\\u1920-\\u1922\\u1927\\u1928\\u1932\\u1939-\\u193B\\u1A17\\u1A18\\u1A56\\u1A58-\\u1A5E\\u1A60\\u1A62\\u1A65-\\u1A6C\\u1A73-\\u1A7C\\u1A7F\\u1B00-\\u1B03\\u1B34\\u1B36-\\u1B3A\\u1B3C\\u1B42\\u1B6B-\\u1B73\\u1B80\\u1B81\\u1BA2-\\u1BA5\\u1BA8\\u1BA9\\u1C2C-\\u1C33\\u1C36\\u1C37\\u1CD0-\\u1CD2\\u1CD4-\\u1CE0\\u1CE2-\\u1CE8\\u1CED\\u1DC0-\\u1DE6\\u1DFD-\\u1DFF\\u20D0-\\u20DC\\u20E1\\u20E5-\\u20F0\\u2CEF-\\u2CF1\\u2DE0-\\u2DFF\\u302A-\\u302F\\u3099\\u309A\\uA66F\\uA67C\\uA67D\\uA6F0\\uA6F1\\uA802\\uA806\\uA80B\\uA825\\uA826\\uA8C4\\uA8E0-\\uA8F1\\uA926-\\uA92D\\uA947-\\uA951\\uA980-\\uA982\\uA9B3\\uA9B6-\\uA9B9\\uA9BC\\uAA29-\\uAA2E\\uAA31\\uAA32\\uAA35\\uAA36\\uAA43\\uAA4C\\uAAB0\\uAAB2-\\uAAB4\\uAAB7\\uAAB8\\uAABE\\uAABF\\uAAC1\\uABE5\\uABE8\\uABED\\uFB1E\\uFE00-\\uFE0F\\uFE20-\\uFE26]"),space_combining_mark:new RegExp("[\\u0903\\u093E-\\u0940\\u0949-\\u094C\\u094E\\u0982\\u0983\\u09BE-\\u09C0\\u09C7\\u09C8\\u09CB\\u09CC\\u09D7\\u0A03\\u0A3E-\\u0A40\\u0A83\\u0ABE-\\u0AC0\\u0AC9\\u0ACB\\u0ACC\\u0B02\\u0B03\\u0B3E\\u0B40\\u0B47\\u0B48\\u0B4B\\u0B4C\\u0B57\\u0BBE\\u0BBF\\u0BC1\\u0BC2\\u0BC6-\\u0BC8\\u0BCA-\\u0BCC\\u0BD7\\u0C01-\\u0C03\\u0C41-\\u0C44\\u0C82\\u0C83\\u0CBE\\u0CC0-\\u0CC4\\u0CC7\\u0CC8\\u0CCA\\u0CCB\\u0CD5\\u0CD6\\u0D02\\u0D03\\u0D3E-\\u0D40\\u0D46-\\u0D48\\u0D4A-\\u0D4C\\u0D57\\u0D82\\u0D83\\u0DCF-\\u0DD1\\u0DD8-\\u0DDF\\u0DF2\\u0DF3\\u0F3E\\u0F3F\\u0F7F\\u102B\\u102C\\u1031\\u1038\\u103B\\u103C\\u1056\\u1057\\u1062-\\u1064\\u1067-\\u106D\\u1083\\u1084\\u1087-\\u108C\\u108F\\u109A-\\u109C\\u17B6\\u17BE-\\u17C5\\u17C7\\u17C8\\u1923-\\u1926\\u1929-\\u192B\\u1930\\u1931\\u1933-\\u1938\\u19B0-\\u19C0\\u19C8\\u19C9\\u1A19-\\u1A1B\\u1A55\\u1A57\\u1A61\\u1A63\\u1A64\\u1A6D-\\u1A72\\u1B04\\u1B35\\u1B3B\\u1B3D-\\u1B41\\u1B43\\u1B44\\u1B82\\u1BA1\\u1BA6\\u1BA7\\u1BAA\\u1C24-\\u1C2B\\u1C34\\u1C35\\u1CE1\\u1CF2\\uA823\\uA824\\uA827\\uA880\\uA881\\uA8B4-\\uA8C3\\uA952\\uA953\\uA983\\uA9B4\\uA9B5\\uA9BA\\uA9BB\\uA9BD-\\uA9C0\\uAA2F\\uAA30\\uAA33\\uAA34\\uAA4D\\uAA7B\\uABE3\\uABE4\\uABE6\\uABE7\\uABE9\\uABEA\\uABEC]"),connector_punctuation:new RegExp("[\\u005F\\u203F\\u2040\\u2054\\uFE33\\uFE34\\uFE4D-\\uFE4F\\uFF3F]")};function is_letter(code){return code>=97&&code<=122||code>=65&&code<=90||code>=170&&UNICODE.letter.test(String.fromCharCode(code))}function is_surrogate_pair_head(code){if(typeof code=="string")code=code.charCodeAt(0);return code>=55296&&code<=56319}function is_surrogate_pair_tail(code){if(typeof code=="string")code=code.charCodeAt(0);return code>=56320&&code<=57343}function is_digit(code){return code>=48&&code<=57}function is_alphanumeric_char(code){return is_digit(code)||is_letter(code)}function is_unicode_digit(code){return UNICODE.digit.test(String.fromCharCode(code))}function is_unicode_combining_mark(ch){return UNICODE.non_spacing_mark.test(ch)||UNICODE.space_combining_mark.test(ch)}function is_unicode_connector_punctuation(ch){return UNICODE.connector_punctuation.test(ch)}function is_identifier(name){return!RESERVED_WORDS[name]&&/^[a-z_$][a-z0-9_$]*$/i.test(name)}function is_identifier_start(code){return code==36||code==95||is_letter(code)}function is_identifier_char(ch){var code=ch.charCodeAt(0);return is_identifier_start(code)||is_digit(code)||code==8204||code==8205||is_unicode_combining_mark(ch)||is_unicode_connector_punctuation(ch)||is_unicode_digit(code)}function is_identifier_string(str){return/^[a-z_$][a-z0-9_$]*$/i.test(str)}function parse_js_number(num){if(RE_HEX_NUMBER.test(num)){return parseInt(num.substr(2),16)}else if(RE_OCT_NUMBER.test(num)){return parseInt(num.substr(1),8)}else{var val=parseFloat(num);if(val==num)return val}}function JS_Parse_Error(message,filename,line,col,pos){this.message=message;this.filename=filename;this.line=line;this.col=col;this.pos=pos}JS_Parse_Error.prototype=Object.create(Error.prototype);JS_Parse_Error.prototype.constructor=JS_Parse_Error;JS_Parse_Error.prototype.name="SyntaxError";configure_error_stack(JS_Parse_Error);function js_error(message,filename,line,col,pos){throw new JS_Parse_Error(message,filename,line,col,pos)}function is_token(token,type,val){return token.type==type&&(val==null||token.value==val)}var EX_EOF={};function tokenizer($TEXT,filename,html5_comments,shebang){var S={text:$TEXT,filename:filename,pos:0,tokpos:0,line:1,tokline:0,col:0,tokcol:0,newline_before:false,regex_allowed:false,comments_before:[],directives:{},directive_stack:[]};function peek(){return S.text.charAt(S.pos)}function next(signal_eof,in_string){var ch=S.text.charAt(S.pos++);if(signal_eof&&!ch)throw EX_EOF;if(NEWLINE_CHARS[ch]){S.newline_before=S.newline_before||!in_string;++S.line;S.col=0;if(!in_string&&ch=="\r"&&peek()=="\n"){++S.pos;ch="\n"}}else{++S.col}return ch}function forward(i){while(i-- >0)next()}function looking_at(str){return S.text.substr(S.pos,str.length)==str}function find_eol(){var text=S.text;for(var i=S.pos,n=S.text.length;i<n;++i){var ch=text[i];if(NEWLINE_CHARS[ch])return i}return-1}function find(what,signal_eof){var pos=S.text.indexOf(what,S.pos);if(signal_eof&&pos==-1)throw EX_EOF;return pos}function start_token(){S.tokline=S.line;S.tokcol=S.col;S.tokpos=S.pos}var prev_was_dot=false;function token(type,value,is_comment){S.regex_allowed=type=="operator"&&!UNARY_POSTFIX[value]||type=="keyword"&&KEYWORDS_BEFORE_EXPRESSION[value]||type=="punc"&&PUNC_BEFORE_EXPRESSION[value];if(type=="punc"&&value=="."){prev_was_dot=true}else if(!is_comment){prev_was_dot=false}var ret={type:type,value:value,line:S.tokline,col:S.tokcol,pos:S.tokpos,endline:S.line,endcol:S.col,endpos:S.pos,nlb:S.newline_before,file:filename};if(/^(?:num|string|regexp)$/i.test(type)){ret.raw=$TEXT.substring(ret.pos,ret.endpos)}if(!is_comment){ret.comments_before=S.comments_before;ret.comments_after=S.comments_before=[]}S.newline_before=false;return new AST_Token(ret)}function skip_whitespace(){while(WHITESPACE_CHARS[peek()])next()}function read_while(pred){var ret="",ch,i=0;while((ch=peek())&&pred(ch,i++))ret+=next();return ret}function parse_error(err){js_error(err,filename,S.tokline,S.tokcol,S.tokpos)}function read_num(prefix){var has_e=false,after_e=false,has_x=false,has_dot=prefix==".";var num=read_while(function(ch,i){var code=ch.charCodeAt(0);switch(code){case 120:case 88:return has_x?false:has_x=true;case 101:case 69:return has_x?true:has_e?false:has_e=after_e=true;case 45:return after_e||i==0&&!prefix;case 43:return after_e;case after_e=false,46:return!has_dot&&!has_x&&!has_e?has_dot=true:false}return is_alphanumeric_char(code)});if(prefix)num=prefix+num;if(RE_OCT_NUMBER.test(num)&&next_token.has_directive("use strict")){parse_error("Legacy octal literals are not allowed in strict mode")}var valid=parse_js_number(num);if(!isNaN(valid)){return token("num",valid)}else{parse_error("Invalid syntax: "+num)}}function read_escaped_char(in_string){var ch=next(true,in_string);switch(ch.charCodeAt(0)){case 110:return"\n";case 114:return"\r";case 116:return"\t";case 98:return"\b";case 118:return"\v";case 102:return"\f";case 120:return String.fromCharCode(hex_bytes(2));case 117:return String.fromCharCode(hex_bytes(4));case 10:return"";case 13:if(peek()=="\n"){next(true,in_string);return""}}if(ch>="0"&&ch<="7")return read_octal_escape_sequence(ch);return ch}function read_octal_escape_sequence(ch){var p=peek();if(p>="0"&&p<="7"){ch+=next(true);if(ch[0]<="3"&&(p=peek())>="0"&&p<="7")ch+=next(true)}if(ch==="0")return"\0";if(ch.length>0&&next_token.has_directive("use strict"))parse_error("Legacy octal escape sequences are not allowed in strict mode");return String.fromCharCode(parseInt(ch,8))}function hex_bytes(n){var num=0;for(;n>0;--n){var digit=parseInt(next(true),16);if(isNaN(digit))parse_error("Invalid hex-character pattern in string");num=num<<4|digit}return num}var read_string=with_eof_error("Unterminated string constant",function(quote_char){var quote=next(),ret="";for(;;){var ch=next(true,true);if(ch=="\\")ch=read_escaped_char(true);else if(NEWLINE_CHARS[ch])parse_error("Unterminated string constant");else if(ch==quote)break;ret+=ch}var tok=token("string",ret);tok.quote=quote_char;return tok});function skip_line_comment(type){var regex_allowed=S.regex_allowed;var i=find_eol(),ret;if(i==-1){ret=S.text.substr(S.pos);S.pos=S.text.length}else{ret=S.text.substring(S.pos,i);S.pos=i}S.col=S.tokcol+(S.pos-S.tokpos);S.comments_before.push(token(type,ret,true));S.regex_allowed=regex_allowed;return next_token}var skip_multiline_comment=with_eof_error("Unterminated multiline comment",function(){var regex_allowed=S.regex_allowed;var i=find("*/",true);var text=S.text.substring(S.pos,i).replace(/\r\n|\r|\u2028|\u2029/g,"\n");forward(text.length+2);S.comments_before.push(token("comment2",text,true));S.regex_allowed=regex_allowed;return next_token});function read_name(){var backslash=false,name="",ch,escaped=false,hex;while((ch=peek())!=null){if(!backslash){if(ch=="\\")escaped=backslash=true,next();else if(is_identifier_char(ch))name+=next();else break}else{if(ch!="u")parse_error("Expecting UnicodeEscapeSequence -- uXXXX");ch=read_escaped_char();if(!is_identifier_char(ch))parse_error("Unicode char: "+ch.charCodeAt(0)+" is not valid in identifier");name+=ch;backslash=false}}if(KEYWORDS[name]&&escaped){hex=name.charCodeAt(0).toString(16).toUpperCase();name="\\u"+"0000".substr(hex.length)+hex+name.slice(1)}return name}var read_regexp=with_eof_error("Unterminated regular expression",function(source){var prev_backslash=false,ch,in_class=false;while(ch=next(true))if(NEWLINE_CHARS[ch]){parse_error("Unexpected line terminator")}else if(prev_backslash){source+="\\"+ch;prev_backslash=false}else if(ch=="["){in_class=true;source+=ch}else if(ch=="]"&&in_class){in_class=false;source+=ch}else if(ch=="/"&&!in_class){break}else if(ch=="\\"){prev_backslash=true}else{source+=ch}var mods=read_name();try{var regexp=new RegExp(source,mods);regexp.raw_source=source;return token("regexp",regexp)}catch(e){parse_error(e.message)}});function read_operator(prefix){function grow(op){if(!peek())return op;var bigger=op+peek();if(OPERATORS[bigger]){next();return grow(bigger)}else{return op}}return token("operator",grow(prefix||next()))}function handle_slash(){next();switch(peek()){case"/":next();return skip_line_comment("comment1");case"*":next();return skip_multiline_comment()}return S.regex_allowed?read_regexp(""):read_operator("/")}function handle_dot(){next();return is_digit(peek().charCodeAt(0))?read_num("."):token("punc",".")}function read_word(){var word=read_name();if(prev_was_dot)return token("name",word);return KEYWORDS_ATOM[word]?token("atom",word):!KEYWORDS[word]?token("name",word):OPERATORS[word]?token("operator",word):token("keyword",word)}function with_eof_error(eof_error,cont){return function(x){try{return cont(x)}catch(ex){if(ex===EX_EOF)parse_error(eof_error);else throw ex}}}function next_token(force_regexp){if(force_regexp!=null)return read_regexp(force_regexp);if(shebang&&S.pos==0&&looking_at("#!")){start_token();forward(2);skip_line_comment("comment5")}for(;;){skip_whitespace();start_token();if(html5_comments){if(looking_at("\x3c!--")){forward(4);skip_line_comment("comment3");continue}if(looking_at("--\x3e")&&S.newline_before){forward(3);skip_line_comment("comment4");continue}}var ch=peek();if(!ch)return token("eof");var code=ch.charCodeAt(0);switch(code){case 34:case 39:return read_string(ch);case 46:return handle_dot();case 47:{var tok=handle_slash();if(tok===next_token)continue;return tok}}if(is_digit(code))return read_num();if(PUNC_CHARS[ch])return token("punc",next());if(OPERATOR_CHARS[ch])return read_operator();if(code==92||is_identifier_start(code))return read_word();break}parse_error("Unexpected character '"+ch+"'")}next_token.context=function(nc){if(nc)S=nc;return S};next_token.add_directive=function(directive){S.directive_stack[S.directive_stack.length-1].push(directive);if(S.directives[directive]===undefined){S.directives[directive]=1}else{S.directives[directive]++}};next_token.push_directives_stack=function(){S.directive_stack.push([])};next_token.pop_directives_stack=function(){var directives=S.directive_stack[S.directive_stack.length-1];for(var i=0;i<directives.length;i++){S.directives[directives[i]]--}S.directive_stack.pop()};next_token.has_directive=function(directive){return S.directives[directive]>0};return next_token}var UNARY_PREFIX=makePredicate(["typeof","void","delete","--","++","!","~","-","+"]);var UNARY_POSTFIX=makePredicate(["--","++"]);var ASSIGNMENT=makePredicate(["=","+=","-=","/=","*=","%=",">>=","<<=",">>>=","|=","^=","&="]);var PRECEDENCE=function(a,ret){for(var i=0;i<a.length;++i){var b=a[i];for(var j=0;j<b.length;++j){ret[b[j]]=i+1}}return ret}([["||"],["&&"],["|"],["^"],["&"],["==","===","!=","!=="],["<",">","<=",">=","in","instanceof"],[">>","<<",">>>"],["+","-"],["*","/","%"]],{});var ATOMIC_START_TOKEN=makePredicate(["atom","num","string","regexp","name"]);function parse($TEXT,options){options=defaults(options,{bare_returns:false,expression:false,filename:null,html5_comments:true,shebang:true,strict:false,toplevel:null},true);var S={input:typeof $TEXT=="string"?tokenizer($TEXT,options.filename,options.html5_comments,options.shebang):$TEXT,token:null,prev:null,peeked:null,in_function:0,in_directives:true,in_loop:0,labels:[]};S.token=next();function is(type,value){return is_token(S.token,type,value)}function peek(){return S.peeked||(S.peeked=S.input())}function next(){S.prev=S.token;if(S.peeked){S.token=S.peeked;S.peeked=null}else{S.token=S.input()}S.in_directives=S.in_directives&&(S.token.type=="string"||is("punc",";"));return S.token}function prev(){return S.prev}function croak(msg,line,col,pos){var ctx=S.input.context();js_error(msg,ctx.filename,line!=null?line:ctx.tokline,col!=null?col:ctx.tokcol,pos!=null?pos:ctx.tokpos)}function token_error(token,msg){croak(msg,token.line,token.col)}function unexpected(token){if(token==null)token=S.token;token_error(token,"Unexpected token: "+token.type+" ("+token.value+")")}function expect_token(type,val){if(is(type,val)){return next()}token_error(S.token,"Unexpected token "+S.token.type+" «"+S.token.value+"»"+", expected "+type+" «"+val+"»")}function expect(punc){return expect_token("punc",punc)}function has_newline_before(token){return token.nlb||!all(token.comments_before,function(comment){return!comment.nlb})}function can_insert_semicolon(){return!options.strict&&(is("eof")||is("punc","}")||has_newline_before(S.token))}function semicolon(optional){if(is("punc",";"))next();else if(!optional&&!can_insert_semicolon())unexpected()}function parenthesised(){expect("(");var exp=expression(true);expect(")");return exp}function embed_tokens(parser){return function(){var start=S.token;var expr=parser.apply(null,arguments);var end=prev();expr.start=start;expr.end=end;return expr}}function handle_regexp(){if(is("operator","/")||is("operator","/=")){S.peeked=null;S.token=S.input(S.token.value.substr(1))}}var statement=embed_tokens(function(strict_defun){handle_regexp();switch(S.token.type){case"string":if(S.in_directives){var token=peek();if(S.token.raw.indexOf("\\")==-1&&(is_token(token,"punc",";")||is_token(token,"punc","}")||has_newline_before(token)||is_token(token,"eof"))){S.input.add_directive(S.token.value)}else{S.in_directives=false}}var dir=S.in_directives,stat=simple_statement();return dir?new AST_Directive(stat.body):stat;case"num":case"regexp":case"operator":case"atom":return simple_statement();case"name":return is_token(peek(),"punc",":")?labeled_statement():simple_statement();case"punc":switch(S.token.value){case"{":return new AST_BlockStatement({start:S.token,body:block_(),end:prev()});case"[":case"(":return simple_statement();case";":S.in_directives=false;next();return new AST_EmptyStatement;default:unexpected()}case"keyword":switch(S.token.value){case"break":next();return break_cont(AST_Break);case"continue":next();return break_cont(AST_Continue);case"debugger":next();semicolon();return new AST_Debugger;case"do":next();var body=in_loop(statement);expect_token("keyword","while");var condition=parenthesised();semicolon(true);return new AST_Do({body:body,condition:condition});case"while":next();return new AST_While({condition:parenthesised(),body:in_loop(statement)});case"for":next();return for_();case"function":if(!strict_defun&&S.input.has_directive("use strict")){croak("In strict mode code, functions can only be declared at top level or immediately within another function.")}next();return function_(AST_Defun);case"if":next();return if_();case"return":if(S.in_function==0&&!options.bare_returns)croak("'return' outside of function");next();var value=null;if(is("punc",";")){next()}else if(!can_insert_semicolon()){value=expression(true);semicolon()}return new AST_Return({value:value});case"switch":next();return new AST_Switch({expression:parenthesised(),body:in_loop(switch_body_)});case"throw":next();if(has_newline_before(S.token))croak("Illegal newline after 'throw'");var value=expression(true);semicolon();return new AST_Throw({value:value});case"try":next();return try_();case"var":next();var node=var_();semicolon();return node;case"with":if(S.input.has_directive("use strict")){croak("Strict mode may not include a with statement")}next();return new AST_With({expression:parenthesised(),body:statement()})}}unexpected()});function labeled_statement(){var label=as_symbol(AST_Label);if(!all(S.labels,function(l){return l.name!=label.name})){croak("Label "+label.name+" defined twice")}expect(":");S.labels.push(label);var stat=statement();S.labels.pop();if(!(stat instanceof AST_IterationStatement)){label.references.forEach(function(ref){if(ref instanceof AST_Continue){ref=ref.label.start;croak("Continue label `"+label.name+"` refers to non-IterationStatement.",ref.line,ref.col,ref.pos)}})}return new AST_LabeledStatement({body:stat,label:label})}function simple_statement(tmp){return new AST_SimpleStatement({body:(tmp=expression(true),semicolon(),tmp)})}function break_cont(type){var label=null,ldef;if(!can_insert_semicolon()){label=as_symbol(AST_LabelRef,true)}if(label!=null){ldef=find_if(function(l){return l.name==label.name},S.labels);if(!ldef)croak("Undefined label "+label.name);label.thedef=ldef}else if(S.in_loop==0)croak(type.TYPE+" not inside a loop or switch");semicolon();var stat=new type({label:label});if(ldef)ldef.references.push(stat);return stat}function for_(){expect("(");var init=null;if(!is("punc",";")){init=is("keyword","var")?(next(),var_(true)):expression(true,true);if(is("operator","in")){if(init instanceof AST_Var){if(init.definitions.length>1)croak("Only one variable declaration allowed in for..in loop",init.start.line,init.start.col,init.start.pos)}else if(!is_assignable(init)){croak("Invalid left-hand side in for..in loop",init.start.line,init.start.col,init.start.pos)}next();return for_in(init)}}return regular_for(init)}function regular_for(init){expect(";");var test=is("punc",";")?null:expression(true);expect(";");var step=is("punc",")")?null:expression(true);expect(")");return new AST_For({init:init,condition:test,step:step,body:in_loop(statement)})}function for_in(init){var obj=expression(true);expect(")");return new AST_ForIn({init:init,object:obj,body:in_loop(statement)})}var function_=function(ctor){var in_statement=ctor===AST_Defun;var name=is("name")?as_symbol(in_statement?AST_SymbolDefun:AST_SymbolLambda):null;if(in_statement&&!name)unexpected();if(name&&ctor!==AST_Accessor&&!(name instanceof AST_SymbolDeclaration))unexpected(prev());expect("(");var argnames=[];for(var first=true;!is("punc",")");){if(first)first=false;else expect(",");argnames.push(as_symbol(AST_SymbolFunarg))}next();var loop=S.in_loop;var labels=S.labels;++S.in_function;S.in_directives=true;S.input.push_directives_stack();S.in_loop=0;S.labels=[];var body=block_(true);if(S.input.has_directive("use strict")){if(name)strict_verify_symbol(name);argnames.forEach(strict_verify_symbol)}S.input.pop_directives_stack();--S.in_function;S.in_loop=loop;S.labels=labels;return new ctor({name:name,argnames:argnames,body:body})};function if_(){var cond=parenthesised(),body=statement(),belse=null;if(is("keyword","else")){next();belse=statement()}return new AST_If({condition:cond,body:body,alternative:belse})}function block_(strict_defun){expect("{");var a=[];while(!is("punc","}")){if(is("eof"))unexpected();a.push(statement(strict_defun))}next();return a}function switch_body_(){expect("{");var a=[],cur=null,branch=null,tmp;while(!is("punc","}")){if(is("eof"))unexpected();if(is("keyword","case")){if(branch)branch.end=prev();cur=[];branch=new AST_Case({start:(tmp=S.token,next(),tmp),expression:expression(true),body:cur});a.push(branch);expect(":")}else if(is("keyword","default")){if(branch)branch.end=prev();cur=[];branch=new AST_Default({start:(tmp=S.token,next(),expect(":"),tmp),body:cur});a.push(branch)}else{if(!cur)unexpected();cur.push(statement())}}if(branch)branch.end=prev();next();return a}function try_(){var body=block_(),bcatch=null,bfinally=null;if(is("keyword","catch")){var start=S.token;next();expect("(");var name=as_symbol(AST_SymbolCatch);expect(")");bcatch=new AST_Catch({start:start,argname:name,body:block_(),end:prev()})}if(is("keyword","finally")){var start=S.token;next();bfinally=new AST_Finally({start:start,body:block_(),end:prev()})}if(!bcatch&&!bfinally)croak("Missing catch/finally blocks");return new AST_Try({body:body,bcatch:bcatch,bfinally:bfinally})}function vardefs(no_in){var a=[];for(;;){a.push(new AST_VarDef({start:S.token,name:as_symbol(AST_SymbolVar),value:is("operator","=")?(next(),expression(false,no_in)):null,end:prev()}));if(!is("punc",","))break;next()}return a}var var_=function(no_in){return new AST_Var({start:prev(),definitions:vardefs(no_in),end:prev()})};var new_=function(allow_calls){var start=S.token;expect_token("operator","new");var newexp=expr_atom(false),args;if(is("punc","(")){next();args=expr_list(")")}else{args=[]}var call=new AST_New({start:start,expression:newexp,args:args,end:prev()});mark_pure(call);return subscripts(call,allow_calls)};function as_atom_node(){var tok=S.token,ret;switch(tok.type){case"name":ret=_make_symbol(AST_SymbolRef);break;case"num":ret=new AST_Number({start:tok,end:tok,value:tok.value});break;case"string":ret=new AST_String({start:tok,end:tok,value:tok.value,quote:tok.quote});break;case"regexp":ret=new AST_RegExp({start:tok,end:tok,value:tok.value});break;case"atom":switch(tok.value){case"false":ret=new AST_False({start:tok,end:tok});break;case"true":ret=new AST_True({start:tok,end:tok});break;case"null":ret=new AST_Null({start:tok,end:tok});break}break}next();return ret}var expr_atom=function(allow_calls){if(is("operator","new")){return new_(allow_calls)}var start=S.token;if(is("punc")){switch(start.value){case"(":next();var ex=expression(true);var len=start.comments_before.length;[].unshift.apply(ex.start.comments_before,start.comments_before);start.comments_before=ex.start.comments_before;start.comments_before_length=len;if(len==0&&start.comments_before.length>0){var comment=start.comments_before[0];if(!comment.nlb){comment.nlb=start.nlb;start.nlb=false}}start.comments_after=ex.start.comments_after;ex.start=start;expect(")");var end=prev();end.comments_before=ex.end.comments_before;[].push.apply(ex.end.comments_after,end.comments_after);end.comments_after=ex.end.comments_after;ex.end=end;if(ex instanceof AST_Call)mark_pure(ex);return subscripts(ex,allow_calls);case"[":return subscripts(array_(),allow_calls);case"{":return subscripts(object_(),allow_calls)}unexpected()}if(is("keyword","function")){next();var func=function_(AST_Function);func.start=start;func.end=prev();return subscripts(func,allow_calls)}if(ATOMIC_START_TOKEN[S.token.type]){return subscripts(as_atom_node(),allow_calls)}unexpected()};function expr_list(closing,allow_trailing_comma,allow_empty){var first=true,a=[];while(!is("punc",closing)){if(first)first=false;else expect(",");if(allow_trailing_comma&&is("punc",closing))break;if(is("punc",",")&&allow_empty){a.push(new AST_Hole({start:S.token,end:S.token}))}else{a.push(expression(false))}}next();return a}var array_=embed_tokens(function(){expect("[");return new AST_Array({elements:expr_list("]",!options.strict,true)})});var create_accessor=embed_tokens(function(){return function_(AST_Accessor)});var object_=embed_tokens(function(){expect("{");var first=true,a=[];while(!is("punc","}")){if(first)first=false;else expect(",");if(!options.strict&&is("punc","}"))break;var start=S.token;var type=start.type;var name=as_property_name();if(type=="name"&&!is("punc",":")){var key=new AST_SymbolAccessor({start:S.token,name:""+as_property_name(),end:prev()});if(name=="get"){a.push(new AST_ObjectGetter({start:start,key:key,value:create_accessor(),end:prev()}));continue}if(name=="set"){a.push(new AST_ObjectSetter({start:start,key:key,value:create_accessor(),end:prev()}));continue}}expect(":");a.push(new AST_ObjectKeyVal({start:start,quote:start.quote,key:""+name,value:expression(false),end:prev()}))}next();return new AST_Object({properties:a})});function as_property_name(){var tmp=S.token;switch(tmp.type){case"operator":if(!KEYWORDS[tmp.value])unexpected();case"num":case"string":case"name":case"keyword":case"atom":next();return tmp.value;default:unexpected()}}function as_name(){var tmp=S.token;if(tmp.type!="name")unexpected();next();return tmp.value}function _make_symbol(type){var name=S.token.value;return new(name=="this"?AST_This:type)({name:String(name),start:S.token,end:S.token})}function strict_verify_symbol(sym){if(sym.name=="arguments"||sym.name=="eval")croak("Unexpected "+sym.name+" in strict mode",sym.start.line,sym.start.col,sym.start.pos)}function as_symbol(type,noerror){if(!is("name")){if(!noerror)croak("Name expected");return null}var sym=_make_symbol(type);if(S.input.has_directive("use strict")&&sym instanceof AST_SymbolDeclaration){strict_verify_symbol(sym)}next();return sym}function mark_pure(call){var start=call.start;var comments=start.comments_before;var i=HOP(start,"comments_before_length")?start.comments_before_length:comments.length;while(--i>=0){var comment=comments[i];if(/[@#]__PURE__/.test(comment.value)){call.pure=comment;break}}}var subscripts=function(expr,allow_calls){var start=expr.start;if(is("punc",".")){next();return subscripts(new AST_Dot({start:start,expression:expr,property:as_name(),end:prev()}),allow_calls)}if(is("punc","[")){next();var prop=expression(true);expect("]");return subscripts(new AST_Sub({start:start,expression:expr,property:prop,end:prev()}),allow_calls)}if(allow_calls&&is("punc","(")){next();var call=new AST_Call({start:start,expression:expr,args:expr_list(")"),end:prev()});mark_pure(call);return subscripts(call,true)}return expr};var maybe_unary=function(allow_calls){var start=S.token;if(is("operator")&&UNARY_PREFIX[start.value]){next();handle_regexp();var ex=make_unary(AST_UnaryPrefix,start,maybe_unary(allow_calls));ex.start=start;ex.end=prev();return ex}var val=expr_atom(allow_calls);while(is("operator")&&UNARY_POSTFIX[S.token.value]&&!has_newline_before(S.token)){val=make_unary(AST_UnaryPostfix,S.token,val);val.start=start;val.end=S.token;next()}return val};function make_unary(ctor,token,expr){var op=token.value;switch(op){case"++":case"--":if(!is_assignable(expr))croak("Invalid use of "+op+" operator",token.line,token.col,token.pos);break;case"delete":if(expr instanceof AST_SymbolRef&&S.input.has_directive("use strict"))croak("Calling delete on expression not allowed in strict mode",expr.start.line,expr.start.col,expr.start.pos);break}return new ctor({operator:op,expression:expr})}var expr_op=function(left,min_prec,no_in){var op=is("operator")?S.token.value:null;if(op=="in"&&no_in)op=null;var prec=op!=null?PRECEDENCE[op]:null;if(prec!=null&&prec>min_prec){next();var right=expr_op(maybe_unary(true),prec,no_in);return expr_op(new AST_Binary({start:left.start,left:left,operator:op,right:right,end:right.end}),min_prec,no_in)}return left};function expr_ops(no_in){return expr_op(maybe_unary(true),0,no_in)}var maybe_conditional=function(no_in){var start=S.token;var expr=expr_ops(no_in);if(is("operator","?")){next();var yes=expression(false);expect(":");return new AST_Conditional({start:start,condition:expr,consequent:yes,alternative:expression(false,no_in),end:prev()})}return expr};function is_assignable(expr){return expr instanceof AST_PropAccess||expr instanceof AST_SymbolRef}var maybe_assign=function(no_in){var start=S.token;var left=maybe_conditional(no_in),val=S.token.value;if(is("operator")&&ASSIGNMENT[val]){if(is_assignable(left)){next();return new AST_Assign({start:start,left:left,operator:val,right:maybe_assign(no_in),end:prev()})}croak("Invalid assignment")}return left};var expression=function(commas,no_in){var start=S.token;var exprs=[];while(true){exprs.push(maybe_assign(no_in));if(!commas||!is("punc",","))break;next();commas=true}return exprs.length==1?exprs[0]:new AST_Sequence({start:start,expressions:exprs,end:peek()})};function in_loop(cont){++S.in_loop;var ret=cont();--S.in_loop;return ret}if(options.expression){return expression(true)}return function(){var start=S.token;var body=[];S.input.push_directives_stack();while(!is("eof"))body.push(statement(true));S.input.pop_directives_stack();var end=prev();var toplevel=options.toplevel;if(toplevel){toplevel.body=toplevel.body.concat(body);toplevel.end=end}else{toplevel=new AST_Toplevel({start:start,body:body,end:end})}return toplevel}()}"use strict";function TreeTransformer(before,after){TreeWalker.call(this);this.before=before;this.after=after}TreeTransformer.prototype=new TreeWalker;(function(DEF){function do_list(list,tw){return MAP(list,function(node){return node.transform(tw,true)})}DEF(AST_Node,noop);DEF(AST_LabeledStatement,function(self,tw){self.label=self.label.transform(tw);self.body=self.body.transform(tw)});DEF(AST_SimpleStatement,function(self,tw){self.body=self.body.transform(tw)});DEF(AST_Block,function(self,tw){self.body=do_list(self.body,tw)});DEF(AST_Do,function(self,tw){self.body=self.body.transform(tw);self.condition=self.condition.transform(tw)});DEF(AST_While,function(self,tw){self.condition=self.condition.transform(tw);self.body=self.body.transform(tw)});DEF(AST_For,function(self,tw){if(self.init)self.init=self.init.transform(tw);if(self.condition)self.condition=self.condition.transform(tw);if(self.step)self.step=self.step.transform(tw);self.body=self.body.transform(tw)});DEF(AST_ForIn,function(self,tw){self.init=self.init.transform(tw);self.object=self.object.transform(tw);self.body=self.body.transform(tw)});DEF(AST_With,function(self,tw){self.expression=self.expression.transform(tw);self.body=self.body.transform(tw)});DEF(AST_Exit,function(self,tw){if(self.value)self.value=self.value.transform(tw)});DEF(AST_LoopControl,function(self,tw){if(self.label)self.label=self.label.transform(tw)});DEF(AST_If,function(self,tw){self.condition=self.condition.transform(tw);self.body=self.body.transform(tw);if(self.alternative)self.alternative=self.alternative.transform(tw)});DEF(AST_Switch,function(self,tw){self.expression=self.expression.transform(tw);self.body=do_list(self.body,tw)});DEF(AST_Case,function(self,tw){self.expression=self.expression.transform(tw);self.body=do_list(self.body,tw)});DEF(AST_Try,function(self,tw){self.body=do_list(self.body,tw);if(self.bcatch)self.bcatch=self.bcatch.transform(tw);if(self.bfinally)self.bfinally=self.bfinally.transform(tw)});DEF(AST_Catch,function(self,tw){self.argname=self.argname.transform(tw);self.body=do_list(self.body,tw)});DEF(AST_Definitions,function(self,tw){self.definitions=do_list(self.definitions,tw)});DEF(AST_VarDef,function(self,tw){self.name=self.name.transform(tw);if(self.value)self.value=self.value.transform(tw)});DEF(AST_Lambda,function(self,tw){if(self.name)self.name=self.name.transform(tw);self.argnames=do_list(self.argnames,tw);self.body=do_list(self.body,tw)});DEF(AST_Call,function(self,tw){self.expression=self.expression.transform(tw);self.args=do_list(self.args,tw)});DEF(AST_Sequence,function(self,tw){self.expressions=do_list(self.expressions,tw)});DEF(AST_Dot,function(self,tw){self.expression=self.expression.transform(tw)});DEF(AST_Sub,function(self,tw){self.expression=self.expression.transform(tw);self.property=self.property.transform(tw)});DEF(AST_Unary,function(self,tw){self.expression=self.expression.transform(tw)});DEF(AST_Binary,function(self,tw){self.left=self.left.transform(tw);self.right=self.right.transform(tw)});DEF(AST_Conditional,function(self,tw){self.condition=self.condition.transform(tw);self.consequent=self.consequent.transform(tw);self.alternative=self.alternative.transform(tw)});DEF(AST_Array,function(self,tw){self.elements=do_list(self.elements,tw)});DEF(AST_Object,function(self,tw){self.properties=do_list(self.properties,tw)});DEF(AST_ObjectProperty,function(self,tw){self.value=self.value.transform(tw)})})(function(node,descend){node.DEFMETHOD("transform",function(tw,in_list){var x,y;tw.push(this);if(tw.before)x=tw.before(this,descend,in_list);if(typeof x==="undefined"){x=this;descend(x,tw);if(tw.after){y=tw.after(x,in_list);if(typeof y!=="undefined")x=y}}tw.pop();return x})});"use strict";function SymbolDef(scope,orig,init){this.name=orig.name;this.orig=[orig];this.init=init;this.eliminated=0;this.scope=scope;this.references=[];this.replaced=0;this.global=false;this.mangled_name=null;this.undeclared=false;this.id=SymbolDef.next_id++}SymbolDef.next_id=1;SymbolDef.prototype={unmangleable:function(options){if(!options)options={};return this.global&&!options.toplevel||this.undeclared||!options.eval&&this.scope.pinned()||options.keep_fnames&&(this.orig[0]instanceof AST_SymbolLambda||this.orig[0]instanceof AST_SymbolDefun)},mangle:function(options){var cache=options.cache&&options.cache.props;if(this.global&&cache&&cache.has(this.name)){this.mangled_name=cache.get(this.name)}else if(!this.mangled_name&&!this.unmangleable(options)){var def;if(def=this.redefined()){this.mangled_name=def.mangled_name||def.name}else{this.mangled_name=next_mangled_name(this.scope,options,this)}if(this.global&&cache){cache.set(this.name,this.mangled_name)}}},redefined:function(){return this.defun&&this.defun.variables.get(this.name)}};AST_Toplevel.DEFMETHOD("figure_out_scope",function(options){options=defaults(options,{cache:null,ie8:false});var self=this;var scope=self.parent_scope=null;var defun=null;var tw=new TreeWalker(function(node,descend){if(node instanceof AST_Catch){var save_scope=scope;scope=new AST_Scope(node);scope.init_scope_vars(save_scope);descend();scope=save_scope;return true}if(node instanceof AST_Scope){node.init_scope_vars(scope);var save_scope=scope;var save_defun=defun;defun=scope=node;descend();scope=save_scope;defun=save_defun;return true}if(node instanceof AST_With){for(var s=scope;s;s=s.parent_scope)s.uses_with=true;return}if(node instanceof AST_Symbol){node.scope=scope}if(node instanceof AST_Label){node.thedef=node;node.references=[]}if(node instanceof AST_SymbolDefun){(node.scope=defun.parent_scope.resolve()).def_function(node,defun)}else if(node instanceof AST_SymbolLambda){var def=defun.def_function(node,node.name=="arguments"?undefined:defun);if(options.ie8)def.defun=defun.parent_scope.resolve()}else if(node instanceof AST_SymbolVar){defun.def_variable(node,node.TYPE=="SymbolVar"?null:undefined);if(defun!==scope){node.mark_enclosed(options);var def=scope.find_variable(node);if(node.thedef!==def){node.thedef=def}node.reference(options)}}else if(node instanceof AST_SymbolCatch){scope.def_variable(node).defun=defun}});self.walk(tw);self.globals=new Dictionary;var tw=new TreeWalker(function(node){if(node instanceof AST_LoopControl){if(node.label)node.label.thedef.references.push(node);return true}if(node instanceof AST_SymbolRef){var name=node.name;if(name=="eval"&&tw.parent()instanceof AST_Call){for(var s=node.scope;s&&!s.uses_eval;s=s.parent_scope){s.uses_eval=true}}var sym=node.scope.find_variable(name);if(!sym){sym=self.def_global(node)}else if(sym.scope instanceof AST_Lambda&&name=="arguments"){sym.scope.uses_arguments=true}node.thedef=sym;node.reference(options);return true}if(node instanceof AST_SymbolCatch){var def=node.definition().redefined();if(def)for(var s=node.scope;s;s=s.parent_scope){push_uniq(s.enclosed,def);if(s===def.scope)break}return true}});self.walk(tw);if(options.ie8)self.walk(new TreeWalker(function(node){if(node instanceof AST_SymbolCatch){redefine(node,node.thedef.defun);return true}if(node instanceof AST_SymbolLambda){var def=node.thedef;if(def.orig.length==1){redefine(node,node.scope.parent_scope);node.thedef.init=def.init}return true}}));function redefine(node,scope){var name=node.name;var refs=node.thedef.references;var def=scope.find_variable(name)||self.globals.get(name)||scope.def_variable(node);refs.forEach(function(ref){ref.thedef=def;ref.reference(options)});node.thedef=def;node.reference(options)}});AST_Toplevel.DEFMETHOD("def_global",function(node){var globals=this.globals,name=node.name;if(globals.has(name)){return globals.get(name)}else{var g=new SymbolDef(this,node);g.undeclared=true;g.global=true;globals.set(name,g);return g}});AST_Scope.DEFMETHOD("init_scope_vars",function(parent_scope){this.variables=new Dictionary;this.functions=new Dictionary;this.uses_with=false;this.uses_eval=false;this.parent_scope=parent_scope;this.enclosed=[];this.cname=-1});AST_Lambda.DEFMETHOD("init_scope_vars",function(){AST_Scope.prototype.init_scope_vars.apply(this,arguments);this.uses_arguments=false;this.def_variable(new AST_SymbolFunarg({name:"arguments",start:this.start,end:this.end}))});AST_Symbol.DEFMETHOD("mark_enclosed",function(options){var def=this.definition();for(var s=this.scope;s;s=s.parent_scope){push_uniq(s.enclosed,def);if(options.keep_fnames){s.functions.each(function(d){push_uniq(def.scope.enclosed,d)})}if(s===def.scope)break}});AST_Symbol.DEFMETHOD("reference",function(options){this.definition().references.push(this);this.mark_enclosed(options)});AST_Scope.DEFMETHOD("find_variable",function(name){if(name instanceof AST_Symbol)name=name.name;return this.variables.get(name)||this.parent_scope&&this.parent_scope.find_variable(name)});AST_Scope.DEFMETHOD("def_function",function(symbol,init){var def=this.def_variable(symbol,init);if(!def.init||def.init instanceof AST_Defun)def.init=init;this.functions.set(symbol.name,def);return def});AST_Scope.DEFMETHOD("def_variable",function(symbol,init){var def=this.variables.get(symbol.name);if(def){def.orig.push(symbol);if(def.init&&(def.scope!==symbol.scope||def.init instanceof AST_Function)){def.init=init}}else{def=new SymbolDef(this,symbol,init);this.variables.set(symbol.name,def);def.global=!this.parent_scope}return symbol.thedef=def});AST_Lambda.DEFMETHOD("resolve",return_this);AST_Scope.DEFMETHOD("resolve",function(){return this.parent_scope});AST_Toplevel.DEFMETHOD("resolve",return_this);function names_in_use(scope,options){var names=scope.names_in_use;if(!names){scope.names_in_use=names=Object.create(scope.mangled_names||null);scope.cname_holes=[];scope.enclosed.forEach(function(def){if(def.unmangleable(options))names[def.name]=true})}return names}function next_mangled_name(scope,options,def){var in_use=names_in_use(scope,options);var holes=scope.cname_holes;var names=Object.create(null);var scopes=[scope];def.references.forEach(function(sym){var scope=sym.scope;do{if(scopes.indexOf(scope)<0){for(var name in names_in_use(scope,options)){names[name]=true}scopes.push(scope)}else break}while(scope=scope.parent_scope)});var name;for(var i=0,len=holes.length;i<len;i++){name=base54(holes[i]);if(names[name])continue;holes.splice(i,1);scope.names_in_use[name]=true;return name}while(true){name=base54(++scope.cname);if(in_use[name]||!is_identifier(name)||options.reserved.has[name])continue;if(!names[name])break;holes.push(scope.cname)}scope.names_in_use[name]=true;return name}AST_Symbol.DEFMETHOD("unmangleable",function(options){var def=this.definition();return!def||def.unmangleable(options)});AST_Label.DEFMETHOD("unmangleable",return_false);AST_Symbol.DEFMETHOD("unreferenced",function(){return!this.definition().references.length&&!this.scope.pinned()});AST_Symbol.DEFMETHOD("definition",function(){return this.thedef});AST_Symbol.DEFMETHOD("global",function(){return this.definition().global});function _default_mangler_options(options){options=defaults(options,{eval:false,ie8:false,keep_fnames:false,reserved:[],toplevel:false});if(!Array.isArray(options.reserved))options.reserved=[];push_uniq(options.reserved,"arguments");options.reserved.has=makePredicate(options.reserved);return options}AST_Toplevel.DEFMETHOD("mangle_names",function(options){options=_default_mangler_options(options);var lname=-1;if(options.cache&&options.cache.props){var mangled_names=this.mangled_names=Object.create(null);options.cache.props.each(function(mangled_name){mangled_names[mangled_name]=true})}var redefined=[];var tw=new TreeWalker(function(node,descend){if(node instanceof AST_LabeledStatement){var save_nesting=lname;descend();lname=save_nesting;return true}if(node instanceof AST_Scope){descend();if(options.cache&&node instanceof AST_Toplevel){node.globals.each(mangle)}node.variables.each(mangle);return true}if(node instanceof AST_Label){var name;do{name=base54(++lname)}while(!is_identifier(name));node.mangled_name=name;return true}if(!options.ie8&&node instanceof AST_Catch){var def=node.argname.definition();var redef=def.redefined();if(redef){redefined.push(def);reference(node.argname);def.references.forEach(reference)}descend();if(!redef)mangle(def);return true}function reference(sym){sym.thedef=redef;sym.reference(options);sym.thedef=def}});this.walk(tw);redefined.forEach(mangle);function mangle(def){if(options.reserved.has[def.name])return;def.mangle(options)}});AST_Toplevel.DEFMETHOD("find_colliding_names",function(options){var cache=options.cache&&options.cache.props;var avoid=Object.create(null);options.reserved.forEach(to_avoid);this.globals.each(add_def);this.walk(new TreeWalker(function(node){if(node instanceof AST_Scope)node.variables.each(add_def);if(node instanceof AST_SymbolCatch)add_def(node.definition())}));return avoid;function to_avoid(name){avoid[name]=true}function add_def(def){var name=def.name;if(def.global&&cache&&cache.has(name))name=cache.get(name);else if(!def.unmangleable(options))return;to_avoid(name)}});AST_Toplevel.DEFMETHOD("expand_names",function(options){base54.reset();base54.sort();options=_default_mangler_options(options);var avoid=this.find_colliding_names(options);var cname=0;this.globals.each(rename);this.walk(new TreeWalker(function(node){if(node instanceof AST_Scope)node.variables.each(rename);if(node instanceof AST_SymbolCatch)rename(node.definition())}));function next_name(){var name;do{name=base54(cname++)}while(avoid[name]||!is_identifier(name));return name}function rename(def){if(def.global&&options.cache)return;if(def.unmangleable(options))return;if(options.reserved.has[def.name])return;var d=def.redefined();def.name=d?d.name:next_name();def.orig.forEach(function(sym){sym.name=def.name});def.references.forEach(function(sym){sym.name=def.name})}});AST_Node.DEFMETHOD("tail_node",return_this);AST_Sequence.DEFMETHOD("tail_node",function(){return this.expressions[this.expressions.length-1]});AST_Toplevel.DEFMETHOD("compute_char_frequency",function(options){options=_default_mangler_options(options);base54.reset();try{AST_Node.prototype.print=function(stream,force_parens){this._print(stream,force_parens);if(this instanceof AST_Symbol&&!this.unmangleable(options)){base54.consider(this.name,-1)}else if(options.properties){if(this instanceof AST_Dot){base54.consider(this.property,-1)}else if(this instanceof AST_Sub){skip_string(this.property)}}};base54.consider(this.print_to_string(),1)}finally{AST_Node.prototype.print=AST_Node.prototype._print}base54.sort();function skip_string(node){if(node instanceof AST_String){base54.consider(node.value,-1)}else if(node instanceof AST_Conditional){skip_string(node.consequent);skip_string(node.alternative)}else if(node instanceof AST_Sequence){skip_string(node.tail_node())}}});var base54=function(){var freq=Object.create(null);function init(chars){var array=[];for(var i=0,len=chars.length;i<len;i++){var ch=chars[i];array.push(ch);freq[ch]=-.01*i}return array}var digits=init("0123456789");var leading=init("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_");var chars,frequency;function reset(){frequency=Object.create(freq)}base54.consider=function(str,delta){for(var i=str.length;--i>=0;){frequency[str[i]]+=delta}};function compare(a,b){return frequency[b]-frequency[a]}base54.sort=function(){chars=leading.sort(compare).concat(digits.sort(compare))};base54.reset=reset;reset();function base54(num){var ret="",base=54;num++;do{num--;ret+=chars[num%base];num=Math.floor(num/base);base=64}while(num>0);return ret}return base54}();"use strict";var EXPECT_DIRECTIVE=/^$|[;{][\s\n]*$/;function is_some_comments(comment){return comment.type=="comment2"&&/@preserve|@license|@cc_on/i.test(comment.value)}function OutputStream(options){var readonly=!options;options=defaults(options,{ascii_only:false,beautify:false,braces:false,comments:false,ie8:false,indent_level:4,indent_start:0,inline_script:true,keep_quoted_props:false,max_line_len:false,preamble:null,preserve_line:false,quote_keys:false,quote_style:0,semicolons:true,shebang:true,source_map:null,webkit:false,width:80,wrap_iife:false},true);var comment_filter=return_false;if(options.comments){var comments=options.comments;if(typeof options.comments==="string"&&/^\/.*\/[a-zA-Z]*$/.test(options.comments)){var regex_pos=options.comments.lastIndexOf("/");comments=new RegExp(options.comments.substr(1,regex_pos-1),options.comments.substr(regex_pos+1))}if(comments instanceof RegExp){comment_filter=function(comment){return comment.type!="comment5"&&comments.test(comment.value)}}else if(typeof comments==="function"){comment_filter=function(comment){return comment.type!="comment5"&&comments(this,comment)}}else if(comments==="some"){comment_filter=is_some_comments}else{comment_filter=return_true}}var indentation=0;var current_col=0;var current_line=1;var current_pos=0;var OUTPUT="";var to_utf8=options.ascii_only?function(str,identifier){return str.replace(/[\u0000-\u001f\u007f-\uffff]/g,function(ch){var code=ch.charCodeAt(0).toString(16);if(code.length<=2&&!identifier){while(code.length<2)code="0"+code;return"\\x"+code}else{while(code.length<4)code="0"+code;return"\\u"+code}})}:function(str){var s="";for(var i=0,len=str.length;i<len;i++){if(is_surrogate_pair_head(str[i])&&!is_surrogate_pair_tail(str[i+1])||is_surrogate_pair_tail(str[i])&&!is_surrogate_pair_head(str[i-1])){s+="\\u"+str.charCodeAt(i).toString(16)}else{s+=str[i]}}return s};function make_string(str,quote){var dq=0,sq=0;str=str.replace(/[\\\b\f\n\r\v\t\x22\x27\u2028\u2029\0\ufeff]/g,function(s,i){switch(s){case'"':++dq;return'"';case"'":++sq;return"'";case"\\":return"\\\\";case"\n":return"\\n";case"\r":return"\\r";case"\t":return"\\t";case"\b":return"\\b";case"\f":return"\\f";case"\v":return options.ie8?"\\x0B":"\\v";case"\u2028":return"\\u2028";case"\u2029":return"\\u2029";case"\ufeff":return"\\ufeff";case"\0":return/[0-9]/.test(str.charAt(i+1))?"\\x00":"\\0"}return s});function quote_single(){return"'"+str.replace(/\x27/g,"\\'")+"'"}function quote_double(){return'"'+str.replace(/\x22/g,'\\"')+'"'}str=to_utf8(str);switch(options.quote_style){case 1:return quote_single();case 2:return quote_double();case 3:return quote=="'"?quote_single():quote_double();default:return dq>sq?quote_single():quote_double()}}function encode_string(str,quote){var ret=make_string(str,quote);if(options.inline_script){ret=ret.replace(/<\x2f(script)([>\/\t\n\f\r ])/gi,"<\\/$1$2");ret=ret.replace(/\x3c!--/g,"\\x3c!--");ret=ret.replace(/--\x3e/g,"--\\x3e")}return ret}function make_name(name){name=name.toString();name=to_utf8(name,true);return name}function make_indent(back){return repeat_string(" ",options.indent_start+indentation-back*options.indent_level)}var has_parens=false;var line_end=0;var line_fixed=true;var might_need_space=false;var might_need_semicolon=false;var need_newline_indented=false;var need_space=false;var newline_insert=-1;var last="";var mapping_token,mapping_name,mappings=options.source_map&&[];var adjust_mappings=mappings?function(line,col){mappings.forEach(function(mapping){mapping.line+=line;mapping.col+=col})}:noop;var flush_mappings=mappings?function(){mappings.forEach(function(mapping){try{options.source_map.add(mapping.token.file,mapping.line,mapping.col,mapping.token.line,mapping.token.col,!mapping.name&&mapping.token.type=="name"?mapping.token.value:mapping.name)}catch(ex){AST_Node.warn("Couldn't figure out mapping for {file}:{line},{col} → {cline},{ccol} [{name}]",{file:mapping.token.file,line:mapping.token.line,col:mapping.token.col,cline:mapping.line,ccol:mapping.col,name:mapping.name||""})}});mappings=[]}:noop;function insert_newlines(count){var index=OUTPUT.lastIndexOf("\n");if(line_end<index)line_end=index;var left=OUTPUT.slice(0,line_end);var right=OUTPUT.slice(line_end);adjust_mappings(count,right.length-current_col);current_line+=count;current_pos+=count;current_col=right.length;OUTPUT=left;while(count--)OUTPUT+="\n";OUTPUT+=right}var fix_line=options.max_line_len?function(){if(line_fixed){if(current_col>options.max_line_len){AST_Node.warn("Output exceeds {max_line_len} characters",options)}return}if(current_col>options.max_line_len)insert_newlines(1);line_fixed=true;flush_mappings()}:noop;var requireSemicolonChars=makePredicate("( [ + * / - , .");function print(str){str=String(str);var ch=str.charAt(0);if(need_newline_indented&&ch){need_newline_indented=false;if(ch!="\n"){print("\n");indent()}}if(need_space&&ch){need_space=false;if(!/[\s;})]/.test(ch)){space()}}newline_insert=-1;var prev=last.charAt(last.length-1);if(might_need_semicolon){might_need_semicolon=false;if(prev==":"&&ch=="}"||(!ch||";}".indexOf(ch)<0)&&prev!=";"){if(options.semicolons||requireSemicolonChars[ch]){OUTPUT+=";";current_col++;current_pos++}else{fix_line();OUTPUT+="\n";current_pos++;current_line++;current_col=0;if(/^\s+$/.test(str)){might_need_semicolon=true}}if(!options.beautify)might_need_space=false}}if(might_need_space){if(is_identifier_char(prev)&&(is_identifier_char(ch)||ch=="\\")||ch=="/"&&ch==prev||(ch=="+"||ch=="-")&&ch==last){OUTPUT+=" ";current_col++;current_pos++}might_need_space=false}if(mapping_token){mappings.push({token:mapping_token,name:mapping_name,line:current_line,col:current_col});mapping_token=false;if(line_fixed)flush_mappings()}OUTPUT+=str;has_parens=str[str.length-1]=="(";current_pos+=str.length;var a=str.split(/\r?\n/),n=a.length-1;current_line+=n;current_col+=a[0].length;if(n>0){fix_line();current_col=a[n].length}last=str}var space=options.beautify?function(){print(" ")}:function(){might_need_space=true};var indent=options.beautify?function(half){if(options.beautify){print(make_indent(half?.5:0))}}:noop;var with_indent=options.beautify?function(col,cont){if(col===true)col=next_indent();var save_indentation=indentation;indentation=col;var ret=cont();indentation=save_indentation;return ret}:function(col,cont){return cont()};var may_add_newline=options.max_line_len||options.preserve_line?function(){fix_line();line_end=OUTPUT.length;line_fixed=false}:noop;var newline=options.beautify?function(){if(newline_insert<0)return print("\n");if(OUTPUT[newline_insert]!="\n"){OUTPUT=OUTPUT.slice(0,newline_insert)+"\n"+OUTPUT.slice(newline_insert);current_pos++;current_line++}newline_insert++}:may_add_newline;var semicolon=options.beautify?function(){print(";")}:function(){might_need_semicolon=true};function force_semicolon(){might_need_semicolon=false;print(";")}function next_indent(){return indentation+options.indent_level}function with_block(cont){var ret;print("{");newline();with_indent(next_indent(),function(){ret=cont()});indent();print("}");return ret}function with_parens(cont){print("(");may_add_newline();var ret=cont();may_add_newline();print(")");return ret}function with_square(cont){print("[");may_add_newline();var ret=cont();may_add_newline();print("]");return ret}function comma(){may_add_newline();print(",");may_add_newline();space()}function colon(){print(":");space()}var add_mapping=mappings?function(token,name){mapping_token=token;mapping_name=name}:noop;function get(){if(!line_fixed)fix_line();return OUTPUT}function has_nlb(){var index=OUTPUT.lastIndexOf("\n");return/^ *$/.test(OUTPUT.slice(index+1))}function prepend_comments(node){var self=this;var start=node.start;if(!start)return;if(start.comments_before&&start.comments_before._dumped===self)return;var comments=start.comments_before;if(!comments){comments=start.comments_before=[]}comments._dumped=self;if(node instanceof AST_Exit&&node.value){var tw=new TreeWalker(function(node){var parent=tw.parent();if(parent instanceof AST_Exit||parent instanceof AST_Binary&&parent.left===node||parent.TYPE=="Call"&&parent.expression===node||parent instanceof AST_Conditional&&parent.condition===node||parent instanceof AST_Dot&&parent.expression===node||parent instanceof AST_Sequence&&parent.expressions[0]===node||parent instanceof AST_Sub&&parent.expression===node||parent instanceof AST_UnaryPostfix){var text=node.start.comments_before;if(text&&text._dumped!==self){text._dumped=self;comments=comments.concat(text)}}else{return true}});tw.push(node);node.value.walk(tw)}if(current_pos==0){if(comments.length>0&&options.shebang&&comments[0].type=="comment5"){print("#!"+comments.shift().value+"\n");indent()}var preamble=options.preamble;if(preamble){print(preamble.replace(/\r\n?|[\n\u2028\u2029]|\s*$/g,"\n"))}}comments=comments.filter(comment_filter,node);if(comments.length==0)return;var last_nlb=has_nlb();comments.forEach(function(c,i){if(!last_nlb){if(c.nlb){print("\n");indent();last_nlb=true}else if(i>0){space()}}if(/comment[134]/.test(c.type)){print("//"+c.value.replace(/[@#]__PURE__/g," ")+"\n");indent();last_nlb=true}else if(c.type=="comment2"){print("/*"+c.value.replace(/[@#]__PURE__/g," ")+"*/");last_nlb=false}});if(!last_nlb){if(start.nlb){print("\n");indent()}else{space()}}}function append_comments(node,tail){var self=this;var token=node.end;if(!token)return;var comments=token[tail?"comments_before":"comments_after"];if(!comments||comments._dumped===self)return;if(!(node instanceof AST_Statement||all(comments,function(c){return!/comment[134]/.test(c.type)})))return;comments._dumped=self;var insert=OUTPUT.length;comments.filter(comment_filter,node).forEach(function(c,i){need_space=false;if(need_newline_indented){print("\n");indent();need_newline_indented=false}else if(c.nlb&&(i>0||!has_nlb())){print("\n");indent()}else if(i>0||!tail){space()}if(/comment[134]/.test(c.type)){print("//"+c.value.replace(/[@#]__PURE__/g," "));need_newline_indented=true}else if(c.type=="comment2"){print("/*"+c.value.replace(/[@#]__PURE__/g," ")+"*/");need_space=true}});if(OUTPUT.length>insert)newline_insert=insert}var stack=[];return{get:get,toString:get,indent:indent,indentation:function(){return indentation},current_width:function(){return current_col-indentation},should_break:function(){return options.width&&this.current_width()>=options.width},has_parens:function(){return has_parens},newline:newline,print:print,space:space,comma:comma,colon:colon,last:function(){return last},semicolon:semicolon,force_semicolon:force_semicolon,to_utf8:to_utf8,print_name:function(name){print(make_name(name))},print_string:function(str,quote,escape_directive){var encoded=encode_string(str,quote);if(escape_directive===true&&encoded.indexOf("\\")===-1){if(!EXPECT_DIRECTIVE.test(OUTPUT)){force_semicolon()}force_semicolon()}print(encoded)},encode_string:encode_string,next_indent:next_indent,with_indent:with_indent,with_block:with_block,with_parens:with_parens,with_square:with_square,add_mapping:add_mapping,option:function(opt){return options[opt]},prepend_comments:readonly?noop:prepend_comments,append_comments:readonly||comment_filter===return_false?noop:append_comments,line:function(){return current_line},col:function(){return current_col},pos:function(){return current_pos},push_node:function(node){stack.push(node)},pop_node:options.preserve_line?function(){var node=stack.pop();if(node.start&&node.start.line>current_line){insert_newlines(node.start.line-current_line)}}:function(){stack.pop()},parent:function(n){return stack[stack.length-2-(n||0)]}}}(function(){function DEFPRINT(nodetype,generator){nodetype.DEFMETHOD("_codegen",generator)}var in_directive=false;var active_scope=null;var use_asm=null;AST_Node.DEFMETHOD("print",function(stream,force_parens){var self=this,generator=self._codegen;if(self instanceof AST_Scope){active_scope=self}else if(!use_asm&&self instanceof AST_Directive&&self.value=="use asm"){use_asm=active_scope}function doit(){stream.prepend_comments(self);self.add_source_map(stream);generator(self,stream);stream.append_comments(self)}stream.push_node(self);if(force_parens||self.needs_parens(stream)){stream.with_parens(doit)}else{doit()}stream.pop_node();if(self===use_asm){use_asm=null}});AST_Node.DEFMETHOD("_print",AST_Node.prototype.print);AST_Node.DEFMETHOD("print_to_string",function(options){var s=OutputStream(options);this.print(s);return s.get()});function PARENS(nodetype,func){if(Array.isArray(nodetype)){nodetype.forEach(function(nodetype){PARENS(nodetype,func)})}else{nodetype.DEFMETHOD("needs_parens",func)}}PARENS(AST_Node,return_false);PARENS(AST_Function,function(output){if(!output.has_parens()&&first_in_statement(output))return true;if(output.option("webkit")){var p=output.parent();if(p instanceof AST_PropAccess&&p.expression===this)return true}if(output.option("wrap_iife")){var p=output.parent();if(p instanceof AST_Call&&p.expression===this)return true}});PARENS(AST_Object,function(output){return!output.has_parens()&&first_in_statement(output)});PARENS(AST_Unary,function(output){var p=output.parent();return p instanceof AST_PropAccess&&p.expression===this||p instanceof AST_Call&&p.expression===this});PARENS(AST_Sequence,function(output){var p=output.parent();return p instanceof AST_Call||p instanceof AST_Unary||p instanceof AST_Binary||p instanceof AST_VarDef||p instanceof AST_PropAccess||p instanceof AST_Array||p instanceof AST_ObjectProperty||p instanceof AST_Conditional});PARENS(AST_Binary,function(output){var p=output.parent();if(p instanceof AST_Call&&p.expression===this)return true;if(p instanceof AST_Unary)return true;if(p instanceof AST_PropAccess&&p.expression===this)return true;if(p instanceof AST_Binary){var po=p.operator,pp=PRECEDENCE[po];var so=this.operator,sp=PRECEDENCE[so];if(pp>sp||pp==sp&&this===p.right){return true}}});PARENS(AST_PropAccess,function(output){var p=output.parent();if(p instanceof AST_New&&p.expression===this){var parens=false;this.walk(new TreeWalker(function(node){if(parens||node instanceof AST_Scope)return true;if(node instanceof AST_Call){parens=true;return true}}));return parens}});PARENS(AST_Call,function(output){var p=output.parent();if(p instanceof AST_New&&p.expression===this)return true;if(output.option("webkit")){var g=output.parent(1);return this.expression instanceof AST_Function&&p instanceof AST_PropAccess&&p.expression===this&&g instanceof AST_Assign&&g.left===p}});PARENS(AST_New,function(output){var p=output.parent();if(!need_constructor_parens(this,output)&&(p instanceof AST_PropAccess||p instanceof AST_Call&&p.expression===this))return true});PARENS(AST_Number,function(output){var p=output.parent();if(p instanceof AST_PropAccess&&p.expression===this){var value=this.getValue();if(value<0||/^0/.test(make_num(value))){return true}}});PARENS([AST_Assign,AST_Conditional],function(output){var p=output.parent();if(p instanceof AST_Unary)return true;if(p instanceof AST_Binary&&!(p instanceof AST_Assign))return true;if(p instanceof AST_Call&&p.expression===this)return true;if(p instanceof AST_Conditional&&p.condition===this)return true;if(p instanceof AST_PropAccess&&p.expression===this)return true});DEFPRINT(AST_Directive,function(self,output){output.print_string(self.value,self.quote);output.semicolon()});DEFPRINT(AST_Debugger,function(self,output){output.print("debugger");output.semicolon()});function display_body(body,is_toplevel,output,allow_directives){var last=body.length-1;in_directive=allow_directives;body.forEach(function(stmt,i){if(in_directive===true&&!(stmt instanceof AST_Directive||stmt instanceof AST_EmptyStatement||stmt instanceof AST_SimpleStatement&&stmt.body instanceof AST_String)){in_directive=false}if(!(stmt instanceof AST_EmptyStatement)){output.indent();stmt.print(output);if(!(i==last&&is_toplevel)){output.newline();if(is_toplevel)output.newline()}}if(in_directive===true&&stmt instanceof AST_SimpleStatement&&stmt.body instanceof AST_String){in_directive=false}});in_directive=false}AST_StatementWithBody.DEFMETHOD("_do_print_body",function(output){force_statement(this.body,output)});DEFPRINT(AST_Statement,function(self,output){self.body.print(output);output.semicolon()});DEFPRINT(AST_Toplevel,function(self,output){display_body(self.body,true,output,true);output.print("")});DEFPRINT(AST_LabeledStatement,function(self,output){self.label.print(output);output.colon();self.body.print(output)});DEFPRINT(AST_SimpleStatement,function(self,output){self.body.print(output);output.semicolon()});function print_braced_empty(self,output){output.print("{");output.with_indent(output.next_indent(),function(){output.append_comments(self,true)});output.print("}")}function print_braced(self,output,allow_directives){if(self.body.length>0){output.with_block(function(){display_body(self.body,false,output,allow_directives)})}else print_braced_empty(self,output)}DEFPRINT(AST_BlockStatement,function(self,output){print_braced(self,output)});DEFPRINT(AST_EmptyStatement,function(self,output){output.semicolon()});DEFPRINT(AST_Do,function(self,output){output.print("do");output.space();make_block(self.body,output);output.space();output.print("while");output.space();output.with_parens(function(){self.condition.print(output)});output.semicolon()});DEFPRINT(AST_While,function(self,output){output.print("while");output.space();output.with_parens(function(){self.condition.print(output)});output.space();self._do_print_body(output)});DEFPRINT(AST_For,function(self,output){output.print("for");output.space();output.with_parens(function(){if(self.init){if(self.init instanceof AST_Definitions){self.init.print(output)}else{parenthesize_for_noin(self.init,output,true)}output.print(";");output.space()}else{output.print(";")}if(self.condition){self.condition.print(output);output.print(";");output.space()}else{output.print(";")}if(self.step){self.step.print(output)}});output.space();self._do_print_body(output)});DEFPRINT(AST_ForIn,function(self,output){output.print("for");output.space();output.with_parens(function(){self.init.print(output);output.space();output.print("in");output.space();self.object.print(output)});output.space();self._do_print_body(output)});DEFPRINT(AST_With,function(self,output){output.print("with");output.space();output.with_parens(function(){self.expression.print(output)});output.space();self._do_print_body(output)});AST_Lambda.DEFMETHOD("_do_print",function(output,nokeyword){var self=this;if(!nokeyword){output.print("function")}if(self.name){output.space();self.name.print(output)}output.with_parens(function(){self.argnames.forEach(function(arg,i){if(i)output.comma();arg.print(output)})});output.space();print_braced(self,output,true)});DEFPRINT(AST_Lambda,function(self,output){self._do_print(output)});function print_jump(output,kind,target){output.print(kind);if(target){output.space();target.print(output)}output.semicolon()}DEFPRINT(AST_Return,function(self,output){print_jump(output,"return",self.value)});DEFPRINT(AST_Throw,function(self,output){print_jump(output,"throw",self.value)});DEFPRINT(AST_Break,function(self,output){print_jump(output,"break",self.label)});DEFPRINT(AST_Continue,function(self,output){print_jump(output,"continue",self.label)});function make_then(self,output){var b=self.body;if(output.option("braces")||output.option("ie8")&&b instanceof AST_Do)return make_block(b,output);if(!b)return output.force_semicolon();while(true){if(b instanceof AST_If){if(!b.alternative){make_block(self.body,output);return}b=b.alternative}else if(b instanceof AST_StatementWithBody){b=b.body}else break}force_statement(self.body,output)}DEFPRINT(AST_If,function(self,output){output.print("if");output.space();output.with_parens(function(){self.condition.print(output)});output.space();if(self.alternative){make_then(self,output);output.space();output.print("else");output.space();if(self.alternative instanceof AST_If)self.alternative.print(output);else force_statement(self.alternative,output)}else{self._do_print_body(output)}});DEFPRINT(AST_Switch,function(self,output){output.print("switch");output.space();output.with_parens(function(){self.expression.print(output)});output.space();var last=self.body.length-1;if(last<0)print_braced_empty(self,output);else output.with_block(function(){self.body.forEach(function(branch,i){output.indent(true);branch.print(output);if(i<last&&branch.body.length>0)output.newline()})})});AST_SwitchBranch.DEFMETHOD("_do_print_body",function(output){output.newline();this.body.forEach(function(stmt){output.indent();stmt.print(output);output.newline()})});DEFPRINT(AST_Default,function(self,output){output.print("default:");self._do_print_body(output)});DEFPRINT(AST_Case,function(self,output){output.print("case");output.space();self.expression.print(output);output.print(":");self._do_print_body(output)});DEFPRINT(AST_Try,function(self,output){output.print("try");output.space();print_braced(self,output);if(self.bcatch){output.space();self.bcatch.print(output)}if(self.bfinally){output.space();self.bfinally.print(output)}});DEFPRINT(AST_Catch,function(self,output){output.print("catch");output.space();output.with_parens(function(){self.argname.print(output)});output.space();print_braced(self,output)});DEFPRINT(AST_Finally,function(self,output){output.print("finally");output.space();print_braced(self,output)});DEFPRINT(AST_Var,function(self,output){output.print("var");output.space();self.definitions.forEach(function(def,i){if(i)output.comma();def.print(output)});var p=output.parent();if(p&&p.init!==self||!(p instanceof AST_For||p instanceof AST_ForIn))output.semicolon()});function parenthesize_for_noin(node,output,noin){var parens=false;if(noin)node.walk(new TreeWalker(function(node){if(parens||node instanceof AST_Scope)return true;if(node instanceof AST_Binary&&node.operator=="in"){parens=true;return true}}));node.print(output,parens)}DEFPRINT(AST_VarDef,function(self,output){self.name.print(output);if(self.value){output.space();output.print("=");output.space();var p=output.parent(1);var noin=p instanceof AST_For||p instanceof AST_ForIn;parenthesize_for_noin(self.value,output,noin)}});DEFPRINT(AST_Call,function(self,output){self.expression.print(output);if(self instanceof AST_New&&!need_constructor_parens(self,output))return;if(self.expression instanceof AST_Call||self.expression instanceof AST_Lambda){output.add_mapping(self.start)}output.with_parens(function(){self.args.forEach(function(expr,i){if(i)output.comma();expr.print(output)})})});DEFPRINT(AST_New,function(self,output){output.print("new");output.space();AST_Call.prototype._codegen(self,output)});DEFPRINT(AST_Sequence,function(self,output){self.expressions.forEach(function(node,index){if(index>0){output.comma();if(output.should_break()){output.newline();output.indent()}}node.print(output)})});DEFPRINT(AST_Dot,function(self,output){var expr=self.expression;expr.print(output);var prop=self.property;if(output.option("ie8")&&RESERVED_WORDS[prop]){output.print("[");output.add_mapping(self.end);output.print_string(prop);output.print("]")}else{if(expr instanceof AST_Number&&expr.getValue()>=0){if(!/[xa-f.)]/i.test(output.last())){output.print(".")}}output.print(".");output.add_mapping(self.end);output.print_name(prop)}});DEFPRINT(AST_Sub,function(self,output){self.expression.print(output);output.print("[");self.property.print(output);output.print("]")});DEFPRINT(AST_UnaryPrefix,function(self,output){var op=self.operator;output.print(op);if(/^[a-z]/i.test(op)||/[+-]$/.test(op)&&self.expression instanceof AST_UnaryPrefix&&/^[+-]/.test(self.expression.operator)){output.space()}self.expression.print(output)});DEFPRINT(AST_UnaryPostfix,function(self,output){self.expression.print(output);output.print(self.operator)});DEFPRINT(AST_Binary,function(self,output){var op=self.operator;self.left.print(output);if(op[0]==">"&&self.left instanceof AST_UnaryPostfix&&self.left.operator=="--"){output.print(" ")}else{output.space()}output.print(op);if((op=="<"||op=="<<")&&self.right instanceof AST_UnaryPrefix&&self.right.operator=="!"&&self.right.expression instanceof AST_UnaryPrefix&&self.right.expression.operator=="--"){output.print(" ")}else{output.space()}self.right.print(output)});DEFPRINT(AST_Conditional,function(self,output){self.condition.print(output);output.space();output.print("?");output.space();self.consequent.print(output);output.space();output.colon();self.alternative.print(output)});DEFPRINT(AST_Array,function(self,output){output.with_square(function(){var a=self.elements,len=a.length;if(len>0)output.space();a.forEach(function(exp,i){if(i)output.comma();exp.print(output);if(i===len-1&&exp instanceof AST_Hole)output.comma()});if(len>0)output.space()})});DEFPRINT(AST_Object,function(self,output){if(self.properties.length>0)output.with_block(function(){self.properties.forEach(function(prop,i){if(i){output.print(",");output.newline()}output.indent();prop.print(output)});output.newline()});else print_braced_empty(self,output)});function print_property_name(key,quote,output){if(output.option("quote_keys")){output.print_string(key)}else if(""+ +key==key&&key>=0){output.print(make_num(key))}else if(RESERVED_WORDS[key]?!output.option("ie8"):is_identifier_string(key)){if(quote&&output.option("keep_quoted_props")){output.print_string(key,quote)}else{output.print_name(key)}}else{output.print_string(key,quote)}}DEFPRINT(AST_ObjectKeyVal,function(self,output){print_property_name(self.key,self.quote,output);output.colon();self.value.print(output)});AST_ObjectProperty.DEFMETHOD("_print_getter_setter",function(type,output){output.print(type);output.space();print_property_name(this.key.name,this.quote,output);this.value._do_print(output,true)});DEFPRINT(AST_ObjectSetter,function(self,output){self._print_getter_setter("set",output)});DEFPRINT(AST_ObjectGetter,function(self,output){self._print_getter_setter("get",output)});DEFPRINT(AST_Symbol,function(self,output){var def=self.definition();output.print_name(def?def.mangled_name||def.name:self.name)});DEFPRINT(AST_Hole,noop);DEFPRINT(AST_This,function(self,output){output.print("this")});DEFPRINT(AST_Constant,function(self,output){output.print(self.getValue())});DEFPRINT(AST_String,function(self,output){output.print_string(self.getValue(),self.quote,in_directive)});DEFPRINT(AST_Number,function(self,output){if(use_asm&&self.start&&self.start.raw!=null){output.print(self.start.raw)}else{output.print(make_num(self.getValue()))}});DEFPRINT(AST_RegExp,function(self,output){var regexp=self.getValue();var str=regexp.toString();if(regexp.raw_source){str="/"+regexp.raw_source+str.slice(str.lastIndexOf("/"))}str=output.to_utf8(str);output.print(str);var p=output.parent();if(p instanceof AST_Binary&&/^in/.test(p.operator)&&p.left===self)output.print(" ")});function force_statement(stat,output){if(output.option("braces")){make_block(stat,output)}else{if(!stat||stat instanceof AST_EmptyStatement)output.force_semicolon();else stat.print(output)}}function need_constructor_parens(self,output){if(self.args.length>0)return true;return output.option("beautify")}function best_of(a){var best=a[0],len=best.length;for(var i=1;i<a.length;++i){if(a[i].length<len){best=a[i];len=best.length}}return best}function make_num(num){var str=num.toString(10).replace(/^0\./,".").replace("e+","e");var candidates=[str];if(Math.floor(num)===num){if(num<0){candidates.push("-0x"+(-num).toString(16).toLowerCase())}else{candidates.push("0x"+num.toString(16).toLowerCase())}}var match,len,digits;if(match=/^\.0+/.exec(str)){len=match[0].length;digits=str.slice(len);candidates.push(digits+"e-"+(digits.length+len-1))}else if(match=/0+$/.exec(str)){len=match[0].length;candidates.push(str.slice(0,-len)+"e"+len)}else if(match=/^(\d)\.(\d+)e(-?\d+)$/.exec(str)){candidates.push(match[1]+match[2]+"e"+(match[3]-match[2].length))}return best_of(candidates)}function make_block(stmt,output){if(!stmt||stmt instanceof AST_EmptyStatement)output.print("{}");else if(stmt instanceof AST_BlockStatement)stmt.print(output);else output.with_block(function(){output.indent();stmt.print(output);output.newline()})}function DEFMAP(nodetype,generator){nodetype.forEach(function(nodetype){nodetype.DEFMETHOD("add_source_map",generator)})}DEFMAP([AST_Node,AST_LabeledStatement,AST_Toplevel],noop);DEFMAP([AST_Array,AST_BlockStatement,AST_Catch,AST_Constant,AST_Debugger,AST_Definitions,AST_Directive,AST_Finally,AST_Jump,AST_Lambda,AST_New,AST_Object,AST_StatementWithBody,AST_Symbol,AST_Switch,AST_SwitchBranch,AST_Try],function(output){output.add_mapping(this.start)});DEFMAP([AST_ObjectGetter,AST_ObjectSetter],function(output){output.add_mapping(this.start,this.key.name)});DEFMAP([AST_ObjectProperty],function(output){output.add_mapping(this.start,this.key)})})();"use strict";function Compressor(options,false_by_default){if(!(this instanceof Compressor))return new Compressor(options,false_by_default);TreeTransformer.call(this,this.before,this.after);this.options=defaults(options,{arguments:!false_by_default,booleans:!false_by_default,collapse_vars:!false_by_default,comparisons:!false_by_default,conditionals:!false_by_default,dead_code:!false_by_default,directives:!false_by_default,drop_console:false,drop_debugger:!false_by_default,evaluate:!false_by_default,expression:false,global_defs:false,hoist_funs:false,hoist_props:!false_by_default,hoist_vars:false,ie8:false,if_return:!false_by_default,inline:!false_by_default,join_vars:!false_by_default,keep_fargs:true,keep_fnames:false,keep_infinity:false,loops:!false_by_default,negate_iife:!false_by_default,passes:1,properties:!false_by_default,pure_getters:!false_by_default&&"strict",pure_funcs:null,reduce_funcs:!false_by_default,reduce_vars:!false_by_default,sequences:!false_by_default,side_effects:!false_by_default,switches:!false_by_default,top_retain:null,toplevel:!!(options&&options["top_retain"]),typeofs:!false_by_default,unsafe:false,unsafe_comps:false,unsafe_Function:false,unsafe_math:false,unsafe_proto:false,unsafe_regexp:false,unsafe_undefined:false,unused:!false_by_default,warnings:false},true);var global_defs=this.options["global_defs"];if(typeof global_defs=="object")for(var key in global_defs){if(/^@/.test(key)&&HOP(global_defs,key)){global_defs[key.slice(1)]=parse(global_defs[key],{expression:true})}}if(this.options["inline"]===true)this.options["inline"]=3;var pure_funcs=this.options["pure_funcs"];if(typeof pure_funcs=="function"){this.pure_funcs=pure_funcs}else{this.pure_funcs=pure_funcs?function(node){return pure_funcs.indexOf(node.expression.print_to_string())<0}:return_true}var top_retain=this.options["top_retain"];if(top_retain instanceof RegExp){this.top_retain=function(def){return top_retain.test(def.name)}}else if(typeof top_retain=="function"){this.top_retain=top_retain}else if(top_retain){if(typeof top_retain=="string"){top_retain=top_retain.split(/,/)}this.top_retain=function(def){return top_retain.indexOf(def.name)>=0}}var toplevel=this.options["toplevel"];this.toplevel=typeof toplevel=="string"?{funcs:/funcs/.test(toplevel),vars:/vars/.test(toplevel)}:{funcs:toplevel,vars:toplevel};var sequences=this.options["sequences"];this.sequences_limit=sequences==1?800:sequences|0;this.warnings_produced={}}Compressor.prototype=new TreeTransformer;merge(Compressor.prototype,{option:function(key){return this.options[key]},exposed:function(def){if(def.global)for(var i=0,len=def.orig.length;i<len;i++)if(!this.toplevel[def.orig[i]instanceof AST_SymbolDefun?"funcs":"vars"])return true;return false},compress:function(node){node=node.resolve_defines(this);if(this.option("expression")){node.process_expression(true)}var passes=+this.options.passes||1;var min_count=1/0;var stopping=false;var mangle={ie8:this.option("ie8")};for(var pass=0;pass<passes;pass++){node.figure_out_scope(mangle);if(pass>0||this.option("reduce_vars"))node.reset_opt_flags(this);node=node.transform(this);if(passes>1){var count=0;node.walk(new TreeWalker(function(){count++}));this.info("pass "+pass+": last_count: "+min_count+", count: "+count);if(count<min_count){min_count=count;stopping=false}else if(stopping){break}else{stopping=true}}}if(this.option("expression")){node.process_expression(false)}return node},info:function(){if(this.options.warnings=="verbose"){AST_Node.warn.apply(AST_Node,arguments)}},warn:function(text,props){if(this.options.warnings){var message=string_template(text,props);if(!(message in this.warnings_produced)){this.warnings_produced[message]=true;AST_Node.warn.apply(AST_Node,arguments)}}},clear_warnings:function(){this.warnings_produced={}},before:function(node,descend,in_list){if(node._squeezed)return node;var is_scope=node instanceof AST_Scope;if(is_scope){node.hoist_properties(this);node.hoist_declarations(this)}descend(node,this);descend(node,this);var opt=node.optimize(this);if(is_scope){opt.drop_unused(this);descend(opt,this)}if(opt===node)opt._squeezed=true;return opt}});(function(OPT){OPT(AST_Node,function(self,compressor){return self});AST_Node.DEFMETHOD("equivalent_to",function(node){return this.TYPE==node.TYPE&&this.print_to_string()==node.print_to_string()});AST_Scope.DEFMETHOD("process_expression",function(insert,compressor){var self=this;var tt=new TreeTransformer(function(node){if(insert&&node instanceof AST_SimpleStatement){return make_node(AST_Return,node,{value:node.body})}if(!insert&&node instanceof AST_Return){if(compressor){var value=node.value&&node.value.drop_side_effect_free(compressor,true);return value?make_node(AST_SimpleStatement,node,{body:value}):make_node(AST_EmptyStatement,node)}return make_node(AST_SimpleStatement,node,{body:node.value||make_node(AST_UnaryPrefix,node,{operator:"void",expression:make_node(AST_Number,node,{value:0})})})}if(node instanceof AST_Lambda&&node!==self){return node}if(node instanceof AST_Block){var index=node.body.length-1;if(index>=0){node.body[index]=node.body[index].transform(tt)}}else if(node instanceof AST_If){node.body=node.body.transform(tt);if(node.alternative){node.alternative=node.alternative.transform(tt)}}else if(node instanceof AST_With){node.body=node.body.transform(tt)}return node});self.transform(tt)});function read_property(obj,key){key=get_value(key);if(key instanceof AST_Node)return;var value;if(obj instanceof AST_Array){var elements=obj.elements;if(key=="length")return make_node_from_constant(elements.length,obj);if(typeof key=="number"&&key in elements)value=elements[key]}else if(obj instanceof AST_Object){key=""+key;var props=obj.properties;for(var i=props.length;--i>=0;){var prop=props[i];if(!(prop instanceof AST_ObjectKeyVal))return;if(!value&&props[i].key===key)value=props[i].value}}return value instanceof AST_SymbolRef&&value.fixed_value()||value}function is_modified(compressor,tw,node,value,level,immutable){var parent=tw.parent(level);var lhs=is_lhs(node,parent);if(lhs)return lhs;if(!immutable&&parent instanceof AST_Call&&parent.expression===node&&!parent.is_expr_pure(compressor)&&(!(value instanceof AST_Function)||!(parent instanceof AST_New)&&value.contains_this())){return true}if(parent instanceof AST_Array){return is_modified(compressor,tw,parent,parent,level+1)}if(parent instanceof AST_ObjectKeyVal&&node===parent.value){var obj=tw.parent(level+1);return is_modified(compressor,tw,obj,obj,level+2)}if(parent instanceof AST_PropAccess&&parent.expression===node){var prop=read_property(value,parent.property);return!immutable&&is_modified(compressor,tw,parent,prop,level+1)}}(function(def){def(AST_Node,noop);function reset_def(tw,compressor,def){def.assignments=0;def.chained=false;def.direct_access=false;def.escaped=false;def.fixed=!def.scope.pinned()&&!compressor.exposed(def)&&!(def.init instanceof AST_Function&&def.init!==def.scope)&&def.init;if(def.fixed instanceof AST_Defun&&!all(def.references,function(ref){var scope=ref.scope;do{if(def.scope===scope)return true}while(scope instanceof AST_Function&&(scope=scope.parent_scope))})){tw.defun_ids[def.id]=false}def.recursive_refs=0;def.references=[];def.should_replace=undefined;def.single_use=undefined}function reset_variables(tw,compressor,scope){scope.variables.each(function(def){reset_def(tw,compressor,def);if(def.fixed===null){def.safe_ids=tw.safe_ids;mark(tw,def,true)}else if(def.fixed){tw.loop_ids[def.id]=tw.in_loop;mark(tw,def,true)}});scope.may_call_this=function(){scope.may_call_this=noop;if(!scope.contains_this())return;scope.functions.each(function(def){if(def.init instanceof AST_Defun&&!(def.id in tw.defun_ids)){tw.defun_ids[def.id]=false}})}}function mark_defun(tw,def){if(def.id in tw.defun_ids){var marker=tw.defun_ids[def.id];if(!marker)return;var visited=tw.defun_visited[def.id];if(marker===tw.safe_ids){if(!visited)return def.fixed}else if(visited){def.init.enclosed.forEach(function(d){if(def.init.variables.get(d.name)===d)return;if(!safe_to_read(tw,d))d.fixed=false})}else{tw.defun_ids[def.id]=false}}else{if(!tw.in_loop){tw.defun_ids[def.id]=tw.safe_ids;return def.fixed}tw.defun_ids[def.id]=false}}function walk_defuns(tw,scope){scope.functions.each(function(def){if(def.init instanceof AST_Defun&&!tw.defun_visited[def.id]){tw.defun_ids[def.id]=tw.safe_ids;def.init.walk(tw)}})}function push(tw){tw.safe_ids=Object.create(tw.safe_ids)}function pop(tw){tw.safe_ids=Object.getPrototypeOf(tw.safe_ids)}function mark(tw,def,safe){tw.safe_ids[def.id]=safe}function safe_to_read(tw,def){if(def.single_use=="m")return false;if(tw.safe_ids[def.id]){if(def.fixed==null){var orig=def.orig[0];if(orig instanceof AST_SymbolFunarg||orig.name=="arguments")return false;def.fixed=make_node(AST_Undefined,orig)}return true}return def.fixed instanceof AST_Defun}function safe_to_assign(tw,def,scope,value){if(def.fixed===undefined)return true;if(def.fixed===null&&def.safe_ids){def.safe_ids[def.id]=false;delete def.safe_ids;return true}if(!HOP(tw.safe_ids,def.id))return false;if(!safe_to_read(tw,def))return false;if(def.fixed===false)return false;if(def.fixed!=null&&(!value||def.references.length>def.assignments))return false;if(def.fixed instanceof AST_Defun){return value instanceof AST_Node&&def.fixed.parent_scope===scope}return all(def.orig,function(sym){return!(sym instanceof AST_SymbolDefun||sym instanceof AST_SymbolLambda)})}function ref_once(tw,compressor,def){return compressor.option("unused")&&!def.scope.pinned()&&def.references.length-def.recursive_refs==1&&tw.loop_ids[def.id]===tw.in_loop}function is_immutable(value){if(!value)return false;return value.is_constant()||value instanceof AST_Lambda||value instanceof AST_This}function mark_escaped(tw,d,scope,node,value,level,depth){var parent=tw.parent(level);if(value&&value.is_constant())return;if(parent instanceof AST_Assign&&parent.operator=="="&&node===parent.right||parent instanceof AST_Call&&(node!==parent.expression||parent instanceof AST_New)||parent instanceof AST_Exit&&node===parent.value&&node.scope!==d.scope||parent instanceof AST_VarDef&&node===parent.value){if(depth>1&&!(value&&value.is_constant_expression(scope)))depth=1;if(!d.escaped||d.escaped>depth)d.escaped=depth;return}else if(parent instanceof AST_Array||parent instanceof AST_Binary&&lazy_op[parent.operator]||parent instanceof AST_Conditional&&node!==parent.condition||parent instanceof AST_Sequence&&node===parent.tail_node()){mark_escaped(tw,d,scope,parent,parent,level+1,depth)}else if(parent instanceof AST_ObjectKeyVal&&node===parent.value){var obj=tw.parent(level+1);mark_escaped(tw,d,scope,obj,obj,level+2,depth)}else if(parent instanceof AST_PropAccess&&node===parent.expression){value=read_property(value,parent.property);mark_escaped(tw,d,scope,parent,value,level+1,depth+1);if(value)return}if(level>0)return;if(parent instanceof AST_Sequence&&node!==parent.tail_node())return;if(parent instanceof AST_SimpleStatement)return;d.direct_access=true}var suppressor=new TreeWalker(function(node){if(!(node instanceof AST_Symbol))return;var d=node.definition();if(!d)return;if(node instanceof AST_SymbolRef)d.references.push(node);d.fixed=false});def(AST_Accessor,function(tw,descend,compressor){push(tw);reset_variables(tw,compressor,this);descend();pop(tw);walk_defuns(tw,this);return true});def(AST_Assign,function(tw,descend,compressor){var node=this;var sym=node.left;if(!(sym instanceof AST_SymbolRef))return;var d=sym.definition();var safe=safe_to_assign(tw,d,sym.scope,node.right);d.assignments++;if(!safe)return;var fixed=d.fixed;if(!fixed&&node.operator!="=")return;var eq=node.operator=="=";var value=eq?node.right:node;if(is_modified(compressor,tw,node,value,0))return;d.references.push(sym);if(!eq)d.chained=true;d.fixed=eq?function(){return node.right}:function(){return make_node(AST_Binary,node,{operator:node.operator.slice(0,-1),left:fixed instanceof AST_Node?fixed:fixed(),right:node.right})};mark(tw,d,false);node.right.walk(tw);mark(tw,d,true);mark_escaped(tw,d,sym.scope,node,value,0,1);return true});def(AST_Binary,function(tw){if(!lazy_op[this.operator])return;this.left.walk(tw);push(tw);this.right.walk(tw);pop(tw);return true});def(AST_Call,function(tw,descend){tw.find_parent(AST_Scope).may_call_this();var exp=this.expression;if(!(exp instanceof AST_SymbolRef))return;var def=exp.definition();if(!(def.fixed instanceof AST_Defun))return;var defun=mark_defun(tw,def);if(!defun)return;descend();defun.walk(tw);return true});def(AST_Case,function(tw){push(tw);this.expression.walk(tw);pop(tw);push(tw);walk_body(this,tw);pop(tw);return true});def(AST_Conditional,function(tw){this.condition.walk(tw);push(tw);this.consequent.walk(tw);pop(tw);push(tw);this.alternative.walk(tw);pop(tw);return true});def(AST_Default,function(tw,descend){push(tw);descend();pop(tw);return true});def(AST_Defun,function(tw,descend,compressor){var id=this.name.definition().id;if(tw.defun_visited[id])return true;if(tw.defun_ids[id]!==tw.safe_ids)return true;tw.defun_visited[id]=true;this.inlined=false;push(tw);reset_variables(tw,compressor,this);descend();pop(tw);walk_defuns(tw,this);return true});def(AST_Do,function(tw){var saved_loop=tw.in_loop;tw.in_loop=this;push(tw);this.body.walk(tw);if(has_break_or_continue(this)){pop(tw);push(tw)}this.condition.walk(tw);pop(tw);tw.in_loop=saved_loop;return true});def(AST_For,function(tw){if(this.init)this.init.walk(tw);var saved_loop=tw.in_loop;tw.in_loop=this;push(tw);if(this.condition)this.condition.walk(tw);this.body.walk(tw);if(this.step){if(has_break_or_continue(this)){pop(tw);push(tw)}this.step.walk(tw)}pop(tw);tw.in_loop=saved_loop;return true});def(AST_ForIn,function(tw){this.init.walk(suppressor);this.object.walk(tw);var saved_loop=tw.in_loop;tw.in_loop=this;push(tw);this.body.walk(tw);pop(tw);tw.in_loop=saved_loop;return true});def(AST_Function,function(tw,descend,compressor){var node=this;node.inlined=false;push(tw);reset_variables(tw,compressor,node);var iife;if(!node.name&&(iife=tw.parent())instanceof AST_Call&&iife.expression===node){node.argnames.forEach(function(arg,i){var d=arg.definition();if(d.fixed===undefined&&(!node.uses_arguments||tw.has_directive("use strict"))){d.fixed=function(){return iife.args[i]||make_node(AST_Undefined,iife)};tw.loop_ids[d.id]=tw.in_loop;mark(tw,d,true)}else{d.fixed=false}})}descend();pop(tw);walk_defuns(tw,node);return true});def(AST_If,function(tw){this.condition.walk(tw);push(tw);this.body.walk(tw);pop(tw);if(this.alternative){push(tw);this.alternative.walk(tw);pop(tw)}return true});def(AST_LabeledStatement,function(tw){push(tw);this.body.walk(tw);pop(tw);return true});def(AST_SymbolCatch,function(){this.definition().fixed=false});def(AST_SymbolRef,function(tw,descend,compressor){var d=this.definition();d.references.push(this);if(d.references.length==1&&!d.fixed&&d.orig[0]instanceof AST_SymbolDefun){tw.loop_ids[d.id]=tw.in_loop}var value;if(d.fixed===undefined||!safe_to_read(tw,d)){d.fixed=false}else if(d.fixed){value=this.fixed_value();if(value instanceof AST_Lambda&&recursive_ref(tw,d)){d.recursive_refs++}else if(value&&ref_once(tw,compressor,d)){d.single_use=value instanceof AST_Lambda&&!value.pinned()||d.scope===this.scope&&value.is_constant_expression()}else{d.single_use=false}if(is_modified(compressor,tw,this,value,0,is_immutable(value))){if(d.single_use){d.single_use="m"}else{d.fixed=false}}}mark_escaped(tw,d,this.scope,this,value,0,1);var parent;if(d.fixed instanceof AST_Defun&&!((parent=tw.parent())instanceof AST_Call&&parent.expression===this)){var defun=mark_defun(tw,d);if(defun)defun.walk(tw)}});def(AST_Toplevel,function(tw,descend,compressor){this.globals.each(function(def){reset_def(tw,compressor,def)});push(tw);reset_variables(tw,compressor,this);descend();pop(tw);walk_defuns(tw,this);return true});def(AST_Try,function(tw){push(tw);walk_body(this,tw);pop(tw);if(this.bcatch){push(tw);this.bcatch.walk(tw);pop(tw)}if(this.bfinally)this.bfinally.walk(tw);return true});def(AST_Unary,function(tw,descend){var node=this;if(node.operator!="++"&&node.operator!="--")return;var exp=node.expression;if(!(exp instanceof AST_SymbolRef))return;var d=exp.definition();var safe=safe_to_assign(tw,d,exp.scope,true);d.assignments++;if(!safe)return;var fixed=d.fixed;if(!fixed)return;d.references.push(exp);d.chained=true;d.fixed=function(){return make_node(AST_Binary,node,{operator:node.operator.slice(0,-1),left:make_node(AST_UnaryPrefix,node,{operator:"+",expression:fixed instanceof AST_Node?fixed:fixed()}),right:make_node(AST_Number,node,{value:1})})};mark(tw,d,true);return true});def(AST_VarDef,function(tw,descend){var node=this;var d=node.name.definition();if(node.value){if(safe_to_assign(tw,d,node.name.scope,node.value)){d.fixed=function(){return node.value};tw.loop_ids[d.id]=tw.in_loop;mark(tw,d,false);descend();mark(tw,d,true);return true}else{d.fixed=false}}});def(AST_While,function(tw,descend){var saved_loop=tw.in_loop;tw.in_loop=this;push(tw);descend();pop(tw);tw.in_loop=saved_loop;return true})})(function(node,func){node.DEFMETHOD("reduce_vars",func)});AST_Toplevel.DEFMETHOD("reset_opt_flags",function(compressor){var tw=new TreeWalker(compressor.option("reduce_vars")?function(node,descend){node._squeezed=false;node._optimized=false;return node.reduce_vars(tw,descend,compressor)}:function(node){node._squeezed=false;node._optimized=false});tw.defun_ids=Object.create(null);tw.defun_visited=Object.create(null);tw.in_loop=null;tw.loop_ids=Object.create(null);tw.safe_ids=Object.create(null);this.walk(tw)});AST_Symbol.DEFMETHOD("fixed_value",function(){var fixed=this.definition().fixed;if(!fixed||fixed instanceof AST_Node)return fixed;return fixed()});AST_SymbolRef.DEFMETHOD("is_immutable",function(){var orig=this.definition().orig;return orig.length==1&&orig[0]instanceof AST_SymbolLambda});function is_lhs_read_only(lhs){if(lhs instanceof AST_This)return true;if(lhs instanceof AST_SymbolRef)return lhs.definition().orig[0]instanceof AST_SymbolLambda;if(lhs instanceof AST_PropAccess){lhs=lhs.expression;if(lhs instanceof AST_SymbolRef){if(lhs.is_immutable())return false;lhs=lhs.fixed_value()}if(!lhs)return true;if(lhs.is_constant())return true;return is_lhs_read_only(lhs)}return false}function find_variable(compressor,name){var scope,i=0;while(scope=compressor.parent(i++)){if(scope instanceof AST_Scope)break;if(scope instanceof AST_Catch){scope=scope.argname.definition().scope;break}}return scope.find_variable(name)}function make_node(ctor,orig,props){if(!props)props={};if(orig){if(!props.start)props.start=orig.start;if(!props.end)props.end=orig.end}return new ctor(props)}function make_sequence(orig,expressions){if(expressions.length==1)return expressions[0];return make_node(AST_Sequence,orig,{expressions:expressions.reduce(merge_sequence,[])})}function make_node_from_constant(val,orig){switch(typeof val){case"string":return make_node(AST_String,orig,{value:val});case"number":if(isNaN(val))return make_node(AST_NaN,orig);if(isFinite(val)){return 1/val<0?make_node(AST_UnaryPrefix,orig,{operator:"-",expression:make_node(AST_Number,orig,{value:-val})}):make_node(AST_Number,orig,{value:val})}return val<0?make_node(AST_UnaryPrefix,orig,{operator:"-",expression:make_node(AST_Infinity,orig)}):make_node(AST_Infinity,orig);case"boolean":return make_node(val?AST_True:AST_False,orig);case"undefined":return make_node(AST_Undefined,orig);default:if(val===null){return make_node(AST_Null,orig,{value:null})}if(val instanceof RegExp){return make_node(AST_RegExp,orig,{value:val})}throw new Error(string_template("Can't handle constant of type: {type}",{type:typeof val}))}}function needs_unbinding(compressor,val){return val instanceof AST_PropAccess||compressor.has_directive("use strict")&&is_undeclared_ref(val)&&val.name=="eval"}function maintain_this_binding(compressor,parent,orig,val){if(parent instanceof AST_UnaryPrefix&&parent.operator=="delete"||parent.TYPE=="Call"&&parent.expression===orig&&needs_unbinding(compressor,val)){return make_sequence(orig,[make_node(AST_Number,orig,{value:0}),val])}return val}function merge_sequence(array,node){if(node instanceof AST_Sequence){array.push.apply(array,node.expressions)}else{array.push(node)}return array}function as_statement_array(thing){if(thing===null)return[];if(thing instanceof AST_BlockStatement)return thing.body;if(thing instanceof AST_EmptyStatement)return[];if(thing instanceof AST_Statement)return[thing];throw new Error("Can't convert thing to statement array")}function is_empty(thing){if(thing===null)return true;if(thing instanceof AST_EmptyStatement)return true;if(thing instanceof AST_BlockStatement)return thing.body.length==0;return false}function loop_body(x){if(x instanceof AST_IterationStatement){return x.body instanceof AST_BlockStatement?x.body:x}return x}function root_expr(prop){while(prop instanceof AST_PropAccess)prop=prop.expression;return prop}function is_iife_call(node){if(node.TYPE!="Call")return false;return node.expression instanceof AST_Function||is_iife_call(node.expression)}function is_undeclared_ref(node){return node instanceof AST_SymbolRef&&node.definition().undeclared}var global_names=makePredicate("Array Boolean clearInterval clearTimeout console Date decodeURI decodeURIComponent encodeURI encodeURIComponent Error escape eval EvalError Function isFinite isNaN JSON Math Number parseFloat parseInt RangeError ReferenceError RegExp Object setInterval setTimeout String SyntaxError TypeError unescape URIError");AST_SymbolRef.DEFMETHOD("is_declared",function(compressor){return!this.definition().undeclared||compressor.option("unsafe")&&global_names[this.name]});var identifier_atom=makePredicate("Infinity NaN undefined");function is_identifier_atom(node){return node instanceof AST_Infinity||node instanceof AST_NaN||node instanceof AST_Undefined}function tighten_body(statements,compressor){var in_loop,in_try,scope;find_loop_scope_try();var CHANGED,max_iter=10;do{CHANGED=false;eliminate_spurious_blocks(statements);if(compressor.option("dead_code")){eliminate_dead_code(statements,compressor)}if(compressor.option("if_return")){handle_if_return(statements,compressor)}if(compressor.sequences_limit>0){sequencesize(statements,compressor);sequencesize_2(statements,compressor)}if(compressor.option("join_vars")){join_consecutive_vars(statements)}if(compressor.option("collapse_vars")){collapse(statements,compressor)}}while(CHANGED&&max_iter-- >0);function find_loop_scope_try(){var node=compressor.self(),level=0;do{if(node instanceof AST_Catch||node instanceof AST_Finally){level++}else if(node instanceof AST_IterationStatement){in_loop=true}else if(node instanceof AST_Scope){scope=node;break}else if(node instanceof AST_Try){in_try=true}}while(node=compressor.parent(level++))}function collapse(statements,compressor){if(scope.pinned())return statements;var args;var candidates=[];var stat_index=statements.length;var scanner=new TreeTransformer(function(node){if(abort)return node;if(!hit){if(node!==hit_stack[hit_index])return node;hit_index++;if(hit_index<hit_stack.length)return handle_custom_scan_order(node);hit=true;stop_after=find_stop(node,0);if(stop_after===node)abort=true;return node}var parent=scanner.parent();if(should_stop(node,parent)){abort=true;return node}if(!stop_if_hit&&in_conditional(node,parent)){stop_if_hit=parent}var hit_lhs,hit_rhs;if(can_replace&&!(node instanceof AST_SymbolDeclaration)&&(scan_lhs&&(hit_lhs=lhs.equivalent_to(node))||scan_rhs&&(hit_rhs=scan_rhs(node,this)))){if(stop_if_hit&&(hit_rhs||!lhs_local||!replace_all)){abort=true;return node}if(is_lhs(node,parent)){if(value_def)replaced++;return node}else{replaced++;if(value_def&&candidate instanceof AST_VarDef)return node}CHANGED=abort=true;compressor.info("Collapsing {name} [{file}:{line},{col}]",{name:node.print_to_string(),file:node.start.file,line:node.start.line,col:node.start.col});if(candidate instanceof AST_UnaryPostfix){return make_node(AST_UnaryPrefix,candidate,candidate)}if(candidate instanceof AST_VarDef){var def=candidate.name.definition();if(def.references.length-def.replaced==1&&!compressor.exposed(def)){def.replaced++;return maintain_this_binding(compressor,parent,node,candidate.value)}return make_node(AST_Assign,candidate,{operator:"=",left:make_node(AST_SymbolRef,candidate.name,candidate.name),right:candidate.value})}candidate.write_only=false;return candidate}var sym;if(is_last_node(node,parent)||may_throw(node)){stop_after=node;if(node instanceof AST_Scope)abort=true}return handle_custom_scan_order(node)},function(node){if(abort)return;if(stop_after===node)abort=true;if(stop_if_hit===node)stop_if_hit=null});var multi_replacer=new TreeTransformer(function(node){if(abort)return node;if(!hit){if(node!==hit_stack[hit_index])return node;hit_index++;if(hit_index<hit_stack.length)return;hit=true;return node}if(node instanceof AST_SymbolRef&&node.name==def.name){if(!--replaced)abort=true;if(is_lhs(node,multi_replacer.parent()))return node;def.replaced++;value_def.replaced--;return candidate.value.clone()}if(node instanceof AST_Default||node instanceof AST_Scope)return node});while(--stat_index>=0){if(stat_index==0&&compressor.option("unused"))extract_args();var hit_stack=[];extract_candidates(statements[stat_index]);while(candidates.length>0){hit_stack=candidates.pop();var hit_index=0;var candidate=hit_stack[hit_stack.length-1];var value_def=null;var stop_after=null;var stop_if_hit=null;var lhs=get_lhs(candidate);var rhs=get_rhs(candidate);var side_effects=lhs&&lhs.has_side_effects(compressor);var scan_lhs=lhs&&!side_effects&&!is_lhs_read_only(lhs);var scan_rhs=rhs&&foldable(rhs);if(!scan_lhs&&!scan_rhs)continue;var lvalues=get_lvalues(candidate);var lhs_local=is_lhs_local(lhs);if(!side_effects)side_effects=value_has_side_effects(candidate);var replace_all=replace_all_symbols();var may_throw=candidate.may_throw(compressor)?in_try?function(node){return node.has_side_effects(compressor)}:side_effects_external:return_false;var funarg=candidate.name instanceof AST_SymbolFunarg;var hit=funarg;var abort=false,replaced=0,can_replace=!args||!hit;if(!can_replace){for(var j=compressor.self().argnames.lastIndexOf(candidate.name)+1;!abort&&j<args.length;j++){args[j].transform(scanner)}can_replace=true}for(var i=stat_index;!abort&&i<statements.length;i++){statements[i].transform(scanner)}if(value_def){var def=candidate.name.definition();if(abort&&def.references.length-def.replaced>replaced)replaced=false;else{abort=false;hit_index=0;hit=funarg;for(var i=stat_index;!abort&&i<statements.length;i++){statements[i].transform(multi_replacer)}value_def.single_use=false}}if(replaced&&!remove_candidate(candidate))statements.splice(stat_index,1)}}function handle_custom_scan_order(node){if(node instanceof AST_Scope)return node;if(node instanceof AST_Switch){node.expression=node.expression.transform(scanner);for(var i=0,len=node.body.length;!abort&&i<len;i++){var branch=node.body[i];if(branch instanceof AST_Case){if(!hit){if(branch!==hit_stack[hit_index])continue;hit_index++}branch.expression=branch.expression.transform(scanner);if(!replace_all)break}}abort=true;return node}}function should_stop(node,parent){if(parent instanceof AST_For)return node!==parent.init;if(node instanceof AST_Assign){return node.operator!="="&&lhs.equivalent_to(node.left)}if(node instanceof AST_Call){return lhs instanceof AST_PropAccess&&lhs.equivalent_to(node.expression)}if(node instanceof AST_Debugger)return true;if(node instanceof AST_IterationStatement)return!(node instanceof AST_For);if(node instanceof AST_LoopControl)return true;if(node instanceof AST_Try)return true;if(node instanceof AST_With)return true;if(replace_all)return false;return node instanceof AST_SymbolRef&&!node.is_declared(compressor)}function in_conditional(node,parent){if(parent instanceof AST_Binary)return lazy_op[parent.operator]&&parent.left!==node;if(parent instanceof AST_Conditional)return parent.condition!==node;return parent instanceof AST_If&&parent.condition!==node}function is_last_node(node,parent){if(node instanceof AST_Call)return true;if(node instanceof AST_Exit){return side_effects||lhs instanceof AST_PropAccess||may_modify(lhs)}if(node instanceof AST_Function){return compressor.option("ie8")&&node.name&&node.name.name in lvalues}if(node instanceof AST_PropAccess){return side_effects||node.expression.may_throw_on_access(compressor)}if(node instanceof AST_SymbolRef){if(symbol_in_lvalues(node,parent)){return!parent||parent.operator!="="||parent.left!==node}return side_effects&&may_modify(node)}if(node instanceof AST_This)return symbol_in_lvalues(node,parent);if(node instanceof AST_VarDef){if(!node.value)return false;return node.name.name in lvalues||side_effects&&may_modify(node.name)}var sym=is_lhs(node.left,node);if(sym&&sym.name in lvalues)return true;if(sym instanceof AST_PropAccess)return true}function extract_args(){var iife,fn=compressor.self();if(fn instanceof AST_Function&&!fn.name&&!fn.uses_arguments&&!fn.pinned()&&(iife=compressor.parent())instanceof AST_Call&&iife.expression===fn){var fn_strict=compressor.has_directive("use strict");if(fn_strict&&!member(fn_strict,fn.body))fn_strict=false;var len=fn.argnames.length;args=iife.args.slice(len);var names=Object.create(null);for(var i=len;--i>=0;){var sym=fn.argnames[i];var arg=iife.args[i];args.unshift(make_node(AST_VarDef,sym,{name:sym,value:arg}));if(sym.name in names)continue;names[sym.name]=true;if(!arg){arg=make_node(AST_Undefined,sym).transform(compressor)}else if(arg instanceof AST_Lambda&&arg.pinned()){arg=null}else{arg.walk(new TreeWalker(function(node){if(!arg)return true;if(node instanceof AST_SymbolRef&&fn.variables.has(node.name)){var s=node.definition().scope;if(s!==scope)while(s=s.parent_scope){if(s===scope)return true}arg=null}if(node instanceof AST_This&&(fn_strict||!this.find_parent(AST_Scope))){arg=null;return true}}))}if(arg)candidates.unshift([make_node(AST_VarDef,sym,{name:sym,value:arg})])}}}function extract_candidates(expr){hit_stack.push(expr);if(expr instanceof AST_Assign){candidates.push(hit_stack.slice());extract_candidates(expr.right)}else if(expr instanceof AST_Binary){extract_candidates(expr.left);extract_candidates(expr.right)}else if(expr instanceof AST_Call){extract_candidates(expr.expression);expr.args.forEach(extract_candidates)}else if(expr instanceof AST_Case){extract_candidates(expr.expression)}else if(expr instanceof AST_Conditional){extract_candidates(expr.condition);extract_candidates(expr.consequent);extract_candidates(expr.alternative)}else if(expr instanceof AST_Definitions){expr.definitions.forEach(extract_candidates)}else if(expr instanceof AST_DWLoop){extract_candidates(expr.condition);if(!(expr.body instanceof AST_Block)){extract_candidates(expr.body)}}else if(expr instanceof AST_Exit){if(expr.value)extract_candidates(expr.value)}else if(expr instanceof AST_For){if(expr.init)extract_candidates(expr.init);if(expr.condition)extract_candidates(expr.condition);if(expr.step)extract_candidates(expr.step);if(!(expr.body instanceof AST_Block)){extract_candidates(expr.body)}}else if(expr instanceof AST_ForIn){extract_candidates(expr.object);if(!(expr.body instanceof AST_Block)){extract_candidates(expr.body)}}else if(expr instanceof AST_If){extract_candidates(expr.condition);if(!(expr.body instanceof AST_Block)){extract_candidates(expr.body)}if(expr.alternative&&!(expr.alternative instanceof AST_Block)){extract_candidates(expr.alternative)}}else if(expr instanceof AST_Sequence){expr.expressions.forEach(extract_candidates)}else if(expr instanceof AST_SimpleStatement){extract_candidates(expr.body)}else if(expr instanceof AST_Switch){extract_candidates(expr.expression);expr.body.forEach(extract_candidates)}else if(expr instanceof AST_Unary){if(expr.operator=="++"||expr.operator=="--"){candidates.push(hit_stack.slice())}else{extract_candidates(expr.expression)}}else if(expr instanceof AST_VarDef){if(expr.value){var def=expr.name.definition();if(def.references.length>def.replaced){candidates.push(hit_stack.slice())}extract_candidates(expr.value)}}hit_stack.pop()}function find_stop(node,level,write_only){var parent=scanner.parent(level);if(parent instanceof AST_Assign){if(write_only&&!(parent.left instanceof AST_PropAccess||parent.left.name in lvalues)){return find_stop(parent,level+1,write_only)}return node}if(parent instanceof AST_Binary){if(write_only&&(!lazy_op[parent.operator]||parent.left===node)){return find_stop(parent,level+1,write_only)}return node}if(parent instanceof AST_Call)return node;if(parent instanceof AST_Case)return node;if(parent instanceof AST_Conditional){if(write_only&&parent.condition===node){return find_stop(parent,level+1,write_only)}return node}if(parent instanceof AST_Definitions){return find_stop(parent,level+1,true)}if(parent instanceof AST_Exit){return write_only?find_stop(parent,level+1,write_only):node}if(parent instanceof AST_If){if(write_only&&parent.condition===node){return find_stop(parent,level+1,write_only)}return node}if(parent instanceof AST_IterationStatement)return node;if(parent instanceof AST_Sequence){return find_stop(parent,level+1,parent.tail_node()!==node)}if(parent instanceof AST_SimpleStatement){return find_stop(parent,level+1,true)}if(parent instanceof AST_Switch)return node;if(parent instanceof AST_Unary)return node;if(parent instanceof AST_VarDef)return node;return null}function mangleable_var(var_def){var value=var_def.value;if(!(value instanceof AST_SymbolRef))return;if(value.name=="arguments")return;var def=value.definition();if(def.undeclared)return;return value_def=def}function get_lhs(expr){if(expr instanceof AST_VarDef){var def=expr.name.definition();if(!member(expr.name,def.orig))return;var referenced=def.references.length-def.replaced;var declared=def.orig.length-def.eliminated;if(declared>1&&!(expr.name instanceof AST_SymbolFunarg)||(referenced>1?mangleable_var(expr):!compressor.exposed(def))){return make_node(AST_SymbolRef,expr.name,expr.name)}}else{return expr[expr instanceof AST_Assign?"left":"expression"]}}function get_rhs(expr){return candidate instanceof AST_Assign&&candidate.operator=="="&&candidate.right}function get_rvalue(expr){return expr[expr instanceof AST_Assign?"right":"value"]}function invariant(expr){if(expr instanceof AST_Array)return false;if(expr instanceof AST_Binary&&lazy_op[expr.operator]){return invariant(expr.left)&&invariant(expr.right)}if(expr instanceof AST_Call)return false;if(expr instanceof AST_Conditional){return invariant(expr.consequent)&&invariant(expr.alternative)}if(expr instanceof AST_Object)return false;return!expr.has_side_effects(compressor)}function foldable(expr){if(expr instanceof AST_SymbolRef){var value=expr.evaluate(compressor);if(value===expr)return rhs_exact_match;return rhs_fuzzy_match(value,rhs_exact_match)}if(expr instanceof AST_This)return rhs_exact_match;if(expr.is_truthy())return rhs_fuzzy_match(true,return_false);if(expr.is_constant()){return rhs_fuzzy_match(expr.evaluate(compressor),rhs_exact_match)}if(!(lhs instanceof AST_SymbolRef))return false;if(!invariant(expr))return false;var circular;var def=lhs.definition();expr.walk(new TreeWalker(function(node){if(circular)return true;if(node instanceof AST_SymbolRef&&node.definition()===def){circular=true}}));return!circular&&rhs_exact_match}function rhs_exact_match(node){return rhs.equivalent_to(node)}function rhs_fuzzy_match(value,fallback){return function(node,tw){if(tw.in_boolean_context()){if(value&&node.is_truthy()&&!node.has_side_effects(compressor)){return true}if(node.is_constant()){return!node.evaluate(compressor)==!value}}return fallback(node)}}function get_lvalues(expr){var lvalues=Object.create(null);if(candidate instanceof AST_VarDef){lvalues[candidate.name.name]=lhs}var tw=new TreeWalker(function(node){var sym=root_expr(node);if(sym instanceof AST_SymbolRef||sym instanceof AST_This){lvalues[sym.name]=lvalues[sym.name]||is_modified(compressor,tw,node,node,0)}});expr.walk(tw);return lvalues}function remove_candidate(expr){if(expr.name instanceof AST_SymbolFunarg){var index=compressor.self().argnames.indexOf(expr.name);var args=compressor.parent().args;if(args[index])args[index]=make_node(AST_Number,args[index],{value:0});return true}var found=false;return statements[stat_index].transform(new TreeTransformer(function(node,descend,in_list){if(found)return node;if(node===expr||node.body===expr){found=true;if(node instanceof AST_VarDef){node.value=null;return node}return in_list?MAP.skip:null}},function(node){if(node instanceof AST_Sequence)switch(node.expressions.length){case 0:return null;case 1:return node.expressions[0]}}))}function is_lhs_local(lhs){var sym=root_expr(lhs);return sym instanceof AST_SymbolRef&&sym.definition().scope===scope&&!(in_loop&&(sym.name in lvalues&&lvalues[sym.name]!==lhs||candidate instanceof AST_Unary||candidate instanceof AST_Assign&&candidate.operator!="="))}function value_has_side_effects(expr){if(expr instanceof AST_Unary)return false;return get_rvalue(expr).has_side_effects(compressor)}function replace_all_symbols(){if(side_effects)return false;if(value_def)return true;if(lhs instanceof AST_SymbolRef){var def=lhs.definition();if(def.references.length-def.replaced==(candidate instanceof AST_VarDef?1:2)){return true}}return false}function symbol_in_lvalues(sym,parent){var lvalue=lvalues[sym.name];if(!lvalue)return;if(lvalue!==lhs)return!(parent instanceof AST_Call);scan_rhs=false}function may_modify(sym){var def=sym.definition();if(def.orig.length==1&&def.orig[0]instanceof AST_SymbolDefun)return false;if(def.scope!==scope)return true;return!all(def.references,function(ref){return ref.scope.resolve()===scope})}function side_effects_external(node,lhs){if(node instanceof AST_Assign)return side_effects_external(node.left,true);if(node instanceof AST_Unary)return side_effects_external(node.expression,true);if(node instanceof AST_VarDef)return node.value&&side_effects_external(node.value);if(lhs){if(node instanceof AST_Dot)return side_effects_external(node.expression,true);if(node instanceof AST_Sub)return side_effects_external(node.expression,true);if(node instanceof AST_SymbolRef)return node.definition().scope!==scope}return false}}function eliminate_spurious_blocks(statements){var seen_dirs=[];for(var i=0;i<statements.length;){var stat=statements[i];if(stat instanceof AST_BlockStatement){CHANGED=true;eliminate_spurious_blocks(stat.body);[].splice.apply(statements,[i,1].concat(stat.body));i+=stat.body.length}else if(stat instanceof AST_EmptyStatement){CHANGED=true;statements.splice(i,1)}else if(stat instanceof AST_Directive){if(seen_dirs.indexOf(stat.value)<0){i++;seen_dirs.push(stat.value)}else{CHANGED=true;statements.splice(i,1)}}else i++}}function handle_if_return(statements,compressor){var self=compressor.self();var multiple_if_returns=has_multiple_if_returns(statements);var in_lambda=self instanceof AST_Lambda;for(var i=statements.length;--i>=0;){var stat=statements[i];var j=next_index(i);var next=statements[j];if(in_lambda&&!next&&stat instanceof AST_Return){if(!stat.value){CHANGED=true;statements.splice(i,1);continue}if(stat.value instanceof AST_UnaryPrefix&&stat.value.operator=="void"){CHANGED=true;statements[i]=make_node(AST_SimpleStatement,stat,{body:stat.value.expression});continue}}if(stat instanceof AST_If){var ab=aborts(stat.body);if(can_merge_flow(ab)){if(ab.label){remove(ab.label.thedef.references,ab)}CHANGED=true;stat=stat.clone();stat.condition=stat.condition.negate(compressor);var body=as_statement_array_with_return(stat.body,ab);stat.body=make_node(AST_BlockStatement,stat,{body:as_statement_array(stat.alternative).concat(extract_functions())});stat.alternative=make_node(AST_BlockStatement,stat,{body:body});statements[i]=stat.transform(compressor);continue}if(ab&&!stat.alternative&&stat.body instanceof AST_BlockStatement&&next instanceof AST_Jump){var negated=stat.condition.negate(compressor);if(negated.print_to_string().length<=stat.condition.print_to_string().length){CHANGED=true;stat=stat.clone();stat.condition=negated;statements[j]=stat.body;stat.body=next;statements[i]=stat.transform(compressor);continue}}var ab=aborts(stat.alternative);if(can_merge_flow(ab)){if(ab.label){remove(ab.label.thedef.references,ab)}CHANGED=true;stat=stat.clone();stat.body=make_node(AST_BlockStatement,stat.body,{body:as_statement_array(stat.body).concat(extract_functions())});var body=as_statement_array_with_return(stat.alternative,ab);stat.alternative=make_node(AST_BlockStatement,stat.alternative,{body:body});statements[i]=stat.transform(compressor);continue}}if(stat instanceof AST_If&&stat.body instanceof AST_Return){var value=stat.body.value;if(!value&&!stat.alternative&&(in_lambda&&!next||next instanceof AST_Return&&!next.value)){CHANGED=true;statements[i]=make_node(AST_SimpleStatement,stat.condition,{body:stat.condition});continue}if(value&&!stat.alternative&&next instanceof AST_Return&&next.value){CHANGED=true;stat=stat.clone();stat.alternative=next;statements.splice(i,1,stat.transform(compressor));statements.splice(j,1);continue}if(value&&!stat.alternative&&(!next&&in_lambda&&multiple_if_returns||next instanceof AST_Return)){CHANGED=true;stat=stat.clone();stat.alternative=next||make_node(AST_Return,stat,{value:null});statements.splice(i,1,stat.transform(compressor));if(next)statements.splice(j,1);continue}var prev=statements[prev_index(i)];if(compressor.option("sequences")&&in_lambda&&!stat.alternative&&prev instanceof AST_If&&prev.body instanceof AST_Return&&next_index(j)==statements.length&&next instanceof AST_SimpleStatement){CHANGED=true;stat=stat.clone();stat.alternative=make_node(AST_BlockStatement,next,{body:[next,make_node(AST_Return,next,{value:null})]});statements.splice(i,1,stat.transform(compressor));statements.splice(j,1);continue}}}function has_multiple_if_returns(statements){var n=0;for(var i=statements.length;--i>=0;){var stat=statements[i];if(stat instanceof AST_If&&stat.body instanceof AST_Return){if(++n>1)return true}}return false}function is_return_void(value){return!value||value instanceof AST_UnaryPrefix&&value.operator=="void"}function can_merge_flow(ab){if(!ab)return false;var lct=ab instanceof AST_LoopControl?compressor.loopcontrol_target(ab):null;return ab instanceof AST_Return&&in_lambda&&is_return_void(ab.value)||ab instanceof AST_Continue&&self===loop_body(lct)||ab instanceof AST_Break&&lct instanceof AST_BlockStatement&&self===lct}function extract_functions(){var tail=statements.slice(i+1);statements.length=i+1;return tail.filter(function(stat){if(stat instanceof AST_Defun){statements.push(stat);return false}return true})}function as_statement_array_with_return(node,ab){var body=as_statement_array(node).slice(0,-1);if(ab.value){body.push(make_node(AST_SimpleStatement,ab.value,{body:ab.value.expression}))}return body}function next_index(i){for(var j=i+1,len=statements.length;j<len;j++){var stat=statements[j];if(!(stat instanceof AST_Var&&declarations_only(stat))){break}}return j}function prev_index(i){for(var j=i;--j>=0;){var stat=statements[j];if(!(stat instanceof AST_Var&&declarations_only(stat))){break}}return j}}function eliminate_dead_code(statements,compressor){var has_quit;var self=compressor.self();for(var i=0,n=0,len=statements.length;i<len;i++){var stat=statements[i];if(stat instanceof AST_LoopControl){var lct=compressor.loopcontrol_target(stat);if(stat instanceof AST_Break&&!(lct instanceof AST_IterationStatement)&&loop_body(lct)===self||stat instanceof AST_Continue&&loop_body(lct)===self){if(stat.label){remove(stat.label.thedef.references,stat)}}else{statements[n++]=stat}}else{statements[n++]=stat}if(aborts(stat)){has_quit=statements.slice(i+1);break}}statements.length=n;CHANGED=n!=len;if(has_quit)has_quit.forEach(function(stat){extract_declarations_from_unreachable_code(compressor,stat,statements)})}function declarations_only(node){return all(node.definitions,function(var_def){return!var_def.value})}function sequencesize(statements,compressor){if(statements.length<2)return;var seq=[],n=0;function push_seq(){if(!seq.length)return;var body=make_sequence(seq[0],seq);statements[n++]=make_node(AST_SimpleStatement,body,{body:body});seq=[]}for(var i=0,len=statements.length;i<len;i++){var stat=statements[i];if(stat instanceof AST_SimpleStatement){if(seq.length>=compressor.sequences_limit)push_seq();var body=stat.body;if(seq.length>0)body=body.drop_side_effect_free(compressor);if(body)merge_sequence(seq,body)}else if(stat instanceof AST_Definitions&&declarations_only(stat)||stat instanceof AST_Defun){statements[n++]=stat}else{push_seq();statements[n++]=stat}}push_seq();statements.length=n;if(n!=len)CHANGED=true}function to_simple_statement(block,decls){if(!(block instanceof AST_BlockStatement))return block;var stat=null;for(var i=0,len=block.body.length;i<len;i++){var line=block.body[i];if(line instanceof AST_Var&&declarations_only(line)){decls.push(line)}else if(stat){return false}else{stat=line}}return stat}function sequencesize_2(statements,compressor){function cons_seq(right){n--;CHANGED=true;var left=prev.body;return make_sequence(left,[left,right]).transform(compressor)}var n=0,prev;for(var i=0;i<statements.length;i++){var stat=statements[i];if(prev){if(stat instanceof AST_Exit){stat.value=cons_seq(stat.value||make_node(AST_Undefined,stat).transform(compressor))}else if(stat instanceof AST_For){if(!(stat.init instanceof AST_Definitions)){var abort=false;prev.body.walk(new TreeWalker(function(node){if(abort||node instanceof AST_Scope)return true;if(node instanceof AST_Binary&&node.operator=="in"){abort=true;return true}}));if(!abort){if(stat.init)stat.init=cons_seq(stat.init);else{stat.init=prev.body;n--;CHANGED=true}}}}else if(stat instanceof AST_ForIn){stat.object=cons_seq(stat.object)}else if(stat instanceof AST_If){stat.condition=cons_seq(stat.condition)}else if(stat instanceof AST_Switch){stat.expression=cons_seq(stat.expression)}else if(stat instanceof AST_With){stat.expression=cons_seq(stat.expression)}}if(compressor.option("conditionals")&&stat instanceof AST_If){var decls=[];var body=to_simple_statement(stat.body,decls);var alt=to_simple_statement(stat.alternative,decls);if(body!==false&&alt!==false&&decls.length>0){var len=decls.length;decls.push(make_node(AST_If,stat,{condition:stat.condition,body:body||make_node(AST_EmptyStatement,stat.body),alternative:alt}));decls.unshift(n,1);[].splice.apply(statements,decls);i+=len;n+=len+1;prev=null;CHANGED=true;continue}}statements[n++]=stat;prev=stat instanceof AST_SimpleStatement?stat:null}statements.length=n}function join_assigns(defn,body){var exprs;if(body instanceof AST_Assign){exprs=[body]}else if(body instanceof AST_Sequence){exprs=body.expressions.slice()}if(!exprs)return;if(defn instanceof AST_Definitions){var def=defn.definitions[defn.definitions.length-1];if(trim_assigns(def.name,def.value,exprs))return exprs}for(var i=exprs.length-1;--i>=0;){var expr=exprs[i];if(!(expr instanceof AST_Assign))continue;if(expr.operator!="=")continue;if(!(expr.left instanceof AST_SymbolRef))continue;var tail=exprs.slice(i+1);if(!trim_assigns(expr.left,expr.right,tail))continue;return exprs.slice(0,i+1).concat(tail)}}function trim_assigns(name,value,exprs){if(!(value instanceof AST_Object))return;var trimmed=false;do{var node=exprs[0];if(!(node instanceof AST_Assign))break;if(node.operator!="=")break;if(!(node.left instanceof AST_PropAccess))break;var sym=node.left.expression;if(!(sym instanceof AST_SymbolRef))break;if(name.name!=sym.name)break;if(!node.right.is_constant_expression(scope))break;var prop=node.left.property;if(prop instanceof AST_Node){prop=prop.evaluate(compressor)}if(prop instanceof AST_Node)break;prop=""+prop;var diff=compressor.has_directive("use strict")?function(node){return node.key!=prop&&node.key.name!=prop}:function(node){return node.key.name!=prop};if(!all(value.properties,diff))break;value.properties.push(make_node(AST_ObjectKeyVal,node,{key:prop,value:node.right}));exprs.shift();trimmed=true}while(exprs.length);return trimmed}function join_consecutive_vars(statements){var defs;for(var i=0,j=-1,len=statements.length;i<len;i++){var stat=statements[i];var prev=statements[j];if(stat instanceof AST_Definitions){if(prev&&prev.TYPE==stat.TYPE){prev.definitions=prev.definitions.concat(stat.definitions);CHANGED=true}else if(defs&&defs.TYPE==stat.TYPE&&declarations_only(stat)){defs.definitions=defs.definitions.concat(stat.definitions);CHANGED=true}else{statements[++j]=stat;defs=stat}}else if(stat instanceof AST_Exit){stat.value=join_assigns_expr(stat.value)}else if(stat instanceof AST_For){var exprs=join_assigns(prev,stat.init);if(exprs){CHANGED=true;stat.init=exprs.length?make_sequence(stat.init,exprs):null;statements[++j]=stat}else if(prev instanceof AST_Var&&(!stat.init||stat.init.TYPE==prev.TYPE)){if(stat.init){prev.definitions=prev.definitions.concat(stat.init.definitions)}stat.init=prev;statements[j]=stat;CHANGED=true}else if(defs&&stat.init&&defs.TYPE==stat.init.TYPE&&declarations_only(stat.init)){defs.definitions=defs.definitions.concat(stat.init.definitions);stat.init=null;statements[++j]=stat;CHANGED=true}else{statements[++j]=stat}}else if(stat instanceof AST_ForIn){stat.object=join_assigns_expr(stat.object)}else if(stat instanceof AST_If){stat.condition=join_assigns_expr(stat.condition)}else if(stat instanceof AST_SimpleStatement){var exprs=join_assigns(prev,stat.body);if(exprs){CHANGED=true;if(!exprs.length)continue;stat.body=make_sequence(stat.body,exprs)}statements[++j]=stat}else if(stat instanceof AST_Switch){stat.expression=join_assigns_expr(stat.expression)}else if(stat instanceof AST_With){stat.expression=join_assigns_expr(stat.expression)}else{statements[++j]=stat}}statements.length=j+1;function join_assigns_expr(value){statements[++j]=stat;var exprs=join_assigns(prev,value);if(!exprs)return value;CHANGED=true;var tail=value.tail_node();if(exprs[exprs.length-1]!==tail)exprs.push(tail.left);return make_sequence(value,exprs)}}}function extract_declarations_from_unreachable_code(compressor,stat,target){if(!(stat instanceof AST_Defun)){compressor.warn("Dropping unreachable code [{file}:{line},{col}]",stat.start)}stat.walk(new TreeWalker(function(node){if(node instanceof AST_Definitions){compressor.warn("Declarations in unreachable code! [{file}:{line},{col}]",node.start);node.remove_initializers();target.push(node);return true}if(node instanceof AST_Defun){target.push(node);return true}if(node instanceof AST_Scope){return true}}))}function get_value(key){if(key instanceof AST_Constant){return key.getValue()}if(key instanceof AST_UnaryPrefix&&key.operator=="void"&&key.expression instanceof AST_Constant){return}return key}function is_undefined(node,compressor){return node.is_undefined||node instanceof AST_Undefined||node instanceof AST_UnaryPrefix&&node.operator=="void"&&!node.expression.has_side_effects(compressor)}(function(def){def(AST_Node,return_false);def(AST_Array,return_true);def(AST_Assign,function(){return this.operator=="="&&this.right.is_truthy()});def(AST_Lambda,return_true);def(AST_Object,return_true);def(AST_RegExp,return_true);def(AST_Sequence,function(){return this.tail_node().is_truthy()});def(AST_SymbolRef,function(){var fixed=this.fixed_value();return fixed&&fixed.is_truthy()})})(function(node,func){node.DEFMETHOD("is_truthy",func)});(function(def){AST_Node.DEFMETHOD("may_throw_on_access",function(compressor){return!compressor.option("pure_getters")||this._dot_throw(compressor)});function is_strict(compressor){return/strict/.test(compressor.option("pure_getters"))}def(AST_Node,is_strict);def(AST_Null,return_true);def(AST_Undefined,return_true);def(AST_Constant,return_false);def(AST_Array,return_false);def(AST_Object,function(compressor){if(!is_strict(compressor))return false;for(var i=this.properties.length;--i>=0;)if(this.properties[i].value instanceof AST_Accessor)return true;return false});def(AST_Lambda,return_false);def(AST_UnaryPostfix,return_false);def(AST_UnaryPrefix,function(){return this.operator=="void"});def(AST_Binary,function(compressor){return(this.operator=="&&"||this.operator=="||")&&(this.left._dot_throw(compressor)||this.right._dot_throw(compressor))});def(AST_Assign,function(compressor){return this.operator=="="&&this.right._dot_throw(compressor)});def(AST_Conditional,function(compressor){return this.consequent._dot_throw(compressor)||this.alternative._dot_throw(compressor)});def(AST_Dot,function(compressor){if(!is_strict(compressor))return false;var exp=this.expression;if(exp instanceof AST_SymbolRef)exp=exp.fixed_value();return!(exp instanceof AST_Lambda&&this.property=="prototype")});def(AST_Sequence,function(compressor){return this.tail_node()._dot_throw(compressor)});def(AST_SymbolRef,function(compressor){if(this.is_undefined)return true;if(!is_strict(compressor))return false;if(is_undeclared_ref(this)&&this.is_declared(compressor))return false;if(this.is_immutable())return false;var fixed=this.fixed_value();return!fixed||fixed._dot_throw(compressor)})})(function(node,func){node.DEFMETHOD("_dot_throw",func)});(function(def){def(AST_Node,return_false);def(AST_Assign,function(compressor){return this.operator=="="&&this.right.is_boolean(compressor)});var binary=makePredicate("in instanceof == != === !== < <= >= >");def(AST_Binary,function(compressor){return binary[this.operator]||lazy_op[this.operator]&&this.left.is_boolean(compressor)&&this.right.is_boolean(compressor)});def(AST_Boolean,return_true);var fn=makePredicate("every hasOwnProperty isPrototypeOf propertyIsEnumerable some");def(AST_Call,function(compressor){if(!compressor.option("unsafe"))return false;var exp=this.expression;return exp instanceof AST_Dot&&(fn[exp.property]||exp.property=="test"&&exp.expression instanceof AST_RegExp)});def(AST_Conditional,function(compressor){return this.consequent.is_boolean(compressor)&&this.alternative.is_boolean(compressor)});def(AST_New,return_false);def(AST_Sequence,function(compressor){return this.tail_node().is_boolean(compressor)});var unary=makePredicate("! delete");def(AST_UnaryPrefix,function(){return unary[this.operator]})})(function(node,func){node.DEFMETHOD("is_boolean",func)});(function(def){def(AST_Node,return_false);var binary=makePredicate("- * / % & | ^ << >> >>>");def(AST_Assign,function(compressor){return binary[this.operator.slice(0,-1)]||this.operator=="="&&this.right.is_number(compressor)});def(AST_Binary,function(compressor){return binary[this.operator]||this.operator=="+"&&this.left.is_number(compressor)&&this.right.is_number(compressor)});var fn=makePredicate(["charCodeAt","getDate","getDay","getFullYear","getHours","getMilliseconds","getMinutes","getMonth","getSeconds","getTime","getTimezoneOffset","getUTCDate","getUTCDay","getUTCFullYear","getUTCHours","getUTCMilliseconds","getUTCMinutes","getUTCMonth","getUTCSeconds","getYear","indexOf","lastIndexOf","localeCompare","push","search","setDate","setFullYear","setHours","setMilliseconds","setMinutes","setMonth","setSeconds","setTime","setUTCDate","setUTCFullYear","setUTCHours","setUTCMilliseconds","setUTCMinutes","setUTCMonth","setUTCSeconds","setYear","toExponential","toFixed","toPrecision"]);def(AST_Call,function(compressor){if(!compressor.option("unsafe"))return false;var exp=this.expression;return exp instanceof AST_Dot&&(fn[exp.property]||is_undeclared_ref(exp.expression)&&exp.expression.name=="Math")});def(AST_Conditional,function(compressor){return this.consequent.is_number(compressor)&&this.alternative.is_number(compressor)});def(AST_New,return_false);def(AST_Number,return_true);def(AST_Sequence,function(compressor){return this.tail_node().is_number(compressor)});var unary=makePredicate("+ - ~ ++ --");def(AST_Unary,function(){return unary[this.operator]})})(function(node,func){node.DEFMETHOD("is_number",func)});(function(def){def(AST_Node,return_false);def(AST_String,return_true);def(AST_UnaryPrefix,function(){return this.operator=="typeof"});def(AST_Binary,function(compressor){return this.operator=="+"&&(this.left.is_string(compressor)||this.right.is_string(compressor))});def(AST_Assign,function(compressor){return(this.operator=="="||this.operator=="+=")&&this.right.is_string(compressor)});def(AST_Sequence,function(compressor){return this.tail_node().is_string(compressor)});def(AST_Conditional,function(compressor){return this.consequent.is_string(compressor)&&this.alternative.is_string(compressor)})})(function(node,func){node.DEFMETHOD("is_string",func)});var lazy_op=makePredicate("&& ||");var unary_side_effects=makePredicate("delete ++ --");function is_lhs(node,parent){if(parent instanceof AST_Unary&&unary_side_effects[parent.operator])return parent.expression;if(parent instanceof AST_Assign&&parent.left===node)return node}(function(def){function to_node(value,orig){if(value instanceof AST_Node)return make_node(value.CTOR,orig,value);if(Array.isArray(value))return make_node(AST_Array,orig,{elements:value.map(function(value){return to_node(value,orig)})});if(value&&typeof value=="object"){var props=[];for(var key in value)if(HOP(value,key)){props.push(make_node(AST_ObjectKeyVal,orig,{key:key,value:to_node(value[key],orig)}))}return make_node(AST_Object,orig,{properties:props})}return make_node_from_constant(value,orig)}function warn(compressor,node){compressor.warn("global_defs "+node.print_to_string()+" redefined [{file}:{line},{col}]",node.start)}AST_Toplevel.DEFMETHOD("resolve_defines",function(compressor){if(!compressor.option("global_defs"))return this;this.figure_out_scope({ie8:compressor.option("ie8")});return this.transform(new TreeTransformer(function(node){var def=node._find_defs(compressor,"");if(!def)return;var level=0,child=node,parent;while(parent=this.parent(level++)){if(!(parent instanceof AST_PropAccess))break;if(parent.expression!==child)break;child=parent}if(is_lhs(child,parent)){warn(compressor,node);return}return def}))});def(AST_Node,noop);def(AST_Dot,function(compressor,suffix){return this.expression._find_defs(compressor,"."+this.property+suffix)});def(AST_SymbolDeclaration,function(compressor){if(!this.global())return;if(HOP(compressor.option("global_defs"),this.name))warn(compressor,this)});def(AST_SymbolRef,function(compressor,suffix){if(!this.global())return;var defines=compressor.option("global_defs");var name=this.name+suffix;if(HOP(defines,name))return to_node(defines[name],this)})})(function(node,func){node.DEFMETHOD("_find_defs",func)});function best_of_expression(ast1,ast2){return ast1.print_to_string().length>ast2.print_to_string().length?ast2:ast1}function best_of_statement(ast1,ast2){return best_of_expression(make_node(AST_SimpleStatement,ast1,{body:ast1}),make_node(AST_SimpleStatement,ast2,{body:ast2})).body}function best_of(compressor,ast1,ast2){return(first_in_statement(compressor)?best_of_statement:best_of_expression)(ast1,ast2)}function convert_to_predicate(obj){for(var key in obj){obj[key]=makePredicate(obj[key])}}var object_fns=["constructor","toString","valueOf"];var native_fns={Array:["indexOf","join","lastIndexOf","slice"].concat(object_fns),Boolean:object_fns,Function:object_fns,Number:["toExponential","toFixed","toPrecision"].concat(object_fns),Object:object_fns,RegExp:["test"].concat(object_fns),String:["charAt","charCodeAt","concat","indexOf","italics","lastIndexOf","match","replace","search","slice","split","substr","substring","toLowerCase","toUpperCase","trim"].concat(object_fns)};convert_to_predicate(native_fns);var static_fns={Array:["isArray"],Math:["abs","acos","asin","atan","ceil","cos","exp","floor","log","round","sin","sqrt","tan","atan2","pow","max","min"],Number:["isFinite","isNaN"],Object:["create","getOwnPropertyDescriptor","getOwnPropertyNames","getPrototypeOf","isExtensible","isFrozen","isSealed","keys"],String:["fromCharCode"]};convert_to_predicate(static_fns);(function(def){AST_Node.DEFMETHOD("evaluate",function(compressor){if(!compressor.option("evaluate"))return this;var cached=[];var val=this._eval(compressor,cached,1);cached.forEach(function(node){delete node._eval});if(!val||val instanceof RegExp)return val;if(typeof val=="function"||typeof val=="object")return this;return val});var unaryPrefix=makePredicate("! ~ - + void");AST_Node.DEFMETHOD("is_constant",function(){if(this instanceof AST_Constant){return!(this instanceof AST_RegExp)}else{return this instanceof AST_UnaryPrefix&&this.expression instanceof AST_Constant&&unaryPrefix[this.operator]}});def(AST_Statement,function(){throw new Error(string_template("Cannot evaluate a statement [{file}:{line},{col}]",this.start))});def(AST_Lambda,return_this);def(AST_Node,return_this);def(AST_Constant,function(){return this.getValue()});def(AST_Function,function(compressor){if(compressor.option("unsafe")){var fn=function(){};fn.node=this;fn.toString=function(){return"function(){}"};return fn}return this});def(AST_Array,function(compressor,cached,depth){if(compressor.option("unsafe")){var elements=[];for(var i=0,len=this.elements.length;i<len;i++){var element=this.elements[i];var value=element._eval(compressor,cached,depth);if(element===value)return this;elements.push(value)}return elements}return this});def(AST_Object,function(compressor,cached,depth){if(compressor.option("unsafe")){var val={};for(var i=0,len=this.properties.length;i<len;i++){var prop=this.properties[i];var key=prop.key;if(key instanceof AST_Symbol){key=key.name}else if(key instanceof AST_Node){key=key._eval(compressor,cached,depth);if(key===prop.key)return this}if(typeof Object.prototype[key]==="function"){return this}if(prop.value instanceof AST_Function)continue;val[key]=prop.value._eval(compressor,cached,depth);if(val[key]===prop.value)return this}return val}return this});var non_converting_unary=makePredicate("! typeof void");def(AST_UnaryPrefix,function(compressor,cached,depth){var e=this.expression;if(compressor.option("typeofs")&&this.operator=="typeof"&&(e instanceof AST_Lambda||e instanceof AST_SymbolRef&&e.fixed_value()instanceof AST_Lambda)){return typeof function(){}}if(!non_converting_unary[this.operator])depth++;e=e._eval(compressor,cached,depth);if(e===this.expression)return this;switch(this.operator){case"!":return!e;case"typeof":if(e instanceof RegExp)return this;return typeof e;case"void":return void e;case"~":return~e;case"-":return-e;case"+":return+e}return this});var non_converting_binary=makePredicate("&& || === !==");def(AST_Binary,function(compressor,cached,depth){if(!non_converting_binary[this.operator])depth++;var left=this.left._eval(compressor,cached,depth);if(left===this.left)return this;var right=this.right._eval(compressor,cached,depth);if(right===this.right)return this;var result;switch(this.operator){case"&&":result=left&&right;break;case"||":result=left||right;break;case"|":result=left|right;break;case"&":result=left&right;break;case"^":result=left^right;break;case"+":result=left+right;break;case"*":result=left*right;break;case"/":result=left/right;break;case"%":result=left%right;break;case"-":result=left-right;break;case"<<":result=left<<right;break;case">>":result=left>>right;break;case">>>":result=left>>>right;break;case"==":result=left==right;break;case"===":result=left===right;break;case"!=":result=left!=right;break;case"!==":result=left!==right;break;case"<":result=left<right;break;case"<=":result=left<=right;break;case">":result=left>right;break;case">=":result=left>=right;break;default:return this}return isNaN(result)&&compressor.find_parent(AST_With)?this:result});def(AST_Conditional,function(compressor,cached,depth){var condition=this.condition._eval(compressor,cached,depth);if(condition===this.condition)return this;var node=condition?this.consequent:this.alternative;var value=node._eval(compressor,cached,depth);return value===node?this:value});def(AST_SymbolRef,function(compressor,cached,depth){var fixed=this.fixed_value();if(!fixed)return this;var value;if(cached.indexOf(fixed)>=0){value=fixed._eval()}else{this._eval=return_this;value=fixed._eval(compressor,cached,depth);delete this._eval;if(value===fixed)return this;fixed._eval=function(){return value};cached.push(fixed)}if(value&&typeof value=="object"){var escaped=this.definition().escaped;if(escaped&&depth>escaped)return this}return value});var global_objs={Array:Array,Math:Math,Number:Number,Object:Object,String:String};var static_values={Math:["E","LN10","LN2","LOG2E","LOG10E","PI","SQRT1_2","SQRT2"],Number:["MAX_VALUE","MIN_VALUE","NaN","NEGATIVE_INFINITY","POSITIVE_INFINITY"]};convert_to_predicate(static_values);def(AST_PropAccess,function(compressor,cached,depth){if(compressor.option("unsafe")){var key=this.property;if(key instanceof AST_Node){key=key._eval(compressor,cached,depth);if(key===this.property)return this}var exp=this.expression;var val;if(is_undeclared_ref(exp)){var static_value=static_values[exp.name];if(!static_value||!static_value[key])return this;val=global_objs[exp.name]}else{val=exp._eval(compressor,cached,depth+1);if(!val||val===exp||!HOP(val,key))return this;if(typeof val=="function")switch(key){case"name":return val.node.name?val.node.name.name:"";case"length":return val.node.argnames.length;default:return this}}return val[key]}return this});def(AST_Call,function(compressor,cached,depth){var exp=this.expression;if(compressor.option("unsafe")&&exp instanceof AST_PropAccess){var key=exp.property;if(key instanceof AST_Node){key=key._eval(compressor,cached,depth);if(key===exp.property)return this}var val;var e=exp.expression;if(is_undeclared_ref(e)){var static_fn=static_fns[e.name];if(!static_fn||!static_fn[key])return this;val=global_objs[e.name]}else{val=e._eval(compressor,cached,depth+1);if(val===e||!val)return this;var native_fn=native_fns[val.constructor.name];if(!native_fn||!native_fn[key])return this}var args=[];for(var i=0,len=this.args.length;i<len;i++){var arg=this.args[i];var value=arg._eval(compressor,cached,depth);if(arg===value)return this;args.push(value)}try{return val[key].apply(val,args)}catch(ex){compressor.warn("Error evaluating {code} [{file}:{line},{col}]",{code:this.print_to_string(),file:this.start.file,line:this.start.line,col:this.start.col})}}return this});def(AST_New,return_this)})(function(node,func){node.DEFMETHOD("_eval",func)});(function(def){function basic_negation(exp){return make_node(AST_UnaryPrefix,exp,{operator:"!",expression:exp})}function best(orig,alt,first_in_statement){var negated=basic_negation(orig);if(first_in_statement){var stat=make_node(AST_SimpleStatement,alt,{body:alt});return best_of_expression(negated,stat)===stat?alt:negated}return best_of_expression(negated,alt)}def(AST_Node,function(){return basic_negation(this)});def(AST_Statement,function(){throw new Error("Cannot negate a statement")});def(AST_Function,function(){return basic_negation(this)});def(AST_UnaryPrefix,function(){if(this.operator=="!")return this.expression;return basic_negation(this)});def(AST_Sequence,function(compressor){var expressions=this.expressions.slice();expressions.push(expressions.pop().negate(compressor));return make_sequence(this,expressions)});def(AST_Conditional,function(compressor,first_in_statement){var self=this.clone();self.consequent=self.consequent.negate(compressor);self.alternative=self.alternative.negate(compressor);return best(this,self,first_in_statement)});def(AST_Binary,function(compressor,first_in_statement){var self=this.clone(),op=this.operator;if(compressor.option("unsafe_comps")){switch(op){case"<=":self.operator=">";return self;case"<":self.operator=">=";return self;case">=":self.operator="<";return self;case">":self.operator="<=";return self}}switch(op){case"==":self.operator="!=";return self;case"!=":self.operator="==";return self;case"===":self.operator="!==";return self;case"!==":self.operator="===";return self;case"&&":self.operator="||";self.left=self.left.negate(compressor,first_in_statement);self.right=self.right.negate(compressor);return best(this,self,first_in_statement);case"||":self.operator="&&";self.left=self.left.negate(compressor,first_in_statement);self.right=self.right.negate(compressor);return best(this,self,first_in_statement)}return basic_negation(this)})})(function(node,func){node.DEFMETHOD("negate",function(compressor,first_in_statement){return func.call(this,compressor,first_in_statement)})});var global_pure_fns=makePredicate("Boolean decodeURI decodeURIComponent Date encodeURI encodeURIComponent Error escape EvalError isFinite isNaN Number Object parseFloat parseInt RangeError ReferenceError String SyntaxError TypeError unescape URIError");AST_Call.DEFMETHOD("is_expr_pure",function(compressor){if(compressor.option("unsafe")){var expr=this.expression;if(is_undeclared_ref(expr)&&global_pure_fns[expr.name])return true;if(expr instanceof AST_Dot&&is_undeclared_ref(expr.expression)){var static_fn=static_fns[expr.expression.name];return static_fn&&static_fn[expr.property]}}return this.pure||!compressor.pure_funcs(this)});AST_Node.DEFMETHOD("is_call_pure",return_false);AST_Dot.DEFMETHOD("is_call_pure",function(compressor){if(!compressor.option("unsafe"))return;var expr=this.expression;var map;if(expr instanceof AST_Array){map=native_fns.Array}else if(expr.is_boolean(compressor)){map=native_fns.Boolean}else if(expr.is_number(compressor)){map=native_fns.Number}else if(expr instanceof AST_RegExp){map=native_fns.RegExp}else if(expr.is_string(compressor)){map=native_fns.String}else if(!this.may_throw_on_access(compressor)){map=native_fns.Object}return map&&map[this.property]});(function(def){function any(list,compressor){for(var i=list.length;--i>=0;)if(list[i].has_side_effects(compressor))return true;return false}def(AST_Node,return_true);def(AST_Array,function(compressor){return any(this.elements,compressor)});def(AST_Assign,return_true);def(AST_Binary,function(compressor){return this.left.has_side_effects(compressor)||this.right.has_side_effects(compressor)});def(AST_Block,function(compressor){return any(this.body,compressor)});def(AST_Call,function(compressor){if(!this.is_expr_pure(compressor)&&(!this.expression.is_call_pure(compressor)||this.expression.has_side_effects(compressor))){return true}return any(this.args,compressor)});def(AST_Case,function(compressor){return this.expression.has_side_effects(compressor)||any(this.body,compressor)});def(AST_Conditional,function(compressor){return this.condition.has_side_effects(compressor)||this.consequent.has_side_effects(compressor)||this.alternative.has_side_effects(compressor)});def(AST_Constant,return_false);def(AST_Definitions,function(compressor){return any(this.definitions,compressor)});def(AST_Dot,function(compressor){return this.expression.may_throw_on_access(compressor)||this.expression.has_side_effects(compressor)});def(AST_EmptyStatement,return_false);def(AST_If,function(compressor){return this.condition.has_side_effects(compressor)||this.body&&this.body.has_side_effects(compressor)||this.alternative&&this.alternative.has_side_effects(compressor)});def(AST_LabeledStatement,function(compressor){return this.body.has_side_effects(compressor)});def(AST_Lambda,return_false);def(AST_Object,function(compressor){return any(this.properties,compressor)});def(AST_ObjectProperty,function(compressor){return this.value.has_side_effects(compressor)});def(AST_Sub,function(compressor){return this.expression.may_throw_on_access(compressor)||this.expression.has_side_effects(compressor)||this.property.has_side_effects(compressor)});def(AST_Sequence,function(compressor){return any(this.expressions,compressor)});def(AST_SimpleStatement,function(compressor){return this.body.has_side_effects(compressor)});def(AST_Switch,function(compressor){return this.expression.has_side_effects(compressor)||any(this.body,compressor)});def(AST_SymbolDeclaration,return_false);def(AST_SymbolRef,function(compressor){return!this.is_declared(compressor)});def(AST_This,return_false);def(AST_Try,function(compressor){return any(this.body,compressor)||this.bcatch&&this.bcatch.has_side_effects(compressor)||this.bfinally&&this.bfinally.has_side_effects(compressor)});def(AST_Unary,function(compressor){return unary_side_effects[this.operator]||this.expression.has_side_effects(compressor)});def(AST_VarDef,function(compressor){return this.value})})(function(node,func){node.DEFMETHOD("has_side_effects",func)});(function(def){def(AST_Node,return_true);def(AST_Constant,return_false);def(AST_EmptyStatement,return_false);def(AST_Lambda,return_false);def(AST_SymbolDeclaration,return_false);def(AST_This,return_false);function any(list,compressor){for(var i=list.length;--i>=0;)if(list[i].may_throw(compressor))return true;return false}def(AST_Array,function(compressor){return any(this.elements,compressor)});def(AST_Assign,function(compressor){if(this.right.may_throw(compressor))return true;if(!compressor.has_directive("use strict")&&this.operator=="="&&this.left instanceof AST_SymbolRef){return false}return this.left.may_throw(compressor)});def(AST_Binary,function(compressor){return this.left.may_throw(compressor)||this.right.may_throw(compressor)});def(AST_Block,function(compressor){return any(this.body,compressor)});def(AST_Call,function(compressor){if(any(this.args,compressor))return true;if(this.is_expr_pure(compressor))return false;if(this.expression.may_throw(compressor))return true;return!(this.expression instanceof AST_Lambda)||any(this.expression.body,compressor)});def(AST_Case,function(compressor){return this.expression.may_throw(compressor)||any(this.body,compressor)});def(AST_Conditional,function(compressor){return this.condition.may_throw(compressor)||this.consequent.may_throw(compressor)||this.alternative.may_throw(compressor)});def(AST_Definitions,function(compressor){return any(this.definitions,compressor)});def(AST_Dot,function(compressor){return this.expression.may_throw_on_access(compressor)||this.expression.may_throw(compressor)});def(AST_If,function(compressor){return this.condition.may_throw(compressor)||this.body&&this.body.may_throw(compressor)||this.alternative&&this.alternative.may_throw(compressor)});def(AST_LabeledStatement,function(compressor){return this.body.may_throw(compressor)});def(AST_Object,function(compressor){return any(this.properties,compressor)});def(AST_ObjectProperty,function(compressor){return this.value.may_throw(compressor)});def(AST_Return,function(compressor){return this.value&&this.value.may_throw(compressor)});def(AST_Sequence,function(compressor){return any(this.expressions,compressor)});def(AST_SimpleStatement,function(compressor){return this.body.may_throw(compressor)});def(AST_Sub,function(compressor){return this.expression.may_throw_on_access(compressor)||this.expression.may_throw(compressor)||this.property.may_throw(compressor)});def(AST_Switch,function(compressor){return this.expression.may_throw(compressor)||any(this.body,compressor)});def(AST_SymbolRef,function(compressor){return!this.is_declared(compressor)});def(AST_Try,function(compressor){return this.bcatch?this.bcatch.may_throw(compressor):any(this.body,compressor)||this.bfinally&&this.bfinally.may_throw(compressor)});def(AST_Unary,function(compressor){if(this.operator=="typeof"&&this.expression instanceof AST_SymbolRef)return false;return this.expression.may_throw(compressor)});def(AST_VarDef,function(compressor){if(!this.value)return false;return this.value.may_throw(compressor)})})(function(node,func){node.DEFMETHOD("may_throw",func)});(function(def){function all(list){for(var i=list.length;--i>=0;)if(!list[i].is_constant_expression())return false;return true}def(AST_Node,return_false);def(AST_Constant,return_true);def(AST_Lambda,function(scope){var self=this;var result=true;self.walk(new TreeWalker(function(node){if(!result)return true;if(node instanceof AST_SymbolRef){if(self.inlined){result=false;return true}var def=node.definition();if(member(def,self.enclosed)&&!self.variables.has(def.name)){if(scope){var scope_def=scope.find_variable(node);if(def.undeclared?!scope_def:scope_def===def){result="f";return true}}result=false}return true}}));return result});def(AST_Unary,function(){return this.expression.is_constant_expression()});def(AST_Binary,function(){return this.left.is_constant_expression()&&this.right.is_constant_expression()});def(AST_Array,function(){return all(this.elements)});def(AST_Object,function(){return all(this.properties)});def(AST_ObjectProperty,function(){return this.value.is_constant_expression()})})(function(node,func){node.DEFMETHOD("is_constant_expression",func)});function aborts(thing){return thing&&thing.aborts()}(function(def){def(AST_Statement,return_null);def(AST_Jump,return_this);function block_aborts(){var n=this.body.length;return n>0&&aborts(this.body[n-1])}def(AST_BlockStatement,block_aborts);def(AST_SwitchBranch,block_aborts);def(AST_If,function(){return this.alternative&&aborts(this.body)&&aborts(this.alternative)&&this})})(function(node,func){node.DEFMETHOD("aborts",func)});var directives=makePredicate(["use asm","use strict"]);OPT(AST_Directive,function(self,compressor){if(compressor.option("directives")&&(!directives[self.value]||compressor.has_directive(self.value)!==self)){return make_node(AST_EmptyStatement,self)}return self});OPT(AST_Debugger,function(self,compressor){if(compressor.option("drop_debugger"))return make_node(AST_EmptyStatement,self);return self});OPT(AST_LabeledStatement,function(self,compressor){if(self.body instanceof AST_Break&&compressor.loopcontrol_target(self.body)===self.body){return make_node(AST_EmptyStatement,self)}return self.label.references.length==0?self.body:self});OPT(AST_Block,function(self,compressor){tighten_body(self.body,compressor);return self});OPT(AST_BlockStatement,function(self,compressor){tighten_body(self.body,compressor);switch(self.body.length){case 1:return self.body[0];case 0:return make_node(AST_EmptyStatement,self)}return self});OPT(AST_Lambda,function(self,compressor){tighten_body(self.body,compressor);if(compressor.option("side_effects")&&self.body.length==1&&self.body[0]===compressor.has_directive("use strict")){self.body.length=0}return self});AST_Scope.DEFMETHOD("drop_unused",function(compressor){if(!compressor.option("unused"))return;if(compressor.has_directive("use asm"))return;var self=this;if(self.pinned())return;var drop_funcs=!(self instanceof AST_Toplevel)||compressor.toplevel.funcs;var drop_vars=!(self instanceof AST_Toplevel)||compressor.toplevel.vars;var assign_as_unused=/keep_assign/.test(compressor.option("unused"))?return_false:function(node,props){var sym;if(node instanceof AST_Assign&&(node.write_only||node.operator=="=")){sym=node.left}else if(node instanceof AST_Unary&&node.write_only){sym=node.expression}if(!/strict/.test(compressor.option("pure_getters")))return sym instanceof AST_SymbolRef&&sym;while(sym instanceof AST_PropAccess&&!sym.expression.may_throw_on_access(compressor)){if(sym instanceof AST_Sub)props.unshift(sym.property);sym=sym.expression}return sym instanceof AST_SymbolRef&&all(sym.definition().orig,function(sym){return!(sym instanceof AST_SymbolLambda)})&&sym};var in_use=[];var in_use_ids=Object.create(null);var fixed_ids=Object.create(null);var value_read=Object.create(null);var value_modified=Object.create(null);if(self instanceof AST_Toplevel&&compressor.top_retain){self.variables.each(function(def){if(compressor.top_retain(def)&&!(def.id in in_use_ids)){in_use_ids[def.id]=true;in_use.push(def)}})}var var_defs_by_id=new Dictionary;var initializations=new Dictionary;var scope=this;var tw=new TreeWalker(function(node,descend){if(node instanceof AST_Lambda&&node.uses_arguments&&!tw.has_directive("use strict")){node.argnames.forEach(function(argname){var def=argname.definition();if(!(def.id in in_use_ids)){in_use_ids[def.id]=true;in_use.push(def)}})}if(node===self)return;if(node instanceof AST_Defun){var node_def=node.name.definition();if(!drop_funcs&&scope===self){if(!(node_def.id in in_use_ids)){in_use_ids[node_def.id]=true;in_use.push(node_def)}}initializations.add(node_def.id,node);return true}if(node instanceof AST_SymbolFunarg&&scope===self){var_defs_by_id.add(node.definition().id,node)}if(node instanceof AST_Definitions&&scope===self){node.definitions.forEach(function(def){var node_def=def.name.definition();if(def.name instanceof AST_SymbolVar){var_defs_by_id.add(node_def.id,def)}if(!drop_vars){if(!(node_def.id in in_use_ids)){in_use_ids[node_def.id]=true;in_use.push(node_def)}}if(def.value){initializations.add(node_def.id,def.value);if(def.value.has_side_effects(compressor)){def.value.walk(tw)}if(!node_def.chained&&def.name.fixed_value()===def.value){fixed_ids[node_def.id]=def}}});return true}return scan_ref_scoped(node,descend)});self.walk(tw);tw=new TreeWalker(scan_ref_scoped);for(var i=0;i<in_use.length;i++){var init=initializations.get(in_use[i].id);if(init)init.forEach(function(init){init.walk(tw)})}var drop_fn_name=compressor.option("keep_fnames")?return_false:compressor.option("ie8")?function(def){return!compressor.exposed(def)&&!def.references.length}:function(def){return!(def.id in in_use_ids)||def.orig.length>1};var tt=new TreeTransformer(function(node,descend,in_list){var parent=tt.parent();if(drop_vars){var props=[],sym=assign_as_unused(node,props);if(sym){var def=sym.definition();var in_use=def.id in in_use_ids;var value=null;if(node instanceof AST_Assign){if(!in_use||node.left===sym&&def.id in fixed_ids&&fixed_ids[def.id]!==node){value=node.right}}else if(!in_use){value=make_node(AST_Number,node,{value:0})}if(value){props.push(value);return maintain_this_binding(compressor,parent,node,make_sequence(node,props.map(function(prop){return prop.transform(tt)})))}}}if(scope!==self)return;if(node instanceof AST_Function&&node.name&&drop_fn_name(node.name.definition())){node.name=null}if(node instanceof AST_Lambda&&!(node instanceof AST_Accessor)){var trim=!compressor.option("keep_fargs");for(var a=node.argnames,i=a.length;--i>=0;){var sym=a[i];if(!(sym.definition().id in in_use_ids)){sym.__unused=true;if(trim){a.pop();compressor[sym.unreferenced()?"warn":"info"]("Dropping unused function argument {name} [{file}:{line},{col}]",template(sym))}}else{trim=false}}}if(drop_funcs&&node instanceof AST_Defun&&node!==self){var def=node.name.definition();if(!(def.id in in_use_ids)){compressor[node.name.unreferenced()?"warn":"info"]("Dropping unused function {name} [{file}:{line},{col}]",template(node.name));def.eliminated++;return make_node(AST_EmptyStatement,node)}}if(node instanceof AST_Definitions&&!(parent instanceof AST_ForIn&&parent.init===node)){var body=[],head=[],tail=[];var side_effects=[];node.definitions.forEach(function(def){if(def.value)def.value=def.value.transform(tt);var sym=def.name.definition();if(!drop_vars||sym.id in in_use_ids){if(def.value&&sym.id in fixed_ids&&fixed_ids[sym.id]!==def){def.value=def.value.drop_side_effect_free(compressor)}if(def.name instanceof AST_SymbolVar){var var_defs=var_defs_by_id.get(sym.id);if(var_defs.length>1&&(!def.value||sym.orig.indexOf(def.name)>sym.eliminated)){compressor.warn("Dropping duplicated definition of variable {name} [{file}:{line},{col}]",template(def.name));if(def.value){var ref=make_node(AST_SymbolRef,def.name,def.name);sym.references.push(ref);var assign=make_node(AST_Assign,def,{operator:"=",left:ref,right:def.value});if(fixed_ids[sym.id]===def){fixed_ids[sym.id]=assign}side_effects.push(assign.transform(tt))}remove(var_defs,def);sym.eliminated++;return}}if(def.value){if(side_effects.length>0){if(tail.length>0){side_effects.push(def.value);def.value=make_sequence(def.value,side_effects)}else{body.push(make_node(AST_SimpleStatement,node,{body:make_sequence(node,side_effects)}))}side_effects=[]}tail.push(def)}else{head.push(def)}}else if(sym.orig[0]instanceof AST_SymbolCatch){var value=def.value&&def.value.drop_side_effect_free(compressor);if(value)side_effects.push(value);def.value=null;head.push(def)}else{var value=def.value&&def.value.drop_side_effect_free(compressor);if(value){compressor.warn("Side effects in initialization of unused variable {name} [{file}:{line},{col}]",template(def.name));side_effects.push(value)}else{compressor[def.name.unreferenced()?"warn":"info"]("Dropping unused variable {name} [{file}:{line},{col}]",template(def.name))}sym.eliminated++}});if(head.length>0||tail.length>0){node.definitions=head.concat(tail);body.push(node)}if(side_effects.length>0){body.push(make_node(AST_SimpleStatement,node,{body:make_sequence(node,side_effects)}))}switch(body.length){case 0:return in_list?MAP.skip:make_node(AST_EmptyStatement,node);case 1:return body[0];default:return in_list?MAP.splice(body):make_node(AST_BlockStatement,node,{body:body})}}if(node instanceof AST_For){descend(node,this);var block;if(node.init instanceof AST_BlockStatement){block=node.init;node.init=block.body.pop();block.body.push(node)}if(node.init instanceof AST_SimpleStatement){node.init=node.init.body}else if(is_empty(node.init)){node.init=null}return!block?node:in_list?MAP.splice(block.body):block}if(node instanceof AST_LabeledStatement&&node.body instanceof AST_For){descend(node,this);if(node.body instanceof AST_BlockStatement){var block=node.body;node.body=block.body.pop();block.body.push(node);return in_list?MAP.splice(block.body):block}return node}if(node instanceof AST_Scope){var save_scope=scope;scope=node;descend(node,this);scope=save_scope;return node}function template(sym){return{name:sym.name,file:sym.start.file,line:sym.start.line,col:sym.start.col}}});self.transform(tt);function verify_safe_usage(def,read,modified){if(def.id in in_use_ids)return;if(read&&modified){in_use_ids[def.id]=true;in_use.push(def)}else{value_read[def.id]=read;value_modified[def.id]=modified}}function scan_ref_scoped(node,descend){var node_def,props=[],sym=assign_as_unused(node,props);if(sym&&self.variables.get(sym.name)===(node_def=sym.definition())){props.forEach(function(prop){prop.walk(tw)});if(node instanceof AST_Assign){node.right.walk(tw);if(node.left===sym){if(!node_def.chained&&sym.fixed_value()===node.right){fixed_ids[node_def.id]=node}if(!node.write_only){verify_safe_usage(node_def,true,value_modified[node_def.id])}}else{var fixed=sym.fixed_value();if(!fixed||!fixed.is_constant()){verify_safe_usage(node_def,value_read[node_def.id],true)}}}return true}if(node instanceof AST_SymbolRef){node_def=node.definition();if(!(node_def.id in in_use_ids)){in_use_ids[node_def.id]=true;in_use.push(node_def)}return true}if(node instanceof AST_Scope){var save_scope=scope;scope=node;descend();scope=save_scope;return true}}});AST_Scope.DEFMETHOD("hoist_declarations",function(compressor){if(compressor.has_directive("use asm"))return;var hoist_funs=compressor.option("hoist_funs");var hoist_vars=compressor.option("hoist_vars");var self=this;if(hoist_vars){var var_decl=0;self.walk(new TreeWalker(function(node){if(var_decl>1)return true;if(node instanceof AST_Scope&&node!==self)return true;if(node instanceof AST_Var){var_decl++;return true}}));if(var_decl<=1)hoist_vars=false}if(!hoist_funs&&!hoist_vars)return;var dirs=[];var hoisted=[];var vars=new Dictionary,vars_found=0;var tt=new TreeTransformer(function(node){if(node===self)return;if(node instanceof AST_Directive){dirs.push(node);return make_node(AST_EmptyStatement,node)}if(hoist_funs&&node instanceof AST_Defun&&(tt.parent()===self||!compressor.has_directive("use strict"))){hoisted.push(node);return make_node(AST_EmptyStatement,node)}if(hoist_vars&&node instanceof AST_Var){node.definitions.forEach(function(def){vars.set(def.name.name,def);++vars_found});var seq=node.to_assignments(compressor);var p=tt.parent();if(p instanceof AST_ForIn&&p.init===node){if(seq)return seq;var def=node.definitions[0].name;return make_node(AST_SymbolRef,def,def)}if(p instanceof AST_For&&p.init===node)return seq;if(!seq)return make_node(AST_EmptyStatement,node);return make_node(AST_SimpleStatement,node,{body:seq})}if(node instanceof AST_Scope)return node});self.transform(tt);if(vars_found>0){var defs=[];vars.each(function(def,name){if(self instanceof AST_Lambda&&!all(self.argnames,function(argname){return argname.name!=name})){vars.del(name)}else{def=def.clone();def.value=null;defs.push(def);vars.set(name,def)}});if(defs.length>0){for(var i=0;i<self.body.length;){if(self.body[i]instanceof AST_SimpleStatement){var expr=self.body[i].body,sym,assign;if(expr instanceof AST_Assign&&expr.operator=="="&&(sym=expr.left)instanceof AST_Symbol&&vars.has(sym.name)){var def=vars.get(sym.name);if(def.value)break;def.value=expr.right;remove(defs,def);defs.push(def);self.body.splice(i,1);continue}if(expr instanceof AST_Sequence&&(assign=expr.expressions[0])instanceof AST_Assign&&assign.operator=="="&&(sym=assign.left)instanceof AST_Symbol&&vars.has(sym.name)){var def=vars.get(sym.name);if(def.value)break;def.value=assign.right;remove(defs,def);defs.push(def);self.body[i].body=make_sequence(expr,expr.expressions.slice(1));continue}}if(self.body[i]instanceof AST_EmptyStatement){self.body.splice(i,1);continue}if(self.body[i]instanceof AST_BlockStatement){var tmp=[i,1].concat(self.body[i].body);self.body.splice.apply(self.body,tmp);continue}break}defs=make_node(AST_Var,self,{definitions:defs});hoisted.push(defs)}}self.body=dirs.concat(hoisted,self.body)});AST_Scope.DEFMETHOD("var_names",function(){var var_names=this._var_names;if(!var_names){this._var_names=var_names=Object.create(null);this.enclosed.forEach(function(def){var_names[def.name]=true});this.variables.each(function(def,name){var_names[name]=true})}return var_names});AST_Scope.DEFMETHOD("make_var_name",function(prefix){var var_names=this.var_names();prefix=prefix.replace(/(?:^[^a-z_$]|[^a-z0-9_$])/gi,"_");var name=prefix;for(var i=0;var_names[name];i++)name=prefix+"$"+i;var_names[name]=true;return name});AST_Scope.DEFMETHOD("hoist_properties",function(compressor){if(!compressor.option("hoist_props")||compressor.has_directive("use asm"))return;var self=this;var top_retain=self instanceof AST_Toplevel&&compressor.top_retain||return_false;var defs_by_id=Object.create(null);self.transform(new TreeTransformer(function(node,descend){if(node instanceof AST_Assign&&node.operator=="="&&node.write_only&&can_hoist(node.left,node.right,1)){descend(node,this);var defs=new Dictionary;var assignments=[];var decls=[];node.right.properties.forEach(function(prop){var decl=make_sym(node.left,prop.key);decls.push(make_node(AST_VarDef,node,{name:decl,value:null}));var sym=make_node(AST_SymbolRef,node,{name:decl.name,scope:self,thedef:decl.definition()});sym.reference({});assignments.push(make_node(AST_Assign,node,{operator:"=",left:sym,right:prop.value}))});defs_by_id[node.left.definition().id]=defs;self.body.splice(self.body.indexOf(this.stack[1])+1,0,make_node(AST_Var,node,{definitions:decls}));return make_sequence(node,assignments)}if(node instanceof AST_VarDef&&can_hoist(node.name,node.value,0)){descend(node,this);var defs=new Dictionary;var var_defs=[];node.value.properties.forEach(function(prop){var_defs.push(make_node(AST_VarDef,node,{name:make_sym(node.name,prop.key),value:prop.value}))});defs_by_id[node.name.definition().id]=defs;return MAP.splice(var_defs)}if(node instanceof AST_PropAccess&&node.expression instanceof AST_SymbolRef){var defs=defs_by_id[node.expression.definition().id];if(defs){var def=defs.get(get_value(node.property));var sym=make_node(AST_SymbolRef,node,{name:def.name,scope:node.expression.scope,thedef:def});sym.reference({});return sym}}function can_hoist(sym,right,count){if(sym.scope!==self)return;var def=sym.definition();if(def.assignments!=count)return;if(def.direct_access)return;if(def.escaped==1)return;if(def.references.length==count)return;if(def.single_use)return;if(top_retain(def))return;if(sym.fixed_value()!==right)return;return right instanceof AST_Object}function make_sym(sym,key){var new_var=make_node(AST_SymbolVar,sym,{name:self.make_var_name(sym.name+"_"+key),scope:self});var def=self.def_variable(new_var);defs.set(key,def);self.enclosed.push(def);return new_var}}))});(function(def){function trim(nodes,compressor,first_in_statement){var len=nodes.length;if(!len)return null;var ret=[],changed=false;for(var i=0;i<len;i++){var node=nodes[i].drop_side_effect_free(compressor,first_in_statement);changed|=node!==nodes[i];if(node){ret.push(node);first_in_statement=false}}return changed?ret.length?ret:null:nodes}def(AST_Node,return_this);def(AST_Accessor,return_null);def(AST_Array,function(compressor,first_in_statement){var values=trim(this.elements,compressor,first_in_statement);return values&&make_sequence(this,values)});def(AST_Assign,function(compressor){var left=this.left;if(left.has_side_effects(compressor)||compressor.has_directive("use strict")&&left instanceof AST_PropAccess&&left.expression.is_constant()){return this}this.write_only=true;if(root_expr(left).is_constant_expression(compressor.find_parent(AST_Scope))){return this.right.drop_side_effect_free(compressor)}return this});def(AST_Binary,function(compressor,first_in_statement){var right=this.right.drop_side_effect_free(compressor);if(!right)return this.left.drop_side_effect_free(compressor,first_in_statement);if(lazy_op[this.operator]){if(right===this.right)return this;var node=this.clone();node.right=right;return node}else{var left=this.left.drop_side_effect_free(compressor,first_in_statement);if(!left)return this.right.drop_side_effect_free(compressor,first_in_statement);return make_sequence(this,[left,right])}});def(AST_Call,function(compressor,first_in_statement){if(!this.is_expr_pure(compressor)){if(this.expression.is_call_pure(compressor)){var exprs=this.args.slice();exprs.unshift(this.expression.expression);exprs=trim(exprs,compressor,first_in_statement);return exprs&&make_sequence(this,exprs)}if(this.expression instanceof AST_Function&&(!this.expression.name||!this.expression.name.definition().references.length)){var node=this.clone();var exp=node.expression;exp.process_expression(false,compressor);exp.walk(new TreeWalker(function(node){if(node instanceof AST_Return&&node.value){node.value=node.value.drop_side_effect_free(compressor);return true}if(node instanceof AST_Scope&&node!==exp)return true}));return node}return this}if(this.pure){compressor.warn("Dropping __PURE__ call [{file}:{line},{col}]",this.start)}var args=trim(this.args,compressor,first_in_statement);return args&&make_sequence(this,args)});def(AST_Conditional,function(compressor){var consequent=this.consequent.drop_side_effect_free(compressor);var alternative=this.alternative.drop_side_effect_free(compressor);if(consequent===this.consequent&&alternative===this.alternative)return this;if(!consequent)return alternative?make_node(AST_Binary,this,{operator:"||",left:this.condition,right:alternative}):this.condition.drop_side_effect_free(compressor);if(!alternative)return make_node(AST_Binary,this,{operator:"&&",left:this.condition,right:consequent});var node=this.clone();node.consequent=consequent;node.alternative=alternative;return node});def(AST_Constant,return_null);def(AST_Dot,function(compressor,first_in_statement){if(this.expression.may_throw_on_access(compressor))return this;return this.expression.drop_side_effect_free(compressor,first_in_statement)});def(AST_Function,function(compressor){return this.name&&compressor.option("ie8")?this:null});def(AST_Unary,function(compressor,first_in_statement){if(unary_side_effects[this.operator]){this.write_only=!this.expression.has_side_effects(compressor);return this}if(this.operator=="typeof"&&this.expression instanceof AST_SymbolRef)return null;var expression=this.expression.drop_side_effect_free(compressor,first_in_statement);if(first_in_statement&&expression&&is_iife_call(expression)){if(expression===this.expression&&this.operator=="!")return this;return expression.negate(compressor,first_in_statement)}return expression});def(AST_Object,function(compressor,first_in_statement){var values=trim(this.properties,compressor,first_in_statement);return values&&make_sequence(this,values)});def(AST_ObjectProperty,function(compressor,first_in_statement){return this.value.drop_side_effect_free(compressor,first_in_statement)});def(AST_Sequence,function(compressor){var last=this.tail_node();var expr=last.drop_side_effect_free(compressor);if(expr===last)return this;var expressions=this.expressions.slice(0,-1);if(expr)expressions.push(expr);return make_sequence(this,expressions)});def(AST_Sub,function(compressor,first_in_statement){if(this.expression.may_throw_on_access(compressor))return this;var expression=this.expression.drop_side_effect_free(compressor,first_in_statement);if(!expression)return this.property.drop_side_effect_free(compressor,first_in_statement);var property=this.property.drop_side_effect_free(compressor);if(!property)return expression;return make_sequence(this,[expression,property])});def(AST_SymbolRef,function(compressor){return this.is_declared(compressor)?null:this});def(AST_This,return_null)})(function(node,func){node.DEFMETHOD("drop_side_effect_free",func)});OPT(AST_SimpleStatement,function(self,compressor){if(compressor.option("side_effects")){var body=self.body;var node=body.drop_side_effect_free(compressor,true);if(!node){compressor.warn("Dropping side-effect-free statement [{file}:{line},{col}]",self.start);return make_node(AST_EmptyStatement,self)}if(node!==body){return make_node(AST_SimpleStatement,self,{body:node})}}return self});OPT(AST_While,function(self,compressor){return compressor.option("loops")?make_node(AST_For,self,self).optimize(compressor):self});function has_break_or_continue(loop,parent){var found=false;var tw=new TreeWalker(function(node){if(found||node instanceof AST_Scope)return true;if(node instanceof AST_LoopControl&&tw.loopcontrol_target(node)===loop){return found=true}});if(parent instanceof AST_LabeledStatement)tw.push(parent);tw.push(loop);loop.body.walk(tw);return found}OPT(AST_Do,function(self,compressor){if(!compressor.option("loops"))return self;var cond=self.condition.is_truthy()||self.condition.tail_node().evaluate(compressor);if(!(cond instanceof AST_Node)){if(cond)return make_node(AST_For,self,{body:make_node(AST_BlockStatement,self.body,{body:[self.body,make_node(AST_SimpleStatement,self.condition,{body:self.condition})]})}).optimize(compressor);if(!has_break_or_continue(self,compressor.parent())){return make_node(AST_BlockStatement,self.body,{body:[self.body,make_node(AST_SimpleStatement,self.condition,{body:self.condition})]}).optimize(compressor)}}if(self.body instanceof AST_SimpleStatement)return make_node(AST_For,self,{condition:make_sequence(self.condition,[self.body.body,self.condition]),body:make_node(AST_EmptyStatement,self)}).optimize(compressor);return self});function if_break_in_loop(self,compressor){var first=self.body instanceof AST_BlockStatement?self.body.body[0]:self.body;if(compressor.option("dead_code")&&is_break(first)){var body=[];if(self.init instanceof AST_Statement){body.push(self.init)}else if(self.init){body.push(make_node(AST_SimpleStatement,self.init,{body:self.init}))}if(self.condition){body.push(make_node(AST_SimpleStatement,self.condition,{body:self.condition}))}extract_declarations_from_unreachable_code(compressor,self.body,body);return make_node(AST_BlockStatement,self,{body:body})}if(first instanceof AST_If){if(is_break(first.body)){if(self.condition){self.condition=make_node(AST_Binary,self.condition,{left:self.condition,operator:"&&",right:first.condition.negate(compressor)})}else{self.condition=first.condition.negate(compressor)}drop_it(first.alternative)}else if(is_break(first.alternative)){if(self.condition){self.condition=make_node(AST_Binary,self.condition,{left:self.condition,operator:"&&",right:first.condition})}else{self.condition=first.condition}drop_it(first.body)}}return self;function is_break(node){return node instanceof AST_Break&&compressor.loopcontrol_target(node)===compressor.self()}function drop_it(rest){rest=as_statement_array(rest);if(self.body instanceof AST_BlockStatement){self.body=self.body.clone();self.body.body=rest.concat(self.body.body.slice(1));self.body=self.body.transform(compressor)}else{self.body=make_node(AST_BlockStatement,self.body,{body:rest}).transform(compressor)}self=if_break_in_loop(self,compressor)}}OPT(AST_For,function(self,compressor){if(!compressor.option("loops"))return self;if(compressor.option("side_effects")&&self.init){self.init=self.init.drop_side_effect_free(compressor)}if(self.condition){var cond=self.condition.evaluate(compressor);if(!(cond instanceof AST_Node)){if(cond)self.condition=null;else if(!compressor.option("dead_code")){var orig=self.condition;self.condition=make_node_from_constant(cond,self.condition);self.condition=best_of_expression(self.condition.transform(compressor),orig)}}if(cond instanceof AST_Node){cond=self.condition.is_truthy()||self.condition.tail_node().evaluate(compressor)}if(!cond){if(compressor.option("dead_code")){var body=[];extract_declarations_from_unreachable_code(compressor,self.body,body);if(self.init instanceof AST_Statement){body.push(self.init)}else if(self.init){body.push(make_node(AST_SimpleStatement,self.init,{body:self.init}))}body.push(make_node(AST_SimpleStatement,self.condition,{body:self.condition}));return make_node(AST_BlockStatement,self,{body:body}).optimize(compressor)}}else if(self.condition&&!(cond instanceof AST_Node)){self.body=make_node(AST_BlockStatement,self.body,{body:[make_node(AST_SimpleStatement,self.condition,{body:self.condition}),self.body]});self.condition=null}}return if_break_in_loop(self,compressor)});OPT(AST_If,function(self,compressor){if(is_empty(self.alternative))self.alternative=null;if(!compressor.option("conditionals"))return self;var cond=self.condition.evaluate(compressor);if(!compressor.option("dead_code")&&!(cond instanceof AST_Node)){var orig=self.condition;self.condition=make_node_from_constant(cond,orig);self.condition=best_of_expression(self.condition.transform(compressor),orig)}if(compressor.option("dead_code")){if(cond instanceof AST_Node){cond=self.condition.is_truthy()||self.condition.tail_node().evaluate(compressor)}if(!cond){compressor.warn("Condition always false [{file}:{line},{col}]",self.condition.start);var body=[];extract_declarations_from_unreachable_code(compressor,self.body,body);body.push(make_node(AST_SimpleStatement,self.condition,{body:self.condition}));if(self.alternative)body.push(self.alternative);return make_node(AST_BlockStatement,self,{body:body}).optimize(compressor)}else if(!(cond instanceof AST_Node)){compressor.warn("Condition always true [{file}:{line},{col}]",self.condition.start);var body=[];if(self.alternative){extract_declarations_from_unreachable_code(compressor,self.alternative,body)}body.push(make_node(AST_SimpleStatement,self.condition,{body:self.condition}));body.push(self.body);return make_node(AST_BlockStatement,self,{body:body}).optimize(compressor)}}var negated=self.condition.negate(compressor);var self_condition_length=self.condition.print_to_string().length;var negated_length=negated.print_to_string().length;var negated_is_best=negated_length<self_condition_length;if(self.alternative&&negated_is_best){negated_is_best=false;self.condition=negated;var tmp=self.body;self.body=self.alternative||make_node(AST_EmptyStatement,self);self.alternative=tmp}if(is_empty(self.body)&&is_empty(self.alternative)){return make_node(AST_SimpleStatement,self.condition,{body:self.condition.clone()}).optimize(compressor)}if(self.body instanceof AST_SimpleStatement&&self.alternative instanceof AST_SimpleStatement){return make_node(AST_SimpleStatement,self,{body:make_node(AST_Conditional,self,{condition:self.condition,consequent:self.body.body,alternative:self.alternative.body})}).optimize(compressor)}if(is_empty(self.alternative)&&self.body instanceof AST_SimpleStatement){if(self_condition_length===negated_length&&!negated_is_best&&self.condition instanceof AST_Binary&&self.condition.operator=="||"){negated_is_best=true}if(negated_is_best)return make_node(AST_SimpleStatement,self,{body:make_node(AST_Binary,self,{operator:"||",left:negated,right:self.body.body})}).optimize(compressor);return make_node(AST_SimpleStatement,self,{body:make_node(AST_Binary,self,{operator:"&&",left:self.condition,right:self.body.body})}).optimize(compressor)}if(self.body instanceof AST_EmptyStatement&&self.alternative instanceof AST_SimpleStatement){return make_node(AST_SimpleStatement,self,{body:make_node(AST_Binary,self,{operator:"||",left:self.condition,right:self.alternative.body})}).optimize(compressor)}if(self.body instanceof AST_Exit&&self.alternative instanceof AST_Exit&&self.body.TYPE==self.alternative.TYPE){return make_node(self.body.CTOR,self,{value:make_node(AST_Conditional,self,{condition:self.condition,consequent:self.body.value||make_node(AST_Undefined,self.body),alternative:self.alternative.value||make_node(AST_Undefined,self.alternative)}).transform(compressor)}).optimize(compressor)}if(self.body instanceof AST_If&&!self.body.alternative&&!self.alternative){self=make_node(AST_If,self,{condition:make_node(AST_Binary,self.condition,{operator:"&&",left:self.condition,right:self.body.condition}),body:self.body.body,alternative:null})}if(aborts(self.body)){if(self.alternative){var alt=self.alternative;self.alternative=null;return make_node(AST_BlockStatement,self,{body:[self,alt]}).optimize(compressor)}}if(aborts(self.alternative)){var body=self.body;self.body=self.alternative;self.condition=negated_is_best?negated:self.condition.negate(compressor);self.alternative=null;return make_node(AST_BlockStatement,self,{body:[self,body]}).optimize(compressor)}return self});OPT(AST_Switch,function(self,compressor){if(!compressor.option("switches"))return self;var branch;var value=self.expression.evaluate(compressor);if(!(value instanceof AST_Node)){var orig=self.expression;self.expression=make_node_from_constant(value,orig);self.expression=best_of_expression(self.expression.transform(compressor),orig)}if(!compressor.option("dead_code"))return self;if(value instanceof AST_Node){value=self.expression.tail_node().evaluate(compressor)}var decl=[];var body=[];var default_branch;var exact_match;for(var i=0,len=self.body.length;i<len&&!exact_match;i++){branch=self.body[i];if(branch instanceof AST_Default){if(!default_branch){default_branch=branch}else{eliminate_branch(branch,body[body.length-1])}}else if(!(value instanceof AST_Node)){var exp=branch.expression.evaluate(compressor);if(!(exp instanceof AST_Node)&&exp!==value){eliminate_branch(branch,body[body.length-1]);continue}if(exp instanceof AST_Node)exp=branch.expression.tail_node().evaluate(compressor);if(exp===value){exact_match=branch;if(default_branch){var default_index=body.indexOf(default_branch);body.splice(default_index,1);eliminate_branch(default_branch,body[default_index-1]);default_branch=null}}}if(aborts(branch)){var prev=body[body.length-1];if(aborts(prev)&&prev.body.length==branch.body.length&&make_node(AST_BlockStatement,prev,prev).equivalent_to(make_node(AST_BlockStatement,branch,branch))){prev.body=[]}}body.push(branch)}while(i<len)eliminate_branch(self.body[i++],body[body.length-1]);if(body.length>0){body[0].body=decl.concat(body[0].body)}self.body=body;while(branch=body[body.length-1]){var stat=branch.body[branch.body.length-1];if(stat instanceof AST_Break&&compressor.loopcontrol_target(stat)===self)branch.body.pop();if(branch.body.length||branch instanceof AST_Case&&(default_branch||branch.expression.has_side_effects(compressor)))break;if(body.pop()===default_branch)default_branch=null}if(body.length==0){return make_node(AST_BlockStatement,self,{body:decl.concat(make_node(AST_SimpleStatement,self.expression,{body:self.expression}))}).optimize(compressor)}if(body.length==1&&(body[0]===exact_match||body[0]===default_branch)){var has_break=false;var tw=new TreeWalker(function(node){if(has_break||node instanceof AST_Lambda||node instanceof AST_SimpleStatement)return true;if(node instanceof AST_Break&&tw.loopcontrol_target(node)===self)has_break=true});self.walk(tw);if(!has_break){var statements=body[0].body.slice();var exp=body[0].expression;if(exp)statements.unshift(make_node(AST_SimpleStatement,exp,{body:exp}));statements.unshift(make_node(AST_SimpleStatement,self.expression,{body:self.expression}));return make_node(AST_BlockStatement,self,{body:statements}).optimize(compressor)}}return self;function eliminate_branch(branch,prev){if(prev&&!aborts(prev)){prev.body=prev.body.concat(branch.body)}else{extract_declarations_from_unreachable_code(compressor,branch,decl)}}});OPT(AST_Try,function(self,compressor){tighten_body(self.body,compressor);if(self.bcatch&&self.bfinally&&all(self.bfinally.body,is_empty))self.bfinally=null;if(compressor.option("dead_code")&&all(self.body,is_empty)){var body=[];if(self.bcatch){extract_declarations_from_unreachable_code(compressor,self.bcatch,body);body.forEach(function(stat){if(!(stat instanceof AST_Definitions))return;stat.definitions.forEach(function(var_def){var def=var_def.name.definition().redefined();if(!def)return;var_def.name=var_def.name.clone();var_def.name.thedef=def})})}if(self.bfinally)body=body.concat(self.bfinally.body);return make_node(AST_BlockStatement,self,{body:body}).optimize(compressor)}return self});AST_Definitions.DEFMETHOD("remove_initializers",function(){this.definitions.forEach(function(def){def.value=null})});AST_Definitions.DEFMETHOD("to_assignments",function(compressor){var reduce_vars=compressor.option("reduce_vars");var assignments=this.definitions.reduce(function(a,def){if(def.value){var name=make_node(AST_SymbolRef,def.name,def.name);a.push(make_node(AST_Assign,def,{operator:"=",left:name,right:def.value}));if(reduce_vars)name.definition().fixed=false}def=def.name.definition();def.eliminated++;def.replaced--;return a},[]);if(assignments.length==0)return null;return make_sequence(this,assignments)});OPT(AST_Definitions,function(self,compressor){if(self.definitions.length==0)return make_node(AST_EmptyStatement,self);return self});AST_Call.DEFMETHOD("lift_sequences",function(compressor){if(!compressor.option("sequences"))return this;var exp=this.expression;if(!(exp instanceof AST_Sequence))return this;var tail=exp.tail_node();if(needs_unbinding(compressor,tail)&&!(this instanceof AST_New))return this;var expressions=exp.expressions.slice(0,-1);var node=this.clone();node.expression=tail;expressions.push(node);return make_sequence(this,expressions).optimize(compressor)});OPT(AST_Call,function(self,compressor){var seq=self.lift_sequences(compressor);if(seq!==self){return seq}var exp=self.expression;var fn=exp;if(compressor.option("reduce_vars")&&fn instanceof AST_SymbolRef){fn=fn.fixed_value()}var is_func=fn instanceof AST_Lambda;if(compressor.option("unused")&&is_func&&!fn.uses_arguments&&!fn.pinned()){var pos=0,last=0;for(var i=0,len=self.args.length;i<len;i++){var trim=i>=fn.argnames.length;if(trim||fn.argnames[i].__unused){var node=self.args[i].drop_side_effect_free(compressor);if(node){self.args[pos++]=node}else if(!trim){self.args[pos++]=make_node(AST_Number,self.args[i],{value:0});continue}}else{self.args[pos++]=self.args[i]}last=pos}self.args.length=last}if(compressor.option("unsafe")){if(is_undeclared_ref(exp))switch(exp.name){case"Array":if(self.args.length!=1){return make_node(AST_Array,self,{elements:self.args}).optimize(compressor)}break;case"Object":if(self.args.length==0){return make_node(AST_Object,self,{properties:[]})}break;case"String":if(self.args.length==0)return make_node(AST_String,self,{value:""});if(self.args.length<=1)return make_node(AST_Binary,self,{left:self.args[0],operator:"+",right:make_node(AST_String,self,{value:""})}).optimize(compressor);break;case"Number":if(self.args.length==0)return make_node(AST_Number,self,{value:0});if(self.args.length==1)return make_node(AST_UnaryPrefix,self,{expression:self.args[0],operator:"+"}).optimize(compressor);case"Boolean":if(self.args.length==0)return make_node(AST_False,self);if(self.args.length==1)return make_node(AST_UnaryPrefix,self,{expression:make_node(AST_UnaryPrefix,self,{expression:self.args[0],operator:"!"}),operator:"!"}).optimize(compressor);break;case"RegExp":var params=[];if(all(self.args,function(arg){var value=arg.evaluate(compressor);params.unshift(value);return arg!==value})){try{return best_of(compressor,self,make_node(AST_RegExp,self,{value:RegExp.apply(RegExp,params)}))}catch(ex){compressor.warn("Error converting {expr} [{file}:{line},{col}]",{expr:self.print_to_string(),file:self.start.file,line:self.start.line,col:self.start.col})}}break}else if(exp instanceof AST_Dot)switch(exp.property){case"toString":if(self.args.length==0&&!exp.expression.may_throw_on_access(compressor)){return make_node(AST_Binary,self,{left:make_node(AST_String,self,{value:""}),operator:"+",right:exp.expression}).optimize(compressor)}break;case"join":if(exp.expression instanceof AST_Array)EXIT:{var separator;if(self.args.length>0){separator=self.args[0].evaluate(compressor);if(separator===self.args[0])break EXIT}var elements=[];var consts=[];exp.expression.elements.forEach(function(el){var value=el.evaluate(compressor);if(value!==el){consts.push(value)}else{if(consts.length>0){elements.push(make_node(AST_String,self,{value:consts.join(separator)}));consts.length=0}elements.push(el)}});if(consts.length>0){elements.push(make_node(AST_String,self,{value:consts.join(separator)}))}if(elements.length==0)return make_node(AST_String,self,{value:""});if(elements.length==1){if(elements[0].is_string(compressor)){return elements[0]}return make_node(AST_Binary,elements[0],{operator:"+",left:make_node(AST_String,self,{value:""}),right:elements[0]})}if(separator==""){var first;if(elements[0].is_string(compressor)||elements[1].is_string(compressor)){first=elements.shift()}else{first=make_node(AST_String,self,{value:""})}return elements.reduce(function(prev,el){return make_node(AST_Binary,el,{operator:"+",left:prev,right:el})},first).optimize(compressor)}var node=self.clone();node.expression=node.expression.clone();node.expression.expression=node.expression.expression.clone();node.expression.expression.elements=elements;return best_of(compressor,self,node)}break;case"charAt":if(exp.expression.is_string(compressor)){var arg=self.args[0];var index=arg?arg.evaluate(compressor):0;if(index!==arg){return make_node(AST_Sub,exp,{expression:exp.expression,property:make_node_from_constant(index|0,arg||exp)}).optimize(compressor)}}break;case"apply":if(self.args.length==2&&self.args[1]instanceof AST_Array){var args=self.args[1].elements.slice();args.unshift(self.args[0]);return make_node(AST_Call,self,{expression:make_node(AST_Dot,exp,{expression:exp.expression,property:"call"}),args:args}).optimize(compressor)}break;case"call":var func=exp.expression;if(func instanceof AST_SymbolRef){func=func.fixed_value()}if(func instanceof AST_Lambda&&!func.contains_this()){return(self.args.length?make_sequence(this,[self.args[0],make_node(AST_Call,self,{expression:exp.expression,args:self.args.slice(1)})]):make_node(AST_Call,self,{expression:exp.expression,args:[]})).optimize(compressor)}break}}if(compressor.option("unsafe_Function")&&is_undeclared_ref(exp)&&exp.name=="Function"){if(self.args.length==0)return make_node(AST_Function,self,{argnames:[],body:[]});if(all(self.args,function(x){return x instanceof AST_String})){try{var code="n(function("+self.args.slice(0,-1).map(function(arg){return arg.value}).join(",")+"){"+self.args[self.args.length-1].value+"})";var ast=parse(code);var mangle={ie8:compressor.option("ie8")};ast.figure_out_scope(mangle);var comp=new Compressor(compressor.options);ast=ast.transform(comp);ast.figure_out_scope(mangle);ast.compute_char_frequency(mangle);ast.mangle_names(mangle);var fun;ast.walk(new TreeWalker(function(node){if(fun)return true;if(node instanceof AST_Lambda){fun=node;return true}}));var code=OutputStream();AST_BlockStatement.prototype._codegen.call(fun,fun,code);self.args=[make_node(AST_String,self,{value:fun.argnames.map(function(arg){return arg.print_to_string()}).join(",")}),make_node(AST_String,self.args[self.args.length-1],{value:code.get().replace(/^\{|\}$/g,"")})];return self}catch(ex){if(ex instanceof JS_Parse_Error){compressor.warn("Error parsing code passed to new Function [{file}:{line},{col}]",self.args[self.args.length-1].start);compressor.warn(ex.toString())}else{throw ex}}}}var stat=is_func&&fn.body[0];var can_inline=compressor.option("inline")&&!self.is_expr_pure(compressor);if(can_inline&&stat instanceof AST_Return){var value=stat.value;if(!value||value.is_constant_expression()){if(value){value=value.clone(true)}else{value=make_node(AST_Undefined,self)}var args=self.args.concat(value);return make_sequence(self,args).optimize(compressor)}}if(is_func){var def,value,scope,in_loop,level=-1;if(can_inline&&!fn.uses_arguments&&!fn.pinned()&&!(fn.name&&fn instanceof AST_Function)&&(value=can_flatten_body(stat))&&(exp===fn||compressor.option("unused")&&(def=exp.definition()).references.length==1&&!recursive_ref(compressor,def)&&fn.is_constant_expression(exp.scope))&&!self.pure&&!fn.contains_this()&&can_inject_symbols()){fn._squeezed=true;return make_sequence(self,flatten_fn()).optimize(compressor)}if(compressor.option("side_effects")&&all(fn.body,is_empty)){var args=self.args.concat(make_node(AST_Undefined,self));return make_sequence(self,args).optimize(compressor)}}if(compressor.option("drop_console")){if(exp instanceof AST_PropAccess){var name=exp.expression;while(name.expression){name=name.expression}if(is_undeclared_ref(name)&&name.name=="console"){return make_node(AST_Undefined,self).optimize(compressor)}}}if(compressor.option("negate_iife")&&compressor.parent()instanceof AST_SimpleStatement&&is_iife_call(self)){return self.negate(compressor,true)}var ev=self.evaluate(compressor);if(ev!==self){ev=make_node_from_constant(ev,self).optimize(compressor);return best_of(compressor,ev,self)}return self;function return_value(stat){if(!stat)return make_node(AST_Undefined,self);if(stat instanceof AST_Return){if(!stat.value)return make_node(AST_Undefined,self);return stat.value.clone(true)}if(stat instanceof AST_SimpleStatement){return make_node(AST_UnaryPrefix,stat,{operator:"void",expression:stat.body.clone(true)})}}function can_flatten_body(stat){var len=fn.body.length;if(compressor.option("inline")<3){return len==1&&return_value(stat)}stat=null;for(var i=0;i<len;i++){var line=fn.body[i];if(line instanceof AST_Var){if(stat&&!all(line.definitions,function(var_def){return!var_def.value})){return false}}else if(line instanceof AST_EmptyStatement){continue}else if(stat){return false}else{stat=line}}return return_value(stat)}function can_inject_args(catches,safe_to_inject){for(var i=0,len=fn.argnames.length;i<len;i++){var arg=fn.argnames[i];if(arg.__unused)continue;if(!safe_to_inject||catches[arg.name]||identifier_atom[arg.name]||scope.var_names()[arg.name]){return false}if(in_loop)in_loop.push(arg.definition())}return true}function can_inject_vars(catches,safe_to_inject){var len=fn.body.length;for(var i=0;i<len;i++){var stat=fn.body[i];if(!(stat instanceof AST_Var))continue;if(!safe_to_inject)return false;for(var j=stat.definitions.length;--j>=0;){var name=stat.definitions[j].name;if(catches[name.name]||identifier_atom[name.name]||scope.var_names()[name.name]){return false}if(in_loop)in_loop.push(name.definition())}}return true}function can_inject_symbols(){var catches=Object.create(null);do{scope=compressor.parent(++level);if(scope instanceof AST_Catch){catches[scope.argname.name]=true}else if(scope instanceof AST_IterationStatement){in_loop=[]}else if(scope instanceof AST_SymbolRef){if(scope.fixed_value()instanceof AST_Scope)return false}}while(!(scope instanceof AST_Scope));var safe_to_inject=!(scope instanceof AST_Toplevel)||compressor.toplevel.vars;var inline=compressor.option("inline");if(!can_inject_vars(catches,inline>=3&&safe_to_inject))return false;if(!can_inject_args(catches,inline>=2&&safe_to_inject))return false;return!in_loop||in_loop.length==0||!is_reachable(fn,in_loop)}function append_var(decls,expressions,name,value){var def=name.definition();scope.variables.set(name.name,def);scope.enclosed.push(def);if(!scope.var_names()[name.name]){scope.var_names()[name.name]=true;decls.push(make_node(AST_VarDef,name,{name:name,value:null}))}var sym=make_node(AST_SymbolRef,name,name);def.references.push(sym);if(value)expressions.push(make_node(AST_Assign,self,{operator:"=",left:sym,right:value}))}function flatten_args(decls,expressions){var len=fn.argnames.length;for(var i=self.args.length;--i>=len;){expressions.push(self.args[i])}for(i=len;--i>=0;){var name=fn.argnames[i];var value=self.args[i];if(name.__unused||scope.var_names()[name.name]){if(value)expressions.push(value)}else{var symbol=make_node(AST_SymbolVar,name,name);name.definition().orig.push(symbol);if(!value&&in_loop)value=make_node(AST_Undefined,self);append_var(decls,expressions,symbol,value)}}decls.reverse();expressions.reverse()}function flatten_vars(decls,expressions){var pos=expressions.length;for(var i=0,lines=fn.body.length;i<lines;i++){var stat=fn.body[i];if(!(stat instanceof AST_Var))continue;for(var j=0,defs=stat.definitions.length;j<defs;j++){var var_def=stat.definitions[j];var name=var_def.name;var redef=name.definition().redefined();if(redef){name=name.clone();name.thedef=redef}append_var(decls,expressions,name,var_def.value);if(in_loop&&all(fn.argnames,function(argname){return argname.name!=name.name})){var def=fn.variables.get(name.name);var sym=make_node(AST_SymbolRef,name,name);def.references.push(sym);expressions.splice(pos++,0,make_node(AST_Assign,var_def,{operator:"=",left:sym,right:make_node(AST_Undefined,name)}))}}}}function flatten_fn(){var decls=[];var expressions=[];flatten_args(decls,expressions);flatten_vars(decls,expressions);expressions.push(value);if(decls.length){i=scope.body.indexOf(compressor.parent(level-1))+1;scope.body.splice(i,0,make_node(AST_Var,fn,{definitions:decls}))}return expressions}});OPT(AST_New,function(self,compressor){var seq=self.lift_sequences(compressor);if(seq!==self){return seq}if(compressor.option("unsafe")){var exp=self.expression;if(is_undeclared_ref(exp)){switch(exp.name){case"Object":case"RegExp":case"Function":case"Error":case"Array":return make_node(AST_Call,self,self).transform(compressor)}}}return self});OPT(AST_Sequence,function(self,compressor){if(!compressor.option("side_effects"))return self;var expressions=[];filter_for_side_effects();var end=expressions.length-1;trim_right_for_undefined();if(end==0){self=maintain_this_binding(compressor,compressor.parent(),compressor.self(),expressions[0]);if(!(self instanceof AST_Sequence))self=self.optimize(compressor);return self}self.expressions=expressions;return self;function filter_for_side_effects(){var first=first_in_statement(compressor);var last=self.expressions.length-1;self.expressions.forEach(function(expr,index){if(index<last)expr=expr.drop_side_effect_free(compressor,first);if(expr){merge_sequence(expressions,expr);first=false}})}function trim_right_for_undefined(){while(end>0&&is_undefined(expressions[end],compressor))end--;if(end<expressions.length-1){expressions[end]=make_node(AST_UnaryPrefix,self,{operator:"void",expression:expressions[end]});expressions.length=end+1}}});AST_Unary.DEFMETHOD("lift_sequences",function(compressor){if(compressor.option("sequences")&&this.expression instanceof AST_Sequence){var x=this.expression.expressions.slice();var e=this.clone();e.expression=x.pop();x.push(e);return make_sequence(this,x).optimize(compressor)}return this});OPT(AST_UnaryPostfix,function(self,compressor){return self.lift_sequences(compressor)});OPT(AST_UnaryPrefix,function(self,compressor){var e=self.expression;if(self.operator=="delete"&&!(e instanceof AST_SymbolRef||e instanceof AST_PropAccess||is_identifier_atom(e))){if(e instanceof AST_Sequence){e=e.expressions.slice();e.push(make_node(AST_True,self));return make_sequence(self,e).optimize(compressor)}return make_sequence(self,[e,make_node(AST_True,self)]).optimize(compressor)}var seq=self.lift_sequences(compressor);if(seq!==self){return seq}if(compressor.option("side_effects")&&self.operator=="void"){e=e.drop_side_effect_free(compressor);if(e){self.expression=e;return self}else{return make_node(AST_Undefined,self).optimize(compressor)}}if(compressor.option("booleans")){if(self.operator=="!"&&e.is_truthy()){return make_sequence(self,[e,make_node(AST_False,self)]).optimize(compressor)}else if(compressor.in_boolean_context())switch(self.operator){case"!":if(e instanceof AST_UnaryPrefix&&e.operator=="!"){return e.expression}if(e instanceof AST_Binary){self=best_of(compressor,self,e.negate(compressor,first_in_statement(compressor)))}break;case"typeof":compressor.warn("Boolean expression always true [{file}:{line},{col}]",self.start);return(e instanceof AST_SymbolRef?make_node(AST_True,self):make_sequence(self,[e,make_node(AST_True,self)])).optimize(compressor)}}if(self.operator=="-"&&e instanceof AST_Infinity){e=e.transform(compressor)}if(e instanceof AST_Binary&&(self.operator=="+"||self.operator=="-")&&(e.operator=="*"||e.operator=="/"||e.operator=="%")){return make_node(AST_Binary,self,{operator:e.operator,left:make_node(AST_UnaryPrefix,e.left,{operator:self.operator,expression:e.left}),right:e.right})}if(self.operator!="-"||!(e instanceof AST_Number||e instanceof AST_Infinity)){var ev=self.evaluate(compressor);if(ev!==self){ev=make_node_from_constant(ev,self).optimize(compressor);return best_of(compressor,ev,self)}}return self});AST_Binary.DEFMETHOD("lift_sequences",function(compressor){if(compressor.option("sequences")){if(this.left instanceof AST_Sequence){var x=this.left.expressions.slice();var e=this.clone();e.left=x.pop();x.push(e);return make_sequence(this,x).optimize(compressor)}if(this.right instanceof AST_Sequence&&!this.left.has_side_effects(compressor)){var assign=this.operator=="="&&this.left instanceof AST_SymbolRef;var x=this.right.expressions;var last=x.length-1;for(var i=0;i<last;i++){if(!assign&&x[i].has_side_effects(compressor))break}if(i==last){x=x.slice();var e=this.clone();e.right=x.pop();x.push(e);return make_sequence(this,x).optimize(compressor)}else if(i>0){var e=this.clone();e.right=make_sequence(this.right,x.slice(i));x=x.slice(0,i);x.push(e);return make_sequence(this,x).optimize(compressor)}}}return this});var commutativeOperators=makePredicate("== === != !== * & | ^");function is_object(node){return node instanceof AST_Array||node instanceof AST_Lambda||node instanceof AST_Object}OPT(AST_Binary,function(self,compressor){function reversible(){return self.left.is_constant()||self.right.is_constant()||!self.left.has_side_effects(compressor)&&!self.right.has_side_effects(compressor)}function reverse(op){if(reversible()){if(op)self.operator=op;var tmp=self.left;self.left=self.right;self.right=tmp}}if(commutativeOperators[self.operator]){if(self.right.is_constant()&&!self.left.is_constant()){if(!(self.left instanceof AST_Binary&&PRECEDENCE[self.left.operator]>=PRECEDENCE[self.operator])){reverse()}}}self=self.lift_sequences(compressor);if(compressor.option("comparisons"))switch(self.operator){case"===":case"!==":var is_strict_comparison=true;if(self.left.is_string(compressor)&&self.right.is_string(compressor)||self.left.is_number(compressor)&&self.right.is_number(compressor)||self.left.is_boolean(compressor)&&self.right.is_boolean(compressor)||self.left.equivalent_to(self.right)){self.operator=self.operator.substr(0,2)}case"==":case"!=":if(!is_strict_comparison&&is_undefined(self.left,compressor)){self.left=make_node(AST_Null,self.left)}else if(compressor.option("typeofs")&&self.left instanceof AST_String&&self.left.value=="undefined"&&self.right instanceof AST_UnaryPrefix&&self.right.operator=="typeof"){var expr=self.right.expression;if(expr instanceof AST_SymbolRef?expr.is_declared(compressor):!(expr instanceof AST_PropAccess&&compressor.option("ie8"))){self.right=expr;self.left=make_node(AST_Undefined,self.left).optimize(compressor);if(self.operator.length==2)self.operator+="="}}else if(self.left instanceof AST_SymbolRef&&self.right instanceof AST_SymbolRef&&self.left.definition()===self.right.definition()&&is_object(self.left.fixed_value())){return make_node(self.operator[0]=="="?AST_True:AST_False,self)}break;case"&&":case"||":var lhs=self.left;if(lhs.operator==self.operator){lhs=lhs.right}if(lhs instanceof AST_Binary&&lhs.operator==(self.operator=="&&"?"!==":"===")&&self.right instanceof AST_Binary&&lhs.operator==self.right.operator&&(is_undefined(lhs.left,compressor)&&self.right.left instanceof AST_Null||lhs.left instanceof AST_Null&&is_undefined(self.right.left,compressor))&&!lhs.right.has_side_effects(compressor)&&lhs.right.equivalent_to(self.right.right)){var combined=make_node(AST_Binary,self,{operator:lhs.operator.slice(0,-1),left:make_node(AST_Null,self),right:lhs.right});if(lhs!==self.left){combined=make_node(AST_Binary,self,{operator:self.operator,left:self.left.left,right:combined})}return combined}break}if(compressor.option("booleans")&&self.operator=="+"&&compressor.in_boolean_context()){var ll=self.left.evaluate(compressor);var rr=self.right.evaluate(compressor);if(ll&&typeof ll=="string"){compressor.warn("+ in boolean context always true [{file}:{line},{col}]",self.start);return make_sequence(self,[self.right,make_node(AST_True,self)]).optimize(compressor)}if(rr&&typeof rr=="string"){compressor.warn("+ in boolean context always true [{file}:{line},{col}]",self.start);return make_sequence(self,[self.left,make_node(AST_True,self)]).optimize(compressor)}}if(compressor.option("comparisons")&&self.is_boolean(compressor)){if(!(compressor.parent()instanceof AST_Binary)||compressor.parent()instanceof AST_Assign){var negated=make_node(AST_UnaryPrefix,self,{operator:"!",expression:self.negate(compressor,first_in_statement(compressor))});self=best_of(compressor,self,negated)}switch(self.operator){case">":reverse("<");break;case">=":reverse("<=");break}}if(self.operator=="+"){if(self.right instanceof AST_String&&self.right.getValue()==""&&self.left.is_string(compressor)){return self.left}if(self.left instanceof AST_String&&self.left.getValue()==""&&self.right.is_string(compressor)){return self.right}if(self.left instanceof AST_Binary&&self.left.operator=="+"&&self.left.left instanceof AST_String&&self.left.left.getValue()==""&&self.right.is_string(compressor)){self.left=self.left.right;return self.transform(compressor)}}if(compressor.option("evaluate")){switch(self.operator){case"&&":var ll=fuzzy_eval(self.left);if(!ll){compressor.warn("Condition left of && always false [{file}:{line},{col}]",self.start);return maintain_this_binding(compressor,compressor.parent(),compressor.self(),self.left).optimize(compressor)}else if(!(ll instanceof AST_Node)){compressor.warn("Condition left of && always true [{file}:{line},{col}]",self.start);return make_sequence(self,[self.left,self.right]).optimize(compressor)}var rr=self.right.evaluate(compressor);if(!rr){if(compressor.option("booleans")&&compressor.in_boolean_context()){compressor.warn("Boolean && always false [{file}:{line},{col}]",self.start);return make_sequence(self,[self.left,make_node(AST_False,self)]).optimize(compressor)}else self.falsy=true}else if(!(rr instanceof AST_Node)){var parent=compressor.parent();if(parent.operator=="&&"&&parent.left===compressor.self()||compressor.option("booleans")&&compressor.in_boolean_context()){compressor.warn("Dropping side-effect-free && [{file}:{line},{col}]",self.start);return self.left.optimize(compressor)}}if(self.left.operator=="||"){var lr=self.left.right.evaluate(compressor);if(!lr)return make_node(AST_Conditional,self,{condition:self.left.left,consequent:self.right,alternative:self.left.right}).optimize(compressor)}break;case"||":var ll=fuzzy_eval(self.left);if(!ll){compressor.warn("Condition left of || always false [{file}:{line},{col}]",self.start);return make_sequence(self,[self.left,self.right]).optimize(compressor)}else if(!(ll instanceof AST_Node)){compressor.warn("Condition left of || always true [{file}:{line},{col}]",self.start);return maintain_this_binding(compressor,compressor.parent(),compressor.self(),self.left).optimize(compressor)}var rr=self.right.evaluate(compressor);if(!rr){var parent=compressor.parent();if(parent.operator=="||"&&parent.left===compressor.self()||compressor.option("booleans")&&compressor.in_boolean_context()){compressor.warn("Dropping side-effect-free || [{file}:{line},{col}]",self.start);return self.left.optimize(compressor)}}else if(!(rr instanceof AST_Node)){if(compressor.option("booleans")&&compressor.in_boolean_context()){compressor.warn("Boolean || always true [{file}:{line},{col}]",self.start);return make_sequence(self,[self.left,make_node(AST_True,self)]).optimize(compressor)}else self.truthy=true}if(self.left.operator=="&&"){var lr=self.left.right.evaluate(compressor);if(lr&&!(lr instanceof AST_Node))return make_node(AST_Conditional,self,{condition:self.left.left,consequent:self.left.right,alternative:self.right}).optimize(compressor)}break}var associative=true;switch(self.operator){case"+":if(self.left instanceof AST_Constant&&self.right instanceof AST_Binary&&self.right.operator=="+"&&self.right.left instanceof AST_Constant&&self.right.is_string(compressor)){self=make_node(AST_Binary,self,{operator:"+",left:make_node(AST_String,self.left,{value:""+self.left.getValue()+self.right.left.getValue(),start:self.left.start,end:self.right.left.end}),right:self.right.right})}if(self.right instanceof AST_Constant&&self.left instanceof AST_Binary&&self.left.operator=="+"&&self.left.right instanceof AST_Constant&&self.left.is_string(compressor)){self=make_node(AST_Binary,self,{operator:"+",left:self.left.left,right:make_node(AST_String,self.right,{value:""+self.left.right.getValue()+self.right.getValue(),start:self.left.right.start,end:self.right.end})})}if(self.left instanceof AST_Binary&&self.left.operator=="+"&&self.left.is_string(compressor)&&self.left.right instanceof AST_Constant&&self.right instanceof AST_Binary&&self.right.operator=="+"&&self.right.left instanceof AST_Constant&&self.right.is_string(compressor)){self=make_node(AST_Binary,self,{operator:"+",left:make_node(AST_Binary,self.left,{operator:"+",left:self.left.left,right:make_node(AST_String,self.left.right,{value:""+self.left.right.getValue()+self.right.left.getValue(),start:self.left.right.start,end:self.right.left.end})}),right:self.right.right})}if(self.right instanceof AST_UnaryPrefix&&self.right.operator=="-"&&self.left.is_number(compressor)){self=make_node(AST_Binary,self,{operator:"-",left:self.left,right:self.right.expression});break}if(self.left instanceof AST_UnaryPrefix&&self.left.operator=="-"&&reversible()&&self.right.is_number(compressor)){self=make_node(AST_Binary,self,{operator:"-",left:self.right,right:self.left.expression});break}case"*":associative=compressor.option("unsafe_math");case"&":case"|":case"^":if(self.left.is_number(compressor)&&self.right.is_number(compressor)&&reversible()&&!(self.left instanceof AST_Binary&&self.left.operator!=self.operator&&PRECEDENCE[self.left.operator]>=PRECEDENCE[self.operator])){var reversed=make_node(AST_Binary,self,{operator:self.operator,left:self.right,right:self.left});if(self.right instanceof AST_Constant&&!(self.left instanceof AST_Constant)){self=best_of(compressor,reversed,self)}else{self=best_of(compressor,self,reversed)}}if(associative&&self.is_number(compressor)){if(self.right instanceof AST_Binary&&self.right.operator==self.operator){self=make_node(AST_Binary,self,{operator:self.operator,left:make_node(AST_Binary,self.left,{operator:self.operator,left:self.left,right:self.right.left,start:self.left.start,end:self.right.left.end}),right:self.right.right})}if(self.right instanceof AST_Constant&&self.left instanceof AST_Binary&&self.left.operator==self.operator){if(self.left.left instanceof AST_Constant){self=make_node(AST_Binary,self,{operator:self.operator,left:make_node(AST_Binary,self.left,{operator:self.operator,left:self.left.left,right:self.right,start:self.left.left.start,end:self.right.end}),right:self.left.right})}else if(self.left.right instanceof AST_Constant){self=make_node(AST_Binary,self,{operator:self.operator,left:make_node(AST_Binary,self.left,{operator:self.operator,left:self.left.right,right:self.right,start:self.left.right.start,end:self.right.end}),right:self.left.left})}}if(self.left instanceof AST_Binary&&self.left.operator==self.operator&&self.left.right instanceof AST_Constant&&self.right instanceof AST_Binary&&self.right.operator==self.operator&&self.right.left instanceof AST_Constant){self=make_node(AST_Binary,self,{operator:self.operator,left:make_node(AST_Binary,self.left,{operator:self.operator,left:make_node(AST_Binary,self.left.left,{operator:self.operator,left:self.left.right,right:self.right.left,start:self.left.right.start,end:self.right.left.end}),right:self.left.left}),right:self.right.right})}}}}if(self.right instanceof AST_Binary&&self.right.operator==self.operator&&(lazy_op[self.operator]||self.operator=="+"&&(self.right.left.is_string(compressor)||self.left.is_string(compressor)&&self.right.right.is_string(compressor)))){self.left=make_node(AST_Binary,self.left,{operator:self.operator,left:self.left,right:self.right.left});self.right=self.right.right;return self.transform(compressor)}var ev=self.evaluate(compressor);if(ev!==self){ev=make_node_from_constant(ev,self).optimize(compressor);return best_of(compressor,ev,self)}return self;function fuzzy_eval(node){if(node.truthy)return true;if(node.falsy)return false;if(node.is_truthy())return true;return node.evaluate(compressor)}});function recursive_ref(compressor,def){var node;for(var i=0;node=compressor.parent(i);i++){if(node instanceof AST_Lambda){var name=node.name;if(name&&name.definition()===def)break}}return node}OPT(AST_SymbolRef,function(self,compressor){if(!compressor.option("ie8")&&is_undeclared_ref(self)&&!(self.scope.uses_with&&compressor.find_parent(AST_With))){switch(self.name){case"undefined":return make_node(AST_Undefined,self).optimize(compressor);case"NaN":return make_node(AST_NaN,self).optimize(compressor);case"Infinity":return make_node(AST_Infinity,self).optimize(compressor)}}var parent=compressor.parent();if(compressor.option("reduce_vars")&&is_lhs(self,parent)!==self){var def=self.definition();var fixed=self.fixed_value();var single_use=def.single_use&&!(parent instanceof AST_Call&&parent.is_expr_pure(compressor));if(single_use&&fixed instanceof AST_Lambda){if(def.scope!==self.scope&&(!compressor.option("reduce_funcs")||def.escaped==1||fixed.inlined)){single_use=false}else if(recursive_ref(compressor,def)){single_use=false}else if(def.scope!==self.scope||def.orig[0]instanceof AST_SymbolFunarg){single_use=fixed.is_constant_expression(self.scope);if(single_use=="f"){var scope=self.scope;do{if(scope instanceof AST_Defun||scope instanceof AST_Function){scope.inlined=true}}while(scope=scope.parent_scope)}}}if(single_use&&fixed){def.single_use=false;if(fixed instanceof AST_Defun){fixed._squeezed=true;fixed=make_node(AST_Function,fixed,fixed);fixed.name=make_node(AST_SymbolLambda,fixed.name,fixed.name)}var value;if(def.recursive_refs>0){value=fixed.clone(true);var defun_def=value.name.definition();var lambda_def=value.variables.get(value.name.name);var name=lambda_def&&lambda_def.orig[0];if(!(name instanceof AST_SymbolLambda)){name=make_node(AST_SymbolLambda,value.name,value.name);name.scope=value;value.name=name;lambda_def=value.def_function(name)}value.walk(new TreeWalker(function(node){if(!(node instanceof AST_SymbolRef))return;var def=node.definition();if(def===defun_def){node.thedef=lambda_def;lambda_def.references.push(node)}else{def.single_use=false}}))}else{value=fixed.optimize(compressor);if(value===fixed)value=fixed.clone(true)}return value}if(fixed&&def.should_replace===undefined){var init;if(fixed instanceof AST_This){if(!(def.orig[0]instanceof AST_SymbolFunarg)&&all(def.references,function(ref){return def.scope===ref.scope})){init=fixed}}else{var ev=fixed.evaluate(compressor);if(ev!==fixed&&(compressor.option("unsafe_regexp")||!(ev instanceof RegExp))){init=make_node_from_constant(ev,fixed)}}if(init){var value_length=init.optimize(compressor).print_to_string().length;var fn;if(has_symbol_ref(fixed)){fn=function(){var result=init.optimize(compressor);return result===init?result.clone(true):result}}else{value_length=Math.min(value_length,fixed.print_to_string().length);fn=function(){var result=best_of_expression(init.optimize(compressor),fixed);return result===init||result===fixed?result.clone(true):result}}var name_length=def.name.length;var overhead=0;if(compressor.option("unused")&&!compressor.exposed(def)){overhead=(name_length+2+value_length)/(def.references.length-def.assignments)}def.should_replace=value_length<=name_length+overhead?fn:false}else{def.should_replace=false}}if(def.should_replace){return def.should_replace()}}return self;function has_symbol_ref(value){var found;value.walk(new TreeWalker(function(node){if(node instanceof AST_SymbolRef)found=true;if(found)return true}));return found}});function is_atomic(lhs,self){return lhs instanceof AST_SymbolRef||lhs.TYPE===self.TYPE}OPT(AST_Undefined,function(self,compressor){if(compressor.option("unsafe_undefined")){var undef=find_variable(compressor,"undefined");if(undef){var ref=make_node(AST_SymbolRef,self,{name:"undefined",scope:undef.scope,thedef:undef});ref.is_undefined=true;return ref}}var lhs=is_lhs(compressor.self(),compressor.parent());if(lhs&&is_atomic(lhs,self))return self;return make_node(AST_UnaryPrefix,self,{operator:"void",expression:make_node(AST_Number,self,{value:0})})});OPT(AST_Infinity,function(self,compressor){var lhs=is_lhs(compressor.self(),compressor.parent());if(lhs&&is_atomic(lhs,self))return self;if(compressor.option("keep_infinity")&&!(lhs&&!is_atomic(lhs,self))&&!find_variable(compressor,"Infinity"))return self;return make_node(AST_Binary,self,{operator:"/",left:make_node(AST_Number,self,{value:1}),right:make_node(AST_Number,self,{value:0})})});OPT(AST_NaN,function(self,compressor){var lhs=is_lhs(compressor.self(),compressor.parent());if(lhs&&!is_atomic(lhs,self)||find_variable(compressor,"NaN")){return make_node(AST_Binary,self,{operator:"/",left:make_node(AST_Number,self,{value:0}),right:make_node(AST_Number,self,{value:0})})}return self});function is_reachable(self,defs){var reachable=false;var find_ref=new TreeWalker(function(node){if(reachable)return true;if(node instanceof AST_SymbolRef&&member(node.definition(),defs)){return reachable=true}});var scan_scope=new TreeWalker(function(node){if(reachable)return true;if(node instanceof AST_Scope&&node!==self){var parent=scan_scope.parent();if(parent instanceof AST_Call&&parent.expression===node)return;node.walk(find_ref);return true}});self.walk(scan_scope);return reachable}var ASSIGN_OPS=makePredicate("+ - / * % >> << >>> | ^ &");var ASSIGN_OPS_COMMUTATIVE=makePredicate("* | ^ &");OPT(AST_Assign,function(self,compressor){var def;if(compressor.option("dead_code")&&self.left instanceof AST_SymbolRef&&(def=self.left.definition()).scope===compressor.find_parent(AST_Lambda)){var level=0,node,parent=self;do{node=parent;parent=compressor.parent(level++);if(parent instanceof AST_Exit){if(in_try(level,parent))break;if(is_reachable(def.scope,[def]))break;if(self.operator=="=")return self.right;def.fixed=false;return make_node(AST_Binary,self,{operator:self.operator.slice(0,-1),left:self.left,right:self.right}).optimize(compressor)}}while(parent instanceof AST_Binary&&parent.right===node||parent instanceof AST_Sequence&&parent.tail_node()===node)}self=self.lift_sequences(compressor);if(self.operator=="="&&self.left instanceof AST_SymbolRef&&self.right instanceof AST_Binary){if(self.right.left instanceof AST_SymbolRef&&self.right.left.name==self.left.name&&ASSIGN_OPS[self.right.operator]){self.operator=self.right.operator+"=";self.right=self.right.right}else if(self.right.right instanceof AST_SymbolRef&&self.right.right.name==self.left.name&&ASSIGN_OPS_COMMUTATIVE[self.right.operator]&&!self.right.left.has_side_effects(compressor)){self.operator=self.right.operator+"=";self.right=self.right.left}}return self;function in_try(level,node){var right=self.right;self.right=make_node(AST_Null,right);var may_throw=node.may_throw(compressor);self.right=right;var scope=self.left.definition().scope;var parent;while((parent=compressor.parent(level++))!==scope){if(parent instanceof AST_Try){if(parent.bfinally)return true;if(may_throw&&parent.bcatch)return true}}}});OPT(AST_Conditional,function(self,compressor){if(!compressor.option("conditionals"))return self;if(self.condition instanceof AST_Sequence){var expressions=self.condition.expressions.slice();self.condition=expressions.pop();expressions.push(self);return make_sequence(self,expressions)}var cond=self.condition.is_truthy()||self.condition.tail_node().evaluate(compressor);if(!cond){compressor.warn("Condition always false [{file}:{line},{col}]",self.start);return make_sequence(self,[self.condition,self.alternative]).optimize(compressor)}else if(!(cond instanceof AST_Node)){compressor.warn("Condition always true [{file}:{line},{col}]",self.start);return make_sequence(self,[self.condition,self.consequent]).optimize(compressor)}var negated=cond.negate(compressor,first_in_statement(compressor));if(best_of(compressor,cond,negated)===negated){self=make_node(AST_Conditional,self,{condition:negated,consequent:self.alternative,alternative:self.consequent})}var condition=self.condition;var consequent=self.consequent;var alternative=self.alternative;if(condition instanceof AST_SymbolRef&&consequent instanceof AST_SymbolRef&&condition.definition()===consequent.definition()){return make_node(AST_Binary,self,{operator:"||",left:condition,right:alternative})}var seq_tail=consequent.tail_node();if(seq_tail instanceof AST_Assign){var is_eq=seq_tail.operator=="=";var alt_tail=is_eq?alternative.tail_node():alternative;if((is_eq||consequent instanceof AST_Assign)&&alt_tail instanceof AST_Assign&&seq_tail.operator==alt_tail.operator&&seq_tail.left.equivalent_to(alt_tail.left)&&(!condition.has_side_effects(compressor)||is_eq&&!seq_tail.left.has_side_effects(compressor))){return make_node(AST_Assign,self,{operator:seq_tail.operator,left:seq_tail.left,right:make_node(AST_Conditional,self,{condition:condition,consequent:pop_lhs(consequent),alternative:pop_lhs(alternative)})})}}var arg_index;if(consequent instanceof AST_Call&&alternative.TYPE===consequent.TYPE&&consequent.args.length>0&&consequent.args.length==alternative.args.length&&consequent.expression.equivalent_to(alternative.expression)&&!condition.has_side_effects(compressor)&&!consequent.expression.has_side_effects(compressor)&&typeof(arg_index=single_arg_diff())=="number"){var node=consequent.clone();node.args[arg_index]=make_node(AST_Conditional,self,{condition:condition,consequent:consequent.args[arg_index],alternative:alternative.args[arg_index]});return node}if(consequent instanceof AST_Conditional&&consequent.alternative.equivalent_to(alternative)){return make_node(AST_Conditional,self,{condition:make_node(AST_Binary,self,{left:condition,operator:"&&",right:consequent.condition}),consequent:consequent.consequent,alternative:alternative})}if(consequent.equivalent_to(alternative)){return make_sequence(self,[condition,consequent]).optimize(compressor)}if((consequent instanceof AST_Sequence||alternative instanceof AST_Sequence)&&consequent.tail_node().equivalent_to(alternative.tail_node())){return make_sequence(self,[make_node(AST_Conditional,self,{condition:condition,consequent:pop_seq(consequent),alternative:pop_seq(alternative)}),consequent.tail_node()]).optimize(compressor)}if(consequent instanceof AST_Binary&&consequent.operator=="||"&&consequent.right.equivalent_to(alternative)){return make_node(AST_Binary,self,{operator:"||",left:make_node(AST_Binary,self,{operator:"&&",left:condition,right:consequent.left}),right:alternative}).optimize(compressor)}var in_bool=compressor.option("booleans")&&compressor.in_boolean_context();if(is_true(self.consequent)){if(is_false(self.alternative)){return booleanize(condition)}return make_node(AST_Binary,self,{operator:"||",left:booleanize(condition),right:self.alternative})}if(is_false(self.consequent)){if(is_true(self.alternative)){return booleanize(condition.negate(compressor))}return make_node(AST_Binary,self,{operator:"&&",left:booleanize(condition.negate(compressor)),right:self.alternative})}if(is_true(self.alternative)){return make_node(AST_Binary,self,{operator:"||",left:booleanize(condition.negate(compressor)),right:self.consequent})}if(is_false(self.alternative)){return make_node(AST_Binary,self,{operator:"&&",left:booleanize(condition),right:self.consequent})}return self;function booleanize(node){if(node.is_boolean(compressor))return node;return make_node(AST_UnaryPrefix,node,{operator:"!",expression:node.negate(compressor)})}function is_true(node){return node instanceof AST_True||in_bool&&node instanceof AST_Constant&&node.getValue()||node instanceof AST_UnaryPrefix&&node.operator=="!"&&node.expression instanceof AST_Constant&&!node.expression.getValue()}function is_false(node){return node instanceof AST_False||in_bool&&node instanceof AST_Constant&&!node.getValue()||node instanceof AST_UnaryPrefix&&node.operator=="!"&&node.expression instanceof AST_Constant&&node.expression.getValue()}function single_arg_diff(){var a=consequent.args;var b=alternative.args;for(var i=0,len=a.length;i<len;i++){if(!a[i].equivalent_to(b[i])){for(var j=i+1;j<len;j++){if(!a[j].equivalent_to(b[j]))return}return i}}}function pop_lhs(node){if(!(node instanceof AST_Sequence))return node.right;var exprs=node.expressions.slice();exprs.push(exprs.pop().right);return make_sequence(node,exprs)}function pop_seq(node){if(!(node instanceof AST_Sequence))return make_node(AST_Number,node,{value:0});return make_sequence(node,node.expressions.slice(0,-1))}});OPT(AST_Boolean,function(self,compressor){if(!compressor.option("booleans"))return self;if(compressor.in_boolean_context())return make_node(AST_Number,self,{value:+self.value});var p=compressor.parent();if(p instanceof AST_Binary&&(p.operator=="=="||p.operator=="!=")){compressor.warn("Non-strict equality against boolean: {operator} {value} [{file}:{line},{col}]",{operator:p.operator,value:self.value,file:p.start.file,line:p.start.line,col:p.start.col});return make_node(AST_Number,self,{value:+self.value})}return make_node(AST_UnaryPrefix,self,{operator:"!",expression:make_node(AST_Number,self,{value:1-self.value})})});function safe_to_flatten(value,compressor){if(value instanceof AST_SymbolRef){value=value.fixed_value()}if(!value)return false;return!(value instanceof AST_Lambda)||compressor.parent()instanceof AST_New||!value.contains_this()}OPT(AST_Sub,function(self,compressor){var expr=self.expression;var prop=self.property;if(compressor.option("properties")){var key=prop.evaluate(compressor);if(key!==prop){if(typeof key=="string"){if(key=="undefined"){key=undefined}else{var value=parseFloat(key);if(value.toString()==key){key=value}}}prop=self.property=best_of_expression(prop,make_node_from_constant(key,prop).transform(compressor));var property=""+key;if(is_identifier_string(property)&&property.length<=prop.print_to_string().length+1){return make_node(AST_Dot,self,{expression:expr,property:property}).optimize(compressor)}}}var fn;if(compressor.option("arguments")&&expr instanceof AST_SymbolRef&&expr.name=="arguments"&&expr.definition().orig.length==1&&(fn=expr.scope)instanceof AST_Lambda&&prop instanceof AST_Number){var index=prop.getValue();var argname=fn.argnames[index];if(argname&&compressor.has_directive("use strict")){var def=argname.definition();if(!compressor.option("reduce_vars")||def.assignments||def.orig.length>1){argname=null}}else if(!argname&&!compressor.option("keep_fargs")&&index<fn.argnames.length+5){while(index>=fn.argnames.length){argname=make_node(AST_SymbolFunarg,fn,{name:fn.make_var_name("argument_"+fn.argnames.length),scope:fn});fn.argnames.push(argname);fn.enclosed.push(fn.def_variable(argname))}}if(argname&&find_if(function(node){return node.name===argname.name},fn.argnames)===argname){var sym=make_node(AST_SymbolRef,self,argname);sym.reference({});delete argname.__unused;return sym}}if(is_lhs(self,compressor.parent()))return self;if(key!==prop){var sub=self.flatten_object(property,compressor);if(sub){expr=self.expression=sub.expression;prop=self.property=sub.property}}if(compressor.option("properties")&&compressor.option("side_effects")&&prop instanceof AST_Number&&expr instanceof AST_Array){var index=prop.getValue();var elements=expr.elements;var retValue=elements[index];if(safe_to_flatten(retValue,compressor)){var flatten=true;var values=[];for(var i=elements.length;--i>index;){var value=elements[i].drop_side_effect_free(compressor);if(value){values.unshift(value);if(flatten&&value.has_side_effects(compressor))flatten=false}}retValue=retValue instanceof AST_Hole?make_node(AST_Undefined,retValue):retValue;if(!flatten)values.unshift(retValue);while(--i>=0){var value=elements[i].drop_side_effect_free(compressor);if(value)values.unshift(value);else index--}if(flatten){values.push(retValue);return make_sequence(self,values).optimize(compressor)}else return make_node(AST_Sub,self,{expression:make_node(AST_Array,expr,{elements:values}),property:make_node(AST_Number,prop,{value:index})})}}var ev=self.evaluate(compressor);if(ev!==self){ev=make_node_from_constant(ev,self).optimize(compressor);return best_of(compressor,ev,self)}return self});AST_Scope.DEFMETHOD("contains_this",function(){var result;var self=this;self.walk(new TreeWalker(function(node){if(result)return true;if(node instanceof AST_This)return result=true;if(node!==self&&node instanceof AST_Scope)return true}));return result});AST_PropAccess.DEFMETHOD("flatten_object",function(key,compressor){if(!compressor.option("properties"))return;var expr=this.expression;if(expr instanceof AST_Object){var props=expr.properties;for(var i=props.length;--i>=0;){var prop=props[i];if(""+prop.key==key){if(!all(props,function(prop){return prop instanceof AST_ObjectKeyVal}))break;if(!safe_to_flatten(prop.value,compressor))break;return make_node(AST_Sub,this,{expression:make_node(AST_Array,expr,{elements:props.map(function(prop){return prop.value})}),property:make_node(AST_Number,this,{value:i})})}}}});OPT(AST_Dot,function(self,compressor){if(self.property=="arguments"||self.property=="caller"){compressor.warn("Function.protoype.{prop} not supported [{file}:{line},{col}]",{prop:self.property,file:self.start.file,line:self.start.line,col:self.start.col})}if(is_lhs(self,compressor.parent()))return self;if(compressor.option("unsafe_proto")&&self.expression instanceof AST_Dot&&self.expression.property=="prototype"){var exp=self.expression.expression;if(is_undeclared_ref(exp))switch(exp.name){case"Array":self.expression=make_node(AST_Array,self.expression,{elements:[]});break;case"Function":self.expression=make_node(AST_Function,self.expression,{argnames:[],body:[]});break;case"Number":self.expression=make_node(AST_Number,self.expression,{value:0});break;case"Object":self.expression=make_node(AST_Object,self.expression,{properties:[]});break;case"RegExp":self.expression=make_node(AST_RegExp,self.expression,{value:/t/});break;case"String":self.expression=make_node(AST_String,self.expression,{value:""});break}}var sub=self.flatten_object(self.property,compressor);if(sub)return sub.optimize(compressor);var ev=self.evaluate(compressor);if(ev!==self){ev=make_node_from_constant(ev,self).optimize(compressor);return best_of(compressor,ev,self)}return self});OPT(AST_Return,function(self,compressor){if(self.value&&is_undefined(self.value,compressor)){self.value=null}return self})})(function(node,optimizer){node.DEFMETHOD("optimize",function(compressor){var self=this;if(self._optimized)return self;if(compressor.has_directive("use asm"))return self;var opt=optimizer(self,compressor);opt._optimized=true;return opt})});"use strict";function SourceMap(options){options=defaults(options,{file:null,root:null,orig:null,orig_line_diff:0,dest_line_diff:0},true);var generator=new MOZ_SourceMap.SourceMapGenerator({file:options.file,sourceRoot:options.root});var maps=options.orig&&Object.create(null);if(maps)for(var source in options.orig){var map=new MOZ_SourceMap.SourceMapConsumer(options.orig[source]);if(Array.isArray(options.orig[source].sources)){map._sources.toArray().forEach(function(source){var sourceContent=map.sourceContentFor(source,true);if(sourceContent)generator.setSourceContent(source,sourceContent)})}maps[source]=map}return{add:function(source,gen_line,gen_col,orig_line,orig_col,name){var map=maps&&maps[source];if(map){var info=map.originalPositionFor({line:orig_line,column:orig_col});if(info.source===null)return;source=info.source;orig_line=info.line;orig_col=info.column;name=info.name||name}generator.addMapping({name:name,source:source,generated:{line:gen_line+options.dest_line_diff,column:gen_col},original:{line:orig_line+options.orig_line_diff,column:orig_col}})},get:function(){return generator},toString:function(){return JSON.stringify(generator.toJSON())}}}"use strict";(function(){function normalize_directives(body){var in_directive=true;for(var i=0;i<body.length;i++){if(in_directive&&body[i]instanceof AST_Statement&&body[i].body instanceof AST_String){body[i]=new AST_Directive({start:body[i].start,end:body[i].end,value:body[i].body.value})}else if(in_directive&&!(body[i]instanceof AST_Statement&&body[i].body instanceof AST_String)){in_directive=false}}return body}var MOZ_TO_ME={Program:function(M){return new AST_Toplevel({start:my_start_token(M),end:my_end_token(M),body:normalize_directives(M.body.map(from_moz))})},FunctionDeclaration:function(M){return new AST_Defun({start:my_start_token(M),end:my_end_token(M),name:from_moz(M.id),argnames:M.params.map(from_moz),body:normalize_directives(from_moz(M.body).body)})},FunctionExpression:function(M){return new AST_Function({start:my_start_token(M),end:my_end_token(M),name:from_moz(M.id),argnames:M.params.map(from_moz),body:normalize_directives(from_moz(M.body).body)})},ExpressionStatement:function(M){return new AST_SimpleStatement({start:my_start_token(M),end:my_end_token(M),body:from_moz(M.expression)})},TryStatement:function(M){var handlers=M.handlers||[M.handler];if(handlers.length>1||M.guardedHandlers&&M.guardedHandlers.length){throw new Error("Multiple catch clauses are not supported.")}return new AST_Try({start:my_start_token(M),end:my_end_token(M),body:from_moz(M.block).body,bcatch:from_moz(handlers[0]),bfinally:M.finalizer?new AST_Finally(from_moz(M.finalizer)):null})},Property:function(M){var key=M.key;var args={start:my_start_token(key),end:my_end_token(M.value),key:key.type=="Identifier"?key.name:key.value,value:from_moz(M.value)};if(M.kind=="init")return new AST_ObjectKeyVal(args);args.key=new AST_SymbolAccessor({name:args.key});args.value=new AST_Accessor(args.value);if(M.kind=="get")return new AST_ObjectGetter(args);if(M.kind=="set")return new AST_ObjectSetter(args)},ArrayExpression:function(M){return new AST_Array({start:my_start_token(M),end:my_end_token(M),elements:M.elements.map(function(elem){return elem===null?new AST_Hole:from_moz(elem)})})},ObjectExpression:function(M){return new AST_Object({start:my_start_token(M),end:my_end_token(M),properties:M.properties.map(function(prop){prop.type="Property";return from_moz(prop)})})},SequenceExpression:function(M){return new AST_Sequence({start:my_start_token(M),end:my_end_token(M),expressions:M.expressions.map(from_moz)})},MemberExpression:function(M){return new(M.computed?AST_Sub:AST_Dot)({start:my_start_token(M),end:my_end_token(M),property:M.computed?from_moz(M.property):M.property.name,expression:from_moz(M.object)})},SwitchCase:function(M){return new(M.test?AST_Case:AST_Default)({start:my_start_token(M),end:my_end_token(M),expression:from_moz(M.test),body:M.consequent.map(from_moz)})},VariableDeclaration:function(M){return new AST_Var({start:my_start_token(M),end:my_end_token(M),definitions:M.declarations.map(from_moz)})},Literal:function(M){var val=M.value,args={start:my_start_token(M),end:my_end_token(M)};if(val===null)return new AST_Null(args);var rx=M.regex;if(rx&&rx.pattern){args.value=new RegExp(rx.pattern,rx.flags);args.value.raw_source=rx.pattern;return new AST_RegExp(args)}else if(rx){args.value=M.regex&&M.raw?M.raw:val;return new AST_RegExp(args)}switch(typeof val){case"string":args.value=val;return new AST_String(args);case"number":args.value=val;return new AST_Number(args);case"boolean":return new(val?AST_True:AST_False)(args)}},Identifier:function(M){var p=FROM_MOZ_STACK[FROM_MOZ_STACK.length-2];return new(p.type=="LabeledStatement"?AST_Label:p.type=="VariableDeclarator"&&p.id===M?AST_SymbolVar:p.type=="FunctionExpression"?p.id===M?AST_SymbolLambda:AST_SymbolFunarg:p.type=="FunctionDeclaration"?p.id===M?AST_SymbolDefun:AST_SymbolFunarg:p.type=="CatchClause"?AST_SymbolCatch:p.type=="BreakStatement"||p.type=="ContinueStatement"?AST_LabelRef:AST_SymbolRef)({start:my_start_token(M),end:my_end_token(M),name:M.name})}};MOZ_TO_ME.UpdateExpression=MOZ_TO_ME.UnaryExpression=function To_Moz_Unary(M){var prefix="prefix"in M?M.prefix:M.type=="UnaryExpression"?true:false;return new(prefix?AST_UnaryPrefix:AST_UnaryPostfix)({start:my_start_token(M),end:my_end_token(M),operator:M.operator,expression:from_moz(M.argument)})};map("EmptyStatement",AST_EmptyStatement);map("BlockStatement",AST_BlockStatement,"body@body");map("IfStatement",AST_If,"test>condition, consequent>body, alternate>alternative");map("LabeledStatement",AST_LabeledStatement,"label>label, body>body");map("BreakStatement",AST_Break,"label>label");map("ContinueStatement",AST_Continue,"label>label");map("WithStatement",AST_With,"object>expression, body>body");map("SwitchStatement",AST_Switch,"discriminant>expression, cases@body");map("ReturnStatement",AST_Return,"argument>value");map("ThrowStatement",AST_Throw,"argument>value");map("WhileStatement",AST_While,"test>condition, body>body");map("DoWhileStatement",AST_Do,"test>condition, body>body");map("ForStatement",AST_For,"init>init, test>condition, update>step, body>body");map("ForInStatement",AST_ForIn,"left>init, right>object, body>body");map("DebuggerStatement",AST_Debugger);map("VariableDeclarator",AST_VarDef,"id>name, init>value");map("CatchClause",AST_Catch,"param>argname, body%body");map("ThisExpression",AST_This);map("BinaryExpression",AST_Binary,"operator=operator, left>left, right>right");map("LogicalExpression",AST_Binary,"operator=operator, left>left, right>right");map("AssignmentExpression",AST_Assign,"operator=operator, left>left, right>right");map("ConditionalExpression",AST_Conditional,"test>condition, consequent>consequent, alternate>alternative");map("NewExpression",AST_New,"callee>expression, arguments@args");map("CallExpression",AST_Call,"callee>expression, arguments@args");def_to_moz(AST_Toplevel,function To_Moz_Program(M){return to_moz_scope("Program",M)});def_to_moz(AST_Defun,function To_Moz_FunctionDeclaration(M){return{type:"FunctionDeclaration",id:to_moz(M.name),params:M.argnames.map(to_moz),body:to_moz_scope("BlockStatement",M)}});def_to_moz(AST_Function,function To_Moz_FunctionExpression(M){return{type:"FunctionExpression",id:to_moz(M.name),params:M.argnames.map(to_moz),body:to_moz_scope("BlockStatement",M)}});def_to_moz(AST_Directive,function To_Moz_Directive(M){return{type:"ExpressionStatement",expression:{type:"Literal",value:M.value}}});def_to_moz(AST_SimpleStatement,function To_Moz_ExpressionStatement(M){return{type:"ExpressionStatement",expression:to_moz(M.body)}});def_to_moz(AST_SwitchBranch,function To_Moz_SwitchCase(M){return{type:"SwitchCase",test:to_moz(M.expression),consequent:M.body.map(to_moz)}});def_to_moz(AST_Try,function To_Moz_TryStatement(M){return{type:"TryStatement",block:to_moz_block(M),handler:to_moz(M.bcatch),guardedHandlers:[],finalizer:to_moz(M.bfinally)}});def_to_moz(AST_Catch,function To_Moz_CatchClause(M){return{type:"CatchClause",param:to_moz(M.argname),guard:null,body:to_moz_block(M)}});def_to_moz(AST_Definitions,function To_Moz_VariableDeclaration(M){return{type:"VariableDeclaration",kind:"var",declarations:M.definitions.map(to_moz)}});def_to_moz(AST_Sequence,function To_Moz_SequenceExpression(M){return{type:"SequenceExpression",expressions:M.expressions.map(to_moz)}});def_to_moz(AST_PropAccess,function To_Moz_MemberExpression(M){var isComputed=M instanceof AST_Sub;return{type:"MemberExpression",object:to_moz(M.expression),computed:isComputed,property:isComputed?to_moz(M.property):{type:"Identifier",name:M.property}}});def_to_moz(AST_Unary,function To_Moz_Unary(M){return{type:M.operator=="++"||M.operator=="--"?"UpdateExpression":"UnaryExpression",operator:M.operator,prefix:M instanceof AST_UnaryPrefix,argument:to_moz(M.expression)}});def_to_moz(AST_Binary,function To_Moz_BinaryExpression(M){return{type:M.operator=="&&"||M.operator=="||"?"LogicalExpression":"BinaryExpression",left:to_moz(M.left),operator:M.operator,right:to_moz(M.right)}});def_to_moz(AST_Array,function To_Moz_ArrayExpression(M){return{type:"ArrayExpression",elements:M.elements.map(to_moz)}});def_to_moz(AST_Object,function To_Moz_ObjectExpression(M){return{type:"ObjectExpression",properties:M.properties.map(to_moz)}});def_to_moz(AST_ObjectProperty,function To_Moz_Property(M){var key={type:"Literal",value:M.key instanceof AST_SymbolAccessor?M.key.name:M.key};var kind;if(M instanceof AST_ObjectKeyVal){kind="init"}else if(M instanceof AST_ObjectGetter){kind="get"}else if(M instanceof AST_ObjectSetter){kind="set"}return{type:"Property",kind:kind,key:key,value:to_moz(M.value)}});def_to_moz(AST_Symbol,function To_Moz_Identifier(M){var def=M.definition();return{type:"Identifier",name:def?def.mangled_name||def.name:M.name}});def_to_moz(AST_RegExp,function To_Moz_RegExpLiteral(M){var flags=M.value.toString().match(/[gimuy]*$/)[0];var value="/"+M.value.raw_source+"/"+flags;return{type:"Literal",value:value,raw:value,regex:{pattern:M.value.raw_source,flags:flags}}});def_to_moz(AST_Constant,function To_Moz_Literal(M){var value=M.value;if(typeof value==="number"&&(value<0||value===0&&1/value<0)){return{type:"UnaryExpression",operator:"-",prefix:true,argument:{type:"Literal",value:-value,raw:M.start.raw}}}return{type:"Literal",value:value,raw:M.start.raw}});def_to_moz(AST_Atom,function To_Moz_Atom(M){return{type:"Identifier",name:String(M.value)}});AST_Boolean.DEFMETHOD("to_mozilla_ast",AST_Constant.prototype.to_mozilla_ast);AST_Null.DEFMETHOD("to_mozilla_ast",AST_Constant.prototype.to_mozilla_ast);AST_Hole.DEFMETHOD("to_mozilla_ast",function To_Moz_ArrayHole(){return null});AST_Block.DEFMETHOD("to_mozilla_ast",AST_BlockStatement.prototype.to_mozilla_ast);AST_Lambda.DEFMETHOD("to_mozilla_ast",AST_Function.prototype.to_mozilla_ast);function raw_token(moznode){if(moznode.type=="Literal"){return moznode.raw!=null?moznode.raw:moznode.value+""}}function my_start_token(moznode){var loc=moznode.loc,start=loc&&loc.start;var range=moznode.range;return new AST_Token({file:loc&&loc.source,line:start&&start.line,col:start&&start.column,pos:range?range[0]:moznode.start,endline:start&&start.line,endcol:start&&start.column,endpos:range?range[0]:moznode.start,raw:raw_token(moznode)})}function my_end_token(moznode){var loc=moznode.loc,end=loc&&loc.end;var range=moznode.range;return new AST_Token({file:loc&&loc.source,line:end&&end.line,col:end&&end.column,pos:range?range[1]:moznode.end,endline:end&&end.line,endcol:end&&end.column,endpos:range?range[1]:moznode.end,raw:raw_token(moznode)})}function map(moztype,mytype,propmap){var moz_to_me="function From_Moz_"+moztype+"(M){\n";moz_to_me+="return new U2."+mytype.name+"({\n"+"start: my_start_token(M),\n"+"end: my_end_token(M)";var me_to_moz="function To_Moz_"+moztype+"(M){\n";me_to_moz+="return {\n"+"type: "+JSON.stringify(moztype);if(propmap)propmap.split(/\s*,\s*/).forEach(function(prop){var m=/([a-z0-9$_]+)(=|@|>|%)([a-z0-9$_]+)/i.exec(prop);if(!m)throw new Error("Can't understand property map: "+prop);var moz=m[1],how=m[2],my=m[3];moz_to_me+=",\n"+my+": ";me_to_moz+=",\n"+moz+": ";switch(how){case"@":moz_to_me+="M."+moz+".map(from_moz)";me_to_moz+="M."+my+".map(to_moz)";break;case">":moz_to_me+="from_moz(M."+moz+")";me_to_moz+="to_moz(M."+my+")";break;case"=":moz_to_me+="M."+moz;me_to_moz+="M."+my;break;case"%":moz_to_me+="from_moz(M."+moz+").body";me_to_moz+="to_moz_block(M)";break;default:throw new Error("Can't understand operator in propmap: "+prop)}});moz_to_me+="\n})\n}";me_to_moz+="\n}\n}";moz_to_me=new Function("U2","my_start_token","my_end_token","from_moz","return("+moz_to_me+")")(exports,my_start_token,my_end_token,from_moz);me_to_moz=new Function("to_moz","to_moz_block","to_moz_scope","return("+me_to_moz+")")(to_moz,to_moz_block,to_moz_scope);MOZ_TO_ME[moztype]=moz_to_me;def_to_moz(mytype,me_to_moz)}var FROM_MOZ_STACK=null;function from_moz(node){FROM_MOZ_STACK.push(node);var ret=node!=null?MOZ_TO_ME[node.type](node):null;FROM_MOZ_STACK.pop();return ret}AST_Node.from_mozilla_ast=function(node){var save_stack=FROM_MOZ_STACK;FROM_MOZ_STACK=[];var ast=from_moz(node);FROM_MOZ_STACK=save_stack;ast.walk(new TreeWalker(function(node){if(node instanceof AST_LabelRef){for(var level=0,parent;parent=this.parent(level);level++){if(parent instanceof AST_Scope)break;if(parent instanceof AST_LabeledStatement&&parent.label.name==node.name){node.thedef=parent.label;break}}if(!node.thedef){var s=node.start;js_error("Undefined label "+node.name,s.file,s.line,s.col,s.pos)}}}));return ast};function set_moz_loc(mynode,moznode,myparent){var start=mynode.start;var end=mynode.end;if(start.pos!=null&&end.endpos!=null){moznode.range=[start.pos,end.endpos]}if(start.line){moznode.loc={start:{line:start.line,column:start.col},end:end.endline?{line:end.endline,column:end.endcol}:null};if(start.file){moznode.loc.source=start.file}}return moznode}function def_to_moz(mytype,handler){mytype.DEFMETHOD("to_mozilla_ast",function(){return set_moz_loc(this,handler(this))})}function to_moz(node){return node!=null?node.to_mozilla_ast():null}function to_moz_block(node){return{type:"BlockStatement",body:node.body.map(to_moz)}}function to_moz_scope(type,node){var body=node.body.map(to_moz);if(node.body[0]instanceof AST_SimpleStatement&&node.body[0].body instanceof AST_String){body.unshift(to_moz(new AST_EmptyStatement(node.body[0])))}return{type:type,body:body}}})();"use strict";function find_builtins(reserved){["null","true","false","Infinity","-Infinity","undefined"].forEach(add);[Array,Boolean,Date,Error,Function,Math,Number,Object,RegExp,String].forEach(function(ctor){Object.getOwnPropertyNames(ctor).map(add);if(ctor.prototype){Object.getOwnPropertyNames(ctor.prototype).map(add)}});function add(name){push_uniq(reserved,name)}}function reserve_quoted_keys(ast,reserved){ast.walk(new TreeWalker(function(node){if(node instanceof AST_ObjectKeyVal&&node.quote){add(node.key)}else if(node instanceof AST_Sub){addStrings(node.property,add)}}));function add(name){push_uniq(reserved,name)}}function addStrings(node,add){node.walk(new TreeWalker(function(node){if(node instanceof AST_Sequence){addStrings(node.tail_node(),add)}else if(node instanceof AST_String){add(node.value)}else if(node instanceof AST_Conditional){addStrings(node.consequent,add);addStrings(node.alternative,add)}return true}))}function mangle_properties(ast,options){options=defaults(options,{builtins:false,cache:null,debug:false,keep_quoted:false,only_cache:false,regex:null,reserved:null},true);var reserved=options.reserved;if(!Array.isArray(reserved))reserved=[];if(!options.builtins)find_builtins(reserved);var cname=-1;var cache;if(options.cache){cache=options.cache.props;cache.each(function(mangled_name){push_uniq(reserved,mangled_name)})}else{cache=new Dictionary}var regex=options.regex;var debug=options.debug!==false;var debug_suffix;if(debug)debug_suffix=options.debug===true?"":options.debug;var names_to_mangle=[];var unmangleable=[];ast.walk(new TreeWalker(function(node){if(node instanceof AST_ObjectKeyVal){add(node.key)}else if(node instanceof AST_ObjectProperty){add(node.key.name)}else if(node instanceof AST_Dot){add(node.property)}else if(node instanceof AST_Sub){addStrings(node.property,add)}else if(node instanceof AST_Call&&node.expression.print_to_string()=="Object.defineProperty"){addStrings(node.args[1],add)}}));return ast.transform(new TreeTransformer(function(node){if(node instanceof AST_ObjectKeyVal){node.key=mangle(node.key)}else if(node instanceof AST_ObjectProperty){node.key.name=mangle(node.key.name)}else if(node instanceof AST_Dot){node.property=mangle(node.property)}else if(!options.keep_quoted&&node instanceof AST_Sub){node.property=mangleStrings(node.property)}else if(node instanceof AST_Call&&node.expression.print_to_string()=="Object.defineProperty"){node.args[1]=mangleStrings(node.args[1])}}));function can_mangle(name){if(unmangleable.indexOf(name)>=0)return false;if(reserved.indexOf(name)>=0)return false;if(options.only_cache)return cache.has(name);if(/^-?[0-9]+(\.[0-9]+)?(e[+-][0-9]+)?$/.test(name))return false;return true}function should_mangle(name){if(regex&&!regex.test(name))return false;if(reserved.indexOf(name)>=0)return false;return cache.has(name)||names_to_mangle.indexOf(name)>=0}function add(name){if(can_mangle(name))push_uniq(names_to_mangle,name);if(!should_mangle(name))push_uniq(unmangleable,name)}function mangle(name){if(!should_mangle(name)){return name}var mangled=cache.get(name);if(!mangled){if(debug){var debug_mangled="_$"+name+"$"+debug_suffix+"_";if(can_mangle(debug_mangled))mangled=debug_mangled}if(!mangled)do{mangled=base54(++cname)}while(!can_mangle(mangled));cache.set(name,mangled)}return mangled}function mangleStrings(node){return node.transform(new TreeTransformer(function(node){if(node instanceof AST_Sequence){var last=node.expressions.length-1;node.expressions[last]=mangleStrings(node.expressions[last])}else if(node instanceof AST_String){node.value=mangle(node.value)}else if(node instanceof AST_Conditional){node.consequent=mangleStrings(node.consequent);node.alternative=mangleStrings(node.alternative)}return node}))}}"use strict";var to_ascii=typeof atob=="undefined"?function(b64){return new Buffer(b64,"base64").toString()}:atob;var to_base64=typeof btoa=="undefined"?function(str){return new Buffer(str).toString("base64")}:btoa;function read_source_map(name,code){var match=/\n\/\/# sourceMappingURL=data:application\/json(;.*?)?;base64,(.*)/.exec(code);if(!match){AST_Node.warn("inline source map not found: "+name);return null}return to_ascii(match[2])}function parse_source_map(content){try{return JSON.parse(content)}catch(ex){throw new Error("invalid input source map: "+content)}}function set_shorthand(name,options,keys){if(options[name]){keys.forEach(function(key){if(options[key]){if(typeof options[key]!="object")options[key]={};if(!(name in options[key]))options[key][name]=options[name]}})}}function init_cache(cache){if(!cache)return;if(!("props"in cache)){cache.props=new Dictionary}else if(!(cache.props instanceof Dictionary)){cache.props=Dictionary.fromObject(cache.props)}}function to_json(cache){return{props:cache.props.toObject()}}function minify(files,options){var warn_function=AST_Node.warn_function;try{options=defaults(options,{compress:{},enclose:false,ie8:false,keep_fnames:false,mangle:{},nameCache:null,output:{},parse:{},rename:undefined,sourceMap:false,timings:false,toplevel:false,warnings:false,wrap:false},true);var timings=options.timings&&{start:Date.now()};if(options.rename===undefined){options.rename=options.compress&&options.mangle}set_shorthand("ie8",options,["compress","mangle","output"]);set_shorthand("keep_fnames",options,["compress","mangle"]);set_shorthand("toplevel",options,["compress","mangle"]);set_shorthand("warnings",options,["compress"]);var quoted_props;if(options.mangle){options.mangle=defaults(options.mangle,{cache:options.nameCache&&(options.nameCache.vars||{}),eval:false,ie8:false,keep_fnames:false,properties:false,reserved:[],toplevel:false},true);if(options.mangle.properties){if(typeof options.mangle.properties!="object"){options.mangle.properties={}}if(options.mangle.properties.keep_quoted){quoted_props=options.mangle.properties.reserved;if(!Array.isArray(quoted_props))quoted_props=[];options.mangle.properties.reserved=quoted_props}if(options.nameCache&&!("cache"in options.mangle.properties)){options.mangle.properties.cache=options.nameCache.props||{}}}init_cache(options.mangle.cache);init_cache(options.mangle.properties.cache)}if(options.sourceMap){options.sourceMap=defaults(options.sourceMap,{content:null,filename:null,includeSources:false,root:null,url:null},true)}var warnings=[];if(options.warnings&&!AST_Node.warn_function){AST_Node.warn_function=function(warning){warnings.push(warning)}}if(timings)timings.parse=Date.now();var source_maps,toplevel;if(files instanceof AST_Toplevel){toplevel=files}else{if(typeof files=="string"){files=[files]}options.parse=options.parse||{};options.parse.toplevel=null;var source_map_content=options.sourceMap&&options.sourceMap.content;if(typeof source_map_content=="string"&&source_map_content!="inline"){source_map_content=parse_source_map(source_map_content)}source_maps=source_map_content&&Object.create(null);for(var name in files)if(HOP(files,name)){options.parse.filename=name;options.parse.toplevel=parse(files[name],options.parse);if(source_maps){if(source_map_content=="inline"){var inlined_content=read_source_map(name,files[name]);if(inlined_content){source_maps[name]=parse_source_map(inlined_content)}}else{source_maps[name]=source_map_content}}}toplevel=options.parse.toplevel}if(quoted_props){reserve_quoted_keys(toplevel,quoted_props)}if(options.wrap){toplevel=toplevel.wrap_commonjs(options.wrap)}if(options.enclose){toplevel=toplevel.wrap_enclose(options.enclose)}if(timings)timings.rename=Date.now();if(options.rename){toplevel.figure_out_scope(options.mangle);toplevel.expand_names(options.mangle)}if(timings)timings.compress=Date.now();if(options.compress)toplevel=new Compressor(options.compress).compress(toplevel);if(timings)timings.scope=Date.now();if(options.mangle)toplevel.figure_out_scope(options.mangle);if(timings)timings.mangle=Date.now();if(options.mangle){toplevel.compute_char_frequency(options.mangle);toplevel.mangle_names(options.mangle)}if(timings)timings.properties=Date.now();if(options.mangle&&options.mangle.properties){toplevel=mangle_properties(toplevel,options.mangle.properties)}if(timings)timings.output=Date.now();var result={};if(options.output.ast){result.ast=toplevel}if(!HOP(options.output,"code")||options.output.code){if(options.sourceMap){options.output.source_map=SourceMap({file:options.sourceMap.filename,orig:source_maps,root:options.sourceMap.root});if(options.sourceMap.includeSources){if(files instanceof AST_Toplevel){throw new Error("original source content unavailable")}else for(var name in files)if(HOP(files,name)){options.output.source_map.get().setSourceContent(name,files[name])}}else{options.output.source_map.get()._sourcesContents=null}}delete options.output.ast;delete options.output.code;var stream=OutputStream(options.output);toplevel.print(stream);result.code=stream.get();if(options.sourceMap){result.map=options.output.source_map.toString();if(options.sourceMap.url=="inline"){result.code+="\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,"+to_base64(result.map)}else if(options.sourceMap.url){result.code+="\n//# sourceMappingURL="+options.sourceMap.url}}}if(options.nameCache&&options.mangle){if(options.mangle.cache)options.nameCache.vars=to_json(options.mangle.cache);if(options.mangle.properties&&options.mangle.properties.cache){options.nameCache.props=to_json(options.mangle.properties.cache)}}if(timings){timings.end=Date.now();result.timings={parse:.001*(timings.rename-timings.parse),rename:.001*(timings.compress-timings.rename),compress:.001*(timings.scope-timings.compress),scope:.001*(timings.mangle-timings.scope),mangle:.001*(timings.properties-timings.mangle),properties:.001*(timings.output-timings.properties),output:.001*(timings.end-timings.output),total:.001*(timings.end-timings.start)}}if(warnings.length){result.warnings=warnings}return result}catch(ex){return{error:ex}}finally{AST_Node.warn_function=warn_function}}exports["Dictionary"]=Dictionary;exports["minify"]=minify;exports["parse"]=parse;exports["push_uniq"]=push_uniq;exports["TreeTransformer"]=TreeTransformer;exports["TreeWalker"]=TreeWalker})(typeof exports=="undefined"?exports={}:exports);
26184 }).call(this,require("buffer").Buffer)
26185 },{"buffer":4}]},{},["html-minifier"]);