From 2ad25efb57a1abf5a8d00a554676f1955a12f85e Mon Sep 17 00:00:00 2001 From: XhmikosR Date: Sun, 18 May 2014 23:12:05 +0300 Subject: [PATCH] Minify cleancss-browser.js. See https://github.com/GoalSmashers/clean-css/pull/262/ --- assets/cleancss-browser.js | 10319 +---------------------------------- 1 file changed, 4 insertions(+), 10315 deletions(-) diff --git a/assets/cleancss-browser.js b/assets/cleancss-browser.js index 216de08..d4bfb11 100644 --- a/assets/cleancss-browser.js +++ b/assets/cleancss-browser.js @@ -1,10315 +1,4 @@ -!function(e){if("object"==typeof exports)module.exports=e();else if("function"==typeof define&&define.amd)define(e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.CleanCSS=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o -1 ? name : name.replace(/['"]/g, '')); - }); - - // IE shorter filters, but only if single (IE 7 issue) - replace(/progid:DXImageTransform\.Microsoft\.(Alpha|Chroma)(\([^\)]+\))([;}'"])/g, function(match, filter, args, suffix) { - return filter.toLowerCase() + args + suffix; - }); - - replace(function escapeExpressions() { - data = expressionsProcessor.escape(data); - }); - - // strip parentheses in attribute values - replace(/\[([^\]]+)\]/g, function(match, content) { - var eqIndex = content.indexOf('='); - var singleQuoteIndex = content.indexOf('\''); - var doubleQuoteIndex = content.indexOf('"'); - if (eqIndex < 0 && singleQuoteIndex < 0 && doubleQuoteIndex < 0) - return match; - if (singleQuoteIndex === 0 || doubleQuoteIndex === 0) - return match; - - var key = content.substring(0, eqIndex); - var value = content.substring(eqIndex + 1, content.length); - - if (/^['"](?:[a-zA-Z][a-zA-Z\d\-_]+)['"]$/.test(value)) - return '[' + key + '=' + value.substring(1, value.length - 1) + ']'; - else - return match; - }); - - replace(function escapeFreeText() { - data = freeTextProcessor.escape(data); - }); - - replace(function escapeUrls() { - data = urlsProcessor.escape(data); - }); - - // whitespace inside attribute selectors brackets - replace(/\[([^\]]+)\]/g, function(match) { - return match.replace(/\s/g, ''); - }); - - // line breaks - replace(/[\r]?\n/g, ' '); - - // multiple whitespace - replace(/[\t ]+/g, ' '); - - // multiple semicolons (with optional whitespace) - replace(/;[ ]?;+/g, ';'); - - // multiple line breaks to one - replace(/ (?:\r\n|\n)/g, lineBreak); - replace(/(?:\r\n|\n)+/g, lineBreak); - - // remove spaces around selectors - replace(/ ([+~>]) /g, '$1'); - - // remove extra spaces inside content - replace(/([!\(\{\}:;=,\n]) /g, '$1'); - replace(/ ([!\)\{\};=,\n])/g, '$1'); - replace(/(?:\r\n|\n)\}/g, '}'); - replace(/([\{;,])(?:\r\n|\n)/g, '$1'); - replace(/ :([^\{\};]+)([;}])/g, ':$1$2'); - - // restore spaces inside IE filters (IE 7 issue) - replace(/progid:[^(]+\(([^\)]+)/g, function(match) { - return match.replace(/,/g, ', '); - }); - - // trailing semicolons - replace(/;\}/g, '}'); - - replace(function hsl2Hex() { - data = new ColorHSLToHex(data).process(); - }); - - replace(function rgb2Hex() { - data = new ColorRGBToHex(data).process(); - }); - - replace(function longToShortHex() { - data = new ColorLongToShortHex(data).process(); - }); - - replace(function shortenColors() { - data = new ColorShortener(data).process(); - }); - - // replace font weight with numerical value - replace(/(font\-weight|font):(normal|bold)([ ;\}!])(\w*)/g, function(match, property, weight, suffix, next) { - if (suffix == ' ' && next.length > 0 && !/[.\d]/.test(next)) - return match; - - if (weight == 'normal') - return property + ':400' + suffix + next; - else if (weight == 'bold') - return property + ':700' + suffix + next; - else - return match; - }); - - // minus zero to zero - // repeated twice on purpose as if not it doesn't process rgba(-0,-0,-0,-0) correctly - var zerosRegexp = /(\s|:|,|\()\-0([^\.])/g; - replace(zerosRegexp, '$10$2'); - replace(zerosRegexp, '$10$2'); - - // zero(s) + value to value - replace(/(\s|:|,)0+([1-9])/g, '$1$2'); - - // round pixels to 2nd decimal place - replace(/\.(\d{3,})px/g, function(match, decimalPlaces) { - return '.' + Math.round(parseFloat('.' + decimalPlaces) * 100) + 'px'; - }); - - // .0 to 0 - replace(/(\D)\.0+(,|\}|\))/g, '$10$2'); - - // fraction zeros removal - replace(/\.([1-9]*)0+(\D)/g, function(match, nonZeroPart, suffix) { - return (nonZeroPart.length > 0 ? '.' : '') + nonZeroPart + suffix; - }); - - // zero + unit to zero - var units = ['px', 'em', 'ex', 'cm', 'mm', 'in', 'pt', 'pc', '%']; - if (['ie7', 'ie8'].indexOf(options.compatibility) == -1) - units.push('rem'); - - replace(new RegExp('(\\s|:|,)\\-?0(?:' + units.join('|') + ')', 'g'), '$1' + '0'); - replace(new RegExp('(\\s|:|,)\\-?(\\d)\\.(\\D)', 'g'), '$1$2$3'); - replace(new RegExp('rect\\(0(?:' + units.join('|') + ')', 'g'), 'rect(0'); - - // restore % in rgb/rgba and hsl/hsla - replace(/(rgb|rgba|hsl|hsla)\(([^\)]+)\)/g, function(match, colorFunction, colorDef) { - var tokens = colorDef.split(','); - var applies = colorFunction == 'hsl' || colorFunction == 'hsla' || tokens[0].indexOf('%') > -1; - if (!applies) - return match; - - if (tokens[1].indexOf('%') == -1) - tokens[1] += '%'; - if (tokens[2].indexOf('%') == -1) - tokens[2] += '%'; - return colorFunction + '(' + tokens.join(',') + ')'; - }); - - // none to 0 - replace(/outline:none/g, 'outline:0'); - - // background:none to background:0 0 - replace(/background:(?:none|transparent)([;}])/g, 'background:0 0$1'); - - // multiple zeros into one - replace(/box-shadow:0 0 0( 0)?([^\.])/g, 'box-shadow:0 0$2'); - replace(/:0 0 0 0([^\.])/g, ':0$1'); - replace(/([: ,=\-])0\.(\d)/g, '$1.$2'); - - // restore rect(...) zeros syntax for 4 zeros - replace(/rect\(\s?0(\s|,)0[ ,]0[ ,]0\s?\)/g, 'rect(0$10$10$10)'); - - // remove universal selector when not needed (*#id, *.class etc) - replace(/\*([\.#:\[])/g, '$1'); - - // Restore spaces inside calc back - replace(/calc\([^\}]+\}/g, function(match) { - return match.replace(/\+/g, ' + '); - }); - - // remove space after (rgba|hsla) declaration - see #165 - replace(/(rgba|hsla)\(([^\)]+)\) /g, '$1($2)'); - - if (options.noAdvanced) { - if (options.keepBreaks) - replace(/\}/g, '}' + lineBreak); - } else { - replace(function optimizeSelectors() { - data = new SelectorsOptimizer(data, context, { - keepBreaks: options.keepBreaks, - lineBreak: lineBreak, - compatibility: options.compatibility - }).process(); - }); - } - - replace(function restoreUrls() { - data = urlsProcessor.restore(data); - }); - replace(function rebaseUrls() { - data = options.noRebase ? data : new UrlRebase(options, context).process(data); - }); - replace(function restoreFreeText() { - data = freeTextProcessor.restore(data); - }); - replace(function restoreComments() { - data = commentsProcessor.restore(data); - }); - replace(function restoreExpressions() { - data = expressionsProcessor.restore(data); - }); - - // move first charset to the beginning - replace(function moveCharset() { - // get first charset in stylesheet - var match = data.match(/@charset [^;]+;/); - var firstCharset = match ? match[0] : null; - if (!firstCharset) - return; - - // reattach first charset and remove all subsequent - data = firstCharset + - (options.keepBreaks ? lineBreak : '') + - data.replace(new RegExp('@charset [^;]+;(' + lineBreak + ')?', 'g'), '').trim(); - }); - - if (options.noAdvanced) { - replace(function removeEmptySelectors() { - data = new EmptyRemoval(data).process(); - }); - } - - // trim spaces at beginning and end - data = data.trim(); - - if (options.debug) { - var elapsed = process.hrtime(startedAt); - stats.timeSpent = ~~(elapsed[0] * 1e3 + elapsed[1] / 1e6); - stats.efficiency = 1 - data.length / stats.originalSize; - stats.minifiedSize = data.length; - } - - return callback ? - callback.call(this, this.context.errors.length > 0 ? this.context.errors : null, data) : - data; -}; - -}).call(this,_dereq_("Zbi7gb"),_dereq_("buffer").Buffer) -},{"./colors/hsl-to-hex":3,"./colors/long-to-short-hex":4,"./colors/rgb-to-hex":5,"./colors/shortener":6,"./images/url-rebase":7,"./imports/inliner":9,"./selectors/empty-removal":17,"./selectors/optimizer":18,"./text/comments":20,"./text/expressions":22,"./text/free":23,"./text/name-quotes":24,"./text/urls":26,"Zbi7gb":39,"buffer":28}],3:[function(_dereq_,module,exports){ -module.exports = function HSLToHex(data) { - // HSL to RGB converter. Both methods adapted from: - // http://mjijackson.com/2008/02/rgb-to-hsl-and-rgb-to-hsv-color-model-conversion-algorithms-in-javascript - var hslToRgb = function(h, s, l) { - var r, g, b; - - // normalize hue orientation b/w 0 and 360 degrees - h = h % 360; - if (h < 0) - h += 360; - h = ~~h / 360; - - if (s < 0) - s = 0; - else if (s > 100) - s = 100; - s = ~~s / 100; - - if (l < 0) - l = 0; - else if (l > 100) - l = 100; - l = ~~l / 100; - - if (s === 0) { - r = g = b = l; // achromatic - } else { - var q = l < 0.5 ? - l * (1 + s) : - l + s - l * s; - var p = 2 * l - q; - r = hueToRgb(p, q, h + 1/3); - g = hueToRgb(p, q, h); - b = hueToRgb(p, q, h - 1/3); - } - - return [~~(r * 255), ~~(g * 255), ~~(b * 255)]; - }; - - var hueToRgb = function(p, q, t) { - if (t < 0) t += 1; - if (t > 1) t -= 1; - if (t < 1/6) return p + (q - p) * 6 * t; - if (t < 1/2) return q; - if (t < 2/3) return p + (q - p) * (2/3 - t) * 6; - return p; - }; - - return { - process: function() { - return data.replace(/hsl\((-?\d+),(-?\d+)%?,(-?\d+)%?\)/g, function(match, hue, saturation, lightness) { - var asRgb = hslToRgb(hue, saturation, lightness); - var redAsHex = asRgb[0].toString(16); - var greenAsHex = asRgb[1].toString(16); - var blueAsHex = asRgb[2].toString(16); - - return '#' + - ((redAsHex.length == 1 ? '0' : '') + redAsHex) + - ((greenAsHex.length == 1 ? '0' : '') + greenAsHex) + - ((blueAsHex.length == 1 ? '0' : '') + blueAsHex); - }); - } - }; -}; - -},{}],4:[function(_dereq_,module,exports){ -module.exports = function LongToShortHex(data) { - return { - process: function() { - return data.replace(/([,: \(])#([0-9a-f]{6})/gi, function(match, prefix, color) { - if (color[0] == color[1] && color[2] == color[3] && color[4] == color[5]) - return prefix + '#' + color[0] + color[2] + color[4]; - else - return prefix + '#' + color; - }); - } - }; -}; - -},{}],5:[function(_dereq_,module,exports){ -module.exports = function RGBToHex(data) { - return { - process: function() { - return data.replace(/rgb\((\-?\d+),(\-?\d+),(\-?\d+)\)/g, function(match, red, green, blue) { - red = Math.max(0, Math.min(~~red, 255)); - green = Math.max(0, Math.min(~~green, 255)); - blue = Math.max(0, Math.min(~~blue, 255)); - - // Credit: Asen http://jsbin.com/UPUmaGOc/2/edit?js,console - return '#' + ('00000' + (red << 16 | green << 8 | blue).toString(16)).slice(-6); - }); - } - }; -}; - -},{}],6:[function(_dereq_,module,exports){ -module.exports = function Shortener(data) { - var COLORS = { - aliceblue: '#f0f8ff', - antiquewhite: '#faebd7', - aqua: '#0ff', - aquamarine: '#7fffd4', - azure: '#f0ffff', - beige: '#f5f5dc', - bisque: '#ffe4c4', - black: '#000', - blanchedalmond: '#ffebcd', - blue: '#00f', - blueviolet: '#8a2be2', - brown: '#a52a2a', - burlywood: '#deb887', - cadetblue: '#5f9ea0', - chartreuse: '#7fff00', - chocolate: '#d2691e', - coral: '#ff7f50', - cornflowerblue: '#6495ed', - cornsilk: '#fff8dc', - crimson: '#dc143c', - cyan: '#0ff', - darkblue: '#00008b', - darkcyan: '#008b8b', - darkgoldenrod: '#b8860b', - darkgray: '#a9a9a9', - darkgreen: '#006400', - darkkhaki: '#bdb76b', - darkmagenta: '#8b008b', - darkolivegreen: '#556b2f', - darkorange: '#ff8c00', - darkorchid: '#9932cc', - darkred: '#8b0000', - darksalmon: '#e9967a', - darkseagreen: '#8fbc8f', - darkslateblue: '#483d8b', - darkslategray: '#2f4f4f', - darkturquoise: '#00ced1', - darkviolet: '#9400d3', - deeppink: '#ff1493', - deepskyblue: '#00bfff', - dimgray: '#696969', - dodgerblue: '#1e90ff', - firebrick: '#b22222', - floralwhite: '#fffaf0', - forestgreen: '#228b22', - fuchsia: '#f0f', - gainsboro: '#dcdcdc', - ghostwhite: '#f8f8ff', - gold: '#ffd700', - goldenrod: '#daa520', - gray: '#808080', - green: '#008000', - greenyellow: '#adff2f', - honeydew: '#f0fff0', - hotpink: '#ff69b4', - indianred: '#cd5c5c', - indigo: '#4b0082', - ivory: '#fffff0', - khaki: '#f0e68c', - lavender: '#e6e6fa', - lavenderblush: '#fff0f5', - lawngreen: '#7cfc00', - lemonchiffon: '#fffacd', - lightblue: '#add8e6', - lightcoral: '#f08080', - lightcyan: '#e0ffff', - lightgoldenrodyellow: '#fafad2', - lightgray: '#d3d3d3', - lightgreen: '#90ee90', - lightpink: '#ffb6c1', - lightsalmon: '#ffa07a', - lightseagreen: '#20b2aa', - lightskyblue: '#87cefa', - lightslategray: '#778899', - lightsteelblue: '#b0c4de', - lightyellow: '#ffffe0', - lime: '#0f0', - limegreen: '#32cd32', - linen: '#faf0e6', - magenta: '#ff00ff', - maroon: '#800000', - mediumaquamarine: '#66cdaa', - mediumblue: '#0000cd', - mediumorchid: '#ba55d3', - mediumpurple: '#9370db', - mediumseagreen: '#3cb371', - mediumslateblue: '#7b68ee', - mediumspringgreen: '#00fa9a', - mediumturquoise: '#48d1cc', - mediumvioletred: '#c71585', - midnightblue: '#191970', - mintcream: '#f5fffa', - mistyrose: '#ffe4e1', - moccasin: '#ffe4b5', - navajowhite: '#ffdead', - navy: '#000080', - oldlace: '#fdf5e6', - olive: '#808000', - olivedrab: '#6b8e23', - orange: '#ffa500', - orangered: '#ff4500', - orchid: '#da70d6', - palegoldenrod: '#eee8aa', - palegreen: '#98fb98', - paleturquoise: '#afeeee', - palevioletred: '#db7093', - papayawhip: '#ffefd5', - peachpuff: '#ffdab9', - peru: '#cd853f', - pink: '#ffc0cb', - plum: '#dda0dd', - powderblue: '#b0e0e6', - purple: '#800080', - red: '#f00', - rosybrown: '#bc8f8f', - royalblue: '#4169e1', - saddlebrown: '#8b4513', - salmon: '#fa8072', - sandybrown: '#f4a460', - seagreen: '#2e8b57', - seashell: '#fff5ee', - sienna: '#a0522d', - silver: '#c0c0c0', - skyblue: '#87ceeb', - slateblue: '#6a5acd', - slategray: '#708090', - snow: '#fffafa', - springgreen: '#00ff7f', - steelblue: '#4682b4', - tan: '#d2b48c', - teal: '#008080', - thistle: '#d8bfd8', - tomato: '#ff6347', - turquoise: '#40e0d0', - violet: '#ee82ee', - wheat: '#f5deb3', - white: '#fff', - whitesmoke: '#f5f5f5', - yellow: '#ff0', - yellowgreen: '#9acd32' - }; - - var toHex = {}; - var toName = {}; - - for (var name in COLORS) { - var color = COLORS[name]; - if (name.length < color.length) - toName[color] = name; - else - toHex[name] = color; - } - - return { - toHex: toHex, - toName: toName, - - // replace color name with hex values if shorter (or the other way around) - process: function() { - [toHex, toName].forEach(function(conversion) { - var pattern = '(' + Object.keys(conversion).join('|') + ')'; - var colorSwitcher = function(match, prefix, colorValue, suffix) { - return prefix + conversion[colorValue.toLowerCase()] + suffix; - }; - data = data.replace(new RegExp('([ :,\\(])' + pattern + '([;\\}!\\) ])', 'ig'), colorSwitcher); - data = data.replace(new RegExp('(,)' + pattern + '(,)', 'ig'), colorSwitcher); - }); - - return data; - } - }; -}; - -},{}],7:[function(_dereq_,module,exports){ -var path = _dereq_('path'); - -var UrlRewriter = _dereq_('./url-rewriter'); - -module.exports = function UrlRebase(options, context) { - var process = function(data) { - var rebaseOpts = { - absolute: !!options.root, - relative: !options.root && !!options.target, - fromBase: options.relativeTo - }; - - if (!rebaseOpts.absolute && !rebaseOpts.relative) - return data; - - if (rebaseOpts.absolute && !!options.target) - context.warnings.push('Both \'root\' and output file given so rebasing URLs as absolute paths'); - - if (rebaseOpts.absolute) - rebaseOpts.toBase = path.resolve(options.root); - - if (rebaseOpts.relative) - rebaseOpts.toBase = path.resolve(path.dirname(options.target)); - - if (!rebaseOpts.fromBase || !rebaseOpts.toBase) - return data; - - return UrlRewriter.process(data, rebaseOpts); - }; - - return { process: process }; -}; - -},{"./url-rewriter":8,"path":38}],8:[function(_dereq_,module,exports){ -(function (process){ -var path = _dereq_('path'); -var url = _dereq_('url'); - -module.exports = { - process: function(data, options) { - var tempData = []; - var nextStart = 0; - var nextEnd = 0; - var cursor = 0; - - for (; nextEnd < data.length;) { - nextStart = data.indexOf('url(', nextEnd); - if (nextStart == -1) - break; - - nextEnd = data.indexOf(')', nextStart + 4); - if (nextEnd == -1) - break; - - tempData.push(data.substring(cursor, nextStart)); - var url = data.substring(nextStart + 4, nextEnd).replace(/['"]/g, ''); - tempData.push('url(' + this._rebased(url, options) + ')'); - cursor = nextEnd + 1; - } - - return tempData.length > 0 ? - tempData.join('') + data.substring(cursor, data.length) : - data; - }, - - _rebased: function(resource, options) { - var specialUrl = resource[0] == '/' || - resource.substring(resource.length - 4) == '.css' || - resource.indexOf('data:') === 0 || - /^https?:\/\//.exec(resource) !== null || - /__\w+__/.exec(resource) !== null; - var rebased; - - if (specialUrl) - return resource; - - if (/https?:\/\//.test(options.toBase)) - return url.resolve(options.toBase, resource); - - if (options.absolute) { - rebased = path - .resolve(path.join(options.fromBase, resource)) - .replace(options.toBase, ''); - } else { - rebased = path.relative(options.toBase, path.join(options.fromBase, resource)); - } - - return process.platform == 'win32' ? - rebased.replace(/\\/g, '/') : - rebased; - } -}; - -}).call(this,_dereq_("Zbi7gb")) -},{"Zbi7gb":39,"path":38,"url":58}],9:[function(_dereq_,module,exports){ -var fs = _dereq_('fs'); -var path = _dereq_('path'); -var http = _dereq_('http'); -var https = _dereq_('https'); -var url = _dereq_('url'); - -var UrlRewriter = _dereq_('../images/url-rewriter'); - -var merge = function(source1, source2) { - var target = {}; - for (var key1 in source1) - target[key1] = source1[key1]; - for (var key2 in source2) - target[key2] = source2[key2]; - - return target; -}; - -module.exports = function Inliner(context, options) { - var defaultOptions = { - timeout: 5000, - request: {} - }; - var inlinerOptions = merge(defaultOptions, options || {}); - - var process = function(data, options) { - options._shared = options._shared || { - done: [], - left: [] - }; - var shared = options._shared; - - var nextStart = 0; - var nextEnd = 0; - var cursor = 0; - var isComment = commentScanner(data); - var afterContent = contentScanner(data); - - options.relativeTo = options.relativeTo || options.root; - options._baseRelativeTo = options._baseRelativeTo || options.relativeTo; - options.visited = options.visited || []; - - for (; nextEnd < data.length;) { - nextStart = data.indexOf('@import', cursor); - if (nextStart == -1) - break; - - if (isComment(nextStart)) { - cursor = nextStart + 1; - continue; - } - - nextEnd = data.indexOf(';', nextStart); - if (nextEnd == -1) { - cursor = data.length; - data = ''; - break; - } - - shared.done.push(data.substring(0, nextStart)); - shared.left.unshift([data.substring(nextEnd + 1), options]); - - return afterContent(nextStart) ? - processNext(options) : - inline(data, nextStart, nextEnd, options); - } - - // no @import matched in current data - shared.done.push(data); - return processNext(options); - }; - - var processNext = function(options) { - if (options._shared.left.length > 0) - return process.apply(null, options._shared.left.shift()); - else - return options.whenDone(options._shared.done.join('')); - }; - - var commentScanner = function(data) { - var commentRegex = /(\/\*(?!\*\/)[\s\S]*?\*\/)/; - var lastStartIndex = 0; - var lastEndIndex = 0; - var noComments = false; - - // test whether an index is located within a comment - var scanner = function(idx) { - var comment; - var localStartIndex = 0; - var localEndIndex = 0; - var globalStartIndex = 0; - var globalEndIndex = 0; - - // return if we know there are no more comments - if (noComments) - return false; - - // idx can be still within last matched comment (many @import statements inside one comment) - if (idx > lastStartIndex && idx < lastEndIndex) - return true; - - comment = data.match(commentRegex); - - if (!comment) { - noComments = true; - return false; - } - - // get the indexes relative to the current data chunk - lastStartIndex = localStartIndex = comment.index; - localEndIndex = localStartIndex + comment[0].length; - - // calculate the indexes relative to the full original data - globalEndIndex = localEndIndex + lastEndIndex; - globalStartIndex = globalEndIndex - comment[0].length; - - // chop off data up to and including current comment block - data = data.substring(localEndIndex); - lastEndIndex = globalEndIndex; - - // re-run scan if comment ended before the idx - if (globalEndIndex < idx) - return scanner(idx); - - return globalEndIndex > idx && idx > globalStartIndex; - }; - - return scanner; - }; - - var contentScanner = function(data) { - var isComment = commentScanner(data); - var firstContentIdx = -1; - while (true) { - firstContentIdx = data.indexOf('{', firstContentIdx + 1); - if (firstContentIdx == -1 || !isComment(firstContentIdx)) - break; - } - - return function(idx) { - return firstContentIdx > -1 ? - idx > firstContentIdx : - false; - }; - }; - - var inline = function(data, nextStart, nextEnd, options) { - var importDeclaration = data - .substring(data.indexOf(' ', nextStart) + 1, nextEnd) - .trim(); - - var viaUrl = importDeclaration.indexOf('url(') === 0; - var urlStartsAt = viaUrl ? 4 : 0; - var isQuoted = /^['"]/.exec(importDeclaration.substring(urlStartsAt, urlStartsAt + 2)); - var urlEndsAt = isQuoted ? - importDeclaration.indexOf(isQuoted[0], urlStartsAt + 1) : - importDeclaration.split(' ')[0].length; - - var importedFile = importDeclaration - .substring(urlStartsAt, urlEndsAt) - .replace(/['"]/g, '') - .replace(/\)$/, '') - .trim(); - - var mediaQuery = importDeclaration - .substring(urlEndsAt + 1) - .replace(/^\)/, '') - .trim(); - - var isRemote = options.isRemote || - /^(http|https):\/\//.test(importedFile) || - /^\/\//.test(importedFile); - - if (options.localOnly && isRemote) { - context.warnings.push('Ignoring remote @import declaration of "' + importedFile + '" as no callback given.'); - restoreImport(importedFile, mediaQuery, options); - - return processNext(options); - } - - var method = isRemote ? inlineRemoteResource : inlineLocalResource; - return method(importedFile, mediaQuery, options); - }; - - var inlineRemoteResource = function(importedFile, mediaQuery, options) { - var importedUrl = /^https?:\/\//.test(importedFile) ? - importedFile : - url.resolve(options.relativeTo, importedFile); - - if (importedUrl.indexOf('//') === 0) - importedUrl = 'http:' + importedUrl; - - if (options.visited.indexOf(importedUrl) > -1) - return processNext(options); - - - if (context.debug) - console.error('Inlining remote stylesheet: ' + importedUrl); - - options.visited.push(importedUrl); - - var get = importedUrl.indexOf('http://') === 0 ? - http.get : - https.get; - - var timedOut = false; - var handleError = function(message) { - context.errors.push('Broken @import declaration of "' + importedUrl + '" - ' + message); - restoreImport(importedUrl, mediaQuery, options); - - processNext(options); - }; - var requestOptions = merge(url.parse(importedUrl), inlinerOptions.request); - - get(requestOptions, function(res) { - if (res.statusCode < 200 || res.statusCode > 399) { - return handleError('error ' + res.statusCode); - } else if (res.statusCode > 299) { - var movedUrl = url.resolve(importedUrl, res.headers.location); - return inlineRemoteResource(movedUrl, mediaQuery, options); - } - - var chunks = []; - var parsedUrl = url.parse(importedUrl); - res.on('data', function(chunk) { - chunks.push(chunk.toString()); - }); - res.on('end', function() { - var importedData = chunks.join(''); - importedData = UrlRewriter.process(importedData, { toBase: importedUrl }); - - if (mediaQuery.length > 0) - importedData = '@media ' + mediaQuery + '{' + importedData + '}'; - - process(importedData, { - isRemote: true, - relativeTo: parsedUrl.protocol + '//' + parsedUrl.host, - _shared: options._shared, - whenDone: options.whenDone, - visited: options.visited - }); - }); - }) - .on('error', function(res) { - handleError(res.message); - }) - .on('timeout', function() { - // FIX: node 0.8 fires this event twice - if (timedOut) - return; - - handleError('timeout'); - timedOut = true; - }) - .setTimeout(inlinerOptions.timeout); - }; - - var inlineLocalResource = function(importedFile, mediaQuery, options) { - var relativeTo = importedFile[0] == '/' ? - options.root : - options.relativeTo; - - var fullPath = path.resolve(path.join(relativeTo, importedFile)); - - if (!fs.existsSync(fullPath) || !fs.statSync(fullPath).isFile()) { - context.errors.push('Broken @import declaration of "' + importedFile + '"'); - return processNext(options); - } - - if (options.visited.indexOf(fullPath) > -1) - return processNext(options); - - - if (context.debug) - console.error('Inlining local stylesheet: ' + fullPath); - - options.visited.push(fullPath); - - var importedData = fs.readFileSync(fullPath, 'utf8'); - var importRelativeTo = path.dirname(fullPath); - importedData = UrlRewriter.process(importedData, { - relative: true, - fromBase: importRelativeTo, - toBase: options._baseRelativeTo - }); - - if (mediaQuery.length > 0) - importedData = '@media ' + mediaQuery + '{' + importedData + '}'; - - return process(importedData, { - root: options.root, - relativeTo: importRelativeTo, - _baseRelativeTo: options._baseRelativeTo, - _shared: options._shared, - visited: options.visited, - whenDone: options.whenDone, - localOnly: options.localOnly - }); - }; - - var restoreImport = function(importedUrl, mediaQuery, options) { - var restoredImport = '@import url(' + importedUrl + ')' + (mediaQuery.length > 0 ? ' ' + mediaQuery : '') + ';'; - options._shared.done.push(restoredImport); - }; - - // Inlines all imports taking care of repetitions, unknown files, and circular dependencies - return { process: process }; -}; - -},{"../images/url-rewriter":8,"fs":27,"http":32,"https":36,"path":38,"url":58}],10:[function(_dereq_,module,exports){ - -var processableInfo = _dereq_('./processable'); -var overrideCompactor = _dereq_('./override-compactor'); -var shorthandCompactor = _dereq_('./shorthand-compactor'); - -module.exports = function Optimizer(compatibility) { - var overridable = { - 'animation-delay': ['animation'], - 'animation-direction': ['animation'], - 'animation-duration': ['animation'], - 'animation-fill-mode': ['animation'], - 'animation-iteration-count': ['animation'], - 'animation-name': ['animation'], - 'animation-play-state': ['animation'], - 'animation-timing-function': ['animation'], - '-moz-animation-delay': ['-moz-animation'], - '-moz-animation-direction': ['-moz-animation'], - '-moz-animation-duration': ['-moz-animation'], - '-moz-animation-fill-mode': ['-moz-animation'], - '-moz-animation-iteration-count': ['-moz-animation'], - '-moz-animation-name': ['-moz-animation'], - '-moz-animation-play-state': ['-moz-animation'], - '-moz-animation-timing-function': ['-moz-animation'], - '-o-animation-delay': ['-o-animation'], - '-o-animation-direction': ['-o-animation'], - '-o-animation-duration': ['-o-animation'], - '-o-animation-fill-mode': ['-o-animation'], - '-o-animation-iteration-count': ['-o-animation'], - '-o-animation-name': ['-o-animation'], - '-o-animation-play-state': ['-o-animation'], - '-o-animation-timing-function': ['-o-animation'], - '-webkit-animation-delay': ['-webkit-animation'], - '-webkit-animation-direction': ['-webkit-animation'], - '-webkit-animation-duration': ['-webkit-animation'], - '-webkit-animation-fill-mode': ['-webkit-animation'], - '-webkit-animation-iteration-count': ['-webkit-animation'], - '-webkit-animation-name': ['-webkit-animation'], - '-webkit-animation-play-state': ['-webkit-animation'], - '-webkit-animation-timing-function': ['-webkit-animation'], - 'background-attachment': ['background'], - 'background-clip': ['background'], - 'background-color': ['background'], - 'background-image': ['background'], - 'background-origin': ['background'], - 'background-position': ['background'], - 'background-repeat': ['background'], - 'background-size': ['background'], - 'border-color': ['border'], - 'border-style': ['border'], - 'border-width': ['border'], - 'border-bottom': ['border'], - 'border-bottom-color': ['border-bottom', 'border-color', 'border'], - 'border-bottom-style': ['border-bottom', 'border-style', 'border'], - 'border-bottom-width': ['border-bottom', 'border-width', 'border'], - 'border-left': ['border'], - 'border-left-color': ['border-left', 'border-color', 'border'], - 'border-left-style': ['border-left', 'border-style', 'border'], - 'border-left-width': ['border-left', 'border-width', 'border'], - 'border-right': ['border'], - 'border-right-color': ['border-right', 'border-color', 'border'], - 'border-right-style': ['border-right', 'border-style', 'border'], - 'border-right-width': ['border-right', 'border-width', 'border'], - 'border-top': ['border'], - 'border-top-color': ['border-top', 'border-color', 'border'], - 'border-top-style': ['border-top', 'border-style', 'border'], - 'border-top-width': ['border-top', 'border-width', 'border'], - 'font-family': ['font'], - 'font-size': ['font'], - 'font-style': ['font'], - 'font-variant': ['font'], - 'font-weight': ['font'], - 'list-style-image': ['list'], - 'list-style-position': ['list'], - 'list-style-type': ['list'], - 'margin-bottom': ['margin'], - 'margin-left': ['margin'], - 'margin-right': ['margin'], - 'margin-top': ['margin'], - 'outline-color': ['outline'], - 'outline-style': ['outline'], - 'outline-width': ['outline'], - 'padding-bottom': ['padding'], - 'padding-left': ['padding'], - 'padding-right': ['padding'], - 'padding-top': ['padding'], - 'transition-delay': ['transition'], - 'transition-duration': ['transition'], - 'transition-property': ['transition'], - 'transition-timing-function': ['transition'], - '-moz-transition-delay': ['-moz-transition'], - '-moz-transition-duration': ['-moz-transition'], - '-moz-transition-property': ['-moz-transition'], - '-moz-transition-timing-function': ['-moz-transition'], - '-o-transition-delay': ['-o-transition'], - '-o-transition-duration': ['-o-transition'], - '-o-transition-property': ['-o-transition'], - '-o-transition-timing-function': ['-o-transition'], - '-webkit-transition-delay': ['-webkit-transition'], - '-webkit-transition-duration': ['-webkit-transition'], - '-webkit-transition-property': ['-webkit-transition'], - '-webkit-transition-timing-function': ['-webkit-transition'] - }; - - var IE_BACKSLASH_HACK = '\\9'; - - var overrides = {}; - for (var granular in overridable) { - for (var i = 0; i < overridable[granular].length; i++) { - var coarse = overridable[granular][i]; - var list = overrides[coarse]; - - if (list) - list.push(granular); - else - overrides[coarse] = [granular]; - } - } - - var tokenize = function(body) { - var tokens = body.split(';'); - var keyValues = []; - - if (tokens.length === 0 || (tokens.length == 1 && tokens[0].indexOf(IE_BACKSLASH_HACK) == -1)) - return; - - for (var i = 0, l = tokens.length; i < l; i++) { - var token = tokens[i]; - if (token === '') - continue; - - var firstColon = token.indexOf(':'); - keyValues.push([ - token.substring(0, firstColon), - token.substring(firstColon + 1), - token.indexOf('!important') > -1, - token.indexOf(IE_BACKSLASH_HACK, firstColon + 1) > 0 - ]); - } - - return keyValues; - }; - - var optimize = function(tokens, allowAdjacent) { - var merged = []; - var properties = []; - var lastProperty = null; - var rescanTrigger = {}; - - var removeOverridenBy = function(property, isImportant) { - var overrided = overrides[property]; - for (var i = 0, l = overrided.length; i < l; i++) { - for (var j = 0; j < properties.length; j++) { - if (properties[j] != overrided[i] || (merged[j][2] && !isImportant)) - continue; - - merged.splice(j, 1); - properties.splice(j, 1); - j -= 1; - } - } - }; - - var mergeablePosition = function(position) { - if (allowAdjacent === false || allowAdjacent === true) - return allowAdjacent; - - return allowAdjacent.indexOf(position) > -1; - }; - - tokensLoop: - for (var i = 0, l = tokens.length; i < l; i++) { - var token = tokens[i]; - var property = token[0]; - var isImportant = token[2]; - var isIEHack = token[3]; - var _property = (property == '-ms-filter' || property == 'filter') ? - (lastProperty == 'background' || lastProperty == 'background-image' ? lastProperty : property) : - property; - var toOverridePosition = 0; - - if (!compatibility && isIEHack) - continue; - - // comment is necessary - we assume that if two properties are one after another - // then it is intentional way of redefining property which may not be widely supported - // e.g. a{display:inline-block;display:-moz-inline-box} - // however if `mergeablePosition` yields true then the rule does not apply - // (e.g merging two adjacent selectors: `a{display:block}a{display:block}`) - if (_property != lastProperty || mergeablePosition(i)) { - while (true) { - toOverridePosition = properties.indexOf(_property, toOverridePosition); - if (toOverridePosition == -1) - break; - - var lastToken = merged[toOverridePosition]; - var wasImportant = lastToken[2]; - var wasIEHack = lastToken[3]; - - if (wasImportant && !isImportant) - continue tokensLoop; - - if (compatibility && !wasIEHack && isIEHack) - break; - - merged.splice(toOverridePosition, 1); - properties.splice(toOverridePosition, 1); - } - } - - merged.push(token); - properties.push(_property); - - // certain properties (see values of `overridable`) should trigger removal of - // more granular properties (see keys of `overridable`) - if (rescanTrigger[_property]) - removeOverridenBy(_property, isImportant); - - // add rescan triggers - if certain property appears later in the list a rescan needs - // to be triggered, e.g 'border-top' triggers a rescan after 'border-top-width' and - // 'border-top-color' as they can be removed - for (var j = 0, list = overridable[_property] || [], m = list.length; j < m; j++) - rescanTrigger[list[j]] = true; - - lastProperty = _property; - } - - return merged; - }; - - var rebuild = function(tokens) { - var flat = []; - - - for (var i = 0, l = tokens.length; i < l; i++) { - flat.push(tokens[i][0] + ':' + tokens[i][1]); - } - - return flat.join(';'); - }; - - var compact = function (input) { - var processable = processableInfo.processable; - var Token = processableInfo.Token; - - var tokens = Token.tokenize(input); - - tokens = overrideCompactor.compactOverrides(tokens, processable); - tokens = shorthandCompactor.compactShorthands(tokens, false, processable, Token); - tokens = shorthandCompactor.compactShorthands(tokens, true, processable, Token); - - return Token.detokenize(tokens); - }; - - return { - process: function(body, allowAdjacent, skipCompacting) { - var result = body; - - var tokens = tokenize(body); - if (tokens) { - var optimized = optimize(tokens, allowAdjacent); - result = rebuild(optimized); - } - - if (!skipCompacting) { - result = compact(result); - } - - return result; - } - }; -}; - -},{"./override-compactor":11,"./processable":12,"./shorthand-compactor":14}],11:[function(_dereq_,module,exports){ - -// Compacts the given tokens according to their ability to override each other. - -module.exports = (function () { - // Default override function: only allow overrides when the two values are the same - var sameValue = function (val1, val2) { - return val1 === val2; - }; - - var compactOverrides = function (tokens, processable) { - var result, can, token, t, i, ii, oldResult, matchingComponent; - - // Used when searching for a component that matches token - var nameMatchFilter1 = function (x) { - return x.prop === token.prop; - }; - // Used when searching for a component that matches t - var nameMatchFilter2 = function (x) { - return x.prop === t.prop; - }; - - // Go from the end and always take what the current token can't override as the new result set - // NOTE: can't cache result.length here because it will change with every iteration - for (result = tokens, i = 0; (ii = result.length - 1 - i) >= 0; i++) { - token = result[ii]; - can = (processable[token.prop] && processable[token.prop].canOverride) || sameValue; - oldResult = result; - result = []; - - // Special flag which indicates that the current token should be removed - var removeSelf = false; - var oldResultLength = oldResult.length; - - for (var iii = 0; iii < oldResultLength; iii++) { - t = oldResult[iii]; - - // A token can't override itself (checked by reference, not by value) - // NOTE: except when we explicitly tell it to remove itself - if (t === token && !removeSelf) { - result.push(t); - continue; - } - - // Only an important token can even try to override tokens that come after it - if (iii > ii && !token.isImportant) { - result.push(t); - continue; - } - - // A nonimportant token can never override an important one - if (t.isImportant && !token.isImportant) { - result.push(t); - continue; - } - - if (token.isShorthand && !t.isShorthand && t.isComponentOf(token)) { - // token (a shorthand) is trying to override t (a component) - - // Find the matching component in the shorthand - matchingComponent = token.components.filter(nameMatchFilter2)[0]; - can = (processable[t.prop] && processable[t.prop].canOverride) || sameValue; - if (!can(t.value, matchingComponent.value)) { - // The shorthand can't override the component - result.push(t); - } - } else if (t.isShorthand && !token.isShorthand && token.isComponentOf(t)) { - // token (a component) is trying to override a component of t (a shorthand) - - // Find the matching component in the shorthand - matchingComponent = t.components.filter(nameMatchFilter1)[0]; - if (can(matchingComponent.value, token.value)) { - // The component can override the matching component in the shorthand - - if (!token.isImportant) { - // The overriding component is non-important which means we can simply include it into the shorthand - // NOTE: stuff that can't really be included, like inherit, is taken care of at the final step, not here - matchingComponent.value = token.value; - // We use the special flag to get rid of the component - removeSelf = true; - } else { - // The overriding component is important; sadly we can't get rid of it, - // but we can still mark the matching component in the shorthand as irrelevant - matchingComponent.isIrrelevant = true; - } - t.isDirty = true; - } - result.push(t); - } else if (token.isShorthand && t.isShorthand && token.prop === t.prop) { - // token is a shorthand and is trying to override another instance of the same shorthand - - // Can only override other shorthand when each of its components can override each of the other's components - for (var iiii = 0; iiii < t.components.length; iiii++) { - can = (processable[t.components[iiii].prop] && processable[t.components[iiii].prop].canOverride) || sameValue; - if (!can(t.components[iiii].value, token.components[iiii].value)) { - result.push(t); - break; - } - } - } else if (t.prop !== token.prop || !can(t.value, token.value)) { - // in every other case, use the override mechanism - result.push(t); - } - } - if (removeSelf) { - i--; - } - } - - return result; - }; - - return { - compactOverrides: compactOverrides - }; - -})(); - -},{}],12:[function(_dereq_,module,exports){ - -// Contains the interpretation of CSS properties, as used by the property optimizer - - -module.exports = (function () { - - var tokenModule = _dereq_('./token'); - var validator = _dereq_('./validator'); - - // Functions that decide what value can override what. - // The main purpose is to disallow removing CSS fallbacks. - // A separate implementation is needed for every different kind of CSS property. - // ----- - // The generic idea is that properties that have wider browser support are 'more understandable' - // than others and that 'less understandable' values can't override more understandable ones. - var canOverride = { - // Use when two tokens of the same property can always be merged - always: function () { - // NOTE: We could have (val1, val2) parameters here but jshint complains because we don't use them - return true; - }, - // Use when two tokens of the same property can only be merged if they have the same value - sameValue: function(val1, val2) { - return val1 === val2; - }, - sameFunctionOrValue: function(val1, val2) { - // Functions with the same name can override each other - if (validator.areSameFunction(val1, val2)) { - return true; - } - - return val1 === val2; - }, - // Use for properties containing CSS units (margin-top, padding-left, etc.) - unit: function(val1, val2) { - // The idea here is that 'more understandable' values override 'less understandable' values, but not vice versa - // Understandability: (unit without functions) > (same functions | standard functions) > anything else - // NOTE: there is no point in having different vendor-specific functions override each other or standard functions, - // or having standard functions override vendor-specific functions, but standard functions can override each other - // NOTE: vendor-specific property values are not taken into consideration here at the moment - - if (validator.isValidUnitWithoutFunction(val2)) - return true; - if (validator.isValidUnitWithoutFunction(val1)) - return false; - - // Standard non-vendor-prefixed functions can override each other - if (validator.isValidFunctionWithoutVendorPrefix(val2) && validator.isValidFunctionWithoutVendorPrefix(val1)) { - return true; - } - - // Functions with the same name can override each other; same values can override each other - return canOverride.sameFunctionOrValue(val1, val2); - }, - // Use for color properties (color, background-color, border-color, etc.) - color: function(val1, val2) { - // The idea here is that 'more understandable' values override 'less understandable' values, but not vice versa - // Understandability: (hex | named) > (rgba | hsla) > (same function name) > anything else - // NOTE: at this point rgb and hsl are replaced by hex values by clean-css - - // (hex | named) - if (validator.isValidNamedColor(val2) || validator.isValidHexColor(val2)) - return true; - if (validator.isValidNamedColor(val1) || validator.isValidHexColor(val1)) - return false; - - // (rgba|hsla) - if (validator.isValidRgbaColor(val2) || validator.isValidHslColor(val2) || validator.isValidHslaColor(val2)) - return true; - if (validator.isValidRgbaColor(val1) || validator.isValidHslColor(val1) || validator.isValidHslaColor(val1)) - return false; - - // Functions with the same name can override each other; same values can override each other - return canOverride.sameFunctionOrValue(val1, val2); - }, - // Use for background-image - backgroundImage: function(val1, val2) { - // The idea here is that 'more understandable' values override 'less understandable' values, but not vice versa - // Understandability: (none | url | inherit) > (same function) > (same value) - - // (none | url) - if (val2 === 'none' || val2 === 'inherit' || validator.isValidUrl(val2)) - return true; - if (val1 === 'none' || val1 === 'inherit' || validator.isValidUrl(val1)) - return false; - - // Functions with the same name can override each other; same values can override each other - return canOverride.sameFunctionOrValue(val1, val2); - } - }; - canOverride = Object.freeze(canOverride); - - // Functions for breaking up shorthands to components - var breakUp = {}; - breakUp.takeCareOfFourValues = function (splitfunc) { - return function (token) { - var descriptor = processable[token.prop]; - var result = []; - var splitval = splitfunc(token.value); - - if (splitval.length === 0 || (splitval.length < descriptor.components.length && descriptor.components.length > 4)) { - // This token is malformed and we have no idea how to fix it. So let's just keep it intact - return [token]; - } - - // Fix those that we do know how to fix - if (splitval.length < descriptor.components.length && splitval.length < 2) { - // foo{margin:1px} -> foo{margin:1px 1px} - splitval[1] = splitval[0]; - } - if (splitval.length < descriptor.components.length && splitval.length < 3) { - // foo{margin:1px 2px} -> foo{margin:1px 2px 1px} - splitval[2] = splitval[0]; - } - if (splitval.length < descriptor.components.length && splitval.length < 4) { - // foo{margin:1px 2px 3px} -> foo{margin:1px 2px 3px 2px} - splitval[3] = splitval[1]; - } - - // Now break it up to its components - for (var i = 0; i < descriptor.components.length; i++) { - var t = new Token(descriptor.components[i], splitval[i], token.isImportant); - result.push(t); - } - - return result; - }; - }; - // Use this for properties with 4 unit values (like margin or padding) - // NOTE: it handles shorter forms of these properties too (like, only 1, 2, or 3 units) - breakUp.fourUnits = breakUp.takeCareOfFourValues(function (val) { - return val.match(new RegExp(validator.cssUnitAnyRegexStr, 'gi')); - }); - // Use this when you simply want to break up four values along spaces - breakUp.fourBySpaces = breakUp.takeCareOfFourValues(function (val) { - return val.split(' ').filter(function (v) { return v; }); - }); - // Use this for non-length values that can also contain functions - breakUp.fourBySpacesOrFunctions = breakUp.takeCareOfFourValues(function (val) { - var result = []; - var curr = ''; - var parenthesisLevel = 0; - var valLength = val.length; - - for (var i = 0; i < valLength; i++) { - var c = val[i]; - curr += c; - - if (c === '(') { - parenthesisLevel++; - } else if (c === ')') { - parenthesisLevel--; - if (parenthesisLevel === 0) { - result.push(curr.trim()); - curr = ''; - } - } else if (c === ' ' && parenthesisLevel === 0) { - result.push(curr.trim()); - curr = ''; - } - } - - if (curr) { - result.push(curr.trim()); - curr = ''; - } - - return result; - }); - // Breaks up a background property value - breakUp.background = function (token) { - // Default values - var result = Token.makeDefaults(['background-color', 'background-image', 'background-repeat', 'background-position', 'background-attachment'], token.isImportant); - var color = result[0], image = result[1], repeat = result[2], position = result[3], attachment = result[4]; - - // Take care of inherit - if (token.value === 'inherit') { - // NOTE: 'inherit' is not a valid value for background-attachment so there we'll leave the default value - color.value = image.value = repeat.value = position.value = attachment.value = 'inherit'; - return result; - } - - // Break the background up into parts - var parts = token.value.split(' '); - if (parts.length === 0) - return result; - - // The trick here is that we start going through the parts from the end, then stop after background repeat, - // then start from the from the beginning until we find a valid color value. What remains will be treated as background-image. - - var currentIndex = parts.length - 1; - var current = parts[currentIndex]; - // Attachment - if (validator.isValidBackgroundAttachment(current)) { - // Found attachment - attachment.value = current; - currentIndex--; - current = parts[currentIndex]; - } - // Position - var pos = parts[currentIndex - 1] + ' ' + parts[currentIndex]; - if (currentIndex >= 1 && validator.isValidBackgroundPosition(pos)) { - // Found position (containing two parts) - position.value = pos; - currentIndex -= 2; - current = parts[currentIndex]; - } else if (currentIndex >= 0 && validator.isValidBackgroundPosition(current)) { - // Found position (containing just one part) - position.value = current; - currentIndex--; - current = parts[currentIndex]; - } - // Repeat - if (currentIndex >= 0 && validator.isValidBackgroundRepeat(current)) { - // Found repeat - repeat.value = current; - currentIndex--; - current = parts[currentIndex]; - } - // Color - var fromBeginning = 0; - if (validator.isValidColor(parts[0])) { - // Found color - color.value = parts[0]; - fromBeginning = 1; - } - // Image - image.value = (parts.splice(fromBeginning, currentIndex - fromBeginning + 1).join(' ')) || 'none'; - - return result; - }; - // Breaks up a list-style property value - breakUp.listStyle = function (token) { - // Default values - var result = Token.makeDefaults(['list-style-type', 'list-style-position', 'list-style-image'], token.isImportant); - var type = result[0], position = result[1], image = result[2]; - - if (token.value === 'inherit') { - type.value = position.value = image.value = 'inherit'; - return result; - } - - var parts = token.value.split(' '); - var ci = 0; - - // Type - if (ci < parts.length && validator.isValidListStyleType(parts[ci])) { - type.value = parts[ci]; - ci++; - } - // Position - if (ci < parts.length && validator.isValidListStylePosition(parts[ci])) { - position.value = parts[ci]; - ci++; - } - // Image - if (ci < parts.length) { - image.value = parts.splice(ci, parts.length - ci + 1).join(' '); - } - - return result; - }; - // Breaks up outline - breakUp.outline = function (token) { - // Default values - var result = Token.makeDefaults(['outline-color', 'outline-style', 'outline-width'], token.isImportant); - var color = result[0], style = result[1], width = result[2]; - - // Take care of inherit - if (token.value === 'inherit' || token.value === 'inherit inherit inherit') { - color.value = style.value = width.value = 'inherit'; - return result; - } - - // NOTE: usually users don't follow the required order of parts in this shorthand, - // so we'll try to parse it caring as little about order as possible - - var parts = token.value.split(' '), w; - - if (parts.length === 0) { - return result; - } - - if (parts.length >= 1) { - // Try to find outline-width, excluding inherit because that can be anything - w = parts.filter(function(p) { return p !== 'inherit' && validator.isValidOutlineWidth(p); }); - if (w.length) { - width.value = w[0]; - parts.splice(parts.indexOf(w[0]), 1); - } - } - if (parts.length >= 1) { - // Try to find outline-style, excluding inherit because that can be anything - w = parts.filter(function(p) { return p !== 'inherit' && validator.isValidOutlineStyle(p); }); - if (w.length) { - style.value = w[0]; - parts.splice(parts.indexOf(w[0]), 1); - } - } - if (parts.length >= 1) { - // Find outline-color but this time can catch inherit - w = parts.filter(function(p) { return validator.isValidOutlineColor(p); }); - if (w.length) { - color.value = w[0]; - parts.splice(parts.indexOf(w[0]), 1); - } - } - - return result; - }; - - // Contains functions that can put together shorthands from their components - // NOTE: correct order of tokens is assumed inside these functions! - var putTogether = { - // Use this for properties which have four unit values (margin, padding, etc.) - // NOTE: optimizes to shorter forms too (that only specify 1, 2, or 3 values) - fourUnits: function (prop, tokens, isImportant) { - // See about irrelevant tokens - // NOTE: This will enable some crazy optimalizations for us. - if (tokens[0].isIrrelevant) - tokens[0].value = tokens[2].value; - if (tokens[2].isIrrelevant) - tokens[2].value = tokens[0].value; - if (tokens[1].isIrrelevant) - tokens[1].value = tokens[3].value; - if (tokens[3].isIrrelevant) - tokens[3].value = tokens[1].value; - - if (tokens[0].isIrrelevant && tokens[2].isIrrelevant) { - if (tokens[1].value === tokens[3].value) - tokens[0].value = tokens[2].value = tokens[1].value; - else - tokens[0].value = tokens[2].value = '0'; - } - if (tokens[1].isIrrelevant && tokens[3].isIrrelevant) { - if (tokens[0].value === tokens[2].value) - tokens[1].value = tokens[3].value = tokens[0].value; - else - tokens[1].value = tokens[3].value = '0'; - } - - var result = new Token(prop, tokens[0].value, isImportant); - result.granularValues = []; - result.granularValues[tokens[0].prop] = tokens[0].value; - result.granularValues[tokens[1].prop] = tokens[1].value; - result.granularValues[tokens[2].prop] = tokens[2].value; - result.granularValues[tokens[3].prop] = tokens[3].value; - - // If all of them are irrelevant - if (tokens[0].isIrrelevant && tokens[1].isIrrelevant && tokens[2].isIrrelevant && tokens[3].isIrrelevant) { - result.value = processable[prop].shortestValue || processable[prop].defaultValue; - return result; - } - - // 1-value short form: all four components are equal - if (tokens[0].value === tokens[1].value && tokens[0].value === tokens[2].value && tokens[0].value === tokens[3].value) { - return result; - } - result.value += ' ' + tokens[1].value; - // 2-value short form: first and third; second and fourth values are equal - if (tokens[0].value === tokens[2].value && tokens[1].value === tokens[3].value) { - return result; - } - result.value += ' ' + tokens[2].value; - // 3-value short form: second and fourth values are equal - if (tokens[1].value === tokens[3].value) { - return result; - } - // 4-value form (none of the above optimalizations could be accomplished) - result.value += ' ' + tokens[3].value; - return result; - }, - // Puts together the components by spaces and omits default values (this is the case for most shorthands) - bySpacesOmitDefaults: function (prop, tokens, isImportant) { - var result = new Token(prop, '', isImportant); - // Get irrelevant tokens - var irrelevantTokens = tokens.filter(function (t) { return t.isIrrelevant; }); - - // If every token is irrelevant, return shortest possible value, fallback to default value - if (irrelevantTokens.length === tokens.length) { - result.isIrrelevant = true; - result.value = processable[prop].shortestValue || processable[prop].defaultValue; - return result; - } - - // This will be the value of the shorthand if all the components are default - var valueIfAllDefault = processable[prop].defaultValue; - - // Go through all tokens and concatenate their values as necessary - for (var i = 0; i < tokens.length; i++) { - var token = tokens[i]; - - // Set granular value so that other parts of the code can use this for optimalization opportunities - result.granularValues = result.granularValues || { }; - result.granularValues[token.prop] = token.value; - - // Use irrelevant tokens for optimalization opportunity - if (token.isIrrelevant) { - // Get shortest possible value, fallback to default value - var tokenShortest = processable[token.prop].shortestValue || processable[token.prop].defaultValue; - // If the shortest possible value of this token is shorter than the default value of the shorthand, use it instead - if (tokenShortest.length < valueIfAllDefault.length) { - valueIfAllDefault = tokenShortest; - } - } - - // Omit default / irrelevant value - if (token.isIrrelevant || (processable[token.prop] && processable[token.prop].defaultValue === token.value)) { - continue; - } - - result.value += ' ' + token.value; - } - - result.value = result.value.trim(); - if (!result.value) { - result.value = valueIfAllDefault; - } - - return result; - }, - // Handles the cases when some or all the fine-grained properties are set to inherit - takeCareOfInherit: function (innerFunc) { - return function (prop, tokens, isImportant) { - // Filter out the inheriting and non-inheriting tokens in one iteration - var inheritingTokens = []; - var nonInheritingTokens = []; - var result2Shorthandable = []; - var i; - for (i = 0; i < tokens.length; i++) { - if (tokens[i].value === 'inherit') { - inheritingTokens.push(tokens[i]); - - // Indicate that this property is irrelevant and its value can safely be set to anything else - var r2s = new Token(tokens[i].prop, tokens[i].isImportant); - r2s.isIrrelevant = true; - result2Shorthandable.push(r2s); - } else { - nonInheritingTokens.push(tokens[i]); - result2Shorthandable.push(tokens[i]); - } - } - - if (nonInheritingTokens.length === 0) { - // When all the tokens are 'inherit' - return new Token(prop, 'inherit', isImportant); - } else if (inheritingTokens.length > 0) { - // When some (but not all) of the tokens are 'inherit' - - // Result 1. Shorthand just the inherit values and have it overridden with the non-inheriting ones - var result1 = [new Token(prop, 'inherit', isImportant)].concat(nonInheritingTokens); - - // Result 2. Shorthand every non-inherit value and then have it overridden with the inheriting ones - var result2 = [innerFunc(prop, result2Shorthandable, isImportant)].concat(inheritingTokens); - - // Return whichever is shorter - var dl1 = Token.getDetokenizedLength(result1); - var dl2 = Token.getDetokenizedLength(result2); - - return dl1 < dl2 ? result1 : result2; - } else { - // When none of tokens are 'inherit' - return innerFunc(prop, tokens, isImportant); - } - }; - } - }; - - // Properties to process - // Extend this object in order to add support for more properties in the optimizer. - // - // Each key in this object represents a CSS property and should be an object. - // Such an object contains properties that describe how the represented CSS property should be handled. - // Possible options: - // - // * components: array (Only specify for shorthand properties.) - // Contains the names of the granular properties this shorthand compacts. - // - // * canOverride: function (Default is canOverride.sameValue - meaning that they'll only be merged if they have the same value.) - // Returns whether two tokens of this property can be merged with each other. - // This property has no meaning for shorthands. - // - // * defaultValue: string - // Specifies the default value of the property according to the CSS standard. - // 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. - // - // * shortestValue: string - // Specifies the shortest possible value the property can possibly have. - // (Falls back to defaultValue if unspecified.) - // - // * breakUp: function (Only specify for shorthand properties.) - // Breaks the shorthand up to its components. - // - // * putTogether: function (Only specify for shorthand properties.) - // Puts the shorthand together from its components. - // - var processable = { - 'color': { - canOverride: canOverride.color, - defaultValue: 'transparent', - shortestValue: 'red' - }, - // background ------------------------------------------------------------------------------ - 'background': { - components: [ - 'background-color', - 'background-image', - 'background-repeat', - 'background-position', - 'background-attachment' - ], - breakUp: breakUp.background, - putTogether: putTogether.takeCareOfInherit(putTogether.bySpacesOmitDefaults), - defaultValue: '0 0', - shortestValue: '0' - }, - 'background-color': { - canOverride: canOverride.color, - defaultValue: 'transparent', - shortestValue: 'red' - }, - 'background-image': { - canOverride: canOverride.backgroundImage, - defaultValue: 'none' - }, - 'background-repeat': { - canOverride: canOverride.always, - defaultValue: 'repeat' - }, - 'background-position': { - canOverride: canOverride.always, - defaultValue: '0 0', - shortestValue: '0' - }, - 'background-attachment': { - canOverride: canOverride.always, - defaultValue: 'scroll' - }, - // list-style ------------------------------------------------------------------------------ - 'list-style': { - components: [ - 'list-style-type', - 'list-style-position', - 'list-style-image' - ], - canOverride: canOverride.always, - breakUp: breakUp.listStyle, - putTogether: putTogether.takeCareOfInherit(putTogether.bySpacesOmitDefaults), - defaultValue: 'outside', // can't use 'disc' because that'd override default 'decimal' for
    - shortestValue: 'none' - }, - 'list-style-type' : { - canOverride: canOverride.always, - shortestValue: 'none', - defaultValue: '__hack' - // NOTE: we can't tell the real default value here, it's 'disc' for
      and 'decimal' for
        - // -- this is a hack, but it doesn't matter because this value will be either overridden or it will disappear at the final step anyway - }, - 'list-style-position' : { - canOverride: canOverride.always, - defaultValue: 'outside', - shortestValue: 'inside' - }, - 'list-style-image' : { - canOverride: canOverride.always, - defaultValue: 'none' - }, - // outline ------------------------------------------------------------------------------ - 'outline': { - components: [ - 'outline-color', - 'outline-style', - 'outline-width' - ], - breakUp: breakUp.outline, - putTogether: putTogether.takeCareOfInherit(putTogether.bySpacesOmitDefaults), - defaultValue: '0' - }, - 'outline-color': { - canOverride: canOverride.color, - defaultValue: 'invert', - shortestValue: 'red' - }, - 'outline-style': { - canOverride: canOverride.always, - defaultValue: 'none' - }, - 'outline-width': { - canOverride: canOverride.unit, - defaultValue: 'medium', - shortestValue: '0' - } - }; - - var addFourValueShorthand = function (prop, components, breakup, puttogether, canoverride, defaultValue, shortestValue) { - processable[prop] = { - components: components, - breakUp: breakup || breakUp.fourUnits, - putTogether: puttogether || putTogether.takeCareOfInherit(putTogether.fourUnits), - defaultValue: defaultValue || '0', - shortestValue: shortestValue - }; - for (var i = 0; i < components.length; i++) { - processable[components[i]] = { - canOverride: canoverride || canOverride.unit, - defaultValue: defaultValue || '0', - shortestValue: shortestValue - }; - } - }; - - addFourValueShorthand('border-radius', [ - 'border-top-left-radius', - 'border-top-right-radius', - 'border-bottom-right-radius', - 'border-bottom-left-radius' - ]); - - addFourValueShorthand('-moz-border-radius', [ - '-moz-border-top-left-radius', - '-moz-border-top-right-radius', - '-moz-border-bottom-right-radius', - '-moz-border-bottom-left-radius' - ]); - - addFourValueShorthand('-webkit-border-radius', [ - '-webkit-border-top-left-radius', - '-webkit-border-top-right-radius', - '-webkit-border-bottom-right-radius', - '-webkit-border-bottom-left-radius' - ]); - - addFourValueShorthand('-o-border-radius', [ - '-o-border-top-left-radius', - '-o-border-top-right-radius', - '-o-border-bottom-right-radius', - '-o-border-bottom-left-radius' - ]); - - addFourValueShorthand('border-color', [ - 'border-top-color', - 'border-right-color', - 'border-bottom-color', - 'border-left-color' - ], breakUp.fourBySpacesOrFunctions, null, canOverride.color, 'currentColor', 'red'); - - addFourValueShorthand('border-style', [ - 'border-top-style', - 'border-right-style', - 'border-bottom-style', - 'border-left-style' - ], breakUp.fourBySpaces, null, canOverride.always, 'none'); - - addFourValueShorthand('border-width', [ - 'border-top-width', - 'border-right-width', - 'border-bottom-width', - 'border-left-width' - ], null, null, null, 'medium', '0'); - - addFourValueShorthand('padding', [ - 'padding-top', - 'padding-right', - 'padding-bottom', - 'padding-left' - ]); - - addFourValueShorthand('margin', [ - 'margin-top', - 'margin-right', - 'margin-bottom', - 'margin-left' - ]); - - // Set some stuff iteratively - for (var proc in processable) { - if (!processable.hasOwnProperty(proc)) - continue; - - var currDesc = processable[proc]; - - if (!(currDesc.components instanceof Array) || currDesc.components.length === 0) - continue; - - currDesc.isShorthand = true; - - for (var cI = 0; cI < currDesc.components.length; cI++) { - if (!processable[currDesc.components[cI]]) { - throw new Error('"' + currDesc.components[cI] + '" is defined as a component of "' + proc + '" but isn\'t defined in processable.'); - } - processable[currDesc.components[cI]].componentOf = proc; - } - } - - var Token = tokenModule.createTokenPrototype(processable); - - return { - processable: processable, - Token: Token - }; -})(); - -},{"./token":15,"./validator":16}],13:[function(_dereq_,module,exports){ -(function() { - var OPEN_BRACE = '{'; - var SEMICOLON = ';'; - var COLON = ':'; - - var PropertyScanner = function PropertyScanner(data) { - this.data = data; - }; - - PropertyScanner.prototype.nextAt = function(cursor) { - var lastColon = this.data.lastIndexOf(COLON, cursor); - var lastOpenBrace = this.data.lastIndexOf(OPEN_BRACE, cursor); - var lastSemicolon = this.data.lastIndexOf(SEMICOLON, cursor); - var startAt = Math.max(lastOpenBrace, lastSemicolon); - - return this.data.substring(startAt + 1, lastColon).trim(); - }; - - module.exports = PropertyScanner; -})(); - -},{}],14:[function(_dereq_,module,exports){ - -// Compacts the tokens by transforming properties into their shorthand notations when possible - -module.exports = (function () { - var isHackValue = function (t) { return t.value === '__hack'; }; - - var compactShorthands = function(tokens, isImportant, processable, Token) { - // Contains the components found so far, grouped by shorthand name - var componentsSoFar = { }; - - // Initializes a prop in componentsSoFar - var initSoFar = function (shprop, last, clearAll) { - var found = {}; - var shorthandPosition; - - if (!clearAll && componentsSoFar[shprop]) { - for (var i = 0; i < processable[shprop].components.length; i++) { - var prop = processable[shprop].components[i]; - found[prop] = []; - - if (!(componentsSoFar[shprop].found[prop])) - continue; - - for (var ii = 0; ii < componentsSoFar[shprop].found[prop].length; ii++) { - var comp = componentsSoFar[shprop].found[prop][ii]; - - if (comp.isMarkedForDeletion) - continue; - - found[prop].push(comp); - - if (comp.position && (!shorthandPosition || comp.position < shorthandPosition)) - shorthandPosition = comp.position; - } - } - } - componentsSoFar[shprop] = { - lastShorthand: last, - found: found, - shorthandPosition: shorthandPosition - }; - }; - - // Adds a component to componentsSoFar - var addComponentSoFar = function (token, index) { - var shprop = processable[token.prop].componentOf; - if (!componentsSoFar[shprop]) - initSoFar(shprop); - if (!componentsSoFar[shprop].found[token.prop]) - componentsSoFar[shprop].found[token.prop] = []; - - // Add the newfound component to componentsSoFar - componentsSoFar[shprop].found[token.prop].push(token); - - if (!componentsSoFar[shprop].shorthandPosition && index) { - // If the haven't decided on where the shorthand should go, put it in the place of this component - componentsSoFar[shprop].shorthandPosition = index; - } - }; - - // Tries to compact a prop in componentsSoFar - var compactSoFar = function (prop) { - var i; - - // Check basics - if (!componentsSoFar[prop] || !componentsSoFar[prop].found) - return false; - - // Find components for the shorthand - var components = []; - var realComponents = []; - for (i = 0; i < processable[prop].components.length; i++) { - // Get property name - var pp = processable[prop].components[i]; - - if (componentsSoFar[prop].found[pp] && componentsSoFar[prop].found[pp].length) { - // We really found it - var foundRealComp = componentsSoFar[prop].found[pp][0]; - components.push(foundRealComp); - if (foundRealComp.isReal !== false) { - realComponents.push(foundRealComp); - } - } else if (componentsSoFar[prop].lastShorthand) { - // It's defined in the previous shorthand - var c = componentsSoFar[prop].lastShorthand.components[i].clone(isImportant); - components.push(c); - } else { - // Couldn't find this component at all - return false; - } - } - - if (realComponents.length === 0) { - // Couldn't find enough components, sorry - return false; - } - - if (realComponents.length === processable[prop].components.length) { - // When all the components are from real values, only allow shorthanding if their understandability allows it - // This is the case when every component can override their default values, or when all of them use the same function - - var canOverrideDefault = true; - var functionNameMatches = true; - var functionName; - - for (var ci = 0; ci < realComponents.length; ci++) { - var rc = realComponents[ci]; - - if (!processable[rc.prop].canOverride(processable[rc.prop].defaultValue, rc.value)) { - canOverrideDefault = false; - } - var iop = rc.value.indexOf('('); - if (iop >= 0) { - var otherFunctionName = rc.value.substring(0, iop); - if (functionName) - functionNameMatches = functionNameMatches && otherFunctionName === functionName; - else - functionName = otherFunctionName; - } - } - - if (!canOverrideDefault || !functionNameMatches) - return false; - } - - // Compact the components into a shorthand - var compacted = processable[prop].putTogether(prop, components, isImportant); - if (!(compacted instanceof Array)) { - compacted = [compacted]; - } - - var compactedLength = Token.getDetokenizedLength(compacted); - var authenticLength = Token.getDetokenizedLength(realComponents); - - if (realComponents.length === processable[prop].components.length || compactedLength < authenticLength || components.some(isHackValue)) { - compacted[0].isShorthand = true; - compacted[0].components = processable[prop].breakUp(compacted[0]); - - // Mark the granular components for deletion - for (i = 0; i < realComponents.length; i++) { - realComponents[i].isMarkedForDeletion = true; - } - - // Mark the position of the new shorthand - tokens[componentsSoFar[prop].shorthandPosition].replaceWith = compacted; - - // Reinitialize the thing for further compacting - initSoFar(prop, compacted[0]); - for (i = 1; i < compacted.length; i++) { - addComponentSoFar(compacted[i]); - } - - // Yes, we can keep the new shorthand! - return true; - } - - return false; - }; - - // Tries to compact all properties currently in componentsSoFar - var compactAllSoFar = function () { - for (var i in componentsSoFar) { - if (componentsSoFar.hasOwnProperty(i)) { - while (compactSoFar(i)) { } - } - } - }; - - var i, token; - - // Go through each token and collect components for each shorthand as we go on - for (i = 0; i < tokens.length; i++) { - token = tokens[i]; - if (token.isMarkedForDeletion) { - continue; - } - if (!processable[token.prop]) { - // We don't know what it is, move on - continue; - } - if (processable[token.prop].isShorthand) { - // Found an instance of a full shorthand - // NOTE: we should NOT mix together tokens that come before and after the shorthands - - if (token.isImportant === isImportant || (token.isImportant && !isImportant)) { - // Try to compact what we've found so far - while (compactSoFar(token.prop)) { } - // Reset - initSoFar(token.prop, token, true); - } - - // TODO: when the old optimizer is removed, take care of this corner case: - // div{background-color:#111;background-image:url(aaa);background:linear-gradient(aaa);background-repeat:no-repeat;background-position:1px 2px;background-attachment:scroll} - // -> should not be shorthanded / minified at all because the result wouldn't be equivalent to the original in any browser - } else if (processable[token.prop].componentOf) { - // Found a component of a shorthand - if (token.isImportant === isImportant) { - // Same importantness - token.position = i; - addComponentSoFar(token, i); - } else if (!isImportant && token.isImportant) { - // Use importants for optimalization opportunities - // https://github.com/GoalSmashers/clean-css/issues/184 - var importantTrickComp = new Token(token.prop, token.value, isImportant); - importantTrickComp.isIrrelevant = true; - importantTrickComp.isReal = false; - addComponentSoFar(importantTrickComp); - } - } else { - // This is not a shorthand and not a component, don't care about it - continue; - } - } - - // Perform all possible compactions - compactAllSoFar(); - - // Process the results - throw away stuff marked for deletion, insert compacted things, etc. - var result = []; - for (i = 0; i < tokens.length; i++) { - token = tokens[i]; - - if (token.replaceWith) { - for (var ii = 0; ii < token.replaceWith.length; ii++) { - result.push(token.replaceWith[ii]); - } - } - if (!token.isMarkedForDeletion) { - result.push(token); - } - - token.isMarkedForDeletion = false; - token.replaceWith = null; - } - - return result; - }; - - return { - compactShorthands: compactShorthands - }; - -})(); - -},{}],15:[function(_dereq_,module,exports){ - -// Helper for tokenizing the contents of a CSS selector block - -module.exports = (function() { - var createTokenPrototype = function (processable) { - var important = '!important'; - - // Constructor for tokens - function Token (prop, p2, p3) { - this.prop = prop; - if (typeof(p2) === 'string') { - this.value = p2; - this.isImportant = p3; - } - else { - this.value = processable[prop].defaultValue; - this.isImportant = p2; - } - } - - Token.prototype.prop = null; - Token.prototype.value = null; - Token.prototype.granularValues = null; - Token.prototype.components = null; - Token.prototype.position = null; - Token.prototype.isImportant = false; - Token.prototype.isDirty = false; - Token.prototype.isShorthand = false; - Token.prototype.isIrrelevant = false; - Token.prototype.isReal = true; - Token.prototype.isMarkedForDeletion = false; - - // Tells if this token is a component of the other one - Token.prototype.isComponentOf = function (other) { - if (!processable[this.prop] || !processable[other.prop]) - return false; - if (!(processable[other.prop].components instanceof Array) || !processable[other.prop].components.length) - return false; - - return processable[other.prop].components.indexOf(this.prop) >= 0; - }; - - // Clones a token - Token.prototype.clone = function (isImportant) { - var token = new Token(this.prop, this.value, (typeof(isImportant) !== 'undefined' ? isImportant : this.isImportant)); - return token; - }; - - // Creates an irrelevant token with the same prop - Token.prototype.cloneIrrelevant = function (isImportant) { - var token = Token.makeDefault(this.prop, (typeof(isImportant) !== 'undefined' ? isImportant : this.isImportant)); - token.isIrrelevant = true; - return token; - }; - - // Creates an array of property tokens with their default values - Token.makeDefaults = function (props, important) { - return props.map(function(prop) { - return new Token(prop, important); - }); - }; - - // Parses one CSS property declaration into a token - Token.tokenizeOne = function (fullProp) { - // Find first colon - var colonPos = fullProp.indexOf(':'); - - if (colonPos < 0) { - // This property doesn't have a colon, it's invalid. Let's keep it intact anyway. - return new Token('', fullProp); - } - - // Parse parts of the property - var prop = fullProp.substr(0, colonPos).trim(); - var value = fullProp.substr(colonPos + 1).trim(); - var isImportant = false; - var importantPos = value.indexOf(important); - - // Check if the property is important - if (importantPos >= 1 && importantPos === value.length - important.length) { - value = value.substr(0, importantPos).trim(); - isImportant = true; - } - - // Return result - var result = new Token(prop, value, isImportant); - - // If this is a shorthand, break up its values - // NOTE: we need to do this for all shorthands because otherwise we couldn't remove default values from them - if (processable[prop] && processable[prop].isShorthand) { - result.isShorthand = true; - result.components = processable[prop].breakUp(result); - result.isDirty = true; - } - - return result; - }; - - // Breaks up a string of CSS property declarations into tokens so that they can be handled more easily - Token.tokenize = function (input) { - // Split the input by semicolons and parse the parts - var tokens = input.split(';').map(Token.tokenizeOne); - return tokens; - }; - - // Transforms tokens back into CSS properties - Token.detokenize = function (tokens) { - // If by mistake the input is not an array, make it an array - if (!(tokens instanceof Array)) { - tokens = [tokens]; - } - - // This step takes care of putting together the components of shorthands - // NOTE: this is necessary to do for every shorthand, otherwise we couldn't remove their default values - for (var i = 0; i < tokens.length; i++) { - var t = tokens[i]; - if (t.isShorthand && t.isDirty) { - var news = processable[t.prop].putTogether(t.prop, t.components, t.isImportant); - Array.prototype.splice.apply(tokens, [i, 1].concat(news)); - t.isDirty = false; - i--; - } - } - - // And now, simply map every token into its string representation and concat them with a semicolon - var str = tokens.map(function(token) { - var result = ''; - - // NOTE: malformed tokens will not have a 'prop' property - if (token.prop) { - result += token.prop + ':'; - } - if (token.value) { - result += token.value; - } - if (token.isImportant) { - result += important; - } - - return result; - }).join(';'); - - return str; - }; - - // Gets the final (detokenized) length of the given tokens - Token.getDetokenizedLength = function (tokens) { - // If by mistake the input is not an array, make it an array - if (!(tokens instanceof Array)) { - tokens = [tokens]; - } - - var result = 0; - - // This step takes care of putting together the components of shorthands - // NOTE: this is necessary to do for every shorthand, otherwise we couldn't remove their default values - for (var i = 0; i < tokens.length; i++) { - var t = tokens[i]; - if (t.isShorthand && t.isDirty) { - var news = processable[t.prop].putTogether(t.prop, t.components, t.isImportant); - Array.prototype.splice.apply(tokens, [i, 1].concat(news)); - t.isDirty = false; - i--; - continue; - } - - if (t.prop) { - result += t.prop.length + 1; - } - if (t.value) { - result += t.value.length; - } - if (t.isImportant) { - result += important.length; - } - } - - return result; - }; - - return Token; - }; - - return { - createTokenPrototype: createTokenPrototype - }; - -})(); - -},{}],16:[function(_dereq_,module,exports){ - -// Validates various CSS property values - -module.exports = (function () { - // Regexes used for stuff - var cssUnitRegexStr = '(\\-?\\.?\\d+\\.?\\d*(px|%|em|rem|in|cm|mm|ex|pt|pc|)|auto|inherit)'; - var cssFunctionNoVendorRegexStr = '[A-Z]+(\\-|[A-Z]|[0-9])+\\(([A-Z]|[0-9]|\\ |\\,|\\#|\\+|\\-|\\%|\\.)*\\)'; - var cssFunctionVendorRegexStr = '\\-(\\-|[A-Z]|[0-9])+\\(([A-Z]|[0-9]|\\ |\\,|\\#|\\+|\\-|\\%|\\.)*\\)'; - var cssFunctionAnyRegexStr = '(' + cssFunctionNoVendorRegexStr + '|' + cssFunctionVendorRegexStr + ')'; - var cssUnitAnyRegexStr = '(' + cssUnitRegexStr + '|' + cssFunctionNoVendorRegexStr + '|' + cssFunctionVendorRegexStr + ')'; - - var backgroundRepeatKeywords = ['repeat', 'no-repeat', 'repeat-x', 'repeat-y', 'inherit']; - var backgroundAttachmentKeywords = ['inherit', 'scroll', 'fixed', 'local']; - var backgroundPositionKeywords = ['center', 'top', 'bottom', 'left', 'right']; - var listStyleTypeKeywords = ['armenian', 'circle', 'cjk-ideographic', 'decimal', 'decimal-leading-zero', 'disc', 'georgian', 'hebrew', 'hiragana', 'hiragana-iroha', 'inherit', 'katakana', 'katakana-iroha', 'lower-alpha', 'lower-greek', 'lower-latin', 'lower-roman', 'none', 'square', 'upper-alpha', 'upper-latin', 'upper-roman']; - var listStylePositionKeywords = ['inside', 'outside', 'inherit']; - var outlineStyleKeywords = ['inherit', 'hidden', 'none', 'dotted', 'dashed', 'solid', 'double', 'groove', 'ridge', 'inset', 'outset']; - var outlineWidthKeywords = ['thin', 'thick', 'medium', 'inherit']; - - var validator = { - isValidHexColor: function (s) { - return (s.length === 4 || s.length === 7) && s[0] === '#'; - }, - isValidRgbaColor: function (s) { - s = s.split(' ').join(''); - return s.length > 0 && s.indexOf('rgba(') === 0 && s.indexOf(')') === s.length - 1; - }, - isValidHslaColor: function (s) { - s = s.split(' ').join(''); - return s.length > 0 && s.indexOf('hsla(') === 0 && s.indexOf(')') === s.length - 1; - }, - isValidNamedColor: function (s) { - // We don't really check if it's a valid color value, but allow any letters in it - return s !== 'auto' && (s === 'transparent' || s === 'inherit' || /^[a-zA-Z]+$/.test(s)); - }, - isValidColor: function (s) { - return validator.isValidNamedColor(s) || validator.isValidHexColor(s) || validator.isValidRgbaColor(s) || validator.isValidHslaColor(s); - }, - isValidUrl: function (s) { - // NOTE: at this point all URLs are replaced with placeholders by clean-css, so we check for those placeholders - return s.indexOf('__ESCAPED_URL_CLEAN_CSS') === 0; - }, - isValidUnit: function (s) { - return new RegExp('^' + cssUnitAnyRegexStr + '$', 'gi').test(s); - }, - isValidUnitWithoutFunction: function (s) { - return new RegExp('^' + cssUnitRegexStr + '$', 'gi').test(s); - }, - isValidFunctionWithoutVendorPrefix: function (s) { - return new RegExp('^' + cssFunctionNoVendorRegexStr + '$', 'gi').test(s); - }, - isValidFunctionWithVendorPrefix: function (s) { - return new RegExp('^' + cssFunctionVendorRegexStr + '$', 'gi').test(s); - }, - isValidFunction: function (s) { - return new RegExp('^' + cssFunctionAnyRegexStr + '$', 'gi').test(s); - }, - isValidBackgroundRepeat: function (s) { - return backgroundRepeatKeywords.indexOf(s) >= 0; - }, - isValidBackgroundAttachment: function (s) { - return backgroundAttachmentKeywords.indexOf(s) >= 0; - }, - isValidBackgroundPositionPart: function (s) { - if (backgroundPositionKeywords.indexOf(s) >= 0) - return true; - - return new RegExp('^' + cssUnitRegexStr + '$', 'gi').test(s); - }, - isValidBackgroundPosition: function (s) { - if (s === 'inherit') - return true; - - return s.split(' ').filter(function (p) { - return p !== ''; - }).every(function(p) { - return validator.isValidBackgroundPositionPart(p); - }); - }, - isValidListStyleType: function (s) { - return listStyleTypeKeywords.indexOf(s) >= 0; - }, - isValidListStylePosition: function (s) { - return listStylePositionKeywords.indexOf(s) >= 0; - }, - isValidOutlineColor: function (s) { - return s === 'invert' || validator.isValidColor(s) || validator.isValidVendorPrefixedValue(s); - }, - isValidOutlineStyle: function (s) { - return outlineStyleKeywords.indexOf(s) >= 0; - }, - isValidOutlineWidth: function (s) { - return validator.isValidUnit(s) || outlineWidthKeywords.indexOf(s) >= 0; - }, - isValidVendorPrefixedValue: function (s) { - return /^-([A-Za-z0-9]|-)*$/gi.test(s); - }, - areSameFunction: function (a, b) { - if (!validator.isValidFunction(a) || !validator.isValidFunction(b)) { - return false; - } - var f1name = a.substring(0, a.indexOf('(')); - var f2name = b.substring(0, b.indexOf('(')); - - return f1name === f2name; - } - }; - - validator.cssUnitRegexStr = cssUnitRegexStr; - validator.cssFunctionNoVendorRegexStr = cssFunctionNoVendorRegexStr; - validator.cssFunctionVendorRegexStr = cssFunctionVendorRegexStr; - validator.cssFunctionAnyRegexStr = cssFunctionAnyRegexStr; - validator.cssUnitAnyRegexStr = cssUnitAnyRegexStr; - - return validator; -})(); - -},{}],17:[function(_dereq_,module,exports){ -module.exports = function EmptyRemoval(data) { - var stripEmpty = function(cssData) { - var tempData = []; - var nextEmpty = 0; - var cursor = 0; - - for (; nextEmpty < cssData.length;) { - nextEmpty = cssData.indexOf('{}', cursor); - if (nextEmpty == -1) - break; - - var startsAt = nextEmpty - 1; - while (cssData[startsAt] && cssData[startsAt] != '}' && cssData[startsAt] != '{' && cssData[startsAt] != ';') - startsAt--; - - tempData.push(cssData.substring(cursor, startsAt + 1)); - cursor = nextEmpty + 2; - } - - return tempData.length > 0 ? - stripEmpty(tempData.join('') + cssData.substring(cursor, cssData.length)) : - cssData; - }; - - return { - process: function() { - return stripEmpty(data); - } - }; -}; - -},{}],18:[function(_dereq_,module,exports){ -var Tokenizer = _dereq_('./tokenizer'); -var PropertyOptimizer = _dereq_('../properties/optimizer'); - -module.exports = function Optimizer(data, context, options) { - var specialSelectors = { - '*': /\-(moz|ms|o|webkit)\-/, - 'ie8': /(\-moz\-|\-ms\-|\-o\-|\-webkit\-|:root|:nth|:first\-of|:last|:only|:empty|:target|:checked|::selection|:enabled|:disabled|:not)/, - 'ie7': /(\-moz\-|\-ms\-|\-o\-|\-webkit\-|:focus|:before|:after|:root|:nth|:first\-of|:last|:only|:empty|:target|:checked|::selection|:enabled|:disabled|:not)/ - }; - - var minificationsMade = []; - - var propertyOptimizer = new PropertyOptimizer(options.compatibility); - - var cleanUpSelector = function(selectors) { - if (selectors.indexOf(',') == -1) - return selectors; - - var plain = []; - var cursor = 0; - var lastComma = 0; - var noBrackets = selectors.indexOf('(') == -1; - var withinBrackets = function(idx) { - if (noBrackets) - return false; - - var previousOpening = selectors.lastIndexOf('(', idx); - var previousClosing = selectors.lastIndexOf(')', idx); - - if (previousOpening == -1) - return false; - if (previousClosing > 0 && previousClosing < idx) - return false; - - return true; - }; - - while (true) { - var nextComma = selectors.indexOf(',', cursor + 1); - var selector; - - if (nextComma === -1) { - nextComma = selectors.length; - } else if (withinBrackets(nextComma)) { - cursor = nextComma + 1; - continue; - } - selector = selectors.substring(lastComma, nextComma); - lastComma = cursor = nextComma + 1; - - if (plain.indexOf(selector) == -1) - plain.push(selector); - - if (nextComma === selectors.length) - break; - } - - return plain.sort().join(','); - }; - - var isSpecial = function(selector) { - return specialSelectors[options.compatibility || '*'].test(selector); - }; - - var removeDuplicates = function(tokens) { - var matched = {}; - var forRemoval = []; - - for (var i = 0, l = tokens.length; i < l; i++) { - var token = tokens[i]; - if (typeof token == 'string' || token.block) - continue; - - var id = token.body + '@' + token.selector; - var alreadyMatched = matched[id]; - - if (alreadyMatched) { - forRemoval.push(alreadyMatched[0]); - alreadyMatched.unshift(i); - } else { - matched[id] = [i]; - } - } - - forRemoval = forRemoval.sort(function(a, b) { - return a > b ? 1 : -1; - }); - - for (var j = 0, n = forRemoval.length; j < n; j++) { - tokens.splice(forRemoval[j] - j, 1); - } - - minificationsMade.unshift(forRemoval.length > 0); - }; - - var mergeAdjacent = function(tokens) { - var forRemoval = []; - var lastToken = { selector: null, body: null }; - - for (var i = 0, l = tokens.length; i < l; i++) { - var token = tokens[i]; - - if (typeof token == 'string' || token.block) - continue; - - if (token.selector == lastToken.selector) { - var joinAt = [lastToken.body.split(';').length]; - lastToken.body = propertyOptimizer.process(lastToken.body + ';' + token.body, joinAt); - forRemoval.push(i); - } else if (token.body == lastToken.body && !isSpecial(token.selector) && !isSpecial(lastToken.selector)) { - lastToken.selector = cleanUpSelector(lastToken.selector + ',' + token.selector); - forRemoval.push(i); - } else { - lastToken = token; - } - } - - for (var j = 0, m = forRemoval.length; j < m; j++) { - tokens.splice(forRemoval[j] - j, 1); - } - - minificationsMade.unshift(forRemoval.length > 0); - }; - - var reduceNonAdjacent = function(tokens) { - var candidates = {}; - var moreThanOnce = []; - - for (var i = tokens.length - 1; i >= 0; i--) { - var token = tokens[i]; - - if (typeof token == 'string' || token.block) - continue; - - var complexSelector = token.selector; - var selectors = complexSelector.indexOf(',') > -1 && !isSpecial(complexSelector) ? - complexSelector.split(',').concat(complexSelector) : // simplification, as :not() can have commas too - [complexSelector]; - - for (var j = 0, m = selectors.length; j < m; j++) { - var selector = selectors[j]; - - if (!candidates[selector]) - candidates[selector] = []; - else - moreThanOnce.push(selector); - - candidates[selector].push({ - where: i, - partial: selector != complexSelector - }); - } - } - - var reducedInSimple = _reduceSimpleNonAdjacentCases(tokens, moreThanOnce, candidates); - var reducedInComplex = _reduceComplexNonAdjacentCases(tokens, candidates); - - minificationsMade.unshift(reducedInSimple || reducedInComplex); - }; - - var _reduceSimpleNonAdjacentCases = function(tokens, matches, positions) { - var reduced = false; - - for (var i = 0, l = matches.length; i < l; i++) { - var selector = matches[i]; - var data = positions[selector]; - - if (data.length < 2) - continue; - - /* jshint loopfunc: true */ - _reduceSelector(tokens, selector, data, { - filterOut: function(idx, bodies) { - return data[idx].partial && bodies.length === 0; - }, - callback: function(token, newBody, processedCount, tokenIdx) { - if (!data[processedCount - tokenIdx - 1].partial) { - token.body = newBody.join(';'); - reduced = true; - } - } - }); - } - - return reduced; - }; - - var _reduceComplexNonAdjacentCases = function(tokens, positions) { - var reduced = false; - - allSelectors: - for (var complexSelector in positions) { - if (complexSelector.indexOf(',') == -1) // simplification, as :not() can have commas too - continue; - - var intoPosition = positions[complexSelector].pop().where; - var intoToken = tokens[intoPosition]; - - var selectors = isSpecial(complexSelector) ? - [complexSelector] : - complexSelector.split(','); - var reducedBodies = []; - - for (var j = 0, m = selectors.length; j < m; j++) { - var selector = selectors[j]; - var data = positions[selector]; - - if (data.length < 2) - continue allSelectors; - - /* jshint loopfunc: true */ - _reduceSelector(tokens, selector, data, { - filterOut: function(idx) { - return data[idx].where < intoPosition; - }, - callback: function(token, newBody, processedCount, tokenIdx) { - if (tokenIdx === 0) - reducedBodies.push(newBody.join(';')); - } - }); - - if (reducedBodies[reducedBodies.length - 1] != reducedBodies[0]) - continue allSelectors; - } - - intoToken.body = reducedBodies[0]; - reduced = true; - } - - return reduced; - }; - - var _reduceSelector = function(tokens, selector, data, options) { - var bodies = []; - var joinsAt = []; - var splitBodies = []; - var processedTokens = []; - - for (var j = data.length - 1, m = 0; j >= 0; j--) { - if (options.filterOut(j, bodies)) - continue; - - var where = data[j].where; - var token = tokens[where]; - var body = token.body; - bodies.push(body); - splitBodies.push(body.split(';')); - processedTokens.push(where); - } - - for (j = 0, m = bodies.length; j < m; j++) { - if (bodies[j].length > 0) - joinsAt.push((joinsAt[j - 1] || 0) + splitBodies[j].length); - } - - var optimizedBody = propertyOptimizer.process(bodies.join(';'), joinsAt, true); - var optimizedProperties = optimizedBody.split(';'); - - var processedCount = processedTokens.length; - var propertyIdx = optimizedProperties.length - 1; - var tokenIdx = processedCount - 1; - - while (tokenIdx >= 0) { - if ((tokenIdx === 0 || splitBodies[tokenIdx].indexOf(optimizedProperties[propertyIdx]) > -1) && propertyIdx > -1) { - propertyIdx--; - continue; - } - - var newBody = optimizedProperties.splice(propertyIdx + 1); - options.callback(tokens[processedTokens[tokenIdx]], newBody, processedCount, tokenIdx); - - tokenIdx--; - } - }; - - var optimize = function(tokens) { - var noChanges = function() { - return minificationsMade.length > 4 && - minificationsMade[0] === false && - minificationsMade[1] === false; - }; - - tokens = Array.isArray(tokens) ? tokens : [tokens]; - for (var i = 0, l = tokens.length; i < l; i++) { - var token = tokens[i]; - - if (token.selector) { - token.selector = cleanUpSelector(token.selector); - token.body = propertyOptimizer.process(token.body, false); - } else if (token.block) { - optimize(token.body); - } - } - - // Run until 2 last operations do not yield any changes - minificationsMade = []; - while (true) { - if (noChanges()) - break; - removeDuplicates(tokens); - - if (noChanges()) - break; - mergeAdjacent(tokens); - - if (noChanges()) - break; - reduceNonAdjacent(tokens); - } - }; - - var rebuild = function(tokens) { - var rebuilt = []; - - tokens = Array.isArray(tokens) ? tokens : [tokens]; - for (var i = 0, l = tokens.length; i < l; i++) { - var token = tokens[i]; - - if (typeof token == 'string') { - rebuilt.push(token); - continue; - } - - var name = token.block || token.selector; - var body = token.block ? rebuild(token.body) : token.body; - - if (body.length > 0) - rebuilt.push(name + '{' + body + '}'); - } - - return rebuilt.join(options.keepBreaks ? options.lineBreak : ''); - }; - - return { - process: function() { - var tokenized = new Tokenizer(data, context).process(); - optimize(tokenized); - return rebuild(tokenized); - } - }; -}; - -},{"../properties/optimizer":10,"./tokenizer":19}],19:[function(_dereq_,module,exports){ -module.exports = function Tokenizer(data, minifyContext) { - var chunker = new Chunker(data, 128); - var chunk = chunker.next(); - var flatBlock = /^@(font\-face|page|\-ms\-viewport|\-o\-viewport|viewport)/; - - var whatsNext = function(context) { - var cursor = context.cursor; - var mode = context.mode; - var closest; - - if (chunk.length == context.cursor) { - if (chunker.isEmpty()) - return null; - - chunk = chunker.next(); - context.cursor = 0; - } - - if (mode == 'body') { - closest = chunk.indexOf('}', cursor); - return closest > -1 ? - [closest, 'bodyEnd'] : - null; - } - - var nextSpecial = chunk.indexOf('@', context.cursor); - var nextEscape = mode == 'top' ? chunk.indexOf('__ESCAPED_COMMENT_CLEAN_CSS', context.cursor) : -1; - var nextBodyStart = chunk.indexOf('{', context.cursor); - var nextBodyEnd = chunk.indexOf('}', context.cursor); - - closest = nextSpecial; - if (closest == -1 || (nextEscape > -1 && nextEscape < closest)) - closest = nextEscape; - if (closest == -1 || (nextBodyStart > -1 && nextBodyStart < closest)) - closest = nextBodyStart; - if (closest == -1 || (nextBodyEnd > -1 && nextBodyEnd < closest)) - closest = nextBodyEnd; - - if (closest == -1) - return; - if (nextEscape === closest) - return [closest, 'escape']; - if (nextBodyStart === closest) - return [closest, 'bodyStart']; - if (nextBodyEnd === closest) - return [closest, 'bodyEnd']; - if (nextSpecial === closest) - return [closest, 'special']; - }; - - var tokenize = function(context) { - var tokenized = []; - - context = context || { cursor: 0, mode: 'top' }; - - while (true) { - var next = whatsNext(context); - if (!next) { - var whatsLeft = chunk.substring(context.cursor); - if (whatsLeft.length > 0) { - tokenized.push(whatsLeft); - context.cursor += whatsLeft.length; - } - break; - } - - var nextSpecial = next[0]; - var what = next[1]; - var nextEnd; - var oldMode; - - if (what == 'special') { - var fragment = chunk.substring(nextSpecial, context.cursor + '@font-face'.length + 1); - var isSingle = fragment.indexOf('@import') === 0 || fragment.indexOf('@charset') === 0; - if (isSingle) { - nextEnd = chunk.indexOf(';', nextSpecial + 1); - tokenized.push(chunk.substring(context.cursor, nextEnd + 1)); - - context.cursor = nextEnd + 1; - } else { - nextEnd = chunk.indexOf('{', nextSpecial + 1); - var block = chunk.substring(context.cursor, nextEnd).trim(); - - var isFlat = flatBlock.test(block); - oldMode = context.mode; - context.cursor = nextEnd + 1; - context.mode = isFlat ? 'body' : 'block'; - var specialBody = tokenize(context); - context.mode = oldMode; - - tokenized.push({ block: block, body: specialBody }); - } - } else if (what == 'escape') { - nextEnd = chunk.indexOf('__', nextSpecial + 1); - var escaped = chunk.substring(context.cursor, nextEnd + 2); - tokenized.push(escaped); - - context.cursor = nextEnd + 2; - } else if (what == 'bodyStart') { - var selector = chunk.substring(context.cursor, nextSpecial).trim(); - - oldMode = context.mode; - context.cursor = nextSpecial + 1; - context.mode = 'body'; - var body = tokenize(context); - context.mode = oldMode; - - tokenized.push({ selector: selector, body: body }); - } else if (what == 'bodyEnd') { - // extra closing brace at the top level can be safely ignored - if (context.mode == 'top') { - var at = context.cursor; - var warning = chunk[context.cursor] == '}' ? - 'Unexpected \'}\' in \'' + chunk.substring(at - 20, at + 20) + '\'. Ignoring.' : - 'Unexpected content: \'' + chunk.substring(at, nextSpecial + 1) + '\'. Ignoring.'; - - minifyContext.warnings.push(warning); - context.cursor = nextSpecial + 1; - continue; - } - - if (context.mode != 'block') - tokenized = chunk.substring(context.cursor, nextSpecial); - - context.cursor = nextSpecial + 1; - - break; - } - } - - return tokenized; - }; - - return { - process: function() { - return tokenize(); - } - }; -}; - -// Divides `data` into chunks of `chunkSize` for faster processing -var Chunker = function(data, chunkSize) { - var chunks = []; - for (var cursor = 0, dataSize = data.length; cursor < dataSize;) { - var nextCursor = cursor + chunkSize > dataSize ? - dataSize - 1 : - cursor + chunkSize; - - if (data[nextCursor] != '}') - nextCursor = data.indexOf('}', nextCursor); - if (nextCursor == -1) - nextCursor = data.length - 1; - - chunks.push(data.substring(cursor, nextCursor + 1)); - cursor = nextCursor + 1; - } - - return { - isEmpty: function() { - return chunks.length === 0; - }, - - next: function() { - return chunks.shift() || ''; - } - }; -}; - -},{}],20:[function(_dereq_,module,exports){ -var EscapeStore = _dereq_('./escape-store'); - -module.exports = function Comments(keepSpecialComments, keepBreaks, lineBreak) { - var comments = new EscapeStore('COMMENT'); - - return { - // Strip special comments (/*! ... */) by replacing them by a special marker - // for further restoring. Plain comments are removed. It's done by scanning data using - // String#indexOf scanning instead of regexps to speed up the process. - escape: function(data) { - var tempData = []; - var nextStart = 0; - var nextEnd = 0; - var cursor = 0; - - for (; nextEnd < data.length;) { - nextStart = data.indexOf('/*', cursor); - nextEnd = data.indexOf('*/', nextStart + 2); - if (nextStart == -1 || nextEnd == -1) - break; - - tempData.push(data.substring(cursor, nextStart)); - if (data[nextStart + 2] == '!') { - // in case of special comments, replace them with a placeholder - var comment = data.substring(nextStart, nextEnd + 2); - var placeholder = comments.store(comment); - tempData.push(placeholder); - } - cursor = nextEnd + 2; - } - - return tempData.length > 0 ? - tempData.join('') + data.substring(cursor, data.length) : - data; - }, - - restore: function(data) { - var restored = 0; - var breakSuffix = keepBreaks ? lineBreak : ''; - - return data.replace(new RegExp(comments.placeholderPattern + '(' + lineBreak + '| )?', 'g'), function(match, placeholder) { - restored++; - - switch (keepSpecialComments) { - case '*': - return comments.restore(placeholder) + breakSuffix; - case 1: - case '1': - return restored == 1 ? - comments.restore(placeholder) + breakSuffix : - ''; - case 0: - case '0': - return ''; - } - }); - } - }; -}; - -},{"./escape-store":21}],21:[function(_dereq_,module,exports){ -module.exports = function EscapeStore(placeholderRoot) { - placeholderRoot = 'ESCAPED_' + placeholderRoot + '_CLEAN_CSS'; - - var placeholderToData = {}; - var dataToPlaceholder = {}; - var count = 0; - var nextPlaceholder = function() { - return '__' + placeholderRoot + (count++) + '__'; - }; - var pattern = '(__' + placeholderRoot + '\\d{1,}__)'; - - return { - placeholderPattern: pattern, - - placeholderRegExp: new RegExp(pattern, 'g'), - - store: function(data) { - var placeholder = dataToPlaceholder[data]; - if (!placeholder) { - placeholder = nextPlaceholder(); - placeholderToData[placeholder] = data; - dataToPlaceholder[data] = placeholder; - } - - return placeholder; - }, - - restore: function(placeholder) { - return placeholderToData[placeholder]; - } - }; -}; - -},{}],22:[function(_dereq_,module,exports){ -var EscapeStore = _dereq_('./escape-store'); - -module.exports = function Expressions() { - var expressions = new EscapeStore('EXPRESSION'); - - var findEnd = function(data, start) { - var end = start + 'expression'.length; - var level = 0; - var quoted = false; - - while (true) { - var next = data[end++]; - - if (quoted) { - quoted = next != '\'' && next != '"'; - } else { - quoted = next == '\'' || next == '"'; - - if (next == '(') - level++; - if (next == ')') - level--; - if (next == '}' && level == 1) { - end--; - level--; - } - } - - if (level === 0 || !next) - break; - } - - return end; - }; - - return { - // Escapes expressions by replacing them by a special - // marker for further restoring. It's done via string scanning - // instead of regexps to speed up the process. - escape: function(data) { - var nextStart = 0; - var nextEnd = 0; - var cursor = 0; - var tempData = []; - - for (; nextEnd < data.length;) { - nextStart = data.indexOf('expression(', nextEnd); - if (nextStart == -1) - break; - - nextEnd = findEnd(data, nextStart); - - var expression = data.substring(nextStart, nextEnd); - var placeholder = expressions.store(expression); - tempData.push(data.substring(cursor, nextStart)); - tempData.push(placeholder); - cursor = nextEnd; - } - - return tempData.length > 0 ? - tempData.join('') + data.substring(cursor, data.length) : - data; - }, - - restore: function(data) { - return data.replace(expressions.placeholderRegExp, expressions.restore); - } - }; -}; - -},{"./escape-store":21}],23:[function(_dereq_,module,exports){ -(function() { - var EscapeStore = _dereq_('./escape-store'); - var QuoteScanner = _dereq_('./quote-scanner'); - - var Free = function Free() { - this.matches = new EscapeStore('FREE_TEXT'); - }; - - // Strip content tags by replacing them by the a special - // marker for further restoring. It's done via string scanning - // instead of regexps to speed up the process. - Free.prototype.escape = function(data) { - var self = this; - - return new QuoteScanner(data).each(function(match, store) { - var placeholder = self.matches.store(match); - store.push(placeholder); - }); - }; - - Free.prototype.restore = function(data) { - return data.replace(this.matches.placeholderRegExp, this.matches.restore); - }; - - module.exports = Free; -})(); - -},{"./escape-store":21,"./quote-scanner":25}],24:[function(_dereq_,module,exports){ -(function() { - var QuoteScanner = _dereq_('./quote-scanner'); - var PropertyScanner = _dereq_('../properties/scanner'); - - var NameQuotes = function NameQuotes() {}; - - var STRIPPABLE = /^['"][a-zA-Z][a-zA-Z\d\-_]+['"]$/; - - var properties = [ - 'animation', - '-moz-animation', - '-o-animation', - '-webkit-animation', - 'animation-name', - '-moz-animation-name', - '-o-animation-name', - '-webkit-animation-name', - 'font', - 'font-family' - ]; - - NameQuotes.prototype.process = function(data) { - var scanner = new PropertyScanner(data); - - return new QuoteScanner(data).each(function(match, store, cursor) { - var lastProperty = scanner.nextAt(cursor); - if (properties.indexOf(lastProperty) > -1) { - if (STRIPPABLE.test(match)) - match = match.substring(1, match.length - 1); - } - - store.push(match); - }); - }; - - module.exports = NameQuotes; -})(); - -},{"../properties/scanner":13,"./quote-scanner":25}],25:[function(_dereq_,module,exports){ -(function() { - var QuoteScanner = function QuoteScanner(data) { - this.data = data; - }; - - var findNonEscapedEnd = function(data, matched, start) { - var end = start; - while (true) { - end = data.indexOf(matched, end); - - if (end > -1 && data[end - 1] == '\\') { - end += 1; - continue; - } else { - break; - } - } - - return end; - }; - - QuoteScanner.prototype.each = function(callback) { - var data = this.data; - var tempData = []; - var nextStart = 0; - var nextEnd = 0; - var cursor = 0; - var matchedMark = null; - var singleMark = '\''; - var doubleMark = '"'; - var dataLength = data.length; - - for (; nextEnd < data.length;) { - var nextStartSingle = data.indexOf(singleMark, nextEnd + 1); - var nextStartDouble = data.indexOf(doubleMark, nextEnd + 1); - - if (nextStartSingle == -1) - nextStartSingle = dataLength; - if (nextStartDouble == -1) - nextStartDouble = dataLength; - - if (nextStartSingle < nextStartDouble) { - nextStart = nextStartSingle; - matchedMark = singleMark; - } else { - nextStart = nextStartDouble; - matchedMark = doubleMark; - } - - if (nextStart == -1) - break; - - nextEnd = findNonEscapedEnd(data, matchedMark, nextStart + 1); - if (nextEnd == -1) - break; - - var text = data.substring(nextStart, nextEnd + 1); - tempData.push(data.substring(cursor, nextStart)); - callback(text, tempData, nextStart); - - cursor = nextEnd + 1; - } - - return tempData.length > 0 ? - tempData.join('') + data.substring(cursor, data.length) : - data; - }; - - module.exports = QuoteScanner; -})(); - -},{}],26:[function(_dereq_,module,exports){ -var EscapeStore = _dereq_('./escape-store'); - -module.exports = function Urls() { - var urls = new EscapeStore('URL'); - - return { - // Strip urls by replacing them by a special - // marker for further restoring. It's done via string scanning - // instead of regexps to speed up the process. - escape: function(data) { - var nextStart = 0; - var nextEnd = 0; - var cursor = 0; - var tempData = []; - - for (; nextEnd < data.length;) { - nextStart = data.indexOf('url(', nextEnd); - if (nextStart == -1) - break; - - nextEnd = data.indexOf(')', nextStart); - - var url = data.substring(nextStart, nextEnd + 1); - var placeholder = urls.store(url); - tempData.push(data.substring(cursor, nextStart)); - tempData.push(placeholder); - cursor = nextEnd + 1; - } - - return tempData.length > 0 ? - tempData.join('') + data.substring(cursor, data.length) : - data; - }, - - restore: function(data) { - return data.replace(urls.placeholderRegExp, function(placeholder) { - return urls.restore(placeholder).replace(/\s/g, ''); - }); - } - }; -}; - -},{"./escape-store":21}],27:[function(_dereq_,module,exports){ - -},{}],28:[function(_dereq_,module,exports){ -/*! - * The buffer module from node.js, for the browser. - * - * @author Feross Aboukhadijeh - * @license MIT - */ - -var base64 = _dereq_('base64-js') -var ieee754 = _dereq_('ieee754') - -exports.Buffer = Buffer -exports.SlowBuffer = Buffer -exports.INSPECT_MAX_BYTES = 50 -Buffer.poolSize = 8192 - -/** - * If `Buffer._useTypedArrays`: - * === true Use Uint8Array implementation (fastest) - * === false Use Object implementation (compatible down to IE6) - */ -Buffer._useTypedArrays = (function () { - // Detect if browser supports Typed Arrays. Supported browsers are IE 10+, Firefox 4+, - // Chrome 7+, Safari 5.1+, Opera 11.6+, iOS 4.2+. If the browser does not support adding - // properties to `Uint8Array` instances, then that's the same as no `Uint8Array` support - // because we need to be able to add all the node Buffer API methods. This is an issue - // in Firefox 4-29. Now fixed: https://bugzilla.mozilla.org/show_bug.cgi?id=695438 - try { - var buf = new ArrayBuffer(0) - var arr = new Uint8Array(buf) - arr.foo = function () { return 42 } - return 42 === arr.foo() && - typeof arr.subarray === 'function' // Chrome 9-10 lack `subarray` - } catch (e) { - return false - } -})() - -/** - * Class: Buffer - * ============= - * - * The Buffer constructor returns instances of `Uint8Array` that are augmented - * with function properties for all the node `Buffer` API functions. We use - * `Uint8Array` so that square bracket notation works as expected -- it returns - * a single octet. - * - * By augmenting the instances, we can avoid modifying the `Uint8Array` - * prototype. - */ -function Buffer (subject, encoding, noZero) { - if (!(this instanceof Buffer)) - return new Buffer(subject, encoding, noZero) - - var type = typeof subject - - // Workaround: node's base64 implementation allows for non-padded strings - // while base64-js does not. - if (encoding === 'base64' && type === 'string') { - subject = stringtrim(subject) - while (subject.length % 4 !== 0) { - subject = subject + '=' - } - } - - // Find the length - var length - if (type === 'number') - length = coerce(subject) - else if (type === 'string') - length = Buffer.byteLength(subject, encoding) - else if (type === 'object') - length = coerce(subject.length) // assume that object is array-like - else - throw new Error('First argument needs to be a number, array or string.') - - var buf - if (Buffer._useTypedArrays) { - // Preferred: Return an augmented `Uint8Array` instance for best performance - buf = Buffer._augment(new Uint8Array(length)) - } else { - // Fallback: Return THIS instance of Buffer (created by `new`) - buf = this - buf.length = length - buf._isBuffer = true - } - - var i - if (Buffer._useTypedArrays && typeof subject.byteLength === 'number') { - // Speed optimization -- use set if we're copying from a typed array - buf._set(subject) - } else if (isArrayish(subject)) { - // Treat array-ish objects as a byte array - for (i = 0; i < length; i++) { - if (Buffer.isBuffer(subject)) - buf[i] = subject.readUInt8(i) - else - buf[i] = subject[i] - } - } else if (type === 'string') { - buf.write(subject, 0, encoding) - } else if (type === 'number' && !Buffer._useTypedArrays && !noZero) { - for (i = 0; i < length; i++) { - buf[i] = 0 - } - } - - return buf -} - -// STATIC METHODS -// ============== - -Buffer.isEncoding = function (encoding) { - switch (String(encoding).toLowerCase()) { - case 'hex': - case 'utf8': - case 'utf-8': - case 'ascii': - case 'binary': - case 'base64': - case 'raw': - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return true - default: - return false - } -} - -Buffer.isBuffer = function (b) { - return !!(b !== null && b !== undefined && b._isBuffer) -} - -Buffer.byteLength = function (str, encoding) { - var ret - str = str.toString() - switch (encoding || 'utf8') { - case 'hex': - ret = str.length / 2 - break - case 'utf8': - case 'utf-8': - ret = utf8ToBytes(str).length - break - case 'ascii': - case 'binary': - case 'raw': - ret = str.length - break - case 'base64': - ret = base64ToBytes(str).length - break - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - ret = str.length * 2 - break - default: - throw new Error('Unknown encoding') - } - return ret -} - -Buffer.concat = function (list, totalLength) { - assert(isArray(list), 'Usage: Buffer.concat(list[, length])') - - if (list.length === 0) { - return new Buffer(0) - } else if (list.length === 1) { - return list[0] - } - - var i - if (totalLength === undefined) { - totalLength = 0 - for (i = 0; i < list.length; i++) { - totalLength += list[i].length - } - } - - var buf = new Buffer(totalLength) - var pos = 0 - for (i = 0; i < list.length; i++) { - var item = list[i] - item.copy(buf, pos) - pos += item.length - } - return buf -} - -Buffer.compare = function (a, b) { - assert(Buffer.isBuffer(a) && Buffer.isBuffer(b), 'Arguments must be Buffers') - var x = a.length - var y = b.length - for (var i = 0, len = Math.min(x, y); i < len && a[i] === b[i]; i++) {} - if (i !== len) { - x = a[i] - y = b[i] - } - if (x < y) { - return -1 - } - if (y < x) { - return 1 - } - return 0 -} - -// BUFFER INSTANCE METHODS -// ======================= - -function hexWrite (buf, string, offset, length) { - offset = Number(offset) || 0 - var remaining = buf.length - offset - if (!length) { - length = remaining - } else { - length = Number(length) - if (length > remaining) { - length = remaining - } - } - - // must be an even number of digits - var strLen = string.length - assert(strLen % 2 === 0, 'Invalid hex string') - - if (length > strLen / 2) { - length = strLen / 2 - } - for (var i = 0; i < length; i++) { - var byte = parseInt(string.substr(i * 2, 2), 16) - assert(!isNaN(byte), 'Invalid hex string') - buf[offset + i] = byte - } - return i -} - -function utf8Write (buf, string, offset, length) { - var charsWritten = blitBuffer(utf8ToBytes(string), buf, offset, length) - return charsWritten -} - -function asciiWrite (buf, string, offset, length) { - var charsWritten = blitBuffer(asciiToBytes(string), buf, offset, length) - return charsWritten -} - -function binaryWrite (buf, string, offset, length) { - return asciiWrite(buf, string, offset, length) -} - -function base64Write (buf, string, offset, length) { - var charsWritten = blitBuffer(base64ToBytes(string), buf, offset, length) - return charsWritten -} - -function utf16leWrite (buf, string, offset, length) { - var charsWritten = blitBuffer(utf16leToBytes(string), buf, offset, length) - return charsWritten -} - -Buffer.prototype.write = function (string, offset, length, encoding) { - // Support both (string, offset, length, encoding) - // and the legacy (string, encoding, offset, length) - if (isFinite(offset)) { - if (!isFinite(length)) { - encoding = length - length = undefined - } - } else { // legacy - var swap = encoding - encoding = offset - offset = length - length = swap - } - - offset = Number(offset) || 0 - var remaining = this.length - offset - if (!length) { - length = remaining - } else { - length = Number(length) - if (length > remaining) { - length = remaining - } - } - encoding = String(encoding || 'utf8').toLowerCase() - - var ret - switch (encoding) { - case 'hex': - ret = hexWrite(this, string, offset, length) - break - case 'utf8': - case 'utf-8': - ret = utf8Write(this, string, offset, length) - break - case 'ascii': - ret = asciiWrite(this, string, offset, length) - break - case 'binary': - ret = binaryWrite(this, string, offset, length) - break - case 'base64': - ret = base64Write(this, string, offset, length) - break - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - ret = utf16leWrite(this, string, offset, length) - break - default: - throw new Error('Unknown encoding') - } - return ret -} - -Buffer.prototype.toString = function (encoding, start, end) { - var self = this - - encoding = String(encoding || 'utf8').toLowerCase() - start = Number(start) || 0 - end = (end === undefined) ? self.length : Number(end) - - // Fastpath empty strings - if (end === start) - return '' - - var ret - switch (encoding) { - case 'hex': - ret = hexSlice(self, start, end) - break - case 'utf8': - case 'utf-8': - ret = utf8Slice(self, start, end) - break - case 'ascii': - ret = asciiSlice(self, start, end) - break - case 'binary': - ret = binarySlice(self, start, end) - break - case 'base64': - ret = base64Slice(self, start, end) - break - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - ret = utf16leSlice(self, start, end) - break - default: - throw new Error('Unknown encoding') - } - return ret -} - -Buffer.prototype.toJSON = function () { - return { - type: 'Buffer', - data: Array.prototype.slice.call(this._arr || this, 0) - } -} - -Buffer.prototype.equals = function (b) { - assert(Buffer.isBuffer(b), 'Argument must be a Buffer') - return Buffer.compare(this, b) === 0 -} - -Buffer.prototype.compare = function (b) { - assert(Buffer.isBuffer(b), 'Argument must be a Buffer') - return Buffer.compare(this, b) -} - -// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) -Buffer.prototype.copy = function (target, target_start, start, end) { - var source = this - - if (!start) start = 0 - if (!end && end !== 0) end = this.length - if (!target_start) target_start = 0 - - // Copy 0 bytes; we're done - if (end === start) return - if (target.length === 0 || source.length === 0) return - - // Fatal error conditions - assert(end >= start, 'sourceEnd < sourceStart') - assert(target_start >= 0 && target_start < target.length, - 'targetStart out of bounds') - assert(start >= 0 && start < source.length, 'sourceStart out of bounds') - assert(end >= 0 && end <= source.length, 'sourceEnd out of bounds') - - // Are we oob? - if (end > this.length) - end = this.length - if (target.length - target_start < end - start) - end = target.length - target_start + start - - var len = end - start - - if (len < 100 || !Buffer._useTypedArrays) { - for (var i = 0; i < len; i++) { - target[i + target_start] = this[i + start] - } - } else { - target._set(this.subarray(start, start + len), target_start) - } -} - -function base64Slice (buf, start, end) { - if (start === 0 && end === buf.length) { - return base64.fromByteArray(buf) - } else { - return base64.fromByteArray(buf.slice(start, end)) - } -} - -function utf8Slice (buf, start, end) { - var res = '' - var tmp = '' - end = Math.min(buf.length, end) - - for (var i = start; i < end; i++) { - if (buf[i] <= 0x7F) { - res += decodeUtf8Char(tmp) + String.fromCharCode(buf[i]) - tmp = '' - } else { - tmp += '%' + buf[i].toString(16) - } - } - - return res + decodeUtf8Char(tmp) -} - -function asciiSlice (buf, start, end) { - var ret = '' - end = Math.min(buf.length, end) - - for (var i = start; i < end; i++) { - ret += String.fromCharCode(buf[i]) - } - return ret -} - -function binarySlice (buf, start, end) { - return asciiSlice(buf, start, end) -} - -function hexSlice (buf, start, end) { - var len = buf.length - - if (!start || start < 0) start = 0 - if (!end || end < 0 || end > len) end = len - - var out = '' - for (var i = start; i < end; i++) { - out += toHex(buf[i]) - } - return out -} - -function utf16leSlice (buf, start, end) { - var bytes = buf.slice(start, end) - var res = '' - for (var i = 0; i < bytes.length; i += 2) { - res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256) - } - return res -} - -Buffer.prototype.slice = function (start, end) { - var len = this.length - start = clamp(start, len, 0) - end = clamp(end, len, len) - - if (Buffer._useTypedArrays) { - return Buffer._augment(this.subarray(start, end)) - } else { - var sliceLen = end - start - var newBuf = new Buffer(sliceLen, undefined, true) - for (var i = 0; i < sliceLen; i++) { - newBuf[i] = this[i + start] - } - return newBuf - } -} - -// `get` will be removed in Node 0.13+ -Buffer.prototype.get = function (offset) { - console.log('.get() is deprecated. Access using array indexes instead.') - return this.readUInt8(offset) -} - -// `set` will be removed in Node 0.13+ -Buffer.prototype.set = function (v, offset) { - console.log('.set() is deprecated. Access using array indexes instead.') - return this.writeUInt8(v, offset) -} - -Buffer.prototype.readUInt8 = function (offset, noAssert) { - if (!noAssert) { - assert(offset !== undefined && offset !== null, 'missing offset') - assert(offset < this.length, 'Trying to read beyond buffer length') - } - - if (offset >= this.length) - return - - return this[offset] -} - -function readUInt16 (buf, offset, littleEndian, noAssert) { - if (!noAssert) { - assert(typeof littleEndian === 'boolean', 'missing or invalid endian') - assert(offset !== undefined && offset !== null, 'missing offset') - assert(offset + 1 < buf.length, 'Trying to read beyond buffer length') - } - - var len = buf.length - if (offset >= len) - return - - var val - if (littleEndian) { - val = buf[offset] - if (offset + 1 < len) - val |= buf[offset + 1] << 8 - } else { - val = buf[offset] << 8 - if (offset + 1 < len) - val |= buf[offset + 1] - } - return val -} - -Buffer.prototype.readUInt16LE = function (offset, noAssert) { - return readUInt16(this, offset, true, noAssert) -} - -Buffer.prototype.readUInt16BE = function (offset, noAssert) { - return readUInt16(this, offset, false, noAssert) -} - -function readUInt32 (buf, offset, littleEndian, noAssert) { - if (!noAssert) { - assert(typeof littleEndian === 'boolean', 'missing or invalid endian') - assert(offset !== undefined && offset !== null, 'missing offset') - assert(offset + 3 < buf.length, 'Trying to read beyond buffer length') - } - - var len = buf.length - if (offset >= len) - return - - var val - if (littleEndian) { - if (offset + 2 < len) - val = buf[offset + 2] << 16 - if (offset + 1 < len) - val |= buf[offset + 1] << 8 - val |= buf[offset] - if (offset + 3 < len) - val = val + (buf[offset + 3] << 24 >>> 0) - } else { - if (offset + 1 < len) - val = buf[offset + 1] << 16 - if (offset + 2 < len) - val |= buf[offset + 2] << 8 - if (offset + 3 < len) - val |= buf[offset + 3] - val = val + (buf[offset] << 24 >>> 0) - } - return val -} - -Buffer.prototype.readUInt32LE = function (offset, noAssert) { - return readUInt32(this, offset, true, noAssert) -} - -Buffer.prototype.readUInt32BE = function (offset, noAssert) { - return readUInt32(this, offset, false, noAssert) -} - -Buffer.prototype.readInt8 = function (offset, noAssert) { - if (!noAssert) { - assert(offset !== undefined && offset !== null, - 'missing offset') - assert(offset < this.length, 'Trying to read beyond buffer length') - } - - if (offset >= this.length) - return - - var neg = this[offset] & 0x80 - if (neg) - return (0xff - this[offset] + 1) * -1 - else - return this[offset] -} - -function readInt16 (buf, offset, littleEndian, noAssert) { - if (!noAssert) { - assert(typeof littleEndian === 'boolean', 'missing or invalid endian') - assert(offset !== undefined && offset !== null, 'missing offset') - assert(offset + 1 < buf.length, 'Trying to read beyond buffer length') - } - - var len = buf.length - if (offset >= len) - return - - var val = readUInt16(buf, offset, littleEndian, true) - var neg = val & 0x8000 - if (neg) - return (0xffff - val + 1) * -1 - else - return val -} - -Buffer.prototype.readInt16LE = function (offset, noAssert) { - return readInt16(this, offset, true, noAssert) -} - -Buffer.prototype.readInt16BE = function (offset, noAssert) { - return readInt16(this, offset, false, noAssert) -} - -function readInt32 (buf, offset, littleEndian, noAssert) { - if (!noAssert) { - assert(typeof littleEndian === 'boolean', 'missing or invalid endian') - assert(offset !== undefined && offset !== null, 'missing offset') - assert(offset + 3 < buf.length, 'Trying to read beyond buffer length') - } - - var len = buf.length - if (offset >= len) - return - - var val = readUInt32(buf, offset, littleEndian, true) - var neg = val & 0x80000000 - if (neg) - return (0xffffffff - val + 1) * -1 - else - return val -} - -Buffer.prototype.readInt32LE = function (offset, noAssert) { - return readInt32(this, offset, true, noAssert) -} - -Buffer.prototype.readInt32BE = function (offset, noAssert) { - return readInt32(this, offset, false, noAssert) -} - -function readFloat (buf, offset, littleEndian, noAssert) { - if (!noAssert) { - assert(typeof littleEndian === 'boolean', 'missing or invalid endian') - assert(offset + 3 < buf.length, 'Trying to read beyond buffer length') - } - - return ieee754.read(buf, offset, littleEndian, 23, 4) -} - -Buffer.prototype.readFloatLE = function (offset, noAssert) { - return readFloat(this, offset, true, noAssert) -} - -Buffer.prototype.readFloatBE = function (offset, noAssert) { - return readFloat(this, offset, false, noAssert) -} - -function readDouble (buf, offset, littleEndian, noAssert) { - if (!noAssert) { - assert(typeof littleEndian === 'boolean', 'missing or invalid endian') - assert(offset + 7 < buf.length, 'Trying to read beyond buffer length') - } - - return ieee754.read(buf, offset, littleEndian, 52, 8) -} - -Buffer.prototype.readDoubleLE = function (offset, noAssert) { - return readDouble(this, offset, true, noAssert) -} - -Buffer.prototype.readDoubleBE = function (offset, noAssert) { - return readDouble(this, offset, false, noAssert) -} - -Buffer.prototype.writeUInt8 = function (value, offset, noAssert) { - if (!noAssert) { - assert(value !== undefined && value !== null, 'missing value') - assert(offset !== undefined && offset !== null, 'missing offset') - assert(offset < this.length, 'trying to write beyond buffer length') - verifuint(value, 0xff) - } - - if (offset >= this.length) return - - this[offset] = value - return offset + 1 -} - -function writeUInt16 (buf, value, offset, littleEndian, noAssert) { - if (!noAssert) { - assert(value !== undefined && value !== null, 'missing value') - assert(typeof littleEndian === 'boolean', 'missing or invalid endian') - assert(offset !== undefined && offset !== null, 'missing offset') - assert(offset + 1 < buf.length, 'trying to write beyond buffer length') - verifuint(value, 0xffff) - } - - var len = buf.length - if (offset >= len) - return - - for (var i = 0, j = Math.min(len - offset, 2); i < j; i++) { - buf[offset + i] = - (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> - (littleEndian ? i : 1 - i) * 8 - } - return offset + 2 -} - -Buffer.prototype.writeUInt16LE = function (value, offset, noAssert) { - return writeUInt16(this, value, offset, true, noAssert) -} - -Buffer.prototype.writeUInt16BE = function (value, offset, noAssert) { - return writeUInt16(this, value, offset, false, noAssert) -} - -function writeUInt32 (buf, value, offset, littleEndian, noAssert) { - if (!noAssert) { - assert(value !== undefined && value !== null, 'missing value') - assert(typeof littleEndian === 'boolean', 'missing or invalid endian') - assert(offset !== undefined && offset !== null, 'missing offset') - assert(offset + 3 < buf.length, 'trying to write beyond buffer length') - verifuint(value, 0xffffffff) - } - - var len = buf.length - if (offset >= len) - return - - for (var i = 0, j = Math.min(len - offset, 4); i < j; i++) { - buf[offset + i] = - (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff - } - return offset + 4 -} - -Buffer.prototype.writeUInt32LE = function (value, offset, noAssert) { - return writeUInt32(this, value, offset, true, noAssert) -} - -Buffer.prototype.writeUInt32BE = function (value, offset, noAssert) { - return writeUInt32(this, value, offset, false, noAssert) -} - -Buffer.prototype.writeInt8 = function (value, offset, noAssert) { - if (!noAssert) { - assert(value !== undefined && value !== null, 'missing value') - assert(offset !== undefined && offset !== null, 'missing offset') - assert(offset < this.length, 'Trying to write beyond buffer length') - verifsint(value, 0x7f, -0x80) - } - - if (offset >= this.length) - return - - if (value >= 0) - this.writeUInt8(value, offset, noAssert) - else - this.writeUInt8(0xff + value + 1, offset, noAssert) - return offset + 1 -} - -function writeInt16 (buf, value, offset, littleEndian, noAssert) { - if (!noAssert) { - assert(value !== undefined && value !== null, 'missing value') - assert(typeof littleEndian === 'boolean', 'missing or invalid endian') - assert(offset !== undefined && offset !== null, 'missing offset') - assert(offset + 1 < buf.length, 'Trying to write beyond buffer length') - verifsint(value, 0x7fff, -0x8000) - } - - var len = buf.length - if (offset >= len) - return - - if (value >= 0) - writeUInt16(buf, value, offset, littleEndian, noAssert) - else - writeUInt16(buf, 0xffff + value + 1, offset, littleEndian, noAssert) - return offset + 2 -} - -Buffer.prototype.writeInt16LE = function (value, offset, noAssert) { - return writeInt16(this, value, offset, true, noAssert) -} - -Buffer.prototype.writeInt16BE = function (value, offset, noAssert) { - return writeInt16(this, value, offset, false, noAssert) -} - -function writeInt32 (buf, value, offset, littleEndian, noAssert) { - if (!noAssert) { - assert(value !== undefined && value !== null, 'missing value') - assert(typeof littleEndian === 'boolean', 'missing or invalid endian') - assert(offset !== undefined && offset !== null, 'missing offset') - assert(offset + 3 < buf.length, 'Trying to write beyond buffer length') - verifsint(value, 0x7fffffff, -0x80000000) - } - - var len = buf.length - if (offset >= len) - return - - if (value >= 0) - writeUInt32(buf, value, offset, littleEndian, noAssert) - else - writeUInt32(buf, 0xffffffff + value + 1, offset, littleEndian, noAssert) - return offset + 4 -} - -Buffer.prototype.writeInt32LE = function (value, offset, noAssert) { - return writeInt32(this, value, offset, true, noAssert) -} - -Buffer.prototype.writeInt32BE = function (value, offset, noAssert) { - return writeInt32(this, value, offset, false, noAssert) -} - -function writeFloat (buf, value, offset, littleEndian, noAssert) { - if (!noAssert) { - assert(value !== undefined && value !== null, 'missing value') - assert(typeof littleEndian === 'boolean', 'missing or invalid endian') - assert(offset !== undefined && offset !== null, 'missing offset') - assert(offset + 3 < buf.length, 'Trying to write beyond buffer length') - verifIEEE754(value, 3.4028234663852886e+38, -3.4028234663852886e+38) - } - - var len = buf.length - if (offset >= len) - return - - ieee754.write(buf, value, offset, littleEndian, 23, 4) - return offset + 4 -} - -Buffer.prototype.writeFloatLE = function (value, offset, noAssert) { - return writeFloat(this, value, offset, true, noAssert) -} - -Buffer.prototype.writeFloatBE = function (value, offset, noAssert) { - return writeFloat(this, value, offset, false, noAssert) -} - -function writeDouble (buf, value, offset, littleEndian, noAssert) { - if (!noAssert) { - assert(value !== undefined && value !== null, 'missing value') - assert(typeof littleEndian === 'boolean', 'missing or invalid endian') - assert(offset !== undefined && offset !== null, 'missing offset') - assert(offset + 7 < buf.length, - 'Trying to write beyond buffer length') - verifIEEE754(value, 1.7976931348623157E+308, -1.7976931348623157E+308) - } - - var len = buf.length - if (offset >= len) - return - - ieee754.write(buf, value, offset, littleEndian, 52, 8) - return offset + 8 -} - -Buffer.prototype.writeDoubleLE = function (value, offset, noAssert) { - return writeDouble(this, value, offset, true, noAssert) -} - -Buffer.prototype.writeDoubleBE = function (value, offset, noAssert) { - return writeDouble(this, value, offset, false, noAssert) -} - -// fill(value, start=0, end=buffer.length) -Buffer.prototype.fill = function (value, start, end) { - if (!value) value = 0 - if (!start) start = 0 - if (!end) end = this.length - - assert(end >= start, 'end < start') - - // Fill 0 bytes; we're done - if (end === start) return - if (this.length === 0) return - - assert(start >= 0 && start < this.length, 'start out of bounds') - assert(end >= 0 && end <= this.length, 'end out of bounds') - - var i - if (typeof value === 'number') { - for (i = start; i < end; i++) { - this[i] = value - } - } else { - var bytes = utf8ToBytes(value.toString()) - var len = bytes.length - for (i = start; i < end; i++) { - this[i] = bytes[i % len] - } - } - - return this -} - -Buffer.prototype.inspect = function () { - var out = [] - var len = this.length - for (var i = 0; i < len; i++) { - out[i] = toHex(this[i]) - if (i === exports.INSPECT_MAX_BYTES) { - out[i + 1] = '...' - break - } - } - return '' -} - -/** - * Creates a new `ArrayBuffer` with the *copied* memory of the buffer instance. - * Added in Node 0.12. Only available in browsers that support ArrayBuffer. - */ -Buffer.prototype.toArrayBuffer = function () { - if (typeof Uint8Array !== 'undefined') { - if (Buffer._useTypedArrays) { - return (new Buffer(this)).buffer - } else { - var buf = new Uint8Array(this.length) - for (var i = 0, len = buf.length; i < len; i += 1) { - buf[i] = this[i] - } - return buf.buffer - } - } else { - throw new Error('Buffer.toArrayBuffer not supported in this browser') - } -} - -// HELPER FUNCTIONS -// ================ - -var BP = Buffer.prototype - -/** - * Augment a Uint8Array *instance* (not the Uint8Array class!) with Buffer methods - */ -Buffer._augment = function (arr) { - arr._isBuffer = true - - // save reference to original Uint8Array get/set methods before overwriting - arr._get = arr.get - arr._set = arr.set - - // deprecated, will be removed in node 0.13+ - arr.get = BP.get - arr.set = BP.set - - arr.write = BP.write - arr.toString = BP.toString - arr.toLocaleString = BP.toString - arr.toJSON = BP.toJSON - arr.equals = BP.equals - arr.compare = BP.compare - arr.copy = BP.copy - arr.slice = BP.slice - arr.readUInt8 = BP.readUInt8 - arr.readUInt16LE = BP.readUInt16LE - arr.readUInt16BE = BP.readUInt16BE - arr.readUInt32LE = BP.readUInt32LE - arr.readUInt32BE = BP.readUInt32BE - arr.readInt8 = BP.readInt8 - arr.readInt16LE = BP.readInt16LE - arr.readInt16BE = BP.readInt16BE - arr.readInt32LE = BP.readInt32LE - arr.readInt32BE = BP.readInt32BE - arr.readFloatLE = BP.readFloatLE - arr.readFloatBE = BP.readFloatBE - arr.readDoubleLE = BP.readDoubleLE - arr.readDoubleBE = BP.readDoubleBE - arr.writeUInt8 = BP.writeUInt8 - arr.writeUInt16LE = BP.writeUInt16LE - arr.writeUInt16BE = BP.writeUInt16BE - arr.writeUInt32LE = BP.writeUInt32LE - arr.writeUInt32BE = BP.writeUInt32BE - arr.writeInt8 = BP.writeInt8 - arr.writeInt16LE = BP.writeInt16LE - arr.writeInt16BE = BP.writeInt16BE - arr.writeInt32LE = BP.writeInt32LE - arr.writeInt32BE = BP.writeInt32BE - arr.writeFloatLE = BP.writeFloatLE - arr.writeFloatBE = BP.writeFloatBE - arr.writeDoubleLE = BP.writeDoubleLE - arr.writeDoubleBE = BP.writeDoubleBE - arr.fill = BP.fill - arr.inspect = BP.inspect - arr.toArrayBuffer = BP.toArrayBuffer - - return arr -} - -function stringtrim (str) { - if (str.trim) return str.trim() - return str.replace(/^\s+|\s+$/g, '') -} - -// slice(start, end) -function clamp (index, len, defaultValue) { - if (typeof index !== 'number') return defaultValue - index = ~~index; // Coerce to integer. - if (index >= len) return len - if (index >= 0) return index - index += len - if (index >= 0) return index - return 0 -} - -function coerce (length) { - // Coerce length to a number (possibly NaN), round up - // in case it's fractional (e.g. 123.456) then do a - // double negate to coerce a NaN to 0. Easy, right? - length = ~~Math.ceil(+length) - return length < 0 ? 0 : length -} - -function isArray (subject) { - return (Array.isArray || function (subject) { - return Object.prototype.toString.call(subject) === '[object Array]' - })(subject) -} - -function isArrayish (subject) { - return isArray(subject) || Buffer.isBuffer(subject) || - subject && typeof subject === 'object' && - typeof subject.length === 'number' -} - -function toHex (n) { - if (n < 16) return '0' + n.toString(16) - return n.toString(16) -} - -function utf8ToBytes (str) { - var byteArray = [] - for (var i = 0; i < str.length; i++) { - var b = str.charCodeAt(i) - if (b <= 0x7F) { - byteArray.push(b) - } else { - var start = i - if (b >= 0xD800 && b <= 0xDFFF) i++ - var h = encodeURIComponent(str.slice(start, i+1)).substr(1).split('%') - for (var j = 0; j < h.length; j++) { - byteArray.push(parseInt(h[j], 16)) - } - } - } - return byteArray -} - -function asciiToBytes (str) { - var byteArray = [] - for (var i = 0; i < str.length; i++) { - // Node's code seems to be doing this and not & 0x7F.. - byteArray.push(str.charCodeAt(i) & 0xFF) - } - return byteArray -} - -function utf16leToBytes (str) { - var c, hi, lo - var byteArray = [] - for (var i = 0; i < str.length; i++) { - c = str.charCodeAt(i) - hi = c >> 8 - lo = c % 256 - byteArray.push(lo) - byteArray.push(hi) - } - - return byteArray -} - -function base64ToBytes (str) { - return base64.toByteArray(str) -} - -function blitBuffer (src, dst, offset, length) { - for (var i = 0; i < length; i++) { - if ((i + offset >= dst.length) || (i >= src.length)) - break - dst[i + offset] = src[i] - } - return i -} - -function decodeUtf8Char (str) { - try { - return decodeURIComponent(str) - } catch (err) { - return String.fromCharCode(0xFFFD) // UTF 8 invalid char - } -} - -/* - * We have to make sure that the value is a valid integer. This means that it - * is non-negative. It has no fractional component and that it does not - * exceed the maximum allowed value. - */ -function verifuint (value, max) { - assert(typeof value === 'number', 'cannot write a non-number as a number') - assert(value >= 0, 'specified a negative value for writing an unsigned value') - assert(value <= max, 'value is larger than maximum value for type') - assert(Math.floor(value) === value, 'value has a fractional component') -} - -function verifsint (value, max, min) { - assert(typeof value === 'number', 'cannot write a non-number as a number') - assert(value <= max, 'value larger than maximum allowed value') - assert(value >= min, 'value smaller than minimum allowed value') - assert(Math.floor(value) === value, 'value has a fractional component') -} - -function verifIEEE754 (value, max, min) { - assert(typeof value === 'number', 'cannot write a non-number as a number') - assert(value <= max, 'value larger than maximum allowed value') - assert(value >= min, 'value smaller than minimum allowed value') -} - -function assert (test, message) { - if (!test) throw new Error(message || 'Failed assertion') -} - -},{"base64-js":29,"ieee754":30}],29:[function(_dereq_,module,exports){ -var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; - -;(function (exports) { - 'use strict'; - - var Arr = (typeof Uint8Array !== 'undefined') - ? Uint8Array - : Array - - var ZERO = '0'.charCodeAt(0) - var PLUS = '+'.charCodeAt(0) - var SLASH = '/'.charCodeAt(0) - var NUMBER = '0'.charCodeAt(0) - var LOWER = 'a'.charCodeAt(0) - var UPPER = 'A'.charCodeAt(0) - - function decode (elt) { - var code = elt.charCodeAt(0) - if (code === PLUS) - return 62 // '+' - if (code === SLASH) - return 63 // '/' - if (code < NUMBER) - return -1 //no match - if (code < NUMBER + 10) - return code - NUMBER + 26 + 26 - if (code < UPPER + 26) - return code - UPPER - if (code < LOWER + 26) - return code - LOWER + 26 - } - - function b64ToByteArray (b64) { - var i, j, l, tmp, placeHolders, arr - - if (b64.length % 4 > 0) { - throw new Error('Invalid string. Length must be a multiple of 4') - } - - // the number of equal signs (place holders) - // if there are two placeholders, than the two characters before it - // represent one byte - // if there is only one, then the three characters before it represent 2 bytes - // this is just a cheap hack to not do indexOf twice - var len = b64.length - placeHolders = '=' === b64.charAt(len - 2) ? 2 : '=' === b64.charAt(len - 1) ? 1 : 0 - - // base64 is 4/3 + up to two characters of the original data - arr = new Arr(b64.length * 3 / 4 - placeHolders) - - // if there are placeholders, only get up to the last complete 4 chars - l = placeHolders > 0 ? b64.length - 4 : b64.length - - var L = 0 - - function push (v) { - arr[L++] = v - } - - for (i = 0, j = 0; i < l; i += 4, j += 3) { - tmp = (decode(b64.charAt(i)) << 18) | (decode(b64.charAt(i + 1)) << 12) | (decode(b64.charAt(i + 2)) << 6) | decode(b64.charAt(i + 3)) - push((tmp & 0xFF0000) >> 16) - push((tmp & 0xFF00) >> 8) - push(tmp & 0xFF) - } - - if (placeHolders === 2) { - tmp = (decode(b64.charAt(i)) << 2) | (decode(b64.charAt(i + 1)) >> 4) - push(tmp & 0xFF) - } else if (placeHolders === 1) { - tmp = (decode(b64.charAt(i)) << 10) | (decode(b64.charAt(i + 1)) << 4) | (decode(b64.charAt(i + 2)) >> 2) - push((tmp >> 8) & 0xFF) - push(tmp & 0xFF) - } - - return arr - } - - function uint8ToBase64 (uint8) { - var i, - extraBytes = uint8.length % 3, // if we have 1 byte left, pad 2 bytes - output = "", - temp, length - - function encode (num) { - return lookup.charAt(num) - } - - function tripletToBase64 (num) { - return encode(num >> 18 & 0x3F) + encode(num >> 12 & 0x3F) + encode(num >> 6 & 0x3F) + encode(num & 0x3F) - } - - // go through the array every three bytes, we'll deal with trailing stuff later - for (i = 0, length = uint8.length - extraBytes; i < length; i += 3) { - temp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]) - output += tripletToBase64(temp) - } - - // pad the end with zeros, but make sure to not forget the extra bytes - switch (extraBytes) { - case 1: - temp = uint8[uint8.length - 1] - output += encode(temp >> 2) - output += encode((temp << 4) & 0x3F) - output += '==' - break - case 2: - temp = (uint8[uint8.length - 2] << 8) + (uint8[uint8.length - 1]) - output += encode(temp >> 10) - output += encode((temp >> 4) & 0x3F) - output += encode((temp << 2) & 0x3F) - output += '=' - break - } - - return output - } - - module.exports.toByteArray = b64ToByteArray - module.exports.fromByteArray = uint8ToBase64 -}()) - -},{}],30:[function(_dereq_,module,exports){ -exports.read = function(buffer, offset, isLE, mLen, nBytes) { - var e, m, - eLen = nBytes * 8 - mLen - 1, - eMax = (1 << eLen) - 1, - eBias = eMax >> 1, - nBits = -7, - i = isLE ? (nBytes - 1) : 0, - d = isLE ? -1 : 1, - s = buffer[offset + i]; - - i += d; - - e = s & ((1 << (-nBits)) - 1); - s >>= (-nBits); - nBits += eLen; - for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8); - - m = e & ((1 << (-nBits)) - 1); - e >>= (-nBits); - nBits += mLen; - for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8); - - if (e === 0) { - e = 1 - eBias; - } else if (e === eMax) { - return m ? NaN : ((s ? -1 : 1) * Infinity); - } else { - m = m + Math.pow(2, mLen); - e = e - eBias; - } - return (s ? -1 : 1) * m * Math.pow(2, e - mLen); -}; - -exports.write = function(buffer, value, offset, isLE, mLen, nBytes) { - var e, m, c, - eLen = nBytes * 8 - mLen - 1, - eMax = (1 << eLen) - 1, - eBias = eMax >> 1, - rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0), - i = isLE ? 0 : (nBytes - 1), - d = isLE ? 1 : -1, - s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; - - value = Math.abs(value); - - if (isNaN(value) || value === Infinity) { - m = isNaN(value) ? 1 : 0; - e = eMax; - } else { - e = Math.floor(Math.log(value) / Math.LN2); - if (value * (c = Math.pow(2, -e)) < 1) { - e--; - c *= 2; - } - if (e + eBias >= 1) { - value += rt / c; - } else { - value += rt * Math.pow(2, 1 - eBias); - } - if (value * c >= 2) { - e++; - c /= 2; - } - - if (e + eBias >= eMax) { - m = 0; - e = eMax; - } else if (e + eBias >= 1) { - m = (value * c - 1) * Math.pow(2, mLen); - e = e + eBias; - } else { - m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); - e = 0; - } - } - - for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8); - - e = (e << mLen) | m; - eLen += mLen; - for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8); - - buffer[offset + i - d] |= s * 128; -}; - -},{}],31:[function(_dereq_,module,exports){ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -function EventEmitter() { - this._events = this._events || {}; - this._maxListeners = this._maxListeners || undefined; -} -module.exports = EventEmitter; - -// Backwards-compat with node 0.10.x -EventEmitter.EventEmitter = EventEmitter; - -EventEmitter.prototype._events = undefined; -EventEmitter.prototype._maxListeners = undefined; - -// By default EventEmitters will print a warning if more than 10 listeners are -// added to it. This is a useful default which helps finding memory leaks. -EventEmitter.defaultMaxListeners = 10; - -// Obviously not all Emitters should be limited to 10. This function allows -// that to be increased. Set to zero for unlimited. -EventEmitter.prototype.setMaxListeners = function(n) { - if (!isNumber(n) || n < 0 || isNaN(n)) - throw TypeError('n must be a positive number'); - this._maxListeners = n; - return this; -}; - -EventEmitter.prototype.emit = function(type) { - var er, handler, len, args, i, listeners; - - if (!this._events) - this._events = {}; - - // If there is no 'error' event listener then throw. - if (type === 'error') { - if (!this._events.error || - (isObject(this._events.error) && !this._events.error.length)) { - er = arguments[1]; - if (er instanceof Error) { - throw er; // Unhandled 'error' event - } else { - throw TypeError('Uncaught, unspecified "error" event.'); - } - return false; - } - } - - handler = this._events[type]; - - if (isUndefined(handler)) - return false; - - if (isFunction(handler)) { - switch (arguments.length) { - // fast cases - case 1: - handler.call(this); - break; - case 2: - handler.call(this, arguments[1]); - break; - case 3: - handler.call(this, arguments[1], arguments[2]); - break; - // slower - default: - len = arguments.length; - args = new Array(len - 1); - for (i = 1; i < len; i++) - args[i - 1] = arguments[i]; - handler.apply(this, args); - } - } else if (isObject(handler)) { - len = arguments.length; - args = new Array(len - 1); - for (i = 1; i < len; i++) - args[i - 1] = arguments[i]; - - listeners = handler.slice(); - len = listeners.length; - for (i = 0; i < len; i++) - listeners[i].apply(this, args); - } - - return true; -}; - -EventEmitter.prototype.addListener = function(type, listener) { - var m; - - if (!isFunction(listener)) - throw TypeError('listener must be a function'); - - if (!this._events) - this._events = {}; - - // To avoid recursion in the case that type === "newListener"! Before - // adding it to the listeners, first emit "newListener". - if (this._events.newListener) - this.emit('newListener', type, - isFunction(listener.listener) ? - listener.listener : listener); - - if (!this._events[type]) - // Optimize the case of one listener. Don't need the extra array object. - this._events[type] = listener; - else if (isObject(this._events[type])) - // If we've already got an array, just append. - this._events[type].push(listener); - else - // Adding the second element, need to change to array. - this._events[type] = [this._events[type], listener]; - - // Check for listener leak - if (isObject(this._events[type]) && !this._events[type].warned) { - var m; - if (!isUndefined(this._maxListeners)) { - m = this._maxListeners; - } else { - m = EventEmitter.defaultMaxListeners; - } - - if (m && m > 0 && this._events[type].length > m) { - this._events[type].warned = true; - console.error('(node) warning: possible EventEmitter memory ' + - 'leak detected. %d listeners added. ' + - 'Use emitter.setMaxListeners() to increase limit.', - this._events[type].length); - console.trace(); - } - } - - return this; -}; - -EventEmitter.prototype.on = EventEmitter.prototype.addListener; - -EventEmitter.prototype.once = function(type, listener) { - if (!isFunction(listener)) - throw TypeError('listener must be a function'); - - var fired = false; - - function g() { - this.removeListener(type, g); - - if (!fired) { - fired = true; - listener.apply(this, arguments); - } - } - - g.listener = listener; - this.on(type, g); - - return this; -}; - -// emits a 'removeListener' event iff the listener was removed -EventEmitter.prototype.removeListener = function(type, listener) { - var list, position, length, i; - - if (!isFunction(listener)) - throw TypeError('listener must be a function'); - - if (!this._events || !this._events[type]) - return this; - - list = this._events[type]; - length = list.length; - position = -1; - - if (list === listener || - (isFunction(list.listener) && list.listener === listener)) { - delete this._events[type]; - if (this._events.removeListener) - this.emit('removeListener', type, listener); - - } else if (isObject(list)) { - for (i = length; i-- > 0;) { - if (list[i] === listener || - (list[i].listener && list[i].listener === listener)) { - position = i; - break; - } - } - - if (position < 0) - return this; - - if (list.length === 1) { - list.length = 0; - delete this._events[type]; - } else { - list.splice(position, 1); - } - - if (this._events.removeListener) - this.emit('removeListener', type, listener); - } - - return this; -}; - -EventEmitter.prototype.removeAllListeners = function(type) { - var key, listeners; - - if (!this._events) - return this; - - // not listening for removeListener, no need to emit - if (!this._events.removeListener) { - if (arguments.length === 0) - this._events = {}; - else if (this._events[type]) - delete this._events[type]; - return this; - } - - // emit removeListener for all listeners on all events - if (arguments.length === 0) { - for (key in this._events) { - if (key === 'removeListener') continue; - this.removeAllListeners(key); - } - this.removeAllListeners('removeListener'); - this._events = {}; - return this; - } - - listeners = this._events[type]; - - if (isFunction(listeners)) { - this.removeListener(type, listeners); - } else { - // LIFO order - while (listeners.length) - this.removeListener(type, listeners[listeners.length - 1]); - } - delete this._events[type]; - - return this; -}; - -EventEmitter.prototype.listeners = function(type) { - var ret; - if (!this._events || !this._events[type]) - ret = []; - else if (isFunction(this._events[type])) - ret = [this._events[type]]; - else - ret = this._events[type].slice(); - return ret; -}; - -EventEmitter.listenerCount = function(emitter, type) { - var ret; - if (!emitter._events || !emitter._events[type]) - ret = 0; - else if (isFunction(emitter._events[type])) - ret = 1; - else - ret = emitter._events[type].length; - return ret; -}; - -function isFunction(arg) { - return typeof arg === 'function'; -} - -function isNumber(arg) { - return typeof arg === 'number'; -} - -function isObject(arg) { - return typeof arg === 'object' && arg !== null; -} - -function isUndefined(arg) { - return arg === void 0; -} - -},{}],32:[function(_dereq_,module,exports){ -var http = module.exports; -var EventEmitter = _dereq_('events').EventEmitter; -var Request = _dereq_('./lib/request'); -var url = _dereq_('url') - -http.request = function (params, cb) { - if (typeof params === 'string') { - params = url.parse(params) - } - if (!params) params = {}; - if (!params.host && !params.port) { - params.port = parseInt(window.location.port, 10); - } - if (!params.host && params.hostname) { - params.host = params.hostname; - } - - if (!params.scheme) params.scheme = window.location.protocol.split(':')[0]; - if (!params.host) { - params.host = window.location.hostname || window.location.host; - } - if (/:/.test(params.host)) { - if (!params.port) { - params.port = params.host.split(':')[1]; - } - params.host = params.host.split(':')[0]; - } - if (!params.port) params.port = params.scheme == 'https' ? 443 : 80; - - var req = new Request(new xhrHttp, params); - if (cb) req.on('response', cb); - return req; -}; - -http.get = function (params, cb) { - params.method = 'GET'; - var req = http.request(params, cb); - req.end(); - return req; -}; - -http.Agent = function () {}; -http.Agent.defaultMaxSockets = 4; - -var xhrHttp = (function () { - if (typeof window === 'undefined') { - throw new Error('no window object present'); - } - else if (window.XMLHttpRequest) { - return window.XMLHttpRequest; - } - else if (window.ActiveXObject) { - var axs = [ - 'Msxml2.XMLHTTP.6.0', - 'Msxml2.XMLHTTP.3.0', - 'Microsoft.XMLHTTP' - ]; - for (var i = 0; i < axs.length; i++) { - try { - var ax = new(window.ActiveXObject)(axs[i]); - return function () { - if (ax) { - var ax_ = ax; - ax = null; - return ax_; - } - else { - return new(window.ActiveXObject)(axs[i]); - } - }; - } - catch (e) {} - } - throw new Error('ajax not supported in this browser') - } - else { - throw new Error('ajax not supported in this browser'); - } -})(); - -http.STATUS_CODES = { - 100 : 'Continue', - 101 : 'Switching Protocols', - 102 : 'Processing', // RFC 2518, obsoleted by RFC 4918 - 200 : 'OK', - 201 : 'Created', - 202 : 'Accepted', - 203 : 'Non-Authoritative Information', - 204 : 'No Content', - 205 : 'Reset Content', - 206 : 'Partial Content', - 207 : 'Multi-Status', // RFC 4918 - 300 : 'Multiple Choices', - 301 : 'Moved Permanently', - 302 : 'Moved Temporarily', - 303 : 'See Other', - 304 : 'Not Modified', - 305 : 'Use Proxy', - 307 : 'Temporary Redirect', - 400 : 'Bad Request', - 401 : 'Unauthorized', - 402 : 'Payment Required', - 403 : 'Forbidden', - 404 : 'Not Found', - 405 : 'Method Not Allowed', - 406 : 'Not Acceptable', - 407 : 'Proxy Authentication Required', - 408 : 'Request Time-out', - 409 : 'Conflict', - 410 : 'Gone', - 411 : 'Length Required', - 412 : 'Precondition Failed', - 413 : 'Request Entity Too Large', - 414 : 'Request-URI Too Large', - 415 : 'Unsupported Media Type', - 416 : 'Requested Range Not Satisfiable', - 417 : 'Expectation Failed', - 418 : 'I\'m a teapot', // RFC 2324 - 422 : 'Unprocessable Entity', // RFC 4918 - 423 : 'Locked', // RFC 4918 - 424 : 'Failed Dependency', // RFC 4918 - 425 : 'Unordered Collection', // RFC 4918 - 426 : 'Upgrade Required', // RFC 2817 - 428 : 'Precondition Required', // RFC 6585 - 429 : 'Too Many Requests', // RFC 6585 - 431 : 'Request Header Fields Too Large',// RFC 6585 - 500 : 'Internal Server Error', - 501 : 'Not Implemented', - 502 : 'Bad Gateway', - 503 : 'Service Unavailable', - 504 : 'Gateway Time-out', - 505 : 'HTTP Version Not Supported', - 506 : 'Variant Also Negotiates', // RFC 2295 - 507 : 'Insufficient Storage', // RFC 4918 - 509 : 'Bandwidth Limit Exceeded', - 510 : 'Not Extended', // RFC 2774 - 511 : 'Network Authentication Required' // RFC 6585 -}; -},{"./lib/request":33,"events":31,"url":58}],33:[function(_dereq_,module,exports){ -var Stream = _dereq_('stream'); -var Response = _dereq_('./response'); -var Base64 = _dereq_('Base64'); -var inherits = _dereq_('inherits'); - -var Request = module.exports = function (xhr, params) { - var self = this; - self.writable = true; - self.xhr = xhr; - self.body = []; - - self.uri = (params.scheme || 'http') + '://' - + params.host - + (params.port ? ':' + params.port : '') - + (params.path || '/') - ; - - if (typeof params.withCredentials === 'undefined') { - params.withCredentials = true; - } - - try { xhr.withCredentials = params.withCredentials } - catch (e) {} - - xhr.open( - params.method || 'GET', - self.uri, - true - ); - - self._headers = {}; - - if (params.headers) { - var keys = objectKeys(params.headers); - for (var i = 0; i < keys.length; i++) { - var key = keys[i]; - if (!self.isSafeRequestHeader(key)) continue; - var value = params.headers[key]; - self.setHeader(key, value); - } - } - - if (params.auth) { - //basic auth - this.setHeader('Authorization', 'Basic ' + Base64.btoa(params.auth)); - } - - var res = new Response; - res.on('close', function () { - self.emit('close'); - }); - - res.on('ready', function () { - self.emit('response', res); - }); - - xhr.onreadystatechange = function () { - // Fix for IE9 bug - // SCRIPT575: Could not complete the operation due to error c00c023f - // It happens when a request is aborted, calling the success callback anyway with readyState === 4 - if (xhr.__aborted) return; - res.handle(xhr); - }; -}; - -inherits(Request, Stream); - -Request.prototype.setHeader = function (key, value) { - this._headers[key.toLowerCase()] = value -}; - -Request.prototype.getHeader = function (key) { - return this._headers[key.toLowerCase()] -}; - -Request.prototype.removeHeader = function (key) { - delete this._headers[key.toLowerCase()] -}; - -Request.prototype.write = function (s) { - this.body.push(s); -}; - -Request.prototype.destroy = function (s) { - this.xhr.__aborted = true; - this.xhr.abort(); - this.emit('close'); -}; - -Request.prototype.end = function (s) { - if (s !== undefined) this.body.push(s); - - var keys = objectKeys(this._headers); - for (var i = 0; i < keys.length; i++) { - var key = keys[i]; - var value = this._headers[key]; - if (isArray(value)) { - for (var j = 0; j < value.length; j++) { - this.xhr.setRequestHeader(key, value[j]); - } - } - else this.xhr.setRequestHeader(key, value) - } - - if (this.body.length === 0) { - this.xhr.send(''); - } - else if (typeof this.body[0] === 'string') { - this.xhr.send(this.body.join('')); - } - else if (isArray(this.body[0])) { - var body = []; - for (var i = 0; i < this.body.length; i++) { - body.push.apply(body, this.body[i]); - } - this.xhr.send(body); - } - else if (/Array/.test(Object.prototype.toString.call(this.body[0]))) { - var len = 0; - for (var i = 0; i < this.body.length; i++) { - len += this.body[i].length; - } - var body = new(this.body[0].constructor)(len); - var k = 0; - - for (var i = 0; i < this.body.length; i++) { - var b = this.body[i]; - for (var j = 0; j < b.length; j++) { - body[k++] = b[j]; - } - } - this.xhr.send(body); - } - else { - var body = ''; - for (var i = 0; i < this.body.length; i++) { - body += this.body[i].toString(); - } - this.xhr.send(body); - } -}; - -// Taken from http://dxr.mozilla.org/mozilla/mozilla-central/content/base/src/nsXMLHttpRequest.cpp.html -Request.unsafeHeaders = [ - "accept-charset", - "accept-encoding", - "access-control-request-headers", - "access-control-request-method", - "connection", - "content-length", - "cookie", - "cookie2", - "content-transfer-encoding", - "date", - "expect", - "host", - "keep-alive", - "origin", - "referer", - "te", - "trailer", - "transfer-encoding", - "upgrade", - "user-agent", - "via" -]; - -Request.prototype.isSafeRequestHeader = function (headerName) { - if (!headerName) return false; - return indexOf(Request.unsafeHeaders, headerName.toLowerCase()) === -1; -}; - -var objectKeys = Object.keys || function (obj) { - var keys = []; - for (var key in obj) keys.push(key); - return keys; -}; - -var isArray = Array.isArray || function (xs) { - return Object.prototype.toString.call(xs) === '[object Array]'; -}; - -var indexOf = function (xs, x) { - if (xs.indexOf) return xs.indexOf(x); - for (var i = 0; i < xs.length; i++) { - if (xs[i] === x) return i; - } - return -1; -}; - -},{"./response":34,"Base64":35,"inherits":37,"stream":57}],34:[function(_dereq_,module,exports){ -var Stream = _dereq_('stream'); -var util = _dereq_('util'); - -var Response = module.exports = function (res) { - this.offset = 0; - this.readable = true; -}; - -util.inherits(Response, Stream); - -var capable = { - streaming : true, - status2 : true -}; - -function parseHeaders (res) { - var lines = res.getAllResponseHeaders().split(/\r?\n/); - var headers = {}; - for (var i = 0; i < lines.length; i++) { - var line = lines[i]; - if (line === '') continue; - - var m = line.match(/^([^:]+):\s*(.*)/); - if (m) { - var key = m[1].toLowerCase(), value = m[2]; - - if (headers[key] !== undefined) { - - if (isArray(headers[key])) { - headers[key].push(value); - } - else { - headers[key] = [ headers[key], value ]; - } - } - else { - headers[key] = value; - } - } - else { - headers[line] = true; - } - } - return headers; -} - -Response.prototype.getResponse = function (xhr) { - var respType = String(xhr.responseType).toLowerCase(); - if (respType === 'blob') return xhr.responseBlob || xhr.response; - if (respType === 'arraybuffer') return xhr.response; - return xhr.responseText; -} - -Response.prototype.getHeader = function (key) { - return this.headers[key.toLowerCase()]; -}; - -Response.prototype.handle = function (res) { - if (res.readyState === 2 && capable.status2) { - try { - this.statusCode = res.status; - this.headers = parseHeaders(res); - } - catch (err) { - capable.status2 = false; - } - - if (capable.status2) { - this.emit('ready'); - } - } - else if (capable.streaming && res.readyState === 3) { - try { - if (!this.statusCode) { - this.statusCode = res.status; - this.headers = parseHeaders(res); - this.emit('ready'); - } - } - catch (err) {} - - try { - this._emitData(res); - } - catch (err) { - capable.streaming = false; - } - } - else if (res.readyState === 4) { - if (!this.statusCode) { - this.statusCode = res.status; - this.emit('ready'); - } - this._emitData(res); - - if (res.error) { - this.emit('error', this.getResponse(res)); - } - else this.emit('end'); - - this.emit('close'); - } -}; - -Response.prototype._emitData = function (res) { - var respBody = this.getResponse(res); - if (respBody.toString().match(/ArrayBuffer/)) { - this.emit('data', new Uint8Array(respBody, this.offset)); - this.offset = respBody.byteLength; - return; - } - if (respBody.length > this.offset) { - this.emit('data', respBody.slice(this.offset)); - this.offset = respBody.length; - } -}; - -var isArray = Array.isArray || function (xs) { - return Object.prototype.toString.call(xs) === '[object Array]'; -}; - -},{"stream":57,"util":60}],35:[function(_dereq_,module,exports){ -;(function () { - - var object = typeof exports != 'undefined' ? exports : this; // #8: web workers - var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; - - function InvalidCharacterError(message) { - this.message = message; - } - InvalidCharacterError.prototype = new Error; - InvalidCharacterError.prototype.name = 'InvalidCharacterError'; - - // encoder - // [https://gist.github.com/999166] by [https://github.com/nignag] - object.btoa || ( - object.btoa = function (input) { - for ( - // initialize result and counter - var block, charCode, idx = 0, map = chars, output = ''; - // if the next input index does not exist: - // change the mapping table to "=" - // check if d has no fractional digits - input.charAt(idx | 0) || (map = '=', idx % 1); - // "8 - idx % 1 * 8" generates the sequence 2, 4, 6, 8 - output += map.charAt(63 & block >> 8 - idx % 1 * 8) - ) { - charCode = input.charCodeAt(idx += 3/4); - if (charCode > 0xFF) { - throw new InvalidCharacterError("'btoa' failed: The string to be encoded contains characters outside of the Latin1 range."); - } - block = block << 8 | charCode; - } - return output; - }); - - // decoder - // [https://gist.github.com/1020396] by [https://github.com/atk] - object.atob || ( - object.atob = function (input) { - input = input.replace(/=+$/, ''); - if (input.length % 4 == 1) { - throw new InvalidCharacterError("'atob' failed: The string to be decoded is not correctly encoded."); - } - for ( - // initialize result and counters - var bc = 0, bs, buffer, idx = 0, output = ''; - // get next character - buffer = input.charAt(idx++); - // character found in table? initialize bit storage and add its ascii value; - ~buffer && (bs = bc % 4 ? bs * 64 + buffer : buffer, - // and if not first of each 4 characters, - // convert the first 8 bits to one ascii character - bc++ % 4) ? output += String.fromCharCode(255 & bs >> (-2 * bc & 6)) : 0 - ) { - // try to find character in table (0-63, not found => -1) - buffer = chars.indexOf(buffer); - } - return output; - }); - -}()); - -},{}],36:[function(_dereq_,module,exports){ -var http = _dereq_('http'); - -var https = module.exports; - -for (var key in http) { - if (http.hasOwnProperty(key)) https[key] = http[key]; -}; - -https.request = function (params, cb) { - if (!params) params = {}; - params.scheme = 'https'; - return http.request.call(this, params, cb); -} - -},{"http":32}],37:[function(_dereq_,module,exports){ -if (typeof Object.create === 'function') { - // implementation from standard node.js 'util' module - module.exports = function inherits(ctor, superCtor) { - ctor.super_ = superCtor - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true - } - }); - }; -} else { - // old school shim for old browsers - module.exports = function inherits(ctor, superCtor) { - ctor.super_ = superCtor - var TempCtor = function () {} - TempCtor.prototype = superCtor.prototype - ctor.prototype = new TempCtor() - ctor.prototype.constructor = ctor - } -} - -},{}],38:[function(_dereq_,module,exports){ -(function (process){ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// resolves . and .. elements in a path array with directory names there -// must be no slashes, empty elements, or device names (c:\) in the array -// (so also no leading and trailing slashes - it does not distinguish -// relative and absolute paths) -function normalizeArray(parts, allowAboveRoot) { - // if the path tries to go above the root, `up` ends up > 0 - var up = 0; - for (var i = parts.length - 1; i >= 0; i--) { - var last = parts[i]; - if (last === '.') { - parts.splice(i, 1); - } else if (last === '..') { - parts.splice(i, 1); - up++; - } else if (up) { - parts.splice(i, 1); - up--; - } - } - - // if the path is allowed to go above the root, restore leading ..s - if (allowAboveRoot) { - for (; up--; up) { - parts.unshift('..'); - } - } - - return parts; -} - -// Split a filename into [root, dir, basename, ext], unix version -// 'root' is just a slash, or nothing. -var splitPathRe = - /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/; -var splitPath = function(filename) { - return splitPathRe.exec(filename).slice(1); -}; - -// path.resolve([from ...], to) -// posix version -exports.resolve = function() { - var resolvedPath = '', - resolvedAbsolute = false; - - for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) { - var path = (i >= 0) ? arguments[i] : process.cwd(); - - // Skip empty and invalid entries - if (typeof path !== 'string') { - throw new TypeError('Arguments to path.resolve must be strings'); - } else if (!path) { - continue; - } - - resolvedPath = path + '/' + resolvedPath; - resolvedAbsolute = path.charAt(0) === '/'; - } - - // At this point the path should be resolved to a full absolute path, but - // handle relative paths to be safe (might happen when process.cwd() fails) - - // Normalize the path - resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) { - return !!p; - }), !resolvedAbsolute).join('/'); - - return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.'; -}; - -// path.normalize(path) -// posix version -exports.normalize = function(path) { - var isAbsolute = exports.isAbsolute(path), - trailingSlash = substr(path, -1) === '/'; - - // Normalize the path - path = normalizeArray(filter(path.split('/'), function(p) { - return !!p; - }), !isAbsolute).join('/'); - - if (!path && !isAbsolute) { - path = '.'; - } - if (path && trailingSlash) { - path += '/'; - } - - return (isAbsolute ? '/' : '') + path; -}; - -// posix version -exports.isAbsolute = function(path) { - return path.charAt(0) === '/'; -}; - -// posix version -exports.join = function() { - var paths = Array.prototype.slice.call(arguments, 0); - return exports.normalize(filter(paths, function(p, index) { - if (typeof p !== 'string') { - throw new TypeError('Arguments to path.join must be strings'); - } - return p; - }).join('/')); -}; - - -// path.relative(from, to) -// posix version -exports.relative = function(from, to) { - from = exports.resolve(from).substr(1); - to = exports.resolve(to).substr(1); - - function trim(arr) { - var start = 0; - for (; start < arr.length; start++) { - if (arr[start] !== '') break; - } - - var end = arr.length - 1; - for (; end >= 0; end--) { - if (arr[end] !== '') break; - } - - if (start > end) return []; - return arr.slice(start, end - start + 1); - } - - var fromParts = trim(from.split('/')); - var toParts = trim(to.split('/')); - - var length = Math.min(fromParts.length, toParts.length); - var samePartsLength = length; - for (var i = 0; i < length; i++) { - if (fromParts[i] !== toParts[i]) { - samePartsLength = i; - break; - } - } - - var outputParts = []; - for (var i = samePartsLength; i < fromParts.length; i++) { - outputParts.push('..'); - } - - outputParts = outputParts.concat(toParts.slice(samePartsLength)); - - return outputParts.join('/'); -}; - -exports.sep = '/'; -exports.delimiter = ':'; - -exports.dirname = function(path) { - var result = splitPath(path), - root = result[0], - dir = result[1]; - - if (!root && !dir) { - // No dirname whatsoever - return '.'; - } - - if (dir) { - // It has a dirname, strip trailing slash - dir = dir.substr(0, dir.length - 1); - } - - return root + dir; -}; - - -exports.basename = function(path, ext) { - var f = splitPath(path)[2]; - // TODO: make this comparison case-insensitive on windows? - if (ext && f.substr(-1 * ext.length) === ext) { - f = f.substr(0, f.length - ext.length); - } - return f; -}; - - -exports.extname = function(path) { - return splitPath(path)[3]; -}; - -function filter (xs, f) { - if (xs.filter) return xs.filter(f); - var res = []; - for (var i = 0; i < xs.length; i++) { - if (f(xs[i], i, xs)) res.push(xs[i]); - } - return res; -} - -// String.prototype.substr - negative index don't work in IE8 -var substr = 'ab'.substr(-1) === 'b' - ? function (str, start, len) { return str.substr(start, len) } - : function (str, start, len) { - if (start < 0) start = str.length + start; - return str.substr(start, len); - } -; - -}).call(this,_dereq_("Zbi7gb")) -},{"Zbi7gb":39}],39:[function(_dereq_,module,exports){ -// shim for using process in browser - -var process = module.exports = {}; - -process.nextTick = (function () { - var canSetImmediate = typeof window !== 'undefined' - && window.setImmediate; - var canPost = typeof window !== 'undefined' - && window.postMessage && window.addEventListener - ; - - if (canSetImmediate) { - return function (f) { return window.setImmediate(f) }; - } - - if (canPost) { - var queue = []; - window.addEventListener('message', function (ev) { - var source = ev.source; - if ((source === window || source === null) && ev.data === 'process-tick') { - ev.stopPropagation(); - if (queue.length > 0) { - var fn = queue.shift(); - fn(); - } - } - }, true); - - return function nextTick(fn) { - queue.push(fn); - window.postMessage('process-tick', '*'); - }; - } - - return function nextTick(fn) { - setTimeout(fn, 0); - }; -})(); - -process.title = 'browser'; -process.browser = true; -process.env = {}; -process.argv = []; - -function noop() {} - -process.on = noop; -process.addListener = noop; -process.once = noop; -process.off = noop; -process.removeListener = noop; -process.removeAllListeners = noop; -process.emit = noop; - -process.binding = function (name) { - throw new Error('process.binding is not supported'); -} - -// TODO(shtylman) -process.cwd = function () { return '/' }; -process.chdir = function (dir) { - throw new Error('process.chdir is not supported'); -}; - -},{}],40:[function(_dereq_,module,exports){ -(function (global){ -/*! http://mths.be/punycode v1.2.4 by @mathias */ -;(function(root) { - - /** Detect free variables */ - var freeExports = typeof exports == 'object' && exports; - var freeModule = typeof module == 'object' && module && - module.exports == freeExports && module; - var freeGlobal = typeof global == 'object' && global; - if (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal) { - root = freeGlobal; - } - - /** - * The `punycode` object. - * @name punycode - * @type Object - */ - var punycode, - - /** Highest positive signed 32-bit float value */ - maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1 - - /** Bootstring parameters */ - base = 36, - tMin = 1, - tMax = 26, - skew = 38, - damp = 700, - initialBias = 72, - initialN = 128, // 0x80 - delimiter = '-', // '\x2D' - - /** Regular expressions */ - regexPunycode = /^xn--/, - regexNonASCII = /[^ -~]/, // unprintable ASCII chars + non-ASCII chars - regexSeparators = /\x2E|\u3002|\uFF0E|\uFF61/g, // RFC 3490 separators - - /** Error messages */ - errors = { - 'overflow': 'Overflow: input needs wider integers to process', - 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', - 'invalid-input': 'Invalid input' - }, - - /** Convenience shortcuts */ - baseMinusTMin = base - tMin, - floor = Math.floor, - stringFromCharCode = String.fromCharCode, - - /** Temporary variable */ - key; - - /*--------------------------------------------------------------------------*/ - - /** - * A generic error utility function. - * @private - * @param {String} type The error type. - * @returns {Error} Throws a `RangeError` with the applicable error message. - */ - function error(type) { - throw RangeError(errors[type]); - } - - /** - * A generic `Array#map` utility function. - * @private - * @param {Array} array The array to iterate over. - * @param {Function} callback The function that gets called for every array - * item. - * @returns {Array} A new array of values returned by the callback function. - */ - function map(array, fn) { - var length = array.length; - while (length--) { - array[length] = fn(array[length]); - } - return array; - } - - /** - * A simple `Array#map`-like wrapper to work with domain name strings. - * @private - * @param {String} domain The domain name. - * @param {Function} callback The function that gets called for every - * character. - * @returns {Array} A new string of characters returned by the callback - * function. - */ - function mapDomain(string, fn) { - return map(string.split(regexSeparators), fn).join('.'); - } - - /** - * Creates an array containing the numeric code points of each Unicode - * character in the string. While JavaScript uses UCS-2 internally, - * this function will convert a pair of surrogate halves (each of which - * UCS-2 exposes as separate characters) into a single code point, - * matching UTF-16. - * @see `punycode.ucs2.encode` - * @see - * @memberOf punycode.ucs2 - * @name decode - * @param {String} string The Unicode input string (UCS-2). - * @returns {Array} The new array of code points. - */ - function ucs2decode(string) { - var output = [], - counter = 0, - length = string.length, - value, - extra; - while (counter < length) { - value = string.charCodeAt(counter++); - if (value >= 0xD800 && value <= 0xDBFF && counter < length) { - // high surrogate, and there is a next character - extra = string.charCodeAt(counter++); - if ((extra & 0xFC00) == 0xDC00) { // low surrogate - output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); - } else { - // unmatched surrogate; only append this code unit, in case the next - // code unit is the high surrogate of a surrogate pair - output.push(value); - counter--; - } - } else { - output.push(value); - } - } - return output; - } - - /** - * Creates a string based on an array of numeric code points. - * @see `punycode.ucs2.decode` - * @memberOf punycode.ucs2 - * @name encode - * @param {Array} codePoints The array of numeric code points. - * @returns {String} The new Unicode string (UCS-2). - */ - function ucs2encode(array) { - return map(array, function(value) { - var output = ''; - if (value > 0xFFFF) { - value -= 0x10000; - output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800); - value = 0xDC00 | value & 0x3FF; - } - output += stringFromCharCode(value); - return output; - }).join(''); - } - - /** - * Converts a basic code point into a digit/integer. - * @see `digitToBasic()` - * @private - * @param {Number} codePoint The basic numeric code point value. - * @returns {Number} The numeric value of a basic code point (for use in - * representing integers) in the range `0` to `base - 1`, or `base` if - * the code point does not represent a value. - */ - function basicToDigit(codePoint) { - if (codePoint - 48 < 10) { - return codePoint - 22; - } - if (codePoint - 65 < 26) { - return codePoint - 65; - } - if (codePoint - 97 < 26) { - return codePoint - 97; - } - return base; - } - - /** - * Converts a digit/integer into a basic code point. - * @see `basicToDigit()` - * @private - * @param {Number} digit The numeric value of a basic code point. - * @returns {Number} The basic code point whose value (when used for - * representing integers) is `digit`, which needs to be in the range - * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is - * used; else, the lowercase form is used. The behavior is undefined - * if `flag` is non-zero and `digit` has no uppercase form. - */ - function digitToBasic(digit, flag) { - // 0..25 map to ASCII a..z or A..Z - // 26..35 map to ASCII 0..9 - return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); - } - - /** - * Bias adaptation function as per section 3.4 of RFC 3492. - * http://tools.ietf.org/html/rfc3492#section-3.4 - * @private - */ - function adapt(delta, numPoints, firstTime) { - var k = 0; - delta = firstTime ? floor(delta / damp) : delta >> 1; - delta += floor(delta / numPoints); - for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) { - delta = floor(delta / baseMinusTMin); - } - return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); - } - - /** - * Converts a Punycode string of ASCII-only symbols to a string of Unicode - * symbols. - * @memberOf punycode - * @param {String} input The Punycode string of ASCII-only symbols. - * @returns {String} The resulting string of Unicode symbols. - */ - function decode(input) { - // Don't use UCS-2 - var output = [], - inputLength = input.length, - out, - i = 0, - n = initialN, - bias = initialBias, - basic, - j, - index, - oldi, - w, - k, - digit, - t, - /** Cached calculation results */ - baseMinusT; - - // Handle the basic code points: let `basic` be the number of input code - // points before the last delimiter, or `0` if there is none, then copy - // the first basic code points to the output. - - basic = input.lastIndexOf(delimiter); - if (basic < 0) { - basic = 0; - } - - for (j = 0; j < basic; ++j) { - // if it's not a basic code point - if (input.charCodeAt(j) >= 0x80) { - error('not-basic'); - } - output.push(input.charCodeAt(j)); - } - - // Main decoding loop: start just after the last delimiter if any basic code - // points were copied; start at the beginning otherwise. - - for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) { - - // `index` is the index of the next character to be consumed. - // Decode a generalized variable-length integer into `delta`, - // which gets added to `i`. The overflow checking is easier - // if we increase `i` as we go, then subtract off its starting - // value at the end to obtain `delta`. - for (oldi = i, w = 1, k = base; /* no condition */; k += base) { - - if (index >= inputLength) { - error('invalid-input'); - } - - digit = basicToDigit(input.charCodeAt(index++)); - - if (digit >= base || digit > floor((maxInt - i) / w)) { - error('overflow'); - } - - i += digit * w; - t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); - - if (digit < t) { - break; - } - - baseMinusT = base - t; - if (w > floor(maxInt / baseMinusT)) { - error('overflow'); - } - - w *= baseMinusT; - - } - - out = output.length + 1; - bias = adapt(i - oldi, out, oldi == 0); - - // `i` was supposed to wrap around from `out` to `0`, - // incrementing `n` each time, so we'll fix that now: - if (floor(i / out) > maxInt - n) { - error('overflow'); - } - - n += floor(i / out); - i %= out; - - // Insert `n` at position `i` of the output - output.splice(i++, 0, n); - - } - - return ucs2encode(output); - } - - /** - * Converts a string of Unicode symbols to a Punycode string of ASCII-only - * symbols. - * @memberOf punycode - * @param {String} input The string of Unicode symbols. - * @returns {String} The resulting Punycode string of ASCII-only symbols. - */ - function encode(input) { - var n, - delta, - handledCPCount, - basicLength, - bias, - j, - m, - q, - k, - t, - currentValue, - output = [], - /** `inputLength` will hold the number of code points in `input`. */ - inputLength, - /** Cached calculation results */ - handledCPCountPlusOne, - baseMinusT, - qMinusT; - - // Convert the input in UCS-2 to Unicode - input = ucs2decode(input); - - // Cache the length - inputLength = input.length; - - // Initialize the state - n = initialN; - delta = 0; - bias = initialBias; - - // Handle the basic code points - for (j = 0; j < inputLength; ++j) { - currentValue = input[j]; - if (currentValue < 0x80) { - output.push(stringFromCharCode(currentValue)); - } - } - - handledCPCount = basicLength = output.length; - - // `handledCPCount` is the number of code points that have been handled; - // `basicLength` is the number of basic code points. - - // Finish the basic string - if it is not empty - with a delimiter - if (basicLength) { - output.push(delimiter); - } - - // Main encoding loop: - while (handledCPCount < inputLength) { - - // All non-basic code points < n have been handled already. Find the next - // larger one: - for (m = maxInt, j = 0; j < inputLength; ++j) { - currentValue = input[j]; - if (currentValue >= n && currentValue < m) { - m = currentValue; - } - } - - // Increase `delta` enough to advance the decoder's state to , - // but guard against overflow - handledCPCountPlusOne = handledCPCount + 1; - if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { - error('overflow'); - } - - delta += (m - n) * handledCPCountPlusOne; - n = m; - - for (j = 0; j < inputLength; ++j) { - currentValue = input[j]; - - if (currentValue < n && ++delta > maxInt) { - error('overflow'); - } - - if (currentValue == n) { - // Represent delta as a generalized variable-length integer - for (q = delta, k = base; /* no condition */; k += base) { - t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); - if (q < t) { - break; - } - qMinusT = q - t; - baseMinusT = base - t; - output.push( - stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)) - ); - q = floor(qMinusT / baseMinusT); - } - - output.push(stringFromCharCode(digitToBasic(q, 0))); - bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); - delta = 0; - ++handledCPCount; - } - } - - ++delta; - ++n; - - } - return output.join(''); - } - - /** - * Converts a Punycode string representing a domain name to Unicode. Only the - * Punycoded parts of the domain name will be converted, i.e. it doesn't - * matter if you call it on a string that has already been converted to - * Unicode. - * @memberOf punycode - * @param {String} domain The Punycode domain name to convert to Unicode. - * @returns {String} The Unicode representation of the given Punycode - * string. - */ - function toUnicode(domain) { - return mapDomain(domain, function(string) { - return regexPunycode.test(string) - ? decode(string.slice(4).toLowerCase()) - : string; - }); - } - - /** - * Converts a Unicode string representing a domain name to Punycode. Only the - * non-ASCII parts of the domain name will be converted, i.e. it doesn't - * matter if you call it with a domain that's already in ASCII. - * @memberOf punycode - * @param {String} domain The domain name to convert, as a Unicode string. - * @returns {String} The Punycode representation of the given domain name. - */ - function toASCII(domain) { - return mapDomain(domain, function(string) { - return regexNonASCII.test(string) - ? 'xn--' + encode(string) - : string; - }); - } - - /*--------------------------------------------------------------------------*/ - - /** Define the public API */ - punycode = { - /** - * A string representing the current Punycode.js version number. - * @memberOf punycode - * @type String - */ - 'version': '1.2.4', - /** - * An object of methods to convert from JavaScript's internal character - * representation (UCS-2) to Unicode code points, and back. - * @see - * @memberOf punycode - * @type Object - */ - 'ucs2': { - 'decode': ucs2decode, - 'encode': ucs2encode - }, - 'decode': decode, - 'encode': encode, - 'toASCII': toASCII, - 'toUnicode': toUnicode - }; - - /** Expose `punycode` */ - // Some AMD build optimizers, like r.js, check for specific condition patterns - // like the following: - if ( - typeof define == 'function' && - typeof define.amd == 'object' && - define.amd - ) { - define('punycode', function() { - return punycode; - }); - } else if (freeExports && !freeExports.nodeType) { - if (freeModule) { // in Node.js or RingoJS v0.8.0+ - freeModule.exports = punycode; - } else { // in Narwhal or RingoJS v0.7.0- - for (key in punycode) { - punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]); - } - } - } else { // in Rhino or a web browser - root.punycode = punycode; - } - -}(this)); - -}).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{}],41:[function(_dereq_,module,exports){ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -'use strict'; - -// If obj.hasOwnProperty has been overridden, then calling -// obj.hasOwnProperty(prop) will break. -// See: https://github.com/joyent/node/issues/1707 -function hasOwnProperty(obj, prop) { - return Object.prototype.hasOwnProperty.call(obj, prop); -} - -module.exports = function(qs, sep, eq, options) { - sep = sep || '&'; - eq = eq || '='; - var obj = {}; - - if (typeof qs !== 'string' || qs.length === 0) { - return obj; - } - - var regexp = /\+/g; - qs = qs.split(sep); - - var maxKeys = 1000; - if (options && typeof options.maxKeys === 'number') { - maxKeys = options.maxKeys; - } - - var len = qs.length; - // maxKeys <= 0 means that we should not limit keys count - if (maxKeys > 0 && len > maxKeys) { - len = maxKeys; - } - - for (var i = 0; i < len; ++i) { - var x = qs[i].replace(regexp, '%20'), - idx = x.indexOf(eq), - kstr, vstr, k, v; - - if (idx >= 0) { - kstr = x.substr(0, idx); - vstr = x.substr(idx + 1); - } else { - kstr = x; - vstr = ''; - } - - k = decodeURIComponent(kstr); - v = decodeURIComponent(vstr); - - if (!hasOwnProperty(obj, k)) { - obj[k] = v; - } else if (isArray(obj[k])) { - obj[k].push(v); - } else { - obj[k] = [obj[k], v]; - } - } - - return obj; -}; - -var isArray = Array.isArray || function (xs) { - return Object.prototype.toString.call(xs) === '[object Array]'; -}; - -},{}],42:[function(_dereq_,module,exports){ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -'use strict'; - -var stringifyPrimitive = function(v) { - switch (typeof v) { - case 'string': - return v; - - case 'boolean': - return v ? 'true' : 'false'; - - case 'number': - return isFinite(v) ? v : ''; - - default: - return ''; - } -}; - -module.exports = function(obj, sep, eq, name) { - sep = sep || '&'; - eq = eq || '='; - if (obj === null) { - obj = undefined; - } - - if (typeof obj === 'object') { - return map(objectKeys(obj), function(k) { - var ks = encodeURIComponent(stringifyPrimitive(k)) + eq; - if (isArray(obj[k])) { - return obj[k].map(function(v) { - return ks + encodeURIComponent(stringifyPrimitive(v)); - }).join(sep); - } else { - return ks + encodeURIComponent(stringifyPrimitive(obj[k])); - } - }).join(sep); - - } - - if (!name) return ''; - return encodeURIComponent(stringifyPrimitive(name)) + eq + - encodeURIComponent(stringifyPrimitive(obj)); -}; - -var isArray = Array.isArray || function (xs) { - return Object.prototype.toString.call(xs) === '[object Array]'; -}; - -function map (xs, f) { - if (xs.map) return xs.map(f); - var res = []; - for (var i = 0; i < xs.length; i++) { - res.push(f(xs[i], i)); - } - return res; -} - -var objectKeys = Object.keys || function (obj) { - var res = []; - for (var key in obj) { - if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key); - } - return res; -}; - -},{}],43:[function(_dereq_,module,exports){ -'use strict'; - -exports.decode = exports.parse = _dereq_('./decode'); -exports.encode = exports.stringify = _dereq_('./encode'); - -},{"./decode":41,"./encode":42}],44:[function(_dereq_,module,exports){ -module.exports = _dereq_("./lib/_stream_duplex.js") - -},{"./lib/_stream_duplex.js":45}],45:[function(_dereq_,module,exports){ -(function (process){ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// a duplex stream is just a stream that is both readable and writable. -// Since JS doesn't have multiple prototypal inheritance, this class -// prototypally inherits from Readable, and then parasitically from -// Writable. - -module.exports = Duplex; - -/**/ -var objectKeys = Object.keys || function (obj) { - var keys = []; - for (var key in obj) keys.push(key); - return keys; -} -/**/ - - -/**/ -var util = _dereq_('core-util-is'); -util.inherits = _dereq_('inherits'); -/**/ - -var Readable = _dereq_('./_stream_readable'); -var Writable = _dereq_('./_stream_writable'); - -util.inherits(Duplex, Readable); - -forEach(objectKeys(Writable.prototype), function(method) { - if (!Duplex.prototype[method]) - Duplex.prototype[method] = Writable.prototype[method]; -}); - -function Duplex(options) { - if (!(this instanceof Duplex)) - return new Duplex(options); - - Readable.call(this, options); - Writable.call(this, options); - - if (options && options.readable === false) - this.readable = false; - - if (options && options.writable === false) - this.writable = false; - - this.allowHalfOpen = true; - if (options && options.allowHalfOpen === false) - this.allowHalfOpen = false; - - this.once('end', onend); -} - -// the no-half-open enforcer -function onend() { - // if we allow half-open state, or if the writable side ended, - // then we're ok. - if (this.allowHalfOpen || this._writableState.ended) - return; - - // no more data can be written. - // But allow more writes to happen in this tick. - process.nextTick(this.end.bind(this)); -} - -function forEach (xs, f) { - for (var i = 0, l = xs.length; i < l; i++) { - f(xs[i], i); - } -} - -}).call(this,_dereq_("Zbi7gb")) -},{"./_stream_readable":47,"./_stream_writable":49,"Zbi7gb":39,"core-util-is":50,"inherits":37}],46:[function(_dereq_,module,exports){ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// a passthrough stream. -// basically just the most minimal sort of Transform stream. -// Every written chunk gets output as-is. - -module.exports = PassThrough; - -var Transform = _dereq_('./_stream_transform'); - -/**/ -var util = _dereq_('core-util-is'); -util.inherits = _dereq_('inherits'); -/**/ - -util.inherits(PassThrough, Transform); - -function PassThrough(options) { - if (!(this instanceof PassThrough)) - return new PassThrough(options); - - Transform.call(this, options); -} - -PassThrough.prototype._transform = function(chunk, encoding, cb) { - cb(null, chunk); -}; - -},{"./_stream_transform":48,"core-util-is":50,"inherits":37}],47:[function(_dereq_,module,exports){ -(function (process){ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -module.exports = Readable; - -/**/ -var isArray = _dereq_('isarray'); -/**/ - - -/**/ -var Buffer = _dereq_('buffer').Buffer; -/**/ - -Readable.ReadableState = ReadableState; - -var EE = _dereq_('events').EventEmitter; - -/**/ -if (!EE.listenerCount) EE.listenerCount = function(emitter, type) { - return emitter.listeners(type).length; -}; -/**/ - -var Stream = _dereq_('stream'); - -/**/ -var util = _dereq_('core-util-is'); -util.inherits = _dereq_('inherits'); -/**/ - -var StringDecoder; - -util.inherits(Readable, Stream); - -function ReadableState(options, stream) { - options = options || {}; - - // the point at which it stops calling _read() to fill the buffer - // Note: 0 is a valid value, means "don't call _read preemptively ever" - var hwm = options.highWaterMark; - this.highWaterMark = (hwm || hwm === 0) ? hwm : 16 * 1024; - - // cast to ints. - this.highWaterMark = ~~this.highWaterMark; - - this.buffer = []; - this.length = 0; - this.pipes = null; - this.pipesCount = 0; - this.flowing = false; - this.ended = false; - this.endEmitted = false; - this.reading = false; - - // In streams that never have any data, and do push(null) right away, - // the consumer can miss the 'end' event if they do some I/O before - // consuming the stream. So, we don't emit('end') until some reading - // happens. - this.calledRead = false; - - // a flag to be able to tell if the onwrite cb is called immediately, - // or on a later tick. We set this to true at first, becuase any - // actions that shouldn't happen until "later" should generally also - // not happen before the first write call. - this.sync = true; - - // whenever we return null, then we set a flag to say - // that we're awaiting a 'readable' event emission. - this.needReadable = false; - this.emittedReadable = false; - this.readableListening = false; - - - // object stream flag. Used to make read(n) ignore n and to - // make all the buffer merging and length checks go away - this.objectMode = !!options.objectMode; - - // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - this.defaultEncoding = options.defaultEncoding || 'utf8'; - - // when piping, we only care about 'readable' events that happen - // after read()ing all the bytes and not getting any pushback. - this.ranOut = false; - - // the number of writers that are awaiting a drain event in .pipe()s - this.awaitDrain = 0; - - // if true, a maybeReadMore has been scheduled - this.readingMore = false; - - this.decoder = null; - this.encoding = null; - if (options.encoding) { - if (!StringDecoder) - StringDecoder = _dereq_('string_decoder/').StringDecoder; - this.decoder = new StringDecoder(options.encoding); - this.encoding = options.encoding; - } -} - -function Readable(options) { - if (!(this instanceof Readable)) - return new Readable(options); - - this._readableState = new ReadableState(options, this); - - // legacy - this.readable = true; - - Stream.call(this); -} - -// Manually shove something into the read() buffer. -// This returns true if the highWaterMark has not been hit yet, -// similar to how Writable.write() returns true if you should -// write() some more. -Readable.prototype.push = function(chunk, encoding) { - var state = this._readableState; - - if (typeof chunk === 'string' && !state.objectMode) { - encoding = encoding || state.defaultEncoding; - if (encoding !== state.encoding) { - chunk = new Buffer(chunk, encoding); - encoding = ''; - } - } - - return readableAddChunk(this, state, chunk, encoding, false); -}; - -// Unshift should *always* be something directly out of read() -Readable.prototype.unshift = function(chunk) { - var state = this._readableState; - return readableAddChunk(this, state, chunk, '', true); -}; - -function readableAddChunk(stream, state, chunk, encoding, addToFront) { - var er = chunkInvalid(state, chunk); - if (er) { - stream.emit('error', er); - } else if (chunk === null || chunk === undefined) { - state.reading = false; - if (!state.ended) - onEofChunk(stream, state); - } else if (state.objectMode || chunk && chunk.length > 0) { - if (state.ended && !addToFront) { - var e = new Error('stream.push() after EOF'); - stream.emit('error', e); - } else if (state.endEmitted && addToFront) { - var e = new Error('stream.unshift() after end event'); - stream.emit('error', e); - } else { - if (state.decoder && !addToFront && !encoding) - chunk = state.decoder.write(chunk); - - // update the buffer info. - state.length += state.objectMode ? 1 : chunk.length; - if (addToFront) { - state.buffer.unshift(chunk); - } else { - state.reading = false; - state.buffer.push(chunk); - } - - if (state.needReadable) - emitReadable(stream); - - maybeReadMore(stream, state); - } - } else if (!addToFront) { - state.reading = false; - } - - return needMoreData(state); -} - - - -// if it's past the high water mark, we can push in some more. -// Also, if we have no data yet, we can stand some -// more bytes. This is to work around cases where hwm=0, -// such as the repl. Also, if the push() triggered a -// readable event, and the user called read(largeNumber) such that -// needReadable was set, then we ought to push more, so that another -// 'readable' event will be triggered. -function needMoreData(state) { - return !state.ended && - (state.needReadable || - state.length < state.highWaterMark || - state.length === 0); -} - -// backwards compatibility. -Readable.prototype.setEncoding = function(enc) { - if (!StringDecoder) - StringDecoder = _dereq_('string_decoder/').StringDecoder; - this._readableState.decoder = new StringDecoder(enc); - this._readableState.encoding = enc; -}; - -// Don't raise the hwm > 128MB -var MAX_HWM = 0x800000; -function roundUpToNextPowerOf2(n) { - if (n >= MAX_HWM) { - n = MAX_HWM; - } else { - // Get the next highest power of 2 - n--; - for (var p = 1; p < 32; p <<= 1) n |= n >> p; - n++; - } - return n; -} - -function howMuchToRead(n, state) { - if (state.length === 0 && state.ended) - return 0; - - if (state.objectMode) - return n === 0 ? 0 : 1; - - if (isNaN(n) || n === null) { - // only flow one buffer at a time - if (state.flowing && state.buffer.length) - return state.buffer[0].length; - else - return state.length; - } - - if (n <= 0) - return 0; - - // If we're asking for more than the target buffer level, - // then raise the water mark. Bump up to the next highest - // power of 2, to prevent increasing it excessively in tiny - // amounts. - if (n > state.highWaterMark) - state.highWaterMark = roundUpToNextPowerOf2(n); - - // don't have that much. return null, unless we've ended. - if (n > state.length) { - if (!state.ended) { - state.needReadable = true; - return 0; - } else - return state.length; - } - - return n; -} - -// you can override either this method, or the async _read(n) below. -Readable.prototype.read = function(n) { - var state = this._readableState; - state.calledRead = true; - var nOrig = n; - - if (typeof n !== 'number' || n > 0) - state.emittedReadable = false; - - // if we're doing read(0) to trigger a readable event, but we - // already have a bunch of data in the buffer, then just trigger - // the 'readable' event and move on. - if (n === 0 && - state.needReadable && - (state.length >= state.highWaterMark || state.ended)) { - emitReadable(this); - return null; - } - - n = howMuchToRead(n, state); - - // if we've ended, and we're now clear, then finish it up. - if (n === 0 && state.ended) { - if (state.length === 0) - endReadable(this); - return null; - } - - // All the actual chunk generation logic needs to be - // *below* the call to _read. The reason is that in certain - // synthetic stream cases, such as passthrough streams, _read - // may be a completely synchronous operation which may change - // the state of the read buffer, providing enough data when - // before there was *not* enough. - // - // So, the steps are: - // 1. Figure out what the state of things will be after we do - // a read from the buffer. - // - // 2. If that resulting state will trigger a _read, then call _read. - // Note that this may be asynchronous, or synchronous. Yes, it is - // deeply ugly to write APIs this way, but that still doesn't mean - // that the Readable class should behave improperly, as streams are - // designed to be sync/async agnostic. - // Take note if the _read call is sync or async (ie, if the read call - // has returned yet), so that we know whether or not it's safe to emit - // 'readable' etc. - // - // 3. Actually pull the requested chunks out of the buffer and return. - - // if we need a readable event, then we need to do some reading. - var doRead = state.needReadable; - - // if we currently have less than the highWaterMark, then also read some - if (state.length - n <= state.highWaterMark) - doRead = true; - - // however, if we've ended, then there's no point, and if we're already - // reading, then it's unnecessary. - if (state.ended || state.reading) - doRead = false; - - if (doRead) { - state.reading = true; - state.sync = true; - // if the length is currently zero, then we *need* a readable event. - if (state.length === 0) - state.needReadable = true; - // call internal read method - this._read(state.highWaterMark); - state.sync = false; - } - - // If _read called its callback synchronously, then `reading` - // will be false, and we need to re-evaluate how much data we - // can return to the user. - if (doRead && !state.reading) - n = howMuchToRead(nOrig, state); - - var ret; - if (n > 0) - ret = fromList(n, state); - else - ret = null; - - if (ret === null) { - state.needReadable = true; - n = 0; - } - - state.length -= n; - - // If we have nothing in the buffer, then we want to know - // as soon as we *do* get something into the buffer. - if (state.length === 0 && !state.ended) - state.needReadable = true; - - // If we happened to read() exactly the remaining amount in the - // buffer, and the EOF has been seen at this point, then make sure - // that we emit 'end' on the very next tick. - if (state.ended && !state.endEmitted && state.length === 0) - endReadable(this); - - return ret; -}; - -function chunkInvalid(state, chunk) { - var er = null; - if (!Buffer.isBuffer(chunk) && - 'string' !== typeof chunk && - chunk !== null && - chunk !== undefined && - !state.objectMode && - !er) { - er = new TypeError('Invalid non-string/buffer chunk'); - } - return er; -} - - -function onEofChunk(stream, state) { - if (state.decoder && !state.ended) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) { - state.buffer.push(chunk); - state.length += state.objectMode ? 1 : chunk.length; - } - } - state.ended = true; - - // if we've ended and we have some data left, then emit - // 'readable' now to make sure it gets picked up. - if (state.length > 0) - emitReadable(stream); - else - endReadable(stream); -} - -// Don't emit readable right away in sync mode, because this can trigger -// another read() call => stack overflow. This way, it might trigger -// a nextTick recursion warning, but that's not so bad. -function emitReadable(stream) { - var state = stream._readableState; - state.needReadable = false; - if (state.emittedReadable) - return; - - state.emittedReadable = true; - if (state.sync) - process.nextTick(function() { - emitReadable_(stream); - }); - else - emitReadable_(stream); -} - -function emitReadable_(stream) { - stream.emit('readable'); -} - - -// at this point, the user has presumably seen the 'readable' event, -// and called read() to consume some data. that may have triggered -// in turn another _read(n) call, in which case reading = true if -// it's in progress. -// However, if we're not ended, or reading, and the length < hwm, -// then go ahead and try to read some more preemptively. -function maybeReadMore(stream, state) { - if (!state.readingMore) { - state.readingMore = true; - process.nextTick(function() { - maybeReadMore_(stream, state); - }); - } -} - -function maybeReadMore_(stream, state) { - var len = state.length; - while (!state.reading && !state.flowing && !state.ended && - state.length < state.highWaterMark) { - stream.read(0); - if (len === state.length) - // didn't get any data, stop spinning. - break; - else - len = state.length; - } - state.readingMore = false; -} - -// abstract method. to be overridden in specific implementation classes. -// call cb(er, data) where data is <= n in length. -// for virtual (non-string, non-buffer) streams, "length" is somewhat -// arbitrary, and perhaps not very meaningful. -Readable.prototype._read = function(n) { - this.emit('error', new Error('not implemented')); -}; - -Readable.prototype.pipe = function(dest, pipeOpts) { - var src = this; - var state = this._readableState; - - switch (state.pipesCount) { - case 0: - state.pipes = dest; - break; - case 1: - state.pipes = [state.pipes, dest]; - break; - default: - state.pipes.push(dest); - break; - } - state.pipesCount += 1; - - var doEnd = (!pipeOpts || pipeOpts.end !== false) && - dest !== process.stdout && - dest !== process.stderr; - - var endFn = doEnd ? onend : cleanup; - if (state.endEmitted) - process.nextTick(endFn); - else - src.once('end', endFn); - - dest.on('unpipe', onunpipe); - function onunpipe(readable) { - if (readable !== src) return; - cleanup(); - } - - function onend() { - dest.end(); - } - - // when the dest drains, it reduces the awaitDrain counter - // on the source. This would be more elegant with a .once() - // handler in flow(), but adding and removing repeatedly is - // too slow. - var ondrain = pipeOnDrain(src); - dest.on('drain', ondrain); - - function cleanup() { - // cleanup event handlers once the pipe is broken - dest.removeListener('close', onclose); - dest.removeListener('finish', onfinish); - dest.removeListener('drain', ondrain); - dest.removeListener('error', onerror); - dest.removeListener('unpipe', onunpipe); - src.removeListener('end', onend); - src.removeListener('end', cleanup); - - // if the reader is waiting for a drain event from this - // specific writer, then it would cause it to never start - // flowing again. - // So, if this is awaiting a drain, then we just call it now. - // If we don't know, then assume that we are waiting for one. - if (!dest._writableState || dest._writableState.needDrain) - ondrain(); - } - - // if the dest has an error, then stop piping into it. - // however, don't suppress the throwing behavior for this. - function onerror(er) { - unpipe(); - dest.removeListener('error', onerror); - if (EE.listenerCount(dest, 'error') === 0) - dest.emit('error', er); - } - // This is a brutally ugly hack to make sure that our error handler - // is attached before any userland ones. NEVER DO THIS. - if (!dest._events || !dest._events.error) - dest.on('error', onerror); - else if (isArray(dest._events.error)) - dest._events.error.unshift(onerror); - else - dest._events.error = [onerror, dest._events.error]; - - - - // Both close and finish should trigger unpipe, but only once. - function onclose() { - dest.removeListener('finish', onfinish); - unpipe(); - } - dest.once('close', onclose); - function onfinish() { - dest.removeListener('close', onclose); - unpipe(); - } - dest.once('finish', onfinish); - - function unpipe() { - src.unpipe(dest); - } - - // tell the dest that it's being piped to - dest.emit('pipe', src); - - // start the flow if it hasn't been started already. - if (!state.flowing) { - // the handler that waits for readable events after all - // the data gets sucked out in flow. - // This would be easier to follow with a .once() handler - // in flow(), but that is too slow. - this.on('readable', pipeOnReadable); - - state.flowing = true; - process.nextTick(function() { - flow(src); - }); - } - - return dest; -}; - -function pipeOnDrain(src) { - return function() { - var dest = this; - var state = src._readableState; - state.awaitDrain--; - if (state.awaitDrain === 0) - flow(src); - }; -} - -function flow(src) { - var state = src._readableState; - var chunk; - state.awaitDrain = 0; - - function write(dest, i, list) { - var written = dest.write(chunk); - if (false === written) { - state.awaitDrain++; - } - } - - while (state.pipesCount && null !== (chunk = src.read())) { - - if (state.pipesCount === 1) - write(state.pipes, 0, null); - else - forEach(state.pipes, write); - - src.emit('data', chunk); - - // if anyone needs a drain, then we have to wait for that. - if (state.awaitDrain > 0) - return; - } - - // if every destination was unpiped, either before entering this - // function, or in the while loop, then stop flowing. - // - // NB: This is a pretty rare edge case. - if (state.pipesCount === 0) { - state.flowing = false; - - // if there were data event listeners added, then switch to old mode. - if (EE.listenerCount(src, 'data') > 0) - emitDataEvents(src); - return; - } - - // at this point, no one needed a drain, so we just ran out of data - // on the next readable event, start it over again. - state.ranOut = true; -} - -function pipeOnReadable() { - if (this._readableState.ranOut) { - this._readableState.ranOut = false; - flow(this); - } -} - - -Readable.prototype.unpipe = function(dest) { - var state = this._readableState; - - // if we're not piping anywhere, then do nothing. - if (state.pipesCount === 0) - return this; - - // just one destination. most common case. - if (state.pipesCount === 1) { - // passed in one, but it's not the right one. - if (dest && dest !== state.pipes) - return this; - - if (!dest) - dest = state.pipes; - - // got a match. - state.pipes = null; - state.pipesCount = 0; - this.removeListener('readable', pipeOnReadable); - state.flowing = false; - if (dest) - dest.emit('unpipe', this); - return this; - } - - // slow case. multiple pipe destinations. - - if (!dest) { - // remove all. - var dests = state.pipes; - var len = state.pipesCount; - state.pipes = null; - state.pipesCount = 0; - this.removeListener('readable', pipeOnReadable); - state.flowing = false; - - for (var i = 0; i < len; i++) - dests[i].emit('unpipe', this); - return this; - } - - // try to find the right one. - var i = indexOf(state.pipes, dest); - if (i === -1) - return this; - - state.pipes.splice(i, 1); - state.pipesCount -= 1; - if (state.pipesCount === 1) - state.pipes = state.pipes[0]; - - dest.emit('unpipe', this); - - return this; -}; - -// set up data events if they are asked for -// Ensure readable listeners eventually get something -Readable.prototype.on = function(ev, fn) { - var res = Stream.prototype.on.call(this, ev, fn); - - if (ev === 'data' && !this._readableState.flowing) - emitDataEvents(this); - - if (ev === 'readable' && this.readable) { - var state = this._readableState; - if (!state.readableListening) { - state.readableListening = true; - state.emittedReadable = false; - state.needReadable = true; - if (!state.reading) { - this.read(0); - } else if (state.length) { - emitReadable(this, state); - } - } - } - - return res; -}; -Readable.prototype.addListener = Readable.prototype.on; - -// pause() and resume() are remnants of the legacy readable stream API -// If the user uses them, then switch into old mode. -Readable.prototype.resume = function() { - emitDataEvents(this); - this.read(0); - this.emit('resume'); -}; - -Readable.prototype.pause = function() { - emitDataEvents(this, true); - this.emit('pause'); -}; - -function emitDataEvents(stream, startPaused) { - var state = stream._readableState; - - if (state.flowing) { - // https://github.com/isaacs/readable-stream/issues/16 - throw new Error('Cannot switch to old mode now.'); - } - - var paused = startPaused || false; - var readable = false; - - // convert to an old-style stream. - stream.readable = true; - stream.pipe = Stream.prototype.pipe; - stream.on = stream.addListener = Stream.prototype.on; - - stream.on('readable', function() { - readable = true; - - var c; - while (!paused && (null !== (c = stream.read()))) - stream.emit('data', c); - - if (c === null) { - readable = false; - stream._readableState.needReadable = true; - } - }); - - stream.pause = function() { - paused = true; - this.emit('pause'); - }; - - stream.resume = function() { - paused = false; - if (readable) - process.nextTick(function() { - stream.emit('readable'); - }); - else - this.read(0); - this.emit('resume'); - }; - - // now make it start, just in case it hadn't already. - stream.emit('readable'); -} - -// wrap an old-style stream as the async data source. -// This is *not* part of the readable stream interface. -// It is an ugly unfortunate mess of history. -Readable.prototype.wrap = function(stream) { - var state = this._readableState; - var paused = false; - - var self = this; - stream.on('end', function() { - if (state.decoder && !state.ended) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) - self.push(chunk); - } - - self.push(null); - }); - - stream.on('data', function(chunk) { - if (state.decoder) - chunk = state.decoder.write(chunk); - if (!chunk || !state.objectMode && !chunk.length) - return; - - var ret = self.push(chunk); - if (!ret) { - paused = true; - stream.pause(); - } - }); - - // proxy all the other methods. - // important when wrapping filters and duplexes. - for (var i in stream) { - if (typeof stream[i] === 'function' && - typeof this[i] === 'undefined') { - this[i] = function(method) { return function() { - return stream[method].apply(stream, arguments); - }}(i); - } - } - - // proxy certain important events. - var events = ['error', 'close', 'destroy', 'pause', 'resume']; - forEach(events, function(ev) { - stream.on(ev, self.emit.bind(self, ev)); - }); - - // when we try to consume some more bytes, simply unpause the - // underlying stream. - self._read = function(n) { - if (paused) { - paused = false; - stream.resume(); - } - }; - - return self; -}; - - - -// exposed for testing purposes only. -Readable._fromList = fromList; - -// Pluck off n bytes from an array of buffers. -// Length is the combined lengths of all the buffers in the list. -function fromList(n, state) { - var list = state.buffer; - var length = state.length; - var stringMode = !!state.decoder; - var objectMode = !!state.objectMode; - var ret; - - // nothing in the list, definitely empty. - if (list.length === 0) - return null; - - if (length === 0) - ret = null; - else if (objectMode) - ret = list.shift(); - else if (!n || n >= length) { - // read it all, truncate the array. - if (stringMode) - ret = list.join(''); - else - ret = Buffer.concat(list, length); - list.length = 0; - } else { - // read just some of it. - if (n < list[0].length) { - // just take a part of the first list item. - // slice is the same for buffers and strings. - var buf = list[0]; - ret = buf.slice(0, n); - list[0] = buf.slice(n); - } else if (n === list[0].length) { - // first list is a perfect match - ret = list.shift(); - } else { - // complex case. - // we have enough to cover it, but it spans past the first buffer. - if (stringMode) - ret = ''; - else - ret = new Buffer(n); - - var c = 0; - for (var i = 0, l = list.length; i < l && c < n; i++) { - var buf = list[0]; - var cpy = Math.min(n - c, buf.length); - - if (stringMode) - ret += buf.slice(0, cpy); - else - buf.copy(ret, c, 0, cpy); - - if (cpy < buf.length) - list[0] = buf.slice(cpy); - else - list.shift(); - - c += cpy; - } - } - } - - return ret; -} - -function endReadable(stream) { - var state = stream._readableState; - - // If we get here before consuming all the bytes, then that is a - // bug in node. Should never happen. - if (state.length > 0) - throw new Error('endReadable called on non-empty stream'); - - if (!state.endEmitted && state.calledRead) { - state.ended = true; - process.nextTick(function() { - // Check that we didn't get one last unshift. - if (!state.endEmitted && state.length === 0) { - state.endEmitted = true; - stream.readable = false; - stream.emit('end'); - } - }); - } -} - -function forEach (xs, f) { - for (var i = 0, l = xs.length; i < l; i++) { - f(xs[i], i); - } -} - -function indexOf (xs, x) { - for (var i = 0, l = xs.length; i < l; i++) { - if (xs[i] === x) return i; - } - return -1; -} - -}).call(this,_dereq_("Zbi7gb")) -},{"Zbi7gb":39,"buffer":28,"core-util-is":50,"events":31,"inherits":37,"isarray":51,"stream":57,"string_decoder/":52}],48:[function(_dereq_,module,exports){ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - -// a transform stream is a readable/writable stream where you do -// something with the data. Sometimes it's called a "filter", -// but that's not a great name for it, since that implies a thing where -// some bits pass through, and others are simply ignored. (That would -// be a valid example of a transform, of course.) -// -// While the output is causally related to the input, it's not a -// necessarily symmetric or synchronous transformation. For example, -// a zlib stream might take multiple plain-text writes(), and then -// emit a single compressed chunk some time in the future. -// -// Here's how this works: -// -// The Transform stream has all the aspects of the readable and writable -// stream classes. When you write(chunk), that calls _write(chunk,cb) -// internally, and returns false if there's a lot of pending writes -// buffered up. When you call read(), that calls _read(n) until -// there's enough pending readable data buffered up. -// -// In a transform stream, the written data is placed in a buffer. When -// _read(n) is called, it transforms the queued up data, calling the -// buffered _write cb's as it consumes chunks. If consuming a single -// written chunk would result in multiple output chunks, then the first -// outputted bit calls the readcb, and subsequent chunks just go into -// the read buffer, and will cause it to emit 'readable' if necessary. -// -// This way, back-pressure is actually determined by the reading side, -// since _read has to be called to start processing a new chunk. However, -// a pathological inflate type of transform can cause excessive buffering -// here. For example, imagine a stream where every byte of input is -// interpreted as an integer from 0-255, and then results in that many -// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in -// 1kb of data being output. In this case, you could write a very small -// amount of input, and end up with a very large amount of output. In -// such a pathological inflating mechanism, there'd be no way to tell -// the system to stop doing the transform. A single 4MB write could -// cause the system to run out of memory. -// -// However, even in such a pathological case, only a single written chunk -// would be consumed, and then the rest would wait (un-transformed) until -// the results of the previous transformed chunk were consumed. - -module.exports = Transform; - -var Duplex = _dereq_('./_stream_duplex'); - -/**/ -var util = _dereq_('core-util-is'); -util.inherits = _dereq_('inherits'); -/**/ - -util.inherits(Transform, Duplex); - - -function TransformState(options, stream) { - this.afterTransform = function(er, data) { - return afterTransform(stream, er, data); - }; - - this.needTransform = false; - this.transforming = false; - this.writecb = null; - this.writechunk = null; -} - -function afterTransform(stream, er, data) { - var ts = stream._transformState; - ts.transforming = false; - - var cb = ts.writecb; - - if (!cb) - return stream.emit('error', new Error('no writecb in Transform class')); - - ts.writechunk = null; - ts.writecb = null; - - if (data !== null && data !== undefined) - stream.push(data); - - if (cb) - cb(er); - - var rs = stream._readableState; - rs.reading = false; - if (rs.needReadable || rs.length < rs.highWaterMark) { - stream._read(rs.highWaterMark); - } -} - - -function Transform(options) { - if (!(this instanceof Transform)) - return new Transform(options); - - Duplex.call(this, options); - - var ts = this._transformState = new TransformState(options, this); - - // when the writable side finishes, then flush out anything remaining. - var stream = this; - - // start out asking for a readable event once data is transformed. - this._readableState.needReadable = true; - - // we have implemented the _read method, and done the other things - // that Readable wants before the first _read call, so unset the - // sync guard flag. - this._readableState.sync = false; - - this.once('finish', function() { - if ('function' === typeof this._flush) - this._flush(function(er) { - done(stream, er); - }); - else - done(stream); - }); -} - -Transform.prototype.push = function(chunk, encoding) { - this._transformState.needTransform = false; - return Duplex.prototype.push.call(this, chunk, encoding); -}; - -// This is the part where you do stuff! -// override this function in implementation classes. -// 'chunk' is an input chunk. -// -// Call `push(newChunk)` to pass along transformed output -// to the readable side. You may call 'push' zero or more times. -// -// Call `cb(err)` when you are done with this chunk. If you pass -// an error, then that'll put the hurt on the whole operation. If you -// never call cb(), then you'll never get another chunk. -Transform.prototype._transform = function(chunk, encoding, cb) { - throw new Error('not implemented'); -}; - -Transform.prototype._write = function(chunk, encoding, cb) { - var ts = this._transformState; - ts.writecb = cb; - ts.writechunk = chunk; - ts.writeencoding = encoding; - if (!ts.transforming) { - var rs = this._readableState; - if (ts.needTransform || - rs.needReadable || - rs.length < rs.highWaterMark) - this._read(rs.highWaterMark); - } -}; - -// Doesn't matter what the args are here. -// _transform does all the work. -// That we got here means that the readable side wants more data. -Transform.prototype._read = function(n) { - var ts = this._transformState; - - if (ts.writechunk !== null && ts.writecb && !ts.transforming) { - ts.transforming = true; - this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); - } else { - // mark that we need a transform, so that any data that comes in - // will get processed, now that we've asked for it. - ts.needTransform = true; - } -}; - - -function done(stream, er) { - if (er) - return stream.emit('error', er); - - // if there's nothing in the write buffer, then that means - // that nothing more will ever be provided - var ws = stream._writableState; - var rs = stream._readableState; - var ts = stream._transformState; - - if (ws.length) - throw new Error('calling transform done when ws.length != 0'); - - if (ts.transforming) - throw new Error('calling transform done when still transforming'); - - return stream.push(null); -} - -},{"./_stream_duplex":45,"core-util-is":50,"inherits":37}],49:[function(_dereq_,module,exports){ -(function (process){ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// A bit simpler than readable streams. -// Implement an async ._write(chunk, cb), and it'll handle all -// the drain event emission and buffering. - -module.exports = Writable; - -/**/ -var Buffer = _dereq_('buffer').Buffer; -/**/ - -Writable.WritableState = WritableState; - - -/**/ -var util = _dereq_('core-util-is'); -util.inherits = _dereq_('inherits'); -/**/ - - -var Stream = _dereq_('stream'); - -util.inherits(Writable, Stream); - -function WriteReq(chunk, encoding, cb) { - this.chunk = chunk; - this.encoding = encoding; - this.callback = cb; -} - -function WritableState(options, stream) { - options = options || {}; - - // the point at which write() starts returning false - // Note: 0 is a valid value, means that we always return false if - // the entire buffer is not flushed immediately on write() - var hwm = options.highWaterMark; - this.highWaterMark = (hwm || hwm === 0) ? hwm : 16 * 1024; - - // object stream flag to indicate whether or not this stream - // contains buffers or objects. - this.objectMode = !!options.objectMode; - - // cast to ints. - this.highWaterMark = ~~this.highWaterMark; - - this.needDrain = false; - // at the start of calling end() - this.ending = false; - // when end() has been called, and returned - this.ended = false; - // when 'finish' is emitted - this.finished = false; - - // should we decode strings into buffers before passing to _write? - // this is here so that some node-core streams can optimize string - // handling at a lower level. - var noDecode = options.decodeStrings === false; - this.decodeStrings = !noDecode; - - // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - this.defaultEncoding = options.defaultEncoding || 'utf8'; - - // not an actual buffer we keep track of, but a measurement - // of how much we're waiting to get pushed to some underlying - // socket or file. - this.length = 0; - - // a flag to see when we're in the middle of a write. - this.writing = false; - - // a flag to be able to tell if the onwrite cb is called immediately, - // or on a later tick. We set this to true at first, becuase any - // actions that shouldn't happen until "later" should generally also - // not happen before the first write call. - this.sync = true; - - // a flag to know if we're processing previously buffered items, which - // may call the _write() callback in the same tick, so that we don't - // end up in an overlapped onwrite situation. - this.bufferProcessing = false; - - // the callback that's passed to _write(chunk,cb) - this.onwrite = function(er) { - onwrite(stream, er); - }; - - // the callback that the user supplies to write(chunk,encoding,cb) - this.writecb = null; - - // the amount that is being written when _write is called. - this.writelen = 0; - - this.buffer = []; - - // True if the error was already emitted and should not be thrown again - this.errorEmitted = false; -} - -function Writable(options) { - var Duplex = _dereq_('./_stream_duplex'); - - // Writable ctor is applied to Duplexes, though they're not - // instanceof Writable, they're instanceof Readable. - if (!(this instanceof Writable) && !(this instanceof Duplex)) - return new Writable(options); - - this._writableState = new WritableState(options, this); - - // legacy. - this.writable = true; - - Stream.call(this); -} - -// Otherwise people can pipe Writable streams, which is just wrong. -Writable.prototype.pipe = function() { - this.emit('error', new Error('Cannot pipe. Not readable.')); -}; - - -function writeAfterEnd(stream, state, cb) { - var er = new Error('write after end'); - // TODO: defer error events consistently everywhere, not just the cb - stream.emit('error', er); - process.nextTick(function() { - cb(er); - }); -} - -// If we get something that is not a buffer, string, null, or undefined, -// and we're not in objectMode, then that's an error. -// Otherwise stream chunks are all considered to be of length=1, and the -// watermarks determine how many objects to keep in the buffer, rather than -// how many bytes or characters. -function validChunk(stream, state, chunk, cb) { - var valid = true; - if (!Buffer.isBuffer(chunk) && - 'string' !== typeof chunk && - chunk !== null && - chunk !== undefined && - !state.objectMode) { - var er = new TypeError('Invalid non-string/buffer chunk'); - stream.emit('error', er); - process.nextTick(function() { - cb(er); - }); - valid = false; - } - return valid; -} - -Writable.prototype.write = function(chunk, encoding, cb) { - var state = this._writableState; - var ret = false; - - if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } - - if (Buffer.isBuffer(chunk)) - encoding = 'buffer'; - else if (!encoding) - encoding = state.defaultEncoding; - - if (typeof cb !== 'function') - cb = function() {}; - - if (state.ended) - writeAfterEnd(this, state, cb); - else if (validChunk(this, state, chunk, cb)) - ret = writeOrBuffer(this, state, chunk, encoding, cb); - - return ret; -}; - -function decodeChunk(state, chunk, encoding) { - if (!state.objectMode && - state.decodeStrings !== false && - typeof chunk === 'string') { - chunk = new Buffer(chunk, encoding); - } - return chunk; -} - -// if we're already writing something, then just put this -// in the queue, and wait our turn. Otherwise, call _write -// If we return false, then we need a drain event, so set that flag. -function writeOrBuffer(stream, state, chunk, encoding, cb) { - chunk = decodeChunk(state, chunk, encoding); - if (Buffer.isBuffer(chunk)) - encoding = 'buffer'; - var len = state.objectMode ? 1 : chunk.length; - - state.length += len; - - var ret = state.length < state.highWaterMark; - // we must ensure that previous needDrain will not be reset to false. - if (!ret) - state.needDrain = true; - - if (state.writing) - state.buffer.push(new WriteReq(chunk, encoding, cb)); - else - doWrite(stream, state, len, chunk, encoding, cb); - - return ret; -} - -function doWrite(stream, state, len, chunk, encoding, cb) { - state.writelen = len; - state.writecb = cb; - state.writing = true; - state.sync = true; - stream._write(chunk, encoding, state.onwrite); - state.sync = false; -} - -function onwriteError(stream, state, sync, er, cb) { - if (sync) - process.nextTick(function() { - cb(er); - }); - else - cb(er); - - stream._writableState.errorEmitted = true; - stream.emit('error', er); -} - -function onwriteStateUpdate(state) { - state.writing = false; - state.writecb = null; - state.length -= state.writelen; - state.writelen = 0; -} - -function onwrite(stream, er) { - var state = stream._writableState; - var sync = state.sync; - var cb = state.writecb; - - onwriteStateUpdate(state); - - if (er) - onwriteError(stream, state, sync, er, cb); - else { - // Check if we're actually ready to finish, but don't emit yet - var finished = needFinish(stream, state); - - if (!finished && !state.bufferProcessing && state.buffer.length) - clearBuffer(stream, state); - - if (sync) { - process.nextTick(function() { - afterWrite(stream, state, finished, cb); - }); - } else { - afterWrite(stream, state, finished, cb); - } - } -} - -function afterWrite(stream, state, finished, cb) { - if (!finished) - onwriteDrain(stream, state); - cb(); - if (finished) - finishMaybe(stream, state); -} - -// Must force callback to be called on nextTick, so that we don't -// emit 'drain' before the write() consumer gets the 'false' return -// value, and has a chance to attach a 'drain' listener. -function onwriteDrain(stream, state) { - if (state.length === 0 && state.needDrain) { - state.needDrain = false; - stream.emit('drain'); - } -} - - -// if there's something in the buffer waiting, then process it -function clearBuffer(stream, state) { - state.bufferProcessing = true; - - for (var c = 0; c < state.buffer.length; c++) { - var entry = state.buffer[c]; - var chunk = entry.chunk; - var encoding = entry.encoding; - var cb = entry.callback; - var len = state.objectMode ? 1 : chunk.length; - - doWrite(stream, state, len, chunk, encoding, cb); - - // if we didn't call the onwrite immediately, then - // it means that we need to wait until it does. - // also, that means that the chunk and cb are currently - // being processed, so move the buffer counter past them. - if (state.writing) { - c++; - break; - } - } - - state.bufferProcessing = false; - if (c < state.buffer.length) - state.buffer = state.buffer.slice(c); - else - state.buffer.length = 0; -} - -Writable.prototype._write = function(chunk, encoding, cb) { - cb(new Error('not implemented')); -}; - -Writable.prototype.end = function(chunk, encoding, cb) { - var state = this._writableState; - - if (typeof chunk === 'function') { - cb = chunk; - chunk = null; - encoding = null; - } else if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } - - if (typeof chunk !== 'undefined' && chunk !== null) - this.write(chunk, encoding); - - // ignore unnecessary end() calls. - if (!state.ending && !state.finished) - endWritable(this, state, cb); -}; - - -function needFinish(stream, state) { - return (state.ending && - state.length === 0 && - !state.finished && - !state.writing); -} - -function finishMaybe(stream, state) { - var need = needFinish(stream, state); - if (need) { - state.finished = true; - stream.emit('finish'); - } - return need; -} - -function endWritable(stream, state, cb) { - state.ending = true; - finishMaybe(stream, state); - if (cb) { - if (state.finished) - process.nextTick(cb); - else - stream.once('finish', cb); - } - state.ended = true; -} - -}).call(this,_dereq_("Zbi7gb")) -},{"./_stream_duplex":45,"Zbi7gb":39,"buffer":28,"core-util-is":50,"inherits":37,"stream":57}],50:[function(_dereq_,module,exports){ -(function (Buffer){ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// NOTE: These type checking functions intentionally don't use `instanceof` -// because it is fragile and can be easily faked with `Object.create()`. -function isArray(ar) { - return Array.isArray(ar); -} -exports.isArray = isArray; - -function isBoolean(arg) { - return typeof arg === 'boolean'; -} -exports.isBoolean = isBoolean; - -function isNull(arg) { - return arg === null; -} -exports.isNull = isNull; - -function isNullOrUndefined(arg) { - return arg == null; -} -exports.isNullOrUndefined = isNullOrUndefined; - -function isNumber(arg) { - return typeof arg === 'number'; -} -exports.isNumber = isNumber; - -function isString(arg) { - return typeof arg === 'string'; -} -exports.isString = isString; - -function isSymbol(arg) { - return typeof arg === 'symbol'; -} -exports.isSymbol = isSymbol; - -function isUndefined(arg) { - return arg === void 0; -} -exports.isUndefined = isUndefined; - -function isRegExp(re) { - return isObject(re) && objectToString(re) === '[object RegExp]'; -} -exports.isRegExp = isRegExp; - -function isObject(arg) { - return typeof arg === 'object' && arg !== null; -} -exports.isObject = isObject; - -function isDate(d) { - return isObject(d) && objectToString(d) === '[object Date]'; -} -exports.isDate = isDate; - -function isError(e) { - return isObject(e) && - (objectToString(e) === '[object Error]' || e instanceof Error); -} -exports.isError = isError; - -function isFunction(arg) { - return typeof arg === 'function'; -} -exports.isFunction = isFunction; - -function isPrimitive(arg) { - return arg === null || - typeof arg === 'boolean' || - typeof arg === 'number' || - typeof arg === 'string' || - typeof arg === 'symbol' || // ES6 symbol - typeof arg === 'undefined'; -} -exports.isPrimitive = isPrimitive; - -function isBuffer(arg) { - return Buffer.isBuffer(arg); -} -exports.isBuffer = isBuffer; - -function objectToString(o) { - return Object.prototype.toString.call(o); -} -}).call(this,_dereq_("buffer").Buffer) -},{"buffer":28}],51:[function(_dereq_,module,exports){ -module.exports = Array.isArray || function (arr) { - return Object.prototype.toString.call(arr) == '[object Array]'; -}; - -},{}],52:[function(_dereq_,module,exports){ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var Buffer = _dereq_('buffer').Buffer; - -var isBufferEncoding = Buffer.isEncoding - || function(encoding) { - switch (encoding && encoding.toLowerCase()) { - case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': case 'raw': return true; - default: return false; - } - } - - -function assertEncoding(encoding) { - if (encoding && !isBufferEncoding(encoding)) { - throw new Error('Unknown encoding: ' + encoding); - } -} - -var StringDecoder = exports.StringDecoder = function(encoding) { - this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, ''); - assertEncoding(encoding); - switch (this.encoding) { - case 'utf8': - // CESU-8 represents each of Surrogate Pair by 3-bytes - this.surrogateSize = 3; - break; - case 'ucs2': - case 'utf16le': - // UTF-16 represents each of Surrogate Pair by 2-bytes - this.surrogateSize = 2; - this.detectIncompleteChar = utf16DetectIncompleteChar; - break; - case 'base64': - // Base-64 stores 3 bytes in 4 chars, and pads the remainder. - this.surrogateSize = 3; - this.detectIncompleteChar = base64DetectIncompleteChar; - break; - default: - this.write = passThroughWrite; - return; - } - - this.charBuffer = new Buffer(6); - this.charReceived = 0; - this.charLength = 0; -}; - - -StringDecoder.prototype.write = function(buffer) { - var charStr = ''; - var offset = 0; - - // if our last write ended with an incomplete multibyte character - while (this.charLength) { - // determine how many remaining bytes this buffer has to offer for this char - var i = (buffer.length >= this.charLength - this.charReceived) ? - this.charLength - this.charReceived : - buffer.length; - - // add the new bytes to the char buffer - buffer.copy(this.charBuffer, this.charReceived, offset, i); - this.charReceived += (i - offset); - offset = i; - - if (this.charReceived < this.charLength) { - // still not enough chars in this buffer? wait for more ... - return ''; - } - - // get the character that was split - charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding); - - // lead surrogate (D800-DBFF) is also the incomplete character - var charCode = charStr.charCodeAt(charStr.length - 1); - if (charCode >= 0xD800 && charCode <= 0xDBFF) { - this.charLength += this.surrogateSize; - charStr = ''; - continue; - } - this.charReceived = this.charLength = 0; - - // if there are no more bytes in this buffer, just emit our char - if (i == buffer.length) return charStr; - - // otherwise cut off the characters end from the beginning of this buffer - buffer = buffer.slice(i, buffer.length); - break; - } - - var lenIncomplete = this.detectIncompleteChar(buffer); - - var end = buffer.length; - if (this.charLength) { - // buffer the incomplete character bytes we got - buffer.copy(this.charBuffer, 0, buffer.length - lenIncomplete, end); - this.charReceived = lenIncomplete; - end -= lenIncomplete; - } - - charStr += buffer.toString(this.encoding, 0, end); - - var end = charStr.length - 1; - var charCode = charStr.charCodeAt(end); - // lead surrogate (D800-DBFF) is also the incomplete character - if (charCode >= 0xD800 && charCode <= 0xDBFF) { - var size = this.surrogateSize; - this.charLength += size; - this.charReceived += size; - this.charBuffer.copy(this.charBuffer, size, 0, size); - this.charBuffer.write(charStr.charAt(charStr.length - 1), this.encoding); - return charStr.substring(0, end); - } - - // or just emit the charStr - return charStr; -}; - -StringDecoder.prototype.detectIncompleteChar = function(buffer) { - // determine how many bytes we have to check at the end of this buffer - var i = (buffer.length >= 3) ? 3 : buffer.length; - - // Figure out if one of the last i bytes of our buffer announces an - // incomplete char. - for (; i > 0; i--) { - var c = buffer[buffer.length - i]; - - // See http://en.wikipedia.org/wiki/UTF-8#Description - - // 110XXXXX - if (i == 1 && c >> 5 == 0x06) { - this.charLength = 2; - break; - } - - // 1110XXXX - if (i <= 2 && c >> 4 == 0x0E) { - this.charLength = 3; - break; - } - - // 11110XXX - if (i <= 3 && c >> 3 == 0x1E) { - this.charLength = 4; - break; - } - } - - return i; -}; - -StringDecoder.prototype.end = function(buffer) { - var res = ''; - if (buffer && buffer.length) - res = this.write(buffer); - - if (this.charReceived) { - var cr = this.charReceived; - var buf = this.charBuffer; - var enc = this.encoding; - res += buf.slice(0, cr).toString(enc); - } - - return res; -}; - -function passThroughWrite(buffer) { - return buffer.toString(this.encoding); -} - -function utf16DetectIncompleteChar(buffer) { - var incomplete = this.charReceived = buffer.length % 2; - this.charLength = incomplete ? 2 : 0; - return incomplete; -} - -function base64DetectIncompleteChar(buffer) { - var incomplete = this.charReceived = buffer.length % 3; - this.charLength = incomplete ? 3 : 0; - return incomplete; -} - -},{"buffer":28}],53:[function(_dereq_,module,exports){ -module.exports = _dereq_("./lib/_stream_passthrough.js") - -},{"./lib/_stream_passthrough.js":46}],54:[function(_dereq_,module,exports){ -exports = module.exports = _dereq_('./lib/_stream_readable.js'); -exports.Readable = exports; -exports.Writable = _dereq_('./lib/_stream_writable.js'); -exports.Duplex = _dereq_('./lib/_stream_duplex.js'); -exports.Transform = _dereq_('./lib/_stream_transform.js'); -exports.PassThrough = _dereq_('./lib/_stream_passthrough.js'); - -},{"./lib/_stream_duplex.js":45,"./lib/_stream_passthrough.js":46,"./lib/_stream_readable.js":47,"./lib/_stream_transform.js":48,"./lib/_stream_writable.js":49}],55:[function(_dereq_,module,exports){ -module.exports = _dereq_("./lib/_stream_transform.js") - -},{"./lib/_stream_transform.js":48}],56:[function(_dereq_,module,exports){ -module.exports = _dereq_("./lib/_stream_writable.js") - -},{"./lib/_stream_writable.js":49}],57:[function(_dereq_,module,exports){ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -module.exports = Stream; - -var EE = _dereq_('events').EventEmitter; -var inherits = _dereq_('inherits'); - -inherits(Stream, EE); -Stream.Readable = _dereq_('readable-stream/readable.js'); -Stream.Writable = _dereq_('readable-stream/writable.js'); -Stream.Duplex = _dereq_('readable-stream/duplex.js'); -Stream.Transform = _dereq_('readable-stream/transform.js'); -Stream.PassThrough = _dereq_('readable-stream/passthrough.js'); - -// Backwards-compat with node 0.4.x -Stream.Stream = Stream; - - - -// old-style streams. Note that the pipe method (the only relevant -// part of this class) is overridden in the Readable class. - -function Stream() { - EE.call(this); -} - -Stream.prototype.pipe = function(dest, options) { - var source = this; - - function ondata(chunk) { - if (dest.writable) { - if (false === dest.write(chunk) && source.pause) { - source.pause(); - } - } - } - - source.on('data', ondata); - - function ondrain() { - if (source.readable && source.resume) { - source.resume(); - } - } - - dest.on('drain', ondrain); - - // If the 'end' option is not supplied, dest.end() will be called when - // source gets the 'end' or 'close' events. Only dest.end() once. - if (!dest._isStdio && (!options || options.end !== false)) { - source.on('end', onend); - source.on('close', onclose); - } - - var didOnEnd = false; - function onend() { - if (didOnEnd) return; - didOnEnd = true; - - dest.end(); - } - - - function onclose() { - if (didOnEnd) return; - didOnEnd = true; - - if (typeof dest.destroy === 'function') dest.destroy(); - } - - // don't leave dangling pipes when there are errors. - function onerror(er) { - cleanup(); - if (EE.listenerCount(this, 'error') === 0) { - throw er; // Unhandled stream error in pipe. - } - } - - source.on('error', onerror); - dest.on('error', onerror); - - // remove all the event listeners that were added. - function cleanup() { - source.removeListener('data', ondata); - dest.removeListener('drain', ondrain); - - source.removeListener('end', onend); - source.removeListener('close', onclose); - - source.removeListener('error', onerror); - dest.removeListener('error', onerror); - - source.removeListener('end', cleanup); - source.removeListener('close', cleanup); - - dest.removeListener('close', cleanup); - } - - source.on('end', cleanup); - source.on('close', cleanup); - - dest.on('close', cleanup); - - dest.emit('pipe', source); - - // Allow for unix-like usage: A.pipe(B).pipe(C) - return dest; -}; - -},{"events":31,"inherits":37,"readable-stream/duplex.js":44,"readable-stream/passthrough.js":53,"readable-stream/readable.js":54,"readable-stream/transform.js":55,"readable-stream/writable.js":56}],58:[function(_dereq_,module,exports){ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var punycode = _dereq_('punycode'); - -exports.parse = urlParse; -exports.resolve = urlResolve; -exports.resolveObject = urlResolveObject; -exports.format = urlFormat; - -exports.Url = Url; - -function Url() { - this.protocol = null; - this.slashes = null; - this.auth = null; - this.host = null; - this.port = null; - this.hostname = null; - this.hash = null; - this.search = null; - this.query = null; - this.pathname = null; - this.path = null; - this.href = null; -} - -// Reference: RFC 3986, RFC 1808, RFC 2396 - -// define these here so at least they only have to be -// compiled once on the first module load. -var protocolPattern = /^([a-z0-9.+-]+:)/i, - portPattern = /:[0-9]*$/, - - // RFC 2396: characters reserved for delimiting URLs. - // We actually just auto-escape these. - delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'], - - // RFC 2396: characters not allowed for various reasons. - unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims), - - // Allowed by RFCs, but cause of XSS attacks. Always escape these. - autoEscape = ['\''].concat(unwise), - // Characters that are never ever allowed in a hostname. - // Note that any invalid chars are also handled, but these - // are the ones that are *expected* to be seen, so we fast-path - // them. - nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape), - hostEndingChars = ['/', '?', '#'], - hostnameMaxLen = 255, - hostnamePartPattern = /^[a-z0-9A-Z_-]{0,63}$/, - hostnamePartStart = /^([a-z0-9A-Z_-]{0,63})(.*)$/, - // protocols that can allow "unsafe" and "unwise" chars. - unsafeProtocol = { - 'javascript': true, - 'javascript:': true - }, - // protocols that never have a hostname. - hostlessProtocol = { - 'javascript': true, - 'javascript:': true - }, - // protocols that always contain a // bit. - slashedProtocol = { - 'http': true, - 'https': true, - 'ftp': true, - 'gopher': true, - 'file': true, - 'http:': true, - 'https:': true, - 'ftp:': true, - 'gopher:': true, - 'file:': true - }, - querystring = _dereq_('querystring'); - -function urlParse(url, parseQueryString, slashesDenoteHost) { - if (url && isObject(url) && url instanceof Url) return url; - - var u = new Url; - u.parse(url, parseQueryString, slashesDenoteHost); - return u; -} - -Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) { - if (!isString(url)) { - throw new TypeError("Parameter 'url' must be a string, not " + typeof url); - } - - var rest = url; - - // trim before proceeding. - // This is to support parse stuff like " http://foo.com \n" - rest = rest.trim(); - - var proto = protocolPattern.exec(rest); - if (proto) { - proto = proto[0]; - var lowerProto = proto.toLowerCase(); - this.protocol = lowerProto; - rest = rest.substr(proto.length); - } - - // figure out if it's got a host - // user@server is *always* interpreted as a hostname, and url - // resolution will treat //foo/bar as host=foo,path=bar because that's - // how the browser resolves relative URLs. - if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) { - var slashes = rest.substr(0, 2) === '//'; - if (slashes && !(proto && hostlessProtocol[proto])) { - rest = rest.substr(2); - this.slashes = true; - } - } - - if (!hostlessProtocol[proto] && - (slashes || (proto && !slashedProtocol[proto]))) { - - // there's a hostname. - // the first instance of /, ?, ;, or # ends the host. - // - // If there is an @ in the hostname, then non-host chars *are* allowed - // to the left of the last @ sign, unless some host-ending character - // comes *before* the @-sign. - // URLs are obnoxious. - // - // ex: - // http://a@b@c/ => user:a@b host:c - // http://a@b?@c => user:a host:c path:/?@c - - // v0.12 TODO(isaacs): This is not quite how Chrome does things. - // Review our test case against browsers more comprehensively. - - // find the first instance of any hostEndingChars - var hostEnd = -1; - for (var i = 0; i < hostEndingChars.length; i++) { - var hec = rest.indexOf(hostEndingChars[i]); - if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) - hostEnd = hec; - } - - // at this point, either we have an explicit point where the - // auth portion cannot go past, or the last @ char is the decider. - var auth, atSign; - if (hostEnd === -1) { - // atSign can be anywhere. - atSign = rest.lastIndexOf('@'); - } else { - // atSign must be in auth portion. - // http://a@b/c@d => host:b auth:a path:/c@d - atSign = rest.lastIndexOf('@', hostEnd); - } - - // Now we have a portion which is definitely the auth. - // Pull that off. - if (atSign !== -1) { - auth = rest.slice(0, atSign); - rest = rest.slice(atSign + 1); - this.auth = decodeURIComponent(auth); - } - - // the host is the remaining to the left of the first non-host char - hostEnd = -1; - for (var i = 0; i < nonHostChars.length; i++) { - var hec = rest.indexOf(nonHostChars[i]); - if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) - hostEnd = hec; - } - // if we still have not hit it, then the entire thing is a host. - if (hostEnd === -1) - hostEnd = rest.length; - - this.host = rest.slice(0, hostEnd); - rest = rest.slice(hostEnd); - - // pull out port. - this.parseHost(); - - // we've indicated that there is a hostname, - // so even if it's empty, it has to be present. - this.hostname = this.hostname || ''; - - // if hostname begins with [ and ends with ] - // assume that it's an IPv6 address. - var ipv6Hostname = this.hostname[0] === '[' && - this.hostname[this.hostname.length - 1] === ']'; - - // validate a little. - if (!ipv6Hostname) { - var hostparts = this.hostname.split(/\./); - for (var i = 0, l = hostparts.length; i < l; i++) { - var part = hostparts[i]; - if (!part) continue; - if (!part.match(hostnamePartPattern)) { - var newpart = ''; - for (var j = 0, k = part.length; j < k; j++) { - if (part.charCodeAt(j) > 127) { - // we replace non-ASCII char with a temporary placeholder - // we need this to make sure size of hostname is not - // broken by replacing non-ASCII by nothing - newpart += 'x'; - } else { - newpart += part[j]; - } - } - // we test again with ASCII char only - if (!newpart.match(hostnamePartPattern)) { - var validParts = hostparts.slice(0, i); - var notHost = hostparts.slice(i + 1); - var bit = part.match(hostnamePartStart); - if (bit) { - validParts.push(bit[1]); - notHost.unshift(bit[2]); - } - if (notHost.length) { - rest = '/' + notHost.join('.') + rest; - } - this.hostname = validParts.join('.'); - break; - } - } - } - } - - if (this.hostname.length > hostnameMaxLen) { - this.hostname = ''; - } else { - // hostnames are always lower case. - this.hostname = this.hostname.toLowerCase(); - } - - if (!ipv6Hostname) { - // IDNA Support: Returns a puny coded representation of "domain". - // It only converts the part of the domain name that - // has non ASCII characters. I.e. it dosent matter if - // you call it with a domain that already is in ASCII. - var domainArray = this.hostname.split('.'); - var newOut = []; - for (var i = 0; i < domainArray.length; ++i) { - var s = domainArray[i]; - newOut.push(s.match(/[^A-Za-z0-9_-]/) ? - 'xn--' + punycode.encode(s) : s); - } - this.hostname = newOut.join('.'); - } - - var p = this.port ? ':' + this.port : ''; - var h = this.hostname || ''; - this.host = h + p; - this.href += this.host; - - // strip [ and ] from the hostname - // the host field still retains them, though - if (ipv6Hostname) { - this.hostname = this.hostname.substr(1, this.hostname.length - 2); - if (rest[0] !== '/') { - rest = '/' + rest; - } - } - } - - // now rest is set to the post-host stuff. - // chop off any delim chars. - if (!unsafeProtocol[lowerProto]) { - - // First, make 100% sure that any "autoEscape" chars get - // escaped, even if encodeURIComponent doesn't think they - // need to be. - for (var i = 0, l = autoEscape.length; i < l; i++) { - var ae = autoEscape[i]; - var esc = encodeURIComponent(ae); - if (esc === ae) { - esc = escape(ae); - } - rest = rest.split(ae).join(esc); - } - } - - - // chop off from the tail first. - var hash = rest.indexOf('#'); - if (hash !== -1) { - // got a fragment string. - this.hash = rest.substr(hash); - rest = rest.slice(0, hash); - } - var qm = rest.indexOf('?'); - if (qm !== -1) { - this.search = rest.substr(qm); - this.query = rest.substr(qm + 1); - if (parseQueryString) { - this.query = querystring.parse(this.query); - } - rest = rest.slice(0, qm); - } else if (parseQueryString) { - // no query string, but parseQueryString still requested - this.search = ''; - this.query = {}; - } - if (rest) this.pathname = rest; - if (slashedProtocol[lowerProto] && - this.hostname && !this.pathname) { - this.pathname = '/'; - } - - //to support http.request - if (this.pathname || this.search) { - var p = this.pathname || ''; - var s = this.search || ''; - this.path = p + s; - } - - // finally, reconstruct the href based on what has been validated. - this.href = this.format(); - return this; -}; - -// format a parsed object into a url string -function urlFormat(obj) { - // ensure it's an object, and not a string url. - // If it's an obj, this is a no-op. - // this way, you can call url_format() on strings - // to clean up potentially wonky urls. - if (isString(obj)) obj = urlParse(obj); - if (!(obj instanceof Url)) return Url.prototype.format.call(obj); - return obj.format(); -} - -Url.prototype.format = function() { - var auth = this.auth || ''; - if (auth) { - auth = encodeURIComponent(auth); - auth = auth.replace(/%3A/i, ':'); - auth += '@'; - } - - var protocol = this.protocol || '', - pathname = this.pathname || '', - hash = this.hash || '', - host = false, - query = ''; - - if (this.host) { - host = auth + this.host; - } else if (this.hostname) { - host = auth + (this.hostname.indexOf(':') === -1 ? - this.hostname : - '[' + this.hostname + ']'); - if (this.port) { - host += ':' + this.port; - } - } - - if (this.query && - isObject(this.query) && - Object.keys(this.query).length) { - query = querystring.stringify(this.query); - } - - var search = this.search || (query && ('?' + query)) || ''; - - if (protocol && protocol.substr(-1) !== ':') protocol += ':'; - - // only the slashedProtocols get the //. Not mailto:, xmpp:, etc. - // unless they had them to begin with. - if (this.slashes || - (!protocol || slashedProtocol[protocol]) && host !== false) { - host = '//' + (host || ''); - if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname; - } else if (!host) { - host = ''; - } - - if (hash && hash.charAt(0) !== '#') hash = '#' + hash; - if (search && search.charAt(0) !== '?') search = '?' + search; - - pathname = pathname.replace(/[?#]/g, function(match) { - return encodeURIComponent(match); - }); - search = search.replace('#', '%23'); - - return protocol + host + pathname + search + hash; -}; - -function urlResolve(source, relative) { - return urlParse(source, false, true).resolve(relative); -} - -Url.prototype.resolve = function(relative) { - return this.resolveObject(urlParse(relative, false, true)).format(); -}; - -function urlResolveObject(source, relative) { - if (!source) return relative; - return urlParse(source, false, true).resolveObject(relative); -} - -Url.prototype.resolveObject = function(relative) { - if (isString(relative)) { - var rel = new Url(); - rel.parse(relative, false, true); - relative = rel; - } - - var result = new Url(); - Object.keys(this).forEach(function(k) { - result[k] = this[k]; - }, this); - - // hash is always overridden, no matter what. - // even href="" will remove it. - result.hash = relative.hash; - - // if the relative url is empty, then there's nothing left to do here. - if (relative.href === '') { - result.href = result.format(); - return result; - } - - // hrefs like //foo/bar always cut to the protocol. - if (relative.slashes && !relative.protocol) { - // take everything except the protocol from relative - Object.keys(relative).forEach(function(k) { - if (k !== 'protocol') - result[k] = relative[k]; - }); - - //urlParse appends trailing / to urls like http://www.example.com - if (slashedProtocol[result.protocol] && - result.hostname && !result.pathname) { - result.path = result.pathname = '/'; - } - - result.href = result.format(); - return result; - } - - if (relative.protocol && relative.protocol !== result.protocol) { - // if it's a known url protocol, then changing - // the protocol does weird things - // first, if it's not file:, then we MUST have a host, - // and if there was a path - // to begin with, then we MUST have a path. - // if it is file:, then the host is dropped, - // because that's known to be hostless. - // anything else is assumed to be absolute. - if (!slashedProtocol[relative.protocol]) { - Object.keys(relative).forEach(function(k) { - result[k] = relative[k]; - }); - result.href = result.format(); - return result; - } - - result.protocol = relative.protocol; - if (!relative.host && !hostlessProtocol[relative.protocol]) { - var relPath = (relative.pathname || '').split('/'); - while (relPath.length && !(relative.host = relPath.shift())); - if (!relative.host) relative.host = ''; - if (!relative.hostname) relative.hostname = ''; - if (relPath[0] !== '') relPath.unshift(''); - if (relPath.length < 2) relPath.unshift(''); - result.pathname = relPath.join('/'); - } else { - result.pathname = relative.pathname; - } - result.search = relative.search; - result.query = relative.query; - result.host = relative.host || ''; - result.auth = relative.auth; - result.hostname = relative.hostname || relative.host; - result.port = relative.port; - // to support http.request - if (result.pathname || result.search) { - var p = result.pathname || ''; - var s = result.search || ''; - result.path = p + s; - } - result.slashes = result.slashes || relative.slashes; - result.href = result.format(); - return result; - } - - var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'), - isRelAbs = ( - relative.host || - relative.pathname && relative.pathname.charAt(0) === '/' - ), - mustEndAbs = (isRelAbs || isSourceAbs || - (result.host && relative.pathname)), - removeAllDots = mustEndAbs, - srcPath = result.pathname && result.pathname.split('/') || [], - relPath = relative.pathname && relative.pathname.split('/') || [], - psychotic = result.protocol && !slashedProtocol[result.protocol]; - - // if the url is a non-slashed url, then relative - // links like ../.. should be able - // to crawl up to the hostname, as well. This is strange. - // result.protocol has already been set by now. - // Later on, put the first path part into the host field. - if (psychotic) { - result.hostname = ''; - result.port = null; - if (result.host) { - if (srcPath[0] === '') srcPath[0] = result.host; - else srcPath.unshift(result.host); - } - result.host = ''; - if (relative.protocol) { - relative.hostname = null; - relative.port = null; - if (relative.host) { - if (relPath[0] === '') relPath[0] = relative.host; - else relPath.unshift(relative.host); - } - relative.host = null; - } - mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === ''); - } - - if (isRelAbs) { - // it's absolute. - result.host = (relative.host || relative.host === '') ? - relative.host : result.host; - result.hostname = (relative.hostname || relative.hostname === '') ? - relative.hostname : result.hostname; - result.search = relative.search; - result.query = relative.query; - srcPath = relPath; - // fall through to the dot-handling below. - } else if (relPath.length) { - // it's relative - // throw away the existing file, and take the new path instead. - if (!srcPath) srcPath = []; - srcPath.pop(); - srcPath = srcPath.concat(relPath); - result.search = relative.search; - result.query = relative.query; - } else if (!isNullOrUndefined(relative.search)) { - // just pull out the search. - // like href='?foo'. - // Put this after the other two cases because it simplifies the booleans - if (psychotic) { - result.hostname = result.host = srcPath.shift(); - //occationaly the auth can get stuck only in host - //this especialy happens in cases like - //url.resolveObject('mailto:local1@domain1', 'local2@domain2') - var authInHost = result.host && result.host.indexOf('@') > 0 ? - result.host.split('@') : false; - if (authInHost) { - result.auth = authInHost.shift(); - result.host = result.hostname = authInHost.shift(); - } - } - result.search = relative.search; - result.query = relative.query; - //to support http.request - if (!isNull(result.pathname) || !isNull(result.search)) { - result.path = (result.pathname ? result.pathname : '') + - (result.search ? result.search : ''); - } - result.href = result.format(); - return result; - } - - if (!srcPath.length) { - // no path at all. easy. - // we've already handled the other stuff above. - result.pathname = null; - //to support http.request - if (result.search) { - result.path = '/' + result.search; - } else { - result.path = null; - } - result.href = result.format(); - return result; - } - - // if a url ENDs in . or .., then it must get a trailing slash. - // however, if it ends in anything else non-slashy, - // then it must NOT get a trailing slash. - var last = srcPath.slice(-1)[0]; - var hasTrailingSlash = ( - (result.host || relative.host) && (last === '.' || last === '..') || - last === ''); - - // strip single dots, resolve double dots to parent dir - // if the path tries to go above the root, `up` ends up > 0 - var up = 0; - for (var i = srcPath.length; i >= 0; i--) { - last = srcPath[i]; - if (last == '.') { - srcPath.splice(i, 1); - } else if (last === '..') { - srcPath.splice(i, 1); - up++; - } else if (up) { - srcPath.splice(i, 1); - up--; - } - } - - // if the path is allowed to go above the root, restore leading ..s - if (!mustEndAbs && !removeAllDots) { - for (; up--; up) { - srcPath.unshift('..'); - } - } - - if (mustEndAbs && srcPath[0] !== '' && - (!srcPath[0] || srcPath[0].charAt(0) !== '/')) { - srcPath.unshift(''); - } - - if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) { - srcPath.push(''); - } - - var isAbsolute = srcPath[0] === '' || - (srcPath[0] && srcPath[0].charAt(0) === '/'); - - // put the host back - if (psychotic) { - result.hostname = result.host = isAbsolute ? '' : - srcPath.length ? srcPath.shift() : ''; - //occationaly the auth can get stuck only in host - //this especialy happens in cases like - //url.resolveObject('mailto:local1@domain1', 'local2@domain2') - var authInHost = result.host && result.host.indexOf('@') > 0 ? - result.host.split('@') : false; - if (authInHost) { - result.auth = authInHost.shift(); - result.host = result.hostname = authInHost.shift(); - } - } - - mustEndAbs = mustEndAbs || (result.host && srcPath.length); - - if (mustEndAbs && !isAbsolute) { - srcPath.unshift(''); - } - - if (!srcPath.length) { - result.pathname = null; - result.path = null; - } else { - result.pathname = srcPath.join('/'); - } - - //to support request.http - if (!isNull(result.pathname) || !isNull(result.search)) { - result.path = (result.pathname ? result.pathname : '') + - (result.search ? result.search : ''); - } - result.auth = relative.auth || result.auth; - result.slashes = result.slashes || relative.slashes; - result.href = result.format(); - return result; -}; - -Url.prototype.parseHost = function() { - var host = this.host; - var port = portPattern.exec(host); - if (port) { - port = port[0]; - if (port !== ':') { - this.port = port.substr(1); - } - host = host.substr(0, host.length - port.length); - } - if (host) this.hostname = host; -}; - -function isString(arg) { - return typeof arg === "string"; -} - -function isObject(arg) { - return typeof arg === 'object' && arg !== null; -} - -function isNull(arg) { - return arg === null; -} -function isNullOrUndefined(arg) { - return arg == null; -} - -},{"punycode":40,"querystring":43}],59:[function(_dereq_,module,exports){ -module.exports = function isBuffer(arg) { - return arg && typeof arg === 'object' - && typeof arg.copy === 'function' - && typeof arg.fill === 'function' - && typeof arg.readUInt8 === 'function'; -} -},{}],60:[function(_dereq_,module,exports){ -(function (process,global){ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var formatRegExp = /%[sdj%]/g; -exports.format = function(f) { - if (!isString(f)) { - var objects = []; - for (var i = 0; i < arguments.length; i++) { - objects.push(inspect(arguments[i])); - } - return objects.join(' '); - } - - var i = 1; - var args = arguments; - var len = args.length; - var str = String(f).replace(formatRegExp, function(x) { - if (x === '%%') return '%'; - if (i >= len) return x; - switch (x) { - case '%s': return String(args[i++]); - case '%d': return Number(args[i++]); - case '%j': - try { - return JSON.stringify(args[i++]); - } catch (_) { - return '[Circular]'; - } - default: - return x; - } - }); - for (var x = args[i]; i < len; x = args[++i]) { - if (isNull(x) || !isObject(x)) { - str += ' ' + x; - } else { - str += ' ' + inspect(x); - } - } - return str; -}; - - -// Mark that a method should not be used. -// Returns a modified function which warns once by default. -// If --no-deprecation is set, then it is a no-op. -exports.deprecate = function(fn, msg) { - // Allow for deprecating things in the process of starting up. - if (isUndefined(global.process)) { - return function() { - return exports.deprecate(fn, msg).apply(this, arguments); - }; - } - - if (process.noDeprecation === true) { - return fn; - } - - var warned = false; - function deprecated() { - if (!warned) { - if (process.throwDeprecation) { - throw new Error(msg); - } else if (process.traceDeprecation) { - console.trace(msg); - } else { - console.error(msg); - } - warned = true; - } - return fn.apply(this, arguments); - } - - return deprecated; -}; - - -var debugs = {}; -var debugEnviron; -exports.debuglog = function(set) { - if (isUndefined(debugEnviron)) - debugEnviron = process.env.NODE_DEBUG || ''; - set = set.toUpperCase(); - if (!debugs[set]) { - if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { - var pid = process.pid; - debugs[set] = function() { - var msg = exports.format.apply(exports, arguments); - console.error('%s %d: %s', set, pid, msg); - }; - } else { - debugs[set] = function() {}; - } - } - return debugs[set]; -}; - - -/** - * Echos the value of a value. Trys to print the value out - * in the best way possible given the different types. - * - * @param {Object} obj The object to print out. - * @param {Object} opts Optional options object that alters the output. - */ -/* legacy: obj, showHidden, depth, colors*/ -function inspect(obj, opts) { - // default options - var ctx = { - seen: [], - stylize: stylizeNoColor - }; - // legacy... - if (arguments.length >= 3) ctx.depth = arguments[2]; - if (arguments.length >= 4) ctx.colors = arguments[3]; - if (isBoolean(opts)) { - // legacy... - ctx.showHidden = opts; - } else if (opts) { - // got an "options" object - exports._extend(ctx, opts); - } - // set default options - if (isUndefined(ctx.showHidden)) ctx.showHidden = false; - if (isUndefined(ctx.depth)) ctx.depth = 2; - if (isUndefined(ctx.colors)) ctx.colors = false; - if (isUndefined(ctx.customInspect)) ctx.customInspect = true; - if (ctx.colors) ctx.stylize = stylizeWithColor; - return formatValue(ctx, obj, ctx.depth); -} -exports.inspect = inspect; - - -// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics -inspect.colors = { - 'bold' : [1, 22], - 'italic' : [3, 23], - 'underline' : [4, 24], - 'inverse' : [7, 27], - 'white' : [37, 39], - 'grey' : [90, 39], - 'black' : [30, 39], - 'blue' : [34, 39], - 'cyan' : [36, 39], - 'green' : [32, 39], - 'magenta' : [35, 39], - 'red' : [31, 39], - 'yellow' : [33, 39] -}; - -// Don't use 'blue' not visible on cmd.exe -inspect.styles = { - 'special': 'cyan', - 'number': 'yellow', - 'boolean': 'yellow', - 'undefined': 'grey', - 'null': 'bold', - 'string': 'green', - 'date': 'magenta', - // "name": intentionally not styling - 'regexp': 'red' -}; - - -function stylizeWithColor(str, styleType) { - var style = inspect.styles[styleType]; - - if (style) { - return '\u001b[' + inspect.colors[style][0] + 'm' + str + - '\u001b[' + inspect.colors[style][1] + 'm'; - } else { - return str; - } -} - - -function stylizeNoColor(str, styleType) { - return str; -} - - -function arrayToHash(array) { - var hash = {}; - - array.forEach(function(val, idx) { - hash[val] = true; - }); - - return hash; -} - - -function formatValue(ctx, value, recurseTimes) { - // Provide a hook for user-specified inspect functions. - // Check that value is an object with an inspect function on it - if (ctx.customInspect && - value && - isFunction(value.inspect) && - // Filter out the util module, it's inspect function is special - value.inspect !== exports.inspect && - // Also filter out any prototype objects using the circular check. - !(value.constructor && value.constructor.prototype === value)) { - var ret = value.inspect(recurseTimes, ctx); - if (!isString(ret)) { - ret = formatValue(ctx, ret, recurseTimes); - } - return ret; - } - - // Primitive types cannot have properties - var primitive = formatPrimitive(ctx, value); - if (primitive) { - return primitive; - } - - // Look up the keys of the object. - var keys = Object.keys(value); - var visibleKeys = arrayToHash(keys); - - if (ctx.showHidden) { - keys = Object.getOwnPropertyNames(value); - } - - // IE doesn't make error fields non-enumerable - // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx - if (isError(value) - && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { - return formatError(value); - } - - // Some type of object without properties can be shortcutted. - if (keys.length === 0) { - if (isFunction(value)) { - var name = value.name ? ': ' + value.name : ''; - return ctx.stylize('[Function' + name + ']', 'special'); - } - if (isRegExp(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } - if (isDate(value)) { - return ctx.stylize(Date.prototype.toString.call(value), 'date'); - } - if (isError(value)) { - return formatError(value); - } - } - - var base = '', array = false, braces = ['{', '}']; - - // Make Array say that they are Array - if (isArray(value)) { - array = true; - braces = ['[', ']']; - } - - // Make functions say that they are functions - if (isFunction(value)) { - var n = value.name ? ': ' + value.name : ''; - base = ' [Function' + n + ']'; - } - - // Make RegExps say that they are RegExps - if (isRegExp(value)) { - base = ' ' + RegExp.prototype.toString.call(value); - } - - // Make dates with properties first say the date - if (isDate(value)) { - base = ' ' + Date.prototype.toUTCString.call(value); - } - - // Make error with message first say the error - if (isError(value)) { - base = ' ' + formatError(value); - } - - if (keys.length === 0 && (!array || value.length == 0)) { - return braces[0] + base + braces[1]; - } - - if (recurseTimes < 0) { - if (isRegExp(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } else { - return ctx.stylize('[Object]', 'special'); - } - } - - ctx.seen.push(value); - - var output; - if (array) { - output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); - } else { - output = keys.map(function(key) { - return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); - }); - } - - ctx.seen.pop(); - - return reduceToSingleString(output, base, braces); -} - - -function formatPrimitive(ctx, value) { - if (isUndefined(value)) - return ctx.stylize('undefined', 'undefined'); - if (isString(value)) { - var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') - .replace(/'/g, "\\'") - .replace(/\\"/g, '"') + '\''; - return ctx.stylize(simple, 'string'); - } - if (isNumber(value)) - return ctx.stylize('' + value, 'number'); - if (isBoolean(value)) - return ctx.stylize('' + value, 'boolean'); - // For some reason typeof null is "object", so special case here. - if (isNull(value)) - return ctx.stylize('null', 'null'); -} - - -function formatError(value) { - return '[' + Error.prototype.toString.call(value) + ']'; -} - - -function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { - var output = []; - for (var i = 0, l = value.length; i < l; ++i) { - if (hasOwnProperty(value, String(i))) { - output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, - String(i), true)); - } else { - output.push(''); - } - } - keys.forEach(function(key) { - if (!key.match(/^\d+$/)) { - output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, - key, true)); - } - }); - return output; -} - - -function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { - var name, str, desc; - desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; - if (desc.get) { - if (desc.set) { - str = ctx.stylize('[Getter/Setter]', 'special'); - } else { - str = ctx.stylize('[Getter]', 'special'); - } - } else { - if (desc.set) { - str = ctx.stylize('[Setter]', 'special'); - } - } - if (!hasOwnProperty(visibleKeys, key)) { - name = '[' + key + ']'; - } - if (!str) { - if (ctx.seen.indexOf(desc.value) < 0) { - if (isNull(recurseTimes)) { - str = formatValue(ctx, desc.value, null); - } else { - str = formatValue(ctx, desc.value, recurseTimes - 1); - } - if (str.indexOf('\n') > -1) { - if (array) { - str = str.split('\n').map(function(line) { - return ' ' + line; - }).join('\n').substr(2); - } else { - str = '\n' + str.split('\n').map(function(line) { - return ' ' + line; - }).join('\n'); - } - } - } else { - str = ctx.stylize('[Circular]', 'special'); - } - } - if (isUndefined(name)) { - if (array && key.match(/^\d+$/)) { - return str; - } - name = JSON.stringify('' + key); - if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { - name = name.substr(1, name.length - 2); - name = ctx.stylize(name, 'name'); - } else { - name = name.replace(/'/g, "\\'") - .replace(/\\"/g, '"') - .replace(/(^"|"$)/g, "'"); - name = ctx.stylize(name, 'string'); - } - } - - return name + ': ' + str; -} - - -function reduceToSingleString(output, base, braces) { - var numLinesEst = 0; - var length = output.reduce(function(prev, cur) { - numLinesEst++; - if (cur.indexOf('\n') >= 0) numLinesEst++; - return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; - }, 0); - - if (length > 60) { - return braces[0] + - (base === '' ? '' : base + '\n ') + - ' ' + - output.join(',\n ') + - ' ' + - braces[1]; - } - - return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; -} - - -// NOTE: These type checking functions intentionally don't use `instanceof` -// because it is fragile and can be easily faked with `Object.create()`. -function isArray(ar) { - return Array.isArray(ar); -} -exports.isArray = isArray; - -function isBoolean(arg) { - return typeof arg === 'boolean'; -} -exports.isBoolean = isBoolean; - -function isNull(arg) { - return arg === null; -} -exports.isNull = isNull; - -function isNullOrUndefined(arg) { - return arg == null; -} -exports.isNullOrUndefined = isNullOrUndefined; - -function isNumber(arg) { - return typeof arg === 'number'; -} -exports.isNumber = isNumber; - -function isString(arg) { - return typeof arg === 'string'; -} -exports.isString = isString; - -function isSymbol(arg) { - return typeof arg === 'symbol'; -} -exports.isSymbol = isSymbol; - -function isUndefined(arg) { - return arg === void 0; -} -exports.isUndefined = isUndefined; - -function isRegExp(re) { - return isObject(re) && objectToString(re) === '[object RegExp]'; -} -exports.isRegExp = isRegExp; - -function isObject(arg) { - return typeof arg === 'object' && arg !== null; -} -exports.isObject = isObject; - -function isDate(d) { - return isObject(d) && objectToString(d) === '[object Date]'; -} -exports.isDate = isDate; - -function isError(e) { - return isObject(e) && - (objectToString(e) === '[object Error]' || e instanceof Error); -} -exports.isError = isError; - -function isFunction(arg) { - return typeof arg === 'function'; -} -exports.isFunction = isFunction; - -function isPrimitive(arg) { - return arg === null || - typeof arg === 'boolean' || - typeof arg === 'number' || - typeof arg === 'string' || - typeof arg === 'symbol' || // ES6 symbol - typeof arg === 'undefined'; -} -exports.isPrimitive = isPrimitive; - -exports.isBuffer = _dereq_('./support/isBuffer'); - -function objectToString(o) { - return Object.prototype.toString.call(o); -} - - -function pad(n) { - return n < 10 ? '0' + n.toString(10) : n.toString(10); -} - - -var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', - 'Oct', 'Nov', 'Dec']; - -// 26 Feb 16:19:34 -function timestamp() { - var d = new Date(); - var time = [pad(d.getHours()), - pad(d.getMinutes()), - pad(d.getSeconds())].join(':'); - return [d.getDate(), months[d.getMonth()], time].join(' '); -} - - -// log is just a thin wrapper to console.log that prepends a timestamp -exports.log = function() { - console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); -}; - - -/** - * Inherit the prototype methods from one constructor into another. - * - * The Function.prototype.inherits from lang.js rewritten as a standalone - * function (not on Function.prototype). NOTE: If this file is to be loaded - * during bootstrapping this function needs to be rewritten using some native - * functions as prototype setup using normal JavaScript does not work as - * expected during bootstrapping (see mirror.js in r114903). - * - * @param {function} ctor Constructor function which needs to inherit the - * prototype. - * @param {function} superCtor Constructor function to inherit prototype from. - */ -exports.inherits = _dereq_('inherits'); - -exports._extend = function(origin, add) { - // Don't do anything if add isn't an object - if (!add || !isObject(add)) return origin; - - var keys = Object.keys(add); - var i = keys.length; - while (i--) { - origin[keys[i]] = add[keys[i]]; - } - return origin; -}; - -function hasOwnProperty(obj, prop) { - return Object.prototype.hasOwnProperty.call(obj, prop); -} - -}).call(this,_dereq_("Zbi7gb"),typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"./support/isBuffer":59,"Zbi7gb":39,"inherits":37}]},{},[1]) -(1) -}); \ No newline at end of file +!function(e){if("object"==typeof exports)module.exports=e();else if("function"==typeof define&&define.amd)define(e);else{var t;"undefined"!=typeof window?t=window:"undefined"!=typeof global?t=global:"undefined"!=typeof self&&(t=self),t.CleanCSS=e()}}(function(){var e;return function t(e,r,n){function i(a,s){if(!r[a]){if(!e[a]){var u="function"==typeof require&&require;if(!s&&u)return u(a,!0);if(o)return o(a,!0);throw new Error("Cannot find module '"+a+"'")}var l=r[a]={exports:{}};e[a][0].call(l.exports,function(t){var r=e[a][1][t];return i(r?r:t)},l,l.exports,t,e,r,n)}return r[a].exports}for(var o="function"==typeof require&&require,a=0;a-1?r:r.replace(/['"]/g,""))}),E(/progid:DXImageTransform\.Microsoft\.(Alpha|Chroma)(\([^\)]+\))([;}'"])/g,function(e,t,r,n){return t.toLowerCase()+r+n}),E(function(){e=x.escape(e)}),E(/\[([^\]]+)\]/g,function(e,t){var r=t.indexOf("="),n=t.indexOf("'"),i=t.indexOf('"');if(0>r&&0>n&&0>i)return e;if(0===n||0===i)return e;var o=t.substring(0,r),a=t.substring(r+1,t.length);return/^['"](?:[a-zA-Z][a-zA-Z\d\-_]+)['"]$/.test(a)?"["+o+"="+a.substring(1,a.length-1)+"]":e}),E(function(){e=k.escape(e)}),E(function(){e=_.escape(e)}),E(/\[([^\]]+)\]/g,function(e){return e.replace(/\s/g,"")}),E(/[\r]?\n/g," "),E(/[\t ]+/g," "),E(/;[ ]?;+/g,";"),E(/ (?:\r\n|\n)/g,y),E(/(?:\r\n|\n)+/g,y),E(/ ([+~>]) /g,"$1"),E(/([!\(\{\}:;=,\n]) /g,"$1"),E(/ ([!\)\{\};=,\n])/g,"$1"),E(/(?:\r\n|\n)\}/g,"}"),E(/([\{;,])(?:\r\n|\n)/g,"$1"),E(/ :([^\{\};]+)([;}])/g,":$1$2"),E(/progid:[^(]+\(([^\)]+)/g,function(e){return e.replace(/,/g,", ")}),E(/;\}/g,"}"),E(function(){e=new o(e).process()}),E(function(){e=new a(e).process()}),E(function(){e=new s(e).process()}),E(function(){e=new i(e).process()}),E(/(font\-weight|font):(normal|bold)([ ;\}!])(\w*)/g,function(e,t,r,n,i){return" "==n&&i.length>0&&!/[.\d]/.test(i)?e:"normal"==r?t+":400"+n+i:"bold"==r?t+":700"+n+i:e});var I=/(\s|:|,|\()\-0([^\.])/g;E(I,"$10$2"),E(I,"$10$2"),E(/(\s|:|,)0+([1-9])/g,"$1$2"),E(/\.(\d{3,})px/g,function(e,t){return"."+Math.round(100*parseFloat("."+t))+"px"}),E(/(\D)\.0+(,|\}|\))/g,"$10$2"),E(/\.([1-9]*)0+(\D)/g,function(e,t,r){return(t.length>0?".":"")+t+r});var A=["px","em","ex","cm","mm","in","pt","pc","%"];if(-1==["ie7","ie8"].indexOf(v.compatibility)&&A.push("rem"),E(new RegExp("(\\s|:|,)\\-?0(?:"+A.join("|")+")","g"),"$10"),E(new RegExp("(\\s|:|,)\\-?(\\d)\\.(\\D)","g"),"$1$2$3"),E(new RegExp("rect\\(0(?:"+A.join("|")+")","g"),"rect(0"),E(/(rgb|rgba|hsl|hsla)\(([^\)]+)\)/g,function(e,t,r){var n=r.split(","),i="hsl"==t||"hsla"==t||n[0].indexOf("%")>-1;return i?(-1==n[1].indexOf("%")&&(n[1]+="%"),-1==n[2].indexOf("%")&&(n[2]+="%"),t+"("+n.join(",")+")"):e}),E(/outline:none/g,"outline:0"),E(/background:(?:none|transparent)([;}])/g,"background:0 0$1"),E(/box-shadow:0 0 0( 0)?([^\.])/g,"box-shadow:0 0$2"),E(/:0 0 0 0([^\.])/g,":0$1"),E(/([: ,=\-])0\.(\d)/g,"$1.$2"),E(/rect\(\s?0(\s|,)0[ ,]0[ ,]0\s?\)/g,"rect(0$10$10$10)"),E(/\*([\.#:\[])/g,"$1"),E(/calc\([^\}]+\}/g,function(e){return e.replace(/\+/g," + ")}),E(/(rgba|hsla)\(([^\)]+)\) /g,"$1($2)"),v.noAdvanced?v.keepBreaks&&E(/\}/g,"}"+y):E(function(){e=new m(e,b,{keepBreaks:v.keepBreaks,lineBreak:y,compatibility:v.compatibility}).process()}),E(function(){e=_.restore(e)}),E(function(){e=v.noRebase?e:new l(v,b).process(e)}),E(function(){e=k.restore(e)}),E(function(){e=w.restore(e)}),E(function(){e=x.restore(e)}),E(function(){var t=e.match(/@charset [^;]+;/),r=t?t[0]:null;r&&(e=r+(v.keepBreaks?y:"")+e.replace(new RegExp("@charset [^;]+;("+y+")?","g"),"").trim())}),v.noAdvanced&&E(function(){e=new f(e).process()}),e=e.trim(),v.debug){var j=r.hrtime(n);u.timeSpent=~~(1e3*j[0]+j[1]/1e6),u.efficiency=1-e.length/u.originalSize,u.minifiedSize=e.length}return t?t.call(this,this.context.errors.length>0?this.context.errors:null,e):e}}).call(this,e("Zbi7gb"),e("buffer").Buffer)},{"./colors/hsl-to-hex":3,"./colors/long-to-short-hex":4,"./colors/rgb-to-hex":5,"./colors/shortener":6,"./images/url-rebase":7,"./imports/inliner":9,"./selectors/empty-removal":17,"./selectors/optimizer":18,"./text/comments":20,"./text/expressions":22,"./text/free":23,"./text/name-quotes":24,"./text/urls":26,Zbi7gb:39,buffer:28}],3:[function(e,t){t.exports=function(e){var t=function(e,t,n){var i,o,a;if(e%=360,0>e&&(e+=360),e=~~e/360,0>t?t=0:t>100&&(t=100),t=~~t/100,0>n?n=0:n>100&&(n=100),n=~~n/100,0===t)i=o=a=n;else{var s=.5>n?n*(1+t):n+t-n*t,u=2*n-s;i=r(u,s,e+1/3),o=r(u,s,e),a=r(u,s,e-1/3)}return[~~(255*i),~~(255*o),~~(255*a)]},r=function(e,t,r){return 0>r&&(r+=1),r>1&&(r-=1),1/6>r?e+6*(t-e)*r:.5>r?t:2/3>r?e+(t-e)*(2/3-r)*6:e};return{process:function(){return e.replace(/hsl\((-?\d+),(-?\d+)%?,(-?\d+)%?\)/g,function(e,r,n,i){var o=t(r,n,i),a=o[0].toString(16),s=o[1].toString(16),u=o[2].toString(16);return"#"+((1==a.length?"0":"")+a)+((1==s.length?"0":"")+s)+((1==u.length?"0":"")+u)})}}}},{}],4:[function(e,t){t.exports=function(e){return{process:function(){return e.replace(/([,: \(])#([0-9a-f]{6})/gi,function(e,t,r){return r[0]==r[1]&&r[2]==r[3]&&r[4]==r[5]?t+"#"+r[0]+r[2]+r[4]:t+"#"+r})}}}},{}],5:[function(e,t){t.exports=function(e){return{process:function(){return e.replace(/rgb\((\-?\d+),(\-?\d+),(\-?\d+)\)/g,function(e,t,r,n){return t=Math.max(0,Math.min(~~t,255)),r=Math.max(0,Math.min(~~r,255)),n=Math.max(0,Math.min(~~n,255)),"#"+("00000"+(t<<16|r<<8|n).toString(16)).slice(-6)})}}}},{}],6:[function(e,t){t.exports=function(e){var t={aliceblue:"#f0f8ff",antiquewhite:"#faebd7",aqua:"#0ff",aquamarine:"#7fffd4",azure:"#f0ffff",beige:"#f5f5dc",bisque:"#ffe4c4",black:"#000",blanchedalmond:"#ffebcd",blue:"#00f",blueviolet:"#8a2be2",brown:"#a52a2a",burlywood:"#deb887",cadetblue:"#5f9ea0",chartreuse:"#7fff00",chocolate:"#d2691e",coral:"#ff7f50",cornflowerblue:"#6495ed",cornsilk:"#fff8dc",crimson:"#dc143c",cyan:"#0ff",darkblue:"#00008b",darkcyan:"#008b8b",darkgoldenrod:"#b8860b",darkgray:"#a9a9a9",darkgreen:"#006400",darkkhaki:"#bdb76b",darkmagenta:"#8b008b",darkolivegreen:"#556b2f",darkorange:"#ff8c00",darkorchid:"#9932cc",darkred:"#8b0000",darksalmon:"#e9967a",darkseagreen:"#8fbc8f",darkslateblue:"#483d8b",darkslategray:"#2f4f4f",darkturquoise:"#00ced1",darkviolet:"#9400d3",deeppink:"#ff1493",deepskyblue:"#00bfff",dimgray:"#696969",dodgerblue:"#1e90ff",firebrick:"#b22222",floralwhite:"#fffaf0",forestgreen:"#228b22",fuchsia:"#f0f",gainsboro:"#dcdcdc",ghostwhite:"#f8f8ff",gold:"#ffd700",goldenrod:"#daa520",gray:"#808080",green:"#008000",greenyellow:"#adff2f",honeydew:"#f0fff0",hotpink:"#ff69b4",indianred:"#cd5c5c",indigo:"#4b0082",ivory:"#fffff0",khaki:"#f0e68c",lavender:"#e6e6fa",lavenderblush:"#fff0f5",lawngreen:"#7cfc00",lemonchiffon:"#fffacd",lightblue:"#add8e6",lightcoral:"#f08080",lightcyan:"#e0ffff",lightgoldenrodyellow:"#fafad2",lightgray:"#d3d3d3",lightgreen:"#90ee90",lightpink:"#ffb6c1",lightsalmon:"#ffa07a",lightseagreen:"#20b2aa",lightskyblue:"#87cefa",lightslategray:"#778899",lightsteelblue:"#b0c4de",lightyellow:"#ffffe0",lime:"#0f0",limegreen:"#32cd32",linen:"#faf0e6",magenta:"#ff00ff",maroon:"#800000",mediumaquamarine:"#66cdaa",mediumblue:"#0000cd",mediumorchid:"#ba55d3",mediumpurple:"#9370db",mediumseagreen:"#3cb371",mediumslateblue:"#7b68ee",mediumspringgreen:"#00fa9a",mediumturquoise:"#48d1cc",mediumvioletred:"#c71585",midnightblue:"#191970",mintcream:"#f5fffa",mistyrose:"#ffe4e1",moccasin:"#ffe4b5",navajowhite:"#ffdead",navy:"#000080",oldlace:"#fdf5e6",olive:"#808000",olivedrab:"#6b8e23",orange:"#ffa500",orangered:"#ff4500",orchid:"#da70d6",palegoldenrod:"#eee8aa",palegreen:"#98fb98",paleturquoise:"#afeeee",palevioletred:"#db7093",papayawhip:"#ffefd5",peachpuff:"#ffdab9",peru:"#cd853f",pink:"#ffc0cb",plum:"#dda0dd",powderblue:"#b0e0e6",purple:"#800080",red:"#f00",rosybrown:"#bc8f8f",royalblue:"#4169e1",saddlebrown:"#8b4513",salmon:"#fa8072",sandybrown:"#f4a460",seagreen:"#2e8b57",seashell:"#fff5ee",sienna:"#a0522d",silver:"#c0c0c0",skyblue:"#87ceeb",slateblue:"#6a5acd",slategray:"#708090",snow:"#fffafa",springgreen:"#00ff7f",steelblue:"#4682b4",tan:"#d2b48c",teal:"#008080",thistle:"#d8bfd8",tomato:"#ff6347",turquoise:"#40e0d0",violet:"#ee82ee",wheat:"#f5deb3",white:"#fff",whitesmoke:"#f5f5f5",yellow:"#ff0",yellowgreen:"#9acd32"},r={},n={};for(var i in t){var o=t[i];i.length0?r.join("")+e.substring(o,e.length):e},_rebased:function(e,t){var o,a="/"==e[0]||".css"==e.substring(e.length-4)||0===e.indexOf("data:")||null!==/^https?:\/\//.exec(e)||null!==/__\w+__/.exec(e);return a?e:/https?:\/\//.test(t.toBase)?i.resolve(t.toBase,e):(o=t.absolute?n.resolve(n.join(t.fromBase,e)).replace(t.toBase,""):n.relative(t.toBase,n.join(t.fromBase,e)),"win32"==r.platform?o.replace(/\\/g,"/"):o)}}}).call(this,e("Zbi7gb"))},{Zbi7gb:39,path:38,url:58}],9:[function(e,t){var r=e("fs"),n=e("path"),i=e("http"),o=e("https"),a=e("url"),s=e("../images/url-rewriter"),u=function(e,t){var r={};for(var n in e)r[n]=e[n];for(var i in t)r[i]=t[i];return r};t.exports=function(e,t){var l={timeout:5e3,request:{}},f=u(l,t||{}),c=function(e,t){t._shared=t._shared||{done:[],left:[]};var r=t._shared,n=0,i=0,o=0,a=d(e),s=p(e);for(t.relativeTo=t.relativeTo||t.root,t._baseRelativeTo=t._baseRelativeTo||t.relativeTo,t.visited=t.visited||[];i0?c.apply(null,e._shared.left.shift()):e.whenDone(e._shared.done.join(""))},d=function(e){var t=/(\/\*(?!\*\/)[\s\S]*?\*\/)/,r=0,n=0,i=!1,o=function(a){var s,u=0,l=0,f=0,c=0;return i?!1:a>r&&n>a?!0:(s=e.match(t))?(r=u=s.index,l=u+s[0].length,c=l+n,f=c-s[0].length,e=e.substring(l),n=c,a>c?o(a):c>a&&a>f):(i=!0,!1)};return o},p=function(e){for(var t=d(e),r=-1;;)if(r=e.indexOf("{",r+1),-1==r||!t(r))break;return function(e){return r>-1?e>r:!1}},g=function(t,r,n,i){var o=t.substring(t.indexOf(" ",r)+1,n).trim(),a=0===o.indexOf("url("),s=a?4:0,u=/^['"]/.exec(o.substring(s,s+2)),l=u?o.indexOf(u[0],s+1):o.split(" ")[0].length,f=o.substring(s,l).replace(/['"]/g,"").replace(/\)$/,"").trim(),c=o.substring(l+1).replace(/^\)/,"").trim(),d=i.isRemote||/^(http|https):\/\//.test(f)||/^\/\//.test(f);if(i.localOnly&&d)return e.warnings.push('Ignoring remote @import declaration of "'+f+'" as no callback given.'),b(f,c,i),h(i);var p=d?m:v;return p(f,c,i)},m=function(t,r,n){var l=/^https?:\/\//.test(t)?t:a.resolve(n.relativeTo,t);if(0===l.indexOf("//")&&(l="http:"+l),n.visited.indexOf(l)>-1)return h(n);e.debug&&console.error("Inlining remote stylesheet: "+l),n.visited.push(l);var d=0===l.indexOf("http://")?i.get:o.get,p=!1,g=function(t){e.errors.push('Broken @import declaration of "'+l+'" - '+t),b(l,r,n),h(n)},v=u(a.parse(l),f.request);d(v,function(e){if(e.statusCode<200||e.statusCode>399)return g("error "+e.statusCode);if(e.statusCode>299){var t=a.resolve(l,e.headers.location);return m(t,r,n)}var i=[],o=a.parse(l);e.on("data",function(e){i.push(e.toString())}),e.on("end",function(){var e=i.join("");e=s.process(e,{toBase:l}),r.length>0&&(e="@media "+r+"{"+e+"}"),c(e,{isRemote:!0,relativeTo:o.protocol+"//"+o.host,_shared:n._shared,whenDone:n.whenDone,visited:n.visited})})}).on("error",function(e){g(e.message)}).on("timeout",function(){p||(g("timeout"),p=!0)}).setTimeout(f.timeout)},v=function(t,i,o){var a="/"==t[0]?o.root:o.relativeTo,u=n.resolve(n.join(a,t));if(!r.existsSync(u)||!r.statSync(u).isFile())return e.errors.push('Broken @import declaration of "'+t+'"'),h(o);if(o.visited.indexOf(u)>-1)return h(o);e.debug&&console.error("Inlining local stylesheet: "+u),o.visited.push(u);var l=r.readFileSync(u,"utf8"),f=n.dirname(u);return l=s.process(l,{relative:!0,fromBase:f,toBase:o._baseRelativeTo}),i.length>0&&(l="@media "+i+"{"+l+"}"),c(l,{root:o.root,relativeTo:f,_baseRelativeTo:o._baseRelativeTo,_shared:o._shared,visited:o.visited,whenDone:o.whenDone,localOnly:o.localOnly})},b=function(e,t,r){var n="@import url("+e+")"+(t.length>0?" "+t:"")+";";r._shared.done.push(n)};return{process:c}}},{"../images/url-rewriter":8,fs:27,http:32,https:36,path:38,url:58}],10:[function(e,t){var r=e("./processable"),n=e("./override-compactor"),i=e("./shorthand-compactor");t.exports=function(e){var t={"animation-delay":["animation"],"animation-direction":["animation"],"animation-duration":["animation"],"animation-fill-mode":["animation"],"animation-iteration-count":["animation"],"animation-name":["animation"],"animation-play-state":["animation"],"animation-timing-function":["animation"],"-moz-animation-delay":["-moz-animation"],"-moz-animation-direction":["-moz-animation"],"-moz-animation-duration":["-moz-animation"],"-moz-animation-fill-mode":["-moz-animation"],"-moz-animation-iteration-count":["-moz-animation"],"-moz-animation-name":["-moz-animation"],"-moz-animation-play-state":["-moz-animation"],"-moz-animation-timing-function":["-moz-animation"],"-o-animation-delay":["-o-animation"],"-o-animation-direction":["-o-animation"],"-o-animation-duration":["-o-animation"],"-o-animation-fill-mode":["-o-animation"],"-o-animation-iteration-count":["-o-animation"],"-o-animation-name":["-o-animation"],"-o-animation-play-state":["-o-animation"],"-o-animation-timing-function":["-o-animation"],"-webkit-animation-delay":["-webkit-animation"],"-webkit-animation-direction":["-webkit-animation"],"-webkit-animation-duration":["-webkit-animation"],"-webkit-animation-fill-mode":["-webkit-animation"],"-webkit-animation-iteration-count":["-webkit-animation"],"-webkit-animation-name":["-webkit-animation"],"-webkit-animation-play-state":["-webkit-animation"],"-webkit-animation-timing-function":["-webkit-animation"],"background-attachment":["background"],"background-clip":["background"],"background-color":["background"],"background-image":["background"],"background-origin":["background"],"background-position":["background"],"background-repeat":["background"],"background-size":["background"],"border-color":["border"],"border-style":["border"],"border-width":["border"],"border-bottom":["border"],"border-bottom-color":["border-bottom","border-color","border"],"border-bottom-style":["border-bottom","border-style","border"],"border-bottom-width":["border-bottom","border-width","border"],"border-left":["border"],"border-left-color":["border-left","border-color","border"],"border-left-style":["border-left","border-style","border"],"border-left-width":["border-left","border-width","border"],"border-right":["border"],"border-right-color":["border-right","border-color","border"],"border-right-style":["border-right","border-style","border"],"border-right-width":["border-right","border-width","border"],"border-top":["border"],"border-top-color":["border-top","border-color","border"],"border-top-style":["border-top","border-style","border"],"border-top-width":["border-top","border-width","border"],"font-family":["font"],"font-size":["font"],"font-style":["font"],"font-variant":["font"],"font-weight":["font"],"list-style-image":["list"],"list-style-position":["list"],"list-style-type":["list"],"margin-bottom":["margin"],"margin-left":["margin"],"margin-right":["margin"],"margin-top":["margin"],"outline-color":["outline"],"outline-style":["outline"],"outline-width":["outline"],"padding-bottom":["padding"],"padding-left":["padding"],"padding-right":["padding"],"padding-top":["padding"],"transition-delay":["transition"],"transition-duration":["transition"],"transition-property":["transition"],"transition-timing-function":["transition"],"-moz-transition-delay":["-moz-transition"],"-moz-transition-duration":["-moz-transition"],"-moz-transition-property":["-moz-transition"],"-moz-transition-timing-function":["-moz-transition"],"-o-transition-delay":["-o-transition"],"-o-transition-duration":["-o-transition"],"-o-transition-property":["-o-transition"],"-o-transition-timing-function":["-o-transition"],"-webkit-transition-delay":["-webkit-transition"],"-webkit-transition-duration":["-webkit-transition"],"-webkit-transition-property":["-webkit-transition"],"-webkit-transition-timing-function":["-webkit-transition"]},o="\\9",a={};for(var s in t)for(var u=0;un;n++){var a=t[n];if(""!==a){var s=a.indexOf(":");r.push([a.substring(0,s),a.substring(s+1),a.indexOf("!important")>-1,a.indexOf(o,s+1)>0])}}return r}},h=function(r,n){var i=[],o=[],s=null,u={},l=function(e,t){for(var r=a[e],n=0,s=r.length;s>n;n++)for(var u=0;u-1};e:for(var c=0,h=r.length;h>c;c++){var d=r[c],p=d[0],g=d[2],m=d[3],v=!("-ms-filter"!=p&&"filter"!=p||"background"!=s&&"background-image"!=s)?s:p,b=0;if(e||!m){if(v!=s||f(c))for(;;){if(b=o.indexOf(v,b),-1==b)break;var y=i[b],w=y[2],x=y[3];if(w&&!g)continue e;if(e&&!x&&m)break;i.splice(b,1),o.splice(b,1)}i.push(d),o.push(v),u[v]&&l(v,g);for(var k=0,_=t[v]||[],O=_.length;O>k;k++)u[_[k]]=!0;s=v}}return i},d=function(e){for(var t=[],r=0,n=e.length;n>r;r++)t.push(e[r][0]+":"+e[r][1]);return t.join(";")},p=function(e){var t=r.processable,o=r.Token,a=o.tokenize(e);return a=n.compactOverrides(a,t),a=i.compactShorthands(a,!1,t,o),a=i.compactShorthands(a,!0,t,o),o.detokenize(a)};return{process:function(e,t,r){var n=e,i=c(e);if(i){var o=h(i,t);n=d(o)}return r||(n=p(n)),n}}}},{"./override-compactor":11,"./processable":12,"./shorthand-compactor":14}],11:[function(e,t){t.exports=function(){var e=function(e,t){return e===t},t=function(t,r){var n,i,o,a,s,u,l,f,c=function(e){return e.prop===o.prop},h=function(e){return e.prop===a.prop};for(n=t,s=0;(u=n.length-1-s)>=0;s++){o=n[u],i=r[o.prop]&&r[o.prop].canOverride||e,l=n,n=[];for(var d=!1,p=l.length,g=0;p>g;g++)if(a=l[g],a!==o||d)if(g>u&&!o.isImportant)n.push(a);else if(!a.isImportant||o.isImportant)if(o.isShorthand&&!a.isShorthand&&a.isComponentOf(o))f=o.components.filter(h)[0],i=r[a.prop]&&r[a.prop].canOverride||e,i(a.value,f.value)||n.push(a);else if(a.isShorthand&&!o.isShorthand&&o.isComponentOf(a))f=a.components.filter(c)[0],i(f.value,o.value)&&(o.isImportant?f.isIrrelevant=!0:(f.value=o.value,d=!0),a.isDirty=!0),n.push(a);else if(o.isShorthand&&a.isShorthand&&o.prop===a.prop){for(var m=0;m4)return[t];i.lengtho;o++){var a=e[o];r+=a,"("===a?n++:")"===a?(n--,0===n&&(t.push(r.trim()),r="")):" "===a&&0===n&&(t.push(r.trim()),r="")}return r&&(t.push(r.trim()),r=""),t}),i.background=function(e){var t=c.makeDefaults(["background-color","background-image","background-repeat","background-position","background-attachment"],e.isImportant),n=t[0],i=t[1],o=t[2],a=t[3],s=t[4];if("inherit"===e.value)return n.value=i.value=o.value=a.value=s.value="inherit",t;var u=e.value.split(" ");if(0===u.length)return t;var l=u.length-1,f=u[l];r.isValidBackgroundAttachment(f)&&(s.value=f,l--,f=u[l]);var h=u[l-1]+" "+u[l];l>=1&&r.isValidBackgroundPosition(h)?(a.value=h,l-=2,f=u[l]):l>=0&&r.isValidBackgroundPosition(f)&&(a.value=f,l--,f=u[l]),l>=0&&r.isValidBackgroundRepeat(f)&&(o.value=f,l--,f=u[l]);var d=0;return r.isValidColor(u[0])&&(n.value=u[0],d=1),i.value=u.splice(d,l-d+1).join(" ")||"none",t},i.listStyle=function(e){var t=c.makeDefaults(["list-style-type","list-style-position","list-style-image"],e.isImportant),n=t[0],i=t[1],o=t[2];if("inherit"===e.value)return n.value=i.value=o.value="inherit",t;var a=e.value.split(" "),s=0;return s=1&&(a=s.filter(function(e){return"inherit"!==e&&r.isValidOutlineWidth(e)}),a.length&&(o.value=a[0],s.splice(s.indexOf(a[0]),1))),s.length>=1&&(a=s.filter(function(e){return"inherit"!==e&&r.isValidOutlineStyle(e)}),a.length&&(i.value=a[0],s.splice(s.indexOf(a[0]),1))),s.length>=1&&(a=s.filter(function(e){return r.isValidOutlineColor(e)}),a.length&&(n.value=a[0],s.splice(s.indexOf(a[0]),1))),t)};var o={fourUnits:function(e,t,r){t[0].isIrrelevant&&(t[0].value=t[2].value),t[2].isIrrelevant&&(t[2].value=t[0].value),t[1].isIrrelevant&&(t[1].value=t[3].value),t[3].isIrrelevant&&(t[3].value=t[1].value),t[0].isIrrelevant&&t[2].isIrrelevant&&(t[0].value=t[2].value=t[1].value===t[3].value?t[1].value:"0"),t[1].isIrrelevant&&t[3].isIrrelevant&&(t[1].value=t[3].value=t[0].value===t[2].value?t[0].value:"0");var n=new c(e,t[0].value,r);return n.granularValues=[],n.granularValues[t[0].prop]=t[0].value,n.granularValues[t[1].prop]=t[1].value,n.granularValues[t[2].prop]=t[2].value,n.granularValues[t[3].prop]=t[3].value,t[0].isIrrelevant&&t[1].isIrrelevant&&t[2].isIrrelevant&&t[3].isIrrelevant?(n.value=a[e].shortestValue||a[e].defaultValue,n):t[0].value===t[1].value&&t[0].value===t[2].value&&t[0].value===t[3].value?n:(n.value+=" "+t[1].value,t[0].value===t[2].value&&t[1].value===t[3].value?n:(n.value+=" "+t[2].value,t[1].value===t[3].value?n:(n.value+=" "+t[3].value,n)))},bySpacesOmitDefaults:function(e,t,r){var n=new c(e,"",r),i=t.filter(function(e){return e.isIrrelevant});if(i.length===t.length)return n.isIrrelevant=!0,n.value=a[e].shortestValue||a[e].defaultValue,n;for(var o=a[e].defaultValue,s=0;s0){var l=[new c(t,"inherit",n)].concat(a),f=[e(t,s,n)].concat(o),h=c.getDetokenizedLength(l),d=c.getDetokenizedLength(f);return d>h?l:f}return e(t,r,n)}}},a={color:{canOverride:n.color,defaultValue:"transparent",shortestValue:"red"},background:{components:["background-color","background-image","background-repeat","background-position","background-attachment"],breakUp:i.background,putTogether:o.takeCareOfInherit(o.bySpacesOmitDefaults),defaultValue:"0 0",shortestValue:"0"},"background-color":{canOverride:n.color,defaultValue:"transparent",shortestValue:"red"},"background-image":{canOverride:n.backgroundImage,defaultValue:"none"},"background-repeat":{canOverride:n.always,defaultValue:"repeat"},"background-position":{canOverride:n.always,defaultValue:"0 0",shortestValue:"0"},"background-attachment":{canOverride:n.always,defaultValue:"scroll"},"list-style":{components:["list-style-type","list-style-position","list-style-image"],canOverride:n.always,breakUp:i.listStyle,putTogether:o.takeCareOfInherit(o.bySpacesOmitDefaults),defaultValue:"outside",shortestValue:"none"},"list-style-type":{canOverride:n.always,shortestValue:"none",defaultValue:"__hack"},"list-style-position":{canOverride:n.always,defaultValue:"outside",shortestValue:"inside"},"list-style-image":{canOverride:n.always,defaultValue:"none"},outline:{components:["outline-color","outline-style","outline-width"],breakUp:i.outline,putTogether:o.takeCareOfInherit(o.bySpacesOmitDefaults),defaultValue:"0"},"outline-color":{canOverride:n.color,defaultValue:"invert",shortestValue:"red"},"outline-style":{canOverride:n.always,defaultValue:"none"},"outline-width":{canOverride:n.unit,defaultValue:"medium",shortestValue:"0"}},s=function(e,t,r,s,u,l,f){a[e]={components:t,breakUp:r||i.fourUnits,putTogether:s||o.takeCareOfInherit(o.fourUnits),defaultValue:l||"0",shortestValue:f};for(var c=0;c=0){var x=y.value.substring(0,w);g?v=v&&x===g:g=x}}if(!m||!v)return!1}var k=n[o].putTogether(o,f,r);k instanceof Array||(k=[k]);var _=i.getDetokenizedLength(k),O=i.getDetokenizedLength(c);if(c.length===n[o].components.length||O>_||f.some(e)){for(k[0].isShorthand=!0,k[0].components=n[o].breakUp(k[0]),a=0;a=0:!1},t.prototype.clone=function(e){var r=new t(this.prop,this.value,"undefined"!=typeof e?e:this.isImportant);return r},t.prototype.cloneIrrelevant=function(e){var r=t.makeDefault(this.prop,"undefined"!=typeof e?e:this.isImportant);return r.isIrrelevant=!0,r},t.makeDefaults=function(e,r){return e.map(function(e){return new t(e,r)})},t.tokenizeOne=function(n){var i=n.indexOf(":");if(0>i)return new t("",n);var o=n.substr(0,i).trim(),a=n.substr(i+1).trim(),s=!1,u=a.indexOf(r);u>=1&&u===a.length-r.length&&(a=a.substr(0,u).trim(),s=!0);var l=new t(o,a,s);return e[o]&&e[o].isShorthand&&(l.isShorthand=!0,l.components=e[o].breakUp(l),l.isDirty=!0),l},t.tokenize=function(e){var r=e.split(";").map(t.tokenizeOne);return r},t.detokenize=function(t){t instanceof Array||(t=[t]);for(var n=0;n0&&0===e.indexOf("rgba(")&&e.indexOf(")")===e.length-1},isValidHslaColor:function(e){return e=e.split(" ").join(""),e.length>0&&0===e.indexOf("hsla(")&&e.indexOf(")")===e.length-1},isValidNamedColor:function(e){return"auto"!==e&&("transparent"===e||"inherit"===e||/^[a-zA-Z]+$/.test(e))},isValidColor:function(e){return h.isValidNamedColor(e)||h.isValidHexColor(e)||h.isValidRgbaColor(e)||h.isValidHslaColor(e)},isValidUrl:function(e){return 0===e.indexOf("__ESCAPED_URL_CLEAN_CSS")},isValidUnit:function(e){return new RegExp("^"+i+"$","gi").test(e)},isValidUnitWithoutFunction:function(t){return new RegExp("^"+e+"$","gi").test(t)},isValidFunctionWithoutVendorPrefix:function(e){return new RegExp("^"+t+"$","gi").test(e)},isValidFunctionWithVendorPrefix:function(e){return new RegExp("^"+r+"$","gi").test(e)},isValidFunction:function(e){return new RegExp("^"+n+"$","gi").test(e)},isValidBackgroundRepeat:function(e){return o.indexOf(e)>=0},isValidBackgroundAttachment:function(e){return a.indexOf(e)>=0},isValidBackgroundPositionPart:function(t){return s.indexOf(t)>=0?!0:new RegExp("^"+e+"$","gi").test(t)},isValidBackgroundPosition:function(e){return"inherit"===e?!0:e.split(" ").filter(function(e){return""!==e}).every(function(e){return h.isValidBackgroundPositionPart(e)})},isValidListStyleType:function(e){return u.indexOf(e)>=0},isValidListStylePosition:function(e){return l.indexOf(e)>=0},isValidOutlineColor:function(e){return"invert"===e||h.isValidColor(e)||h.isValidVendorPrefixedValue(e)},isValidOutlineStyle:function(e){return f.indexOf(e)>=0},isValidOutlineWidth:function(e){return h.isValidUnit(e)||c.indexOf(e)>=0},isValidVendorPrefixedValue:function(e){return/^-([A-Za-z0-9]|-)*$/gi.test(e)},areSameFunction:function(e,t){if(!h.isValidFunction(e)||!h.isValidFunction(t))return!1;var r=e.substring(0,e.indexOf("(")),n=t.substring(0,t.indexOf("("));return r===n}};return h.cssUnitRegexStr=e,h.cssFunctionNoVendorRegexStr=t,h.cssFunctionVendorRegexStr=r,h.cssFunctionAnyRegexStr=n,h.cssUnitAnyRegexStr=i,h}()},{}],17:[function(e,t){t.exports=function(e){var t=function(e){for(var r=[],n=0,i=0;n0?t(r.join("")+e.substring(i,e.length)):e};return{process:function(){return t(e)}}}},{}],18:[function(e,t){var r=e("./tokenizer"),n=e("../properties/optimizer");t.exports=function(e,t,i){var o={"*":/\-(moz|ms|o|webkit)\-/,ie8:/(\-moz\-|\-ms\-|\-o\-|\-webkit\-|:root|:nth|:first\-of|:last|:only|:empty|:target|:checked|::selection|:enabled|:disabled|:not)/,ie7:/(\-moz\-|\-ms\-|\-o\-|\-webkit\-|:focus|:before|:after|:root|:nth|:first\-of|:last|:only|:empty|:target|:checked|::selection|:enabled|:disabled|:not)/},a=[],s=new n(i.compatibility),u=function(e){if(-1==e.indexOf(","))return e;for(var t=[],r=0,n=0,i=-1==e.indexOf("("),o=function(t){if(i)return!1;var r=e.lastIndexOf("(",t),n=e.lastIndexOf(")",t);return-1==r?!1:n>0&&t>n?!1:!0};;){var a,s=e.indexOf(",",r+1);if(-1===s)s=e.length;else if(o(s)){r=s+1;continue}if(a=e.substring(n,s),n=r=s+1,-1==t.indexOf(a)&&t.push(a),s===e.length)break}return t.sort().join(",")},l=function(e){return o[i.compatibility||"*"].test(e)},f=function(e){for(var t={},r=[],n=0,i=e.length;i>n;n++){var o=e[n];if("string"!=typeof o&&!o.block){var s=o.body+"@"+o.selector,u=t[s];u?(r.push(u[0]),u.unshift(n)):t[s]=[n]}}r=r.sort(function(e,t){return e>t?1:-1});for(var l=0,f=r.length;f>l;l++)e.splice(r[l]-l,1);a.unshift(r.length>0)},c=function(e){for(var t=[],r={selector:null,body:null},n=0,i=e.length;i>n;n++){var o=e[n];if("string"!=typeof o&&!o.block)if(o.selector==r.selector){var f=[r.body.split(";").length];r.body=s.process(r.body+";"+o.body,f),t.push(n)}else o.body!=r.body||l(o.selector)||l(r.selector)?r=o:(r.selector=u(r.selector+","+o.selector),t.push(n))}for(var c=0,h=t.length;h>c;c++)e.splice(t[c]-c,1);a.unshift(t.length>0)},h=function(e){for(var t={},r=[],n=e.length-1;n>=0;n--){var i=e[n];if("string"!=typeof i&&!i.block)for(var o=i.selector,s=o.indexOf(",")>-1&&!l(o)?o.split(",").concat(o):[o],u=0,f=s.length;f>u;u++){var c=s[u];t[c]?r.push(c):t[c]=[],t[c].push({where:n,partial:c!=o})}}var h=d(e,r,t),g=p(e,t);a.unshift(h||g)},d=function(e,t,r){for(var n=!1,i=0,o=t.length;o>i;i++){var a=t[i],s=r[a];s.length<2||g(e,a,s,{filterOut:function(e,t){return s[e].partial&&0===t.length},callback:function(e,t,r,i){s[r-i-1].partial||(e.body=t.join(";"),n=!0)}})}return n},p=function(e,t){var r=!1;e:for(var n in t)if(-1!=n.indexOf(",")){for(var i=t[n].pop().where,o=e[i],a=l(n)?[n]:n.split(","),s=[],u=0,f=a.length;f>u;u++){var c=a[u],h=t[c];if(h.length<2)continue e;if(g(e,c,h,{filterOut:function(e){return h[e].where=0;l--)if(!n.filterOut(l,i)){var c=r[l].where,h=e[c],d=h.body;i.push(d),a.push(d.split(";")),u.push(c)}for(l=0,f=i.length;f>l;l++)i[l].length>0&&o.push((o[l-1]||0)+a[l].length);for(var p=s.process(i.join(";"),o,!0),g=p.split(";"),m=u.length,v=g.length-1,b=m-1;b>=0;)if((0===b||a[b].indexOf(g[v])>-1)&&v>-1)v--;else{var y=g.splice(v+1);n.callback(e[u[b]],y,m,b),b--}},m=function(e){var t=function(){return a.length>4&&a[0]===!1&&a[1]===!1};e=Array.isArray(e)?e:[e];for(var r=0,n=e.length;n>r;r++){var i=e[r];i.selector?(i.selector=u(i.selector),i.body=s.process(i.body,!1)):i.block&&m(i.body)}for(a=[];;){if(t())break;if(f(e),t())break;if(c(e),t())break;h(e)}},v=function(e){var t=[];e=Array.isArray(e)?e:[e];for(var r=0,n=e.length;n>r;r++){var o=e[r];if("string"!=typeof o){var a=o.block||o.selector,s=o.block?v(o.body):o.body;s.length>0&&t.push(a+"{"+s+"}")}else t.push(o)}return t.join(i.keepBreaks?i.lineBreak:"")};return{process:function(){var n=new r(e,t).process();return m(n),v(n)}}}},{"../properties/optimizer":10,"./tokenizer":19}],19:[function(e,t){t.exports=function(e,t){var n=new r(e,128),i=n.next(),o=/^@(font\-face|page|\-ms\-viewport|\-o\-viewport|viewport)/,a=function(e){var t,r=e.cursor,o=e.mode;if(i.length==e.cursor){if(n.isEmpty())return null;i=n.next(),e.cursor=0}if("body"==o)return t=i.indexOf("}",r),t>-1?[t,"bodyEnd"]:null;var a=i.indexOf("@",e.cursor),s="top"==o?i.indexOf("__ESCAPED_COMMENT_CLEAN_CSS",e.cursor):-1,u=i.indexOf("{",e.cursor),l=i.indexOf("}",e.cursor);return t=a,(-1==t||s>-1&&t>s)&&(t=s),(-1==t||u>-1&&t>u)&&(t=u),(-1==t||l>-1&&t>l)&&(t=l),-1!=t?s===t?[t,"escape"]:u===t?[t,"bodyStart"]:l===t?[t,"bodyEnd"]:a===t?[t,"special"]:void 0:void 0},s=function(e){var r=[];for(e=e||{cursor:0,mode:"top"};;){var n=a(e);if(!n){var u=i.substring(e.cursor);u.length>0&&(r.push(u),e.cursor+=u.length);break}var l,f,c=n[0],h=n[1];if("special"==h){var d=i.substring(c,e.cursor+"@font-face".length+1),p=0===d.indexOf("@import")||0===d.indexOf("@charset");if(p)l=i.indexOf(";",c+1),r.push(i.substring(e.cursor,l+1)),e.cursor=l+1;else{l=i.indexOf("{",c+1);var g=i.substring(e.cursor,l).trim(),m=o.test(g);f=e.mode,e.cursor=l+1,e.mode=m?"body":"block";var v=s(e);e.mode=f,r.push({block:g,body:v})}}else if("escape"==h){l=i.indexOf("__",c+1);var b=i.substring(e.cursor,l+2);r.push(b),e.cursor=l+2}else if("bodyStart"==h){var y=i.substring(e.cursor,c).trim();f=e.mode,e.cursor=c+1,e.mode="body";var w=s(e);e.mode=f,r.push({selector:y,body:w})}else if("bodyEnd"==h){if("top"==e.mode){var x=e.cursor,k="}"==i[e.cursor]?"Unexpected '}' in '"+i.substring(x-20,x+20)+"'. Ignoring.":"Unexpected content: '"+i.substring(x,c+1)+"'. Ignoring.";t.warnings.push(k),e.cursor=c+1;continue}"block"!=e.mode&&(r=i.substring(e.cursor,c)),e.cursor=c+1;break}}return r};return{process:function(){return s()}}};var r=function(e,t){for(var r=[],n=0,i=e.length;i>n;){var o=n+t>i?i-1:n+t;"}"!=e[o]&&(o=e.indexOf("}",o)),-1==o&&(o=e.length-1),r.push(e.substring(n,o+1)),n=o+1}return{isEmpty:function(){return 0===r.length},next:function(){return r.shift()||""}}}},{}],20:[function(e,t){var r=e("./escape-store");t.exports=function(e,t,n){var i=new r("COMMENT");return{escape:function(e){for(var t=[],r=0,n=0,o=0;n0?t.join("")+e.substring(o,e.length):e},restore:function(r){var o=0,a=t?n:"";return r.replace(new RegExp(i.placeholderPattern+"("+n+"| )?","g"),function(t,r){switch(o++,e){case"*":return i.restore(r)+a;case 1:case"1":return 1==o?i.restore(r)+a:"";case 0:case"0":return""}})}}}},{"./escape-store":21}],21:[function(e,t){t.exports=function(e){e="ESCAPED_"+e+"_CLEAN_CSS";var t={},r={},n=0,i=function(){return"__"+e+n++ +"__"},o="(__"+e+"\\d{1,}__)";return{placeholderPattern:o,placeholderRegExp:new RegExp(o,"g"),store:function(e){var n=r[e];return n||(n=i(),t[n]=e,r[e]=n),n},restore:function(e){return t[e]}}}},{}],22:[function(e,t){var r=e("./escape-store");t.exports=function(){var e=new r("EXPRESSION"),t=function(e,t){for(var r=t+"expression".length,n=0,i=!1;;){var o=e[r++];if(i?i="'"!=o&&'"'!=o:(i="'"==o||'"'==o,"("==o&&n++,")"==o&&n--,"}"==o&&1==n&&(r--,n--)),0===n||!o)break}return r};return{escape:function(r){for(var n=0,i=0,o=0,a=[];i0?a.join("")+r.substring(o,r.length):r},restore:function(t){return t.replace(e.placeholderRegExp,e.restore)}}}},{"./escape-store":21}],23:[function(e,t){!function(){var r=e("./escape-store"),n=e("./quote-scanner"),i=function(){this.matches=new r("FREE_TEXT")};i.prototype.escape=function(e){var t=this;return new n(e).each(function(e,r){var n=t.matches.store(e);r.push(n)})},i.prototype.restore=function(e){return e.replace(this.matches.placeholderRegExp,this.matches.restore)},t.exports=i}()},{"./escape-store":21,"./quote-scanner":25}],24:[function(e,t){!function(){var r=e("./quote-scanner"),n=e("../properties/scanner"),i=function(){},o=/^['"][a-zA-Z][a-zA-Z\d\-_]+['"]$/,a=["animation","-moz-animation","-o-animation","-webkit-animation","animation-name","-moz-animation-name","-o-animation-name","-webkit-animation-name","font","font-family"];i.prototype.process=function(e){var t=new n(e);return new r(e).each(function(e,r,n){var i=t.nextAt(n);a.indexOf(i)>-1&&o.test(e)&&(e=e.substring(1,e.length-1)),r.push(e)})},t.exports=i}()},{"../properties/scanner":13,"./quote-scanner":25}],25:[function(e,t){!function(){var e=function(e){this.data=e},r=function(e,t,r){for(var n=r;;){n=e.indexOf(t,n);{if(!(n>-1&&"\\"==e[n-1]))break;n+=1}}return n};e.prototype.each=function(e){for(var t=this.data,n=[],i=0,o=0,a=0,s=null,u="'",l='"',f=t.length;oc?(i=c,s=u):(i=h,s=l),-1==i)break;if(o=r(t,s,i+1),-1==o)break;var d=t.substring(i,o+1);n.push(t.substring(a,i)),e(d,n,i),a=o+1}return n.length>0?n.join("")+t.substring(a,t.length):t},t.exports=e}()},{}],26:[function(e,t){var r=e("./escape-store");t.exports=function(){var e=new r("URL");return{escape:function(t){for(var r=0,n=0,i=0,o=[];n0?o.join("")+t.substring(i,t.length):t},restore:function(t){return t.replace(e.placeholderRegExp,function(t){return e.restore(t).replace(/\s/g,"")})}}}},{"./escape-store":21}],27:[function(){},{}],28:[function(e,t,r){function n(e,t,r){if(!(this instanceof n))return new n(e,t,r);var i=typeof e;if("base64"===t&&"string"===i)for(e=A(e);e.length%4!==0;)e+="=";var o;if("number"===i)o=C(e);else if("string"===i)o=n.byteLength(e,t);else{if("object"!==i)throw new Error("First argument needs to be a number, array or string.");o=C(e.length)}var a;n._useTypedArrays?a=n._augment(new Uint8Array(o)):(a=this,a.length=o,a._isBuffer=!0);var s;if(n._useTypedArrays&&"number"==typeof e.byteLength)a._set(e);else if(B(e))for(s=0;o>s;s++)a[s]=n.isBuffer(e)?e.readUInt8(s):e[s];else if("string"===i)a.write(e,0,t);else if("number"===i&&!n._useTypedArrays&&!r)for(s=0;o>s;s++)a[s]=0;return a}function i(e,t,r,n){r=Number(r)||0;var i=e.length-r;n?(n=Number(n),n>i&&(n=i)):n=i;var o=t.length;N(o%2===0,"Invalid hex string"),n>o/2&&(n=o/2);for(var a=0;n>a;a++){var s=parseInt(t.substr(2*a,2),16);N(!isNaN(s),"Invalid hex string"),e[r+a]=s}return a}function o(e,t,r,n){var i=z(V(t),e,r,n);return i}function a(e,t,r,n){var i=z(T(t),e,r,n);return i}function s(e,t,r,n){return a(e,t,r,n)}function u(e,t,r,n){var i=z(U(t),e,r,n);return i}function l(e,t,r,n){var i=z(M(t),e,r,n);return i}function f(e,t,r){return $.fromByteArray(0===t&&r===e.length?e:e.slice(t,r))}function c(e,t,r){var n="",i="";r=Math.min(e.length,r);for(var o=t;r>o;o++)e[o]<=127?(n+=D(i)+String.fromCharCode(e[o]),i=""):i+="%"+e[o].toString(16);return n+D(i)}function h(e,t,r){var n="";r=Math.min(e.length,r);for(var i=t;r>i;i++)n+=String.fromCharCode(e[i]);return n}function d(e,t,r){return h(e,t,r)}function p(e,t,r){var n=e.length;(!t||0>t)&&(t=0),(!r||0>r||r>n)&&(r=n);for(var i="",o=t;r>o;o++)i+=R(e[o]);return i}function g(e,t,r){for(var n=e.slice(t,r),i="",o=0;o=i)){var o;return r?(o=e[t],i>t+1&&(o|=e[t+1]<<8)):(o=e[t]<<8,i>t+1&&(o|=e[t+1])),o}}function v(e,t,r,n){n||(N("boolean"==typeof r,"missing or invalid endian"),N(void 0!==t&&null!==t,"missing offset"),N(t+3=i)){var o;return r?(i>t+2&&(o=e[t+2]<<16),i>t+1&&(o|=e[t+1]<<8),o|=e[t],i>t+3&&(o+=e[t+3]<<24>>>0)):(i>t+1&&(o=e[t+1]<<16),i>t+2&&(o|=e[t+2]<<8),i>t+3&&(o|=e[t+3]),o+=e[t]<<24>>>0),o}}function b(e,t,r,n){n||(N("boolean"==typeof r,"missing or invalid endian"),N(void 0!==t&&null!==t,"missing offset"),N(t+1=i)){var o=m(e,t,r,!0),a=32768&o;return a?-1*(65535-o+1):o}}function y(e,t,r,n){n||(N("boolean"==typeof r,"missing or invalid endian"),N(void 0!==t&&null!==t,"missing offset"),N(t+3=i)){var o=v(e,t,r,!0),a=2147483648&o;return a?-1*(4294967295-o+1):o}}function w(e,t,r,n){return n||(N("boolean"==typeof r,"missing or invalid endian"),N(t+3=o)){for(var a=0,s=Math.min(o-r,2);s>a;a++)e[r+a]=(t&255<<8*(n?a:1-a))>>>8*(n?a:1-a);return r+2}}function _(e,t,r,n,i){i||(N(void 0!==t&&null!==t,"missing value"),N("boolean"==typeof n,"missing or invalid endian"),N(void 0!==r&&null!==r,"missing offset"),N(r+3=o)){for(var a=0,s=Math.min(o-r,4);s>a;a++)e[r+a]=t>>>8*(n?a:3-a)&255;return r+4}}function O(e,t,r,n,i){i||(N(void 0!==t&&null!==t,"missing value"),N("boolean"==typeof n,"missing or invalid endian"),N(void 0!==r&&null!==r,"missing offset"),N(r+1=o))return t>=0?k(e,t,r,n,i):k(e,65535+t+1,r,n,i),r+2}function E(e,t,r,n,i){i||(N(void 0!==t&&null!==t,"missing value"),N("boolean"==typeof n,"missing or invalid endian"),N(void 0!==r&&null!==r,"missing offset"),N(r+3=o))return t>=0?_(e,t,r,n,i):_(e,4294967295+t+1,r,n,i),r+4}function S(e,t,r,n,i){i||(N(void 0!==t&&null!==t,"missing value"),N("boolean"==typeof n,"missing or invalid endian"),N(void 0!==r&&null!==r,"missing offset"),N(r+3=o))return H.write(e,t,r,n,23,4),r+4}function I(e,t,r,n,i){i||(N(void 0!==t&&null!==t,"missing value"),N("boolean"==typeof n,"missing or invalid endian"),N(void 0!==r&&null!==r,"missing offset"),N(r+7=o))return H.write(e,t,r,n,52,8),r+8}function A(e){return e.trim?e.trim():e.replace(/^\s+|\s+$/g,"")}function j(e,t,r){return"number"!=typeof e?r:(e=~~e,e>=t?t:e>=0?e:(e+=t,e>=0?e:0))}function C(e){return e=~~Math.ceil(+e),0>e?0:e}function L(e){return(Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)})(e)}function B(e){return L(e)||n.isBuffer(e)||e&&"object"==typeof e&&"number"==typeof e.length}function R(e){return 16>e?"0"+e.toString(16):e.toString(16)}function V(e){for(var t=[],r=0;r=n)t.push(n);else{var i=r;n>=55296&&57343>=n&&r++;for(var o=encodeURIComponent(e.slice(i,r+1)).substr(1).split("%"),a=0;a>8,n=t%256,i.push(n),i.push(r);return i}function U(e){return $.toByteArray(e)}function z(e,t,r,n){for(var i=0;n>i&&!(i+r>=t.length||i>=e.length);i++)t[i+r]=e[i];return i}function D(e){try{return decodeURIComponent(e)}catch(t){return String.fromCharCode(65533)}}function q(e,t){N("number"==typeof e,"cannot write a non-number as a number"),N(e>=0,"specified a negative value for writing an unsigned value"),N(t>=e,"value is larger than maximum value for type"),N(Math.floor(e)===e,"value has a fractional component")}function F(e,t,r){N("number"==typeof e,"cannot write a non-number as a number"),N(t>=e,"value larger than maximum allowed value"),N(e>=r,"value smaller than minimum allowed value"),N(Math.floor(e)===e,"value has a fractional component")}function P(e,t,r){N("number"==typeof e,"cannot write a non-number as a number"),N(t>=e,"value larger than maximum allowed value"),N(e>=r,"value smaller than minimum allowed value")}function N(e,t){if(!e)throw new Error(t||"Failed assertion")}var $=e("base64-js"),H=e("ieee754");r.Buffer=n,r.SlowBuffer=n,r.INSPECT_MAX_BYTES=50,n.poolSize=8192,n._useTypedArrays=function(){try{var e=new ArrayBuffer(0),t=new Uint8Array(e);return t.foo=function(){return 42},42===t.foo()&&"function"==typeof t.subarray}catch(r){return!1}}(),n.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"raw":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},n.isBuffer=function(e){return!(null===e||void 0===e||!e._isBuffer)},n.byteLength=function(e,t){var r;switch(e=e.toString(),t||"utf8"){case"hex":r=e.length/2;break;case"utf8":case"utf-8":r=V(e).length;break;case"ascii":case"binary":case"raw":r=e.length;break;case"base64":r=U(e).length;break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":r=2*e.length;break;default:throw new Error("Unknown encoding")}return r},n.concat=function(e,t){if(N(L(e),"Usage: Buffer.concat(list[, length])"),0===e.length)return new n(0);if(1===e.length)return e[0];var r;if(void 0===t)for(t=0,r=0;ro&&e[o]===t[o];o++);return o!==a&&(r=e[o],i=t[o]),i>r?-1:r>i?1:0},n.prototype.write=function(e,t,r,n){if(isFinite(t))isFinite(r)||(n=r,r=void 0);else{var f=n;n=t,t=r,r=f}t=Number(t)||0;var c=this.length-t;r?(r=Number(r),r>c&&(r=c)):r=c,n=String(n||"utf8").toLowerCase();var h;switch(n){case"hex":h=i(this,e,t,r);break;case"utf8":case"utf-8":h=o(this,e,t,r);break;case"ascii":h=a(this,e,t,r);break;case"binary":h=s(this,e,t,r);break;case"base64":h=u(this,e,t,r);break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":h=l(this,e,t,r);break;default:throw new Error("Unknown encoding")}return h},n.prototype.toString=function(e,t,r){var n=this;if(e=String(e||"utf8").toLowerCase(),t=Number(t)||0,r=void 0===r?n.length:Number(r),r===t)return"";var i;switch(e){case"hex":i=p(n,t,r);break;case"utf8":case"utf-8":i=c(n,t,r);break;case"ascii":i=h(n,t,r);break;case"binary":i=d(n,t,r);break;case"base64":i=f(n,t,r);break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":i=g(n,t,r);break;default:throw new Error("Unknown encoding")}return i},n.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}},n.prototype.equals=function(e){return N(n.isBuffer(e),"Argument must be a Buffer"),0===n.compare(this,e)},n.prototype.compare=function(e){return N(n.isBuffer(e),"Argument must be a Buffer"),n.compare(this,e)},n.prototype.copy=function(e,t,r,i){var o=this;if(r||(r=0),i||0===i||(i=this.length),t||(t=0),i!==r&&0!==e.length&&0!==o.length){N(i>=r,"sourceEnd < sourceStart"),N(t>=0&&t=0&&r=0&&i<=o.length,"sourceEnd out of bounds"),i>this.length&&(i=this.length),e.length-ta||!n._useTypedArrays)for(var s=0;a>s;s++)e[s+t]=this[s+r];else e._set(this.subarray(r,r+a),t)}},n.prototype.slice=function(e,t){var r=this.length;if(e=j(e,r,0),t=j(t,r,r),n._useTypedArrays)return n._augment(this.subarray(e,t));for(var i=t-e,o=new n(i,void 0,!0),a=0;i>a;a++)o[a]=this[a+e];return o},n.prototype.get=function(e){return console.log(".get() is deprecated. Access using array indexes instead."),this.readUInt8(e)},n.prototype.set=function(e,t){return console.log(".set() is deprecated. Access using array indexes instead."),this.writeUInt8(e,t)},n.prototype.readUInt8=function(e,t){return t||(N(void 0!==e&&null!==e,"missing offset"),N(e=this.length?void 0:this[e]},n.prototype.readUInt16LE=function(e,t){return m(this,e,!0,t)},n.prototype.readUInt16BE=function(e,t){return m(this,e,!1,t)},n.prototype.readUInt32LE=function(e,t){return v(this,e,!0,t)},n.prototype.readUInt32BE=function(e,t){return v(this,e,!1,t)},n.prototype.readInt8=function(e,t){if(t||(N(void 0!==e&&null!==e,"missing offset"),N(e=this.length)){var r=128&this[e];return r?-1*(255-this[e]+1):this[e]}},n.prototype.readInt16LE=function(e,t){return b(this,e,!0,t)},n.prototype.readInt16BE=function(e,t){return b(this,e,!1,t)},n.prototype.readInt32LE=function(e,t){return y(this,e,!0,t)},n.prototype.readInt32BE=function(e,t){return y(this,e,!1,t)},n.prototype.readFloatLE=function(e,t){return w(this,e,!0,t)},n.prototype.readFloatBE=function(e,t){return w(this,e,!1,t)},n.prototype.readDoubleLE=function(e,t){return x(this,e,!0,t)},n.prototype.readDoubleBE=function(e,t){return x(this,e,!1,t)},n.prototype.writeUInt8=function(e,t,r){return r||(N(void 0!==e&&null!==e,"missing value"),N(void 0!==t&&null!==t,"missing offset"),N(t=this.length?void 0:(this[t]=e,t+1)},n.prototype.writeUInt16LE=function(e,t,r){return k(this,e,t,!0,r)},n.prototype.writeUInt16BE=function(e,t,r){return k(this,e,t,!1,r)},n.prototype.writeUInt32LE=function(e,t,r){return _(this,e,t,!0,r)},n.prototype.writeUInt32BE=function(e,t,r){return _(this,e,t,!1,r)},n.prototype.writeInt8=function(e,t,r){return r||(N(void 0!==e&&null!==e,"missing value"),N(void 0!==t&&null!==t,"missing offset"),N(t=this.length?void 0:(e>=0?this.writeUInt8(e,t,r):this.writeUInt8(255+e+1,t,r),t+1)},n.prototype.writeInt16LE=function(e,t,r){return O(this,e,t,!0,r)},n.prototype.writeInt16BE=function(e,t,r){return O(this,e,t,!1,r)},n.prototype.writeInt32LE=function(e,t,r){return E(this,e,t,!0,r)},n.prototype.writeInt32BE=function(e,t,r){return E(this,e,t,!1,r)},n.prototype.writeFloatLE=function(e,t,r){return S(this,e,t,!0,r)},n.prototype.writeFloatBE=function(e,t,r){return S(this,e,t,!1,r)},n.prototype.writeDoubleLE=function(e,t,r){return I(this,e,t,!0,r)},n.prototype.writeDoubleBE=function(e,t,r){return I(this,e,t,!1,r)},n.prototype.fill=function(e,t,r){if(e||(e=0),t||(t=0),r||(r=this.length),N(r>=t,"end < start"),r!==t&&0!==this.length){N(t>=0&&t=0&&r<=this.length,"end out of bounds");var n;if("number"==typeof e)for(n=t;r>n;n++)this[n]=e;else{var i=V(e.toString()),o=i.length;for(n=t;r>n;n++)this[n]=i[n%o]}return this}},n.prototype.inspect=function(){for(var e=[],t=this.length,n=0;t>n;n++)if(e[n]=R(this[n]),n===r.INSPECT_MAX_BYTES){e[n+1]="...";break}return""},n.prototype.toArrayBuffer=function(){if("undefined"!=typeof Uint8Array){if(n._useTypedArrays)return new n(this).buffer;for(var e=new Uint8Array(this.length),t=0,r=e.length;r>t;t+=1)e[t]=this[t];return e.buffer}throw new Error("Buffer.toArrayBuffer not supported in this browser")};var W=n.prototype;n._augment=function(e){return e._isBuffer=!0,e._get=e.get,e._set=e.set,e.get=W.get,e.set=W.set,e.write=W.write,e.toString=W.toString,e.toLocaleString=W.toString,e.toJSON=W.toJSON,e.equals=W.equals,e.compare=W.compare,e.copy=W.copy,e.slice=W.slice,e.readUInt8=W.readUInt8,e.readUInt16LE=W.readUInt16LE,e.readUInt16BE=W.readUInt16BE,e.readUInt32LE=W.readUInt32LE,e.readUInt32BE=W.readUInt32BE,e.readInt8=W.readInt8,e.readInt16LE=W.readInt16LE,e.readInt16BE=W.readInt16BE,e.readInt32LE=W.readInt32LE,e.readInt32BE=W.readInt32BE,e.readFloatLE=W.readFloatLE,e.readFloatBE=W.readFloatBE,e.readDoubleLE=W.readDoubleLE,e.readDoubleBE=W.readDoubleBE,e.writeUInt8=W.writeUInt8,e.writeUInt16LE=W.writeUInt16LE,e.writeUInt16BE=W.writeUInt16BE,e.writeUInt32LE=W.writeUInt32LE,e.writeUInt32BE=W.writeUInt32BE,e.writeInt8=W.writeInt8,e.writeInt16LE=W.writeInt16LE,e.writeInt16BE=W.writeInt16BE,e.writeInt32LE=W.writeInt32LE,e.writeInt32BE=W.writeInt32BE,e.writeFloatLE=W.writeFloatLE,e.writeFloatBE=W.writeFloatBE,e.writeDoubleLE=W.writeDoubleLE,e.writeDoubleBE=W.writeDoubleBE,e.fill=W.fill,e.inspect=W.inspect,e.toArrayBuffer=W.toArrayBuffer,e}},{"base64-js":29,ieee754:30}],29:[function(e,t){var r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";!function(){"use strict";function e(e){var t=e.charCodeAt(0);return t===a?62:t===s?63:u>t?-1:u+10>t?t-u+26+26:f+26>t?t-f:l+26>t?t-l+26:void 0}function n(t){function r(e){l[c++]=e}var n,i,a,s,u,l;if(t.length%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var f=t.length;u="="===t.charAt(f-2)?2:"="===t.charAt(f-1)?1:0,l=new o(3*t.length/4-u),a=u>0?t.length-4:t.length;var c=0;for(n=0,i=0;a>n;n+=4,i+=3)s=e(t.charAt(n))<<18|e(t.charAt(n+1))<<12|e(t.charAt(n+2))<<6|e(t.charAt(n+3)),r((16711680&s)>>16),r((65280&s)>>8),r(255&s); +return 2===u?(s=e(t.charAt(n))<<2|e(t.charAt(n+1))>>4,r(255&s)):1===u&&(s=e(t.charAt(n))<<10|e(t.charAt(n+1))<<4|e(t.charAt(n+2))>>2,r(s>>8&255),r(255&s)),l}function i(e){function t(e){return r.charAt(e)}function n(e){return t(e>>18&63)+t(e>>12&63)+t(e>>6&63)+t(63&e)}var i,o,a,s=e.length%3,u="";for(i=0,a=e.length-s;a>i;i+=3)o=(e[i]<<16)+(e[i+1]<<8)+e[i+2],u+=n(o);switch(s){case 1:o=e[e.length-1],u+=t(o>>2),u+=t(o<<4&63),u+="==";break;case 2:o=(e[e.length-2]<<8)+e[e.length-1],u+=t(o>>10),u+=t(o>>4&63),u+=t(o<<2&63),u+="="}return u}var o="undefined"!=typeof Uint8Array?Uint8Array:Array,a=("0".charCodeAt(0),"+".charCodeAt(0)),s="/".charCodeAt(0),u="0".charCodeAt(0),l="a".charCodeAt(0),f="A".charCodeAt(0);t.exports.toByteArray=n,t.exports.fromByteArray=i}()},{}],30:[function(e,t,r){r.read=function(e,t,r,n,i){var o,a,s=8*i-n-1,u=(1<>1,f=-7,c=r?i-1:0,h=r?-1:1,d=e[t+c];for(c+=h,o=d&(1<<-f)-1,d>>=-f,f+=s;f>0;o=256*o+e[t+c],c+=h,f-=8);for(a=o&(1<<-f)-1,o>>=-f,f+=n;f>0;a=256*a+e[t+c],c+=h,f-=8);if(0===o)o=1-l;else{if(o===u)return a?0/0:1/0*(d?-1:1);a+=Math.pow(2,n),o-=l}return(d?-1:1)*a*Math.pow(2,o-n)},r.write=function(e,t,r,n,i,o){var a,s,u,l=8*o-i-1,f=(1<>1,h=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,d=n?0:o-1,p=n?1:-1,g=0>t||0===t&&0>1/t?1:0;for(t=Math.abs(t),isNaN(t)||1/0===t?(s=isNaN(t)?1:0,a=f):(a=Math.floor(Math.log(t)/Math.LN2),t*(u=Math.pow(2,-a))<1&&(a--,u*=2),t+=a+c>=1?h/u:h*Math.pow(2,1-c),t*u>=2&&(a++,u/=2),a+c>=f?(s=0,a=f):a+c>=1?(s=(t*u-1)*Math.pow(2,i),a+=c):(s=t*Math.pow(2,c-1)*Math.pow(2,i),a=0));i>=8;e[r+d]=255&s,d+=p,s/=256,i-=8);for(a=a<0;e[r+d]=255&a,d+=p,a/=256,l-=8);e[r+d-p]|=128*g}},{}],31:[function(e,t){function r(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}function n(e){return"function"==typeof e}function i(e){return"number"==typeof e}function o(e){return"object"==typeof e&&null!==e}function a(e){return void 0===e}t.exports=r,r.EventEmitter=r,r.prototype._events=void 0,r.prototype._maxListeners=void 0,r.defaultMaxListeners=10,r.prototype.setMaxListeners=function(e){if(!i(e)||0>e||isNaN(e))throw TypeError("n must be a positive number");return this._maxListeners=e,this},r.prototype.emit=function(e){var t,r,i,s,u,l;if(this._events||(this._events={}),"error"===e&&(!this._events.error||o(this._events.error)&&!this._events.error.length))throw t=arguments[1],t instanceof Error?t:TypeError('Uncaught, unspecified "error" event.');if(r=this._events[e],a(r))return!1;if(n(r))switch(arguments.length){case 1:r.call(this);break;case 2:r.call(this,arguments[1]);break;case 3:r.call(this,arguments[1],arguments[2]);break;default:for(i=arguments.length,s=new Array(i-1),u=1;i>u;u++)s[u-1]=arguments[u];r.apply(this,s)}else if(o(r)){for(i=arguments.length,s=new Array(i-1),u=1;i>u;u++)s[u-1]=arguments[u];for(l=r.slice(),i=l.length,u=0;i>u;u++)l[u].apply(this,s)}return!0},r.prototype.addListener=function(e,t){var i;if(!n(t))throw TypeError("listener must be a function");if(this._events||(this._events={}),this._events.newListener&&this.emit("newListener",e,n(t.listener)?t.listener:t),this._events[e]?o(this._events[e])?this._events[e].push(t):this._events[e]=[this._events[e],t]:this._events[e]=t,o(this._events[e])&&!this._events[e].warned){var i;i=a(this._maxListeners)?r.defaultMaxListeners:this._maxListeners,i&&i>0&&this._events[e].length>i&&(this._events[e].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[e].length),console.trace())}return this},r.prototype.on=r.prototype.addListener,r.prototype.once=function(e,t){function r(){this.removeListener(e,r),i||(i=!0,t.apply(this,arguments))}if(!n(t))throw TypeError("listener must be a function");var i=!1;return r.listener=t,this.on(e,r),this},r.prototype.removeListener=function(e,t){var r,i,a,s;if(!n(t))throw TypeError("listener must be a function");if(!this._events||!this._events[e])return this;if(r=this._events[e],a=r.length,i=-1,r===t||n(r.listener)&&r.listener===t)delete this._events[e],this._events.removeListener&&this.emit("removeListener",e,t);else if(o(r)){for(s=a;s-->0;)if(r[s]===t||r[s].listener&&r[s].listener===t){i=s;break}if(0>i)return this;1===r.length?(r.length=0,delete this._events[e]):r.splice(i,1),this._events.removeListener&&this.emit("removeListener",e,t)}return this},r.prototype.removeAllListeners=function(e){var t,r;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[e]&&delete this._events[e],this;if(0===arguments.length){for(t in this._events)"removeListener"!==t&&this.removeAllListeners(t);return this.removeAllListeners("removeListener"),this._events={},this}if(r=this._events[e],n(r))this.removeListener(e,r);else for(;r.length;)this.removeListener(e,r[r.length-1]);return delete this._events[e],this},r.prototype.listeners=function(e){var t;return t=this._events&&this._events[e]?n(this._events[e])?[this._events[e]]:this._events[e].slice():[]},r.listenerCount=function(e,t){var r;return r=e._events&&e._events[t]?n(e._events[t])?1:e._events[t].length:0}},{}],32:[function(e,t){var r=t.exports,n=(e("events").EventEmitter,e("./lib/request")),i=e("url");r.request=function(e,t){"string"==typeof e&&(e=i.parse(e)),e||(e={}),e.host||e.port||(e.port=parseInt(window.location.port,10)),!e.host&&e.hostname&&(e.host=e.hostname),e.scheme||(e.scheme=window.location.protocol.split(":")[0]),e.host||(e.host=window.location.hostname||window.location.host),/:/.test(e.host)&&(e.port||(e.port=e.host.split(":")[1]),e.host=e.host.split(":")[0]),e.port||(e.port="https"==e.scheme?443:80);var r=new n(new o,e);return t&&r.on("response",t),r},r.get=function(e,t){e.method="GET";var n=r.request(e,t);return n.end(),n},r.Agent=function(){},r.Agent.defaultMaxSockets=4;var o=function(){if("undefined"==typeof window)throw new Error("no window object present");if(window.XMLHttpRequest)return window.XMLHttpRequest;if(window.ActiveXObject){for(var e=["Msxml2.XMLHTTP.6.0","Msxml2.XMLHTTP.3.0","Microsoft.XMLHTTP"],t=0;tthis.offset&&(this.emit("data",t.slice(this.offset)),this.offset=t.length))};var s=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)}},{stream:57,util:60}],35:[function(e,t,r){!function(){function e(e){this.message=e}var t="undefined"!=typeof r?r:this,n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";e.prototype=new Error,e.prototype.name="InvalidCharacterError",t.btoa||(t.btoa=function(t){for(var r,i,o=0,a=n,s="";t.charAt(0|o)||(a="=",o%1);s+=a.charAt(63&r>>8-o%1*8)){if(i=t.charCodeAt(o+=.75),i>255)throw new e("'btoa' failed: The string to be encoded contains characters outside of the Latin1 range.");r=r<<8|i}return s}),t.atob||(t.atob=function(t){if(t=t.replace(/=+$/,""),t.length%4==1)throw new e("'atob' failed: The string to be decoded is not correctly encoded.");for(var r,i,o=0,a=0,s="";i=t.charAt(a++);~i&&(r=o%4?64*r+i:i,o++%4)?s+=String.fromCharCode(255&r>>(-2*o&6)):0)i=n.indexOf(i);return s})}()},{}],36:[function(e,t){var r=e("http"),n=t.exports;for(var i in r)r.hasOwnProperty(i)&&(n[i]=r[i]);n.request=function(e,t){return e||(e={}),e.scheme="https",r.request.call(this,e,t)}},{http:32}],37:[function(e,t){t.exports="function"==typeof Object.create?function(e,t){e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}})}:function(e,t){e.super_=t;var r=function(){};r.prototype=t.prototype,e.prototype=new r,e.prototype.constructor=e}},{}],38:[function(e,t,r){(function(e){function t(e,t){for(var r=0,n=e.length-1;n>=0;n--){var i=e[n];"."===i?e.splice(n,1):".."===i?(e.splice(n,1),r++):r&&(e.splice(n,1),r--)}if(t)for(;r--;r)e.unshift("..");return e}function n(e,t){if(e.filter)return e.filter(t);for(var r=[],n=0;n=-1&&!i;o--){var a=o>=0?arguments[o]:e.cwd();if("string"!=typeof a)throw new TypeError("Arguments to path.resolve must be strings");a&&(r=a+"/"+r,i="/"===a.charAt(0))}return r=t(n(r.split("/"),function(e){return!!e}),!i).join("/"),(i?"/":"")+r||"."},r.normalize=function(e){var i=r.isAbsolute(e),o="/"===a(e,-1);return e=t(n(e.split("/"),function(e){return!!e}),!i).join("/"),e||i||(e="."),e&&o&&(e+="/"),(i?"/":"")+e},r.isAbsolute=function(e){return"/"===e.charAt(0)},r.join=function(){var e=Array.prototype.slice.call(arguments,0);return r.normalize(n(e,function(e){if("string"!=typeof e)throw new TypeError("Arguments to path.join must be strings");return e}).join("/"))},r.relative=function(e,t){function n(e){for(var t=0;t=0&&""===e[r];r--);return t>r?[]:e.slice(t,r-t+1)}e=r.resolve(e).substr(1),t=r.resolve(t).substr(1);for(var i=n(e.split("/")),o=n(t.split("/")),a=Math.min(i.length,o.length),s=a,u=0;a>u;u++)if(i[u]!==o[u]){s=u;break}for(var l=[],u=s;ut&&(t=e.length+t),e.substr(t,r)}}).call(this,e("Zbi7gb"))},{Zbi7gb:39}],39:[function(e,t){function r(){}var n=t.exports={};n.nextTick=function(){var e="undefined"!=typeof window&&window.setImmediate,t="undefined"!=typeof window&&window.postMessage&&window.addEventListener;if(e)return function(e){return window.setImmediate(e)};if(t){var r=[];return window.addEventListener("message",function(e){var t=e.source;if((t===window||null===t)&&"process-tick"===e.data&&(e.stopPropagation(),r.length>0)){var n=r.shift();n()}},!0),function(e){r.push(e),window.postMessage("process-tick","*")}}return function(e){setTimeout(e,0)}}(),n.title="browser",n.browser=!0,n.env={},n.argv=[],n.on=r,n.addListener=r,n.once=r,n.off=r,n.removeListener=r,n.removeAllListeners=r,n.emit=r,n.binding=function(){throw new Error("process.binding is not supported")},n.cwd=function(){return"/"},n.chdir=function(){throw new Error("process.chdir is not supported")}},{}],40:[function(t,r,n){(function(t){!function(i){function o(e){throw RangeError(V[e])}function a(e,t){for(var r=e.length;r--;)e[r]=t(e[r]);return e}function s(e,t){return a(e.split(R),t).join(".")}function u(e){for(var t,r,n=[],i=0,o=e.length;o>i;)t=e.charCodeAt(i++),t>=55296&&56319>=t&&o>i?(r=e.charCodeAt(i++),56320==(64512&r)?n.push(((1023&t)<<10)+(1023&r)+65536):(n.push(t),i--)):n.push(t);return n}function l(e){return a(e,function(e){var t="";return e>65535&&(e-=65536,t+=U(e>>>10&1023|55296),e=56320|1023&e),t+=U(e)}).join("")}function f(e){return 10>e-48?e-22:26>e-65?e-65:26>e-97?e-97:_}function c(e,t){return e+22+75*(26>e)-((0!=t)<<5)}function h(e,t,r){var n=0;for(e=r?M(e/I):e>>1,e+=M(e/t);e>T*E>>1;n+=_)e=M(e/T);return M(n+(T+1)*e/(e+S))}function d(e){var t,r,n,i,a,s,u,c,d,p,g=[],m=e.length,v=0,b=j,y=A;for(r=e.lastIndexOf(C),0>r&&(r=0),n=0;r>n;++n)e.charCodeAt(n)>=128&&o("not-basic"),g.push(e.charCodeAt(n));for(i=r>0?r+1:0;m>i;){for(a=v,s=1,u=_;i>=m&&o("invalid-input"),c=f(e.charCodeAt(i++)),(c>=_||c>M((k-v)/s))&&o("overflow"),v+=c*s,d=y>=u?O:u>=y+E?E:u-y,!(d>c);u+=_)p=_-d,s>M(k/p)&&o("overflow"),s*=p;t=g.length+1,y=h(v-a,t,0==a),M(v/t)>k-b&&o("overflow"),b+=M(v/t),v%=t,g.splice(v++,0,b)}return l(g)}function p(e){var t,r,n,i,a,s,l,f,d,p,g,m,v,b,y,w=[];for(e=u(e),m=e.length,t=j,r=0,a=A,s=0;m>s;++s)g=e[s],128>g&&w.push(U(g));for(n=i=w.length,i&&w.push(C);m>n;){for(l=k,s=0;m>s;++s)g=e[s],g>=t&&l>g&&(l=g);for(v=n+1,l-t>M((k-r)/v)&&o("overflow"),r+=(l-t)*v,t=l,s=0;m>s;++s)if(g=e[s],t>g&&++r>k&&o("overflow"),g==t){for(f=r,d=_;p=a>=d?O:d>=a+E?E:d-a,!(p>f);d+=_)y=f-p,b=_-p,w.push(U(c(p+y%b,0))),f=M(y/b);w.push(U(c(f,0))),a=h(r,v,n==i),r=0,++n}++r,++t}return w.join("")}function g(e){return s(e,function(e){return L.test(e)?d(e.slice(4).toLowerCase()):e})}function m(e){return s(e,function(e){return B.test(e)?"xn--"+p(e):e})}var v="object"==typeof n&&n,b="object"==typeof r&&r&&r.exports==v&&r,y="object"==typeof t&&t;(y.global===y||y.window===y)&&(i=y);var w,x,k=2147483647,_=36,O=1,E=26,S=38,I=700,A=72,j=128,C="-",L=/^xn--/,B=/[^ -~]/,R=/\x2E|\u3002|\uFF0E|\uFF61/g,V={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},T=_-O,M=Math.floor,U=String.fromCharCode;if(w={version:"1.2.4",ucs2:{decode:u,encode:l},decode:d,encode:p,toASCII:m,toUnicode:g},"function"==typeof e&&"object"==typeof e.amd&&e.amd)e("punycode",function(){return w});else if(v&&!v.nodeType)if(b)b.exports=w;else for(x in w)w.hasOwnProperty(x)&&(v[x]=w[x]);else i.punycode=w}(this)}).call(this,"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],41:[function(e,t){"use strict";function r(e,t){return Object.prototype.hasOwnProperty.call(e,t)}t.exports=function(e,t,i,o){t=t||"&",i=i||"=";var a={};if("string"!=typeof e||0===e.length)return a;var s=/\+/g;e=e.split(t);var u=1e3;o&&"number"==typeof o.maxKeys&&(u=o.maxKeys);var l=e.length;u>0&&l>u&&(l=u);for(var f=0;l>f;++f){var c,h,d,p,g=e[f].replace(s,"%20"),m=g.indexOf(i);m>=0?(c=g.substr(0,m),h=g.substr(m+1)):(c=g,h=""),d=decodeURIComponent(c),p=decodeURIComponent(h),r(a,d)?n(a[d])?a[d].push(p):a[d]=[a[d],p]:a[d]=p}return a};var n=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)}},{}],42:[function(e,t){"use strict";function r(e,t){if(e.map)return e.map(t);for(var r=[],n=0;nr;r++)t(e[r],r)}t.exports=n;var a=Object.keys||function(e){var t=[];for(var r in e)t.push(r);return t},s=e("core-util-is");s.inherits=e("inherits");var u=e("./_stream_readable"),l=e("./_stream_writable");s.inherits(n,u),o(a(l.prototype),function(e){n.prototype[e]||(n.prototype[e]=l.prototype[e])})}).call(this,e("Zbi7gb"))},{"./_stream_readable":47,"./_stream_writable":49,Zbi7gb:39,"core-util-is":50,inherits:37}],46:[function(e,t){function r(e){return this instanceof r?void n.call(this,e):new r(e)}t.exports=r;var n=e("./_stream_transform"),i=e("core-util-is");i.inherits=e("inherits"),i.inherits(r,n),r.prototype._transform=function(e,t,r){r(null,e)}},{"./_stream_transform":48,"core-util-is":50,inherits:37}],47:[function(e,t){(function(r){function n(t){t=t||{};var r=t.highWaterMark;this.highWaterMark=r||0===r?r:16384,this.highWaterMark=~~this.highWaterMark,this.buffer=[],this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=!1,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.calledRead=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.objectMode=!!t.objectMode,this.defaultEncoding=t.defaultEncoding||"utf8",this.ranOut=!1,this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,t.encoding&&(A||(A=e("string_decoder/").StringDecoder),this.decoder=new A(t.encoding),this.encoding=t.encoding)}function i(e){return this instanceof i?(this._readableState=new n(e,this),this.readable=!0,void S.call(this)):new i(e)}function o(e,t,r,n,i){var o=l(t,r);if(o)e.emit("error",o);else if(null===r||void 0===r)t.reading=!1,t.ended||f(e,t);else if(t.objectMode||r&&r.length>0)if(t.ended&&!i){var s=new Error("stream.push() after EOF");e.emit("error",s)}else if(t.endEmitted&&i){var s=new Error("stream.unshift() after end event");e.emit("error",s)}else!t.decoder||i||n||(r=t.decoder.write(r)),t.length+=t.objectMode?1:r.length,i?t.buffer.unshift(r):(t.reading=!1,t.buffer.push(r)),t.needReadable&&c(e),d(e,t);else i||(t.reading=!1);return a(t)}function a(e){return!e.ended&&(e.needReadable||e.length=j)e=j;else{e--;for(var t=1;32>t;t<<=1)e|=e>>t;e++}return e}function u(e,t){return 0===t.length&&t.ended?0:t.objectMode?0===e?0:1:isNaN(e)||null===e?t.flowing&&t.buffer.length?t.buffer[0].length:t.length:0>=e?0:(e>t.highWaterMark&&(t.highWaterMark=s(e)),e>t.length?t.ended?t.length:(t.needReadable=!0,0):e)}function l(e,t){var r=null;return O.isBuffer(t)||"string"==typeof t||null===t||void 0===t||e.objectMode||r||(r=new TypeError("Invalid non-string/buffer chunk")),r}function f(e,t){if(t.decoder&&!t.ended){var r=t.decoder.end();r&&r.length&&(t.buffer.push(r),t.length+=t.objectMode?1:r.length)}t.ended=!0,t.length>0?c(e):w(e)}function c(e){var t=e._readableState;t.needReadable=!1,t.emittedReadable||(t.emittedReadable=!0,t.sync?r.nextTick(function(){h(e)}):h(e))}function h(e){e.emit("readable")}function d(e,t){t.readingMore||(t.readingMore=!0,r.nextTick(function(){p(e,t)}))}function p(e,t){for(var r=t.length;!t.reading&&!t.flowing&&!t.ended&&t.length0)return;return 0===n.pipesCount?(n.flowing=!1,void(E.listenerCount(e,"data")>0&&b(e))):void(n.ranOut=!0)}function v(){this._readableState.ranOut&&(this._readableState.ranOut=!1,m(this))}function b(e,t){var n=e._readableState;if(n.flowing)throw new Error("Cannot switch to old mode now.");var i=t||!1,o=!1;e.readable=!0,e.pipe=S.prototype.pipe,e.on=e.addListener=S.prototype.on,e.on("readable",function(){o=!0;for(var t;!i&&null!==(t=e.read());)e.emit("data",t);null===t&&(o=!1,e._readableState.needReadable=!0)}),e.pause=function(){i=!0,this.emit("pause")},e.resume=function(){i=!1,o?r.nextTick(function(){e.emit("readable")}):this.read(0),this.emit("resume")},e.emit("readable")}function y(e,t){var r,n=t.buffer,i=t.length,o=!!t.decoder,a=!!t.objectMode;if(0===n.length)return null;if(0===i)r=null;else if(a)r=n.shift();else if(!e||e>=i)r=o?n.join(""):O.concat(n,i),n.length=0;else if(el&&e>u;l++){var s=n[0],c=Math.min(e-u,s.length);o?r+=s.slice(0,c):s.copy(r,u,0,c),c0)throw new Error("endReadable called on non-empty stream");!t.endEmitted&&t.calledRead&&(t.ended=!0,r.nextTick(function(){t.endEmitted||0!==t.length||(t.endEmitted=!0,e.readable=!1,e.emit("end"))}))}function x(e,t){for(var r=0,n=e.length;n>r;r++)t(e[r],r)}function k(e,t){for(var r=0,n=e.length;n>r;r++)if(e[r]===t)return r;return-1}t.exports=i;var _=e("isarray"),O=e("buffer").Buffer;i.ReadableState=n;var E=e("events").EventEmitter;E.listenerCount||(E.listenerCount=function(e,t){return e.listeners(t).length});var S=e("stream"),I=e("core-util-is");I.inherits=e("inherits");var A;I.inherits(i,S),i.prototype.push=function(e,t){var r=this._readableState;return"string"!=typeof e||r.objectMode||(t=t||r.defaultEncoding,t!==r.encoding&&(e=new O(e,t),t="")),o(this,r,e,t,!1)},i.prototype.unshift=function(e){var t=this._readableState;return o(this,t,e,"",!0)},i.prototype.setEncoding=function(t){A||(A=e("string_decoder/").StringDecoder),this._readableState.decoder=new A(t),this._readableState.encoding=t};var j=8388608;i.prototype.read=function(e){var t=this._readableState;t.calledRead=!0;var r=e;if(("number"!=typeof e||e>0)&&(t.emittedReadable=!1),0===e&&t.needReadable&&(t.length>=t.highWaterMark||t.ended))return c(this),null;if(e=u(e,t),0===e&&t.ended)return 0===t.length&&w(this),null;var n=t.needReadable;t.length-e<=t.highWaterMark&&(n=!0),(t.ended||t.reading)&&(n=!1),n&&(t.reading=!0,t.sync=!0,0===t.length&&(t.needReadable=!0),this._read(t.highWaterMark),t.sync=!1),n&&!t.reading&&(e=u(r,t));var i;return i=e>0?y(e,t):null,null===i&&(t.needReadable=!0,e=0),t.length-=e,0!==t.length||t.ended||(t.needReadable=!0),t.ended&&!t.endEmitted&&0===t.length&&w(this),i},i.prototype._read=function(){this.emit("error",new Error("not implemented"))},i.prototype.pipe=function(e,t){function n(e){e===f&&o()}function i(){e.end()}function o(){e.removeListener("close",s),e.removeListener("finish",u),e.removeListener("drain",p),e.removeListener("error",a),e.removeListener("unpipe",n),f.removeListener("end",i),f.removeListener("end",o),(!e._writableState||e._writableState.needDrain)&&p()}function a(t){l(),e.removeListener("error",a),0===E.listenerCount(e,"error")&&e.emit("error",t)}function s(){e.removeListener("finish",u),l()}function u(){e.removeListener("close",s),l()}function l(){f.unpipe(e)}var f=this,c=this._readableState;switch(c.pipesCount){case 0:c.pipes=e;break;case 1:c.pipes=[c.pipes,e];break;default:c.pipes.push(e)}c.pipesCount+=1;var h=(!t||t.end!==!1)&&e!==r.stdout&&e!==r.stderr,d=h?i:o;c.endEmitted?r.nextTick(d):f.once("end",d),e.on("unpipe",n);var p=g(f);return e.on("drain",p),e._events&&e._events.error?_(e._events.error)?e._events.error.unshift(a):e._events.error=[a,e._events.error]:e.on("error",a),e.once("close",s),e.once("finish",u),e.emit("pipe",f),c.flowing||(this.on("readable",v),c.flowing=!0,r.nextTick(function(){m(f)})),e},i.prototype.unpipe=function(e){var t=this._readableState;if(0===t.pipesCount)return this;if(1===t.pipesCount)return e&&e!==t.pipes?this:(e||(e=t.pipes),t.pipes=null,t.pipesCount=0,this.removeListener("readable",v),t.flowing=!1,e&&e.emit("unpipe",this),this);if(!e){var r=t.pipes,n=t.pipesCount;t.pipes=null,t.pipesCount=0,this.removeListener("readable",v),t.flowing=!1;for(var i=0;n>i;i++)r[i].emit("unpipe",this);return this}var i=k(t.pipes,e);return-1===i?this:(t.pipes.splice(i,1),t.pipesCount-=1,1===t.pipesCount&&(t.pipes=t.pipes[0]),e.emit("unpipe",this),this)},i.prototype.on=function(e,t){var r=S.prototype.on.call(this,e,t);if("data"!==e||this._readableState.flowing||b(this),"readable"===e&&this.readable){var n=this._readableState;n.readableListening||(n.readableListening=!0,n.emittedReadable=!1,n.needReadable=!0,n.reading?n.length&&c(this,n):this.read(0))}return r},i.prototype.addListener=i.prototype.on,i.prototype.resume=function(){b(this),this.read(0),this.emit("resume")},i.prototype.pause=function(){b(this,!0),this.emit("pause")},i.prototype.wrap=function(e){var t=this._readableState,r=!1,n=this;e.on("end",function(){if(t.decoder&&!t.ended){var e=t.decoder.end();e&&e.length&&n.push(e)}n.push(null)}),e.on("data",function(i){if(t.decoder&&(i=t.decoder.write(i)),i&&(t.objectMode||i.length)){var o=n.push(i);o||(r=!0,e.pause())}});for(var i in e)"function"==typeof e[i]&&"undefined"==typeof this[i]&&(this[i]=function(t){return function(){return e[t].apply(e,arguments)}}(i));var o=["error","close","destroy","pause","resume"];return x(o,function(t){e.on(t,n.emit.bind(n,t))}),n._read=function(){r&&(r=!1,e.resume())},n},i._fromList=y}).call(this,e("Zbi7gb"))},{Zbi7gb:39,buffer:28,"core-util-is":50,events:31,inherits:37,isarray:51,stream:57,"string_decoder/":52}],48:[function(e,t){function r(e,t){this.afterTransform=function(e,r){return n(t,e,r)},this.needTransform=!1,this.transforming=!1,this.writecb=null,this.writechunk=null}function n(e,t,r){var n=e._transformState;n.transforming=!1;var i=n.writecb;if(!i)return e.emit("error",new Error("no writecb in Transform class"));n.writechunk=null,n.writecb=null,null!==r&&void 0!==r&&e.push(r),i&&i(t);var o=e._readableState;o.reading=!1,(o.needReadable||o.length=this.charLength-this.charReceived?this.charLength-this.charReceived:e.length;if(e.copy(this.charBuffer,this.charReceived,r,n),this.charReceived+=n-r,r=n,this.charReceived=55296&&56319>=i)){if(this.charReceived=this.charLength=0,n==e.length)return t;e=e.slice(n,e.length);break}this.charLength+=this.surrogateSize,t=""}var o=this.detectIncompleteChar(e),a=e.length;this.charLength&&(e.copy(this.charBuffer,0,e.length-o,a),this.charReceived=o,a-=o),t+=e.toString(this.encoding,0,a);var a=t.length-1,i=t.charCodeAt(a);if(i>=55296&&56319>=i){var s=this.surrogateSize;return this.charLength+=s,this.charReceived+=s,this.charBuffer.copy(this.charBuffer,s,0,s),this.charBuffer.write(t.charAt(t.length-1),this.encoding),t.substring(0,a)}return t},l.prototype.detectIncompleteChar=function(e){for(var t=e.length>=3?3:e.length;t>0;t--){var r=e[e.length-t];if(1==t&&r>>5==6){this.charLength=2;break}if(2>=t&&r>>4==14){this.charLength=3;break}if(3>=t&&r>>3==30){this.charLength=4;break}}return t},l.prototype.end=function(e){var t="";if(e&&e.length&&(t=this.write(e)),this.charReceived){var r=this.charReceived,n=this.charBuffer,i=this.encoding;t+=n.slice(0,r).toString(i)}return t}},{buffer:28}],53:[function(e,t){t.exports=e("./lib/_stream_passthrough.js")},{"./lib/_stream_passthrough.js":46}],54:[function(e,t,r){r=t.exports=e("./lib/_stream_readable.js"),r.Readable=r,r.Writable=e("./lib/_stream_writable.js"),r.Duplex=e("./lib/_stream_duplex.js"),r.Transform=e("./lib/_stream_transform.js"),r.PassThrough=e("./lib/_stream_passthrough.js")},{"./lib/_stream_duplex.js":45,"./lib/_stream_passthrough.js":46,"./lib/_stream_readable.js":47,"./lib/_stream_transform.js":48,"./lib/_stream_writable.js":49}],55:[function(e,t){t.exports=e("./lib/_stream_transform.js")},{"./lib/_stream_transform.js":48}],56:[function(e,t){t.exports=e("./lib/_stream_writable.js")},{"./lib/_stream_writable.js":49}],57:[function(e,t){function r(){n.call(this)}t.exports=r;var n=e("events").EventEmitter,i=e("inherits");i(r,n),r.Readable=e("readable-stream/readable.js"),r.Writable=e("readable-stream/writable.js"),r.Duplex=e("readable-stream/duplex.js"),r.Transform=e("readable-stream/transform.js"),r.PassThrough=e("readable-stream/passthrough.js"),r.Stream=r,r.prototype.pipe=function(e,t){function r(t){e.writable&&!1===e.write(t)&&l.pause&&l.pause()}function i(){l.readable&&l.resume&&l.resume()}function o(){f||(f=!0,e.end())}function a(){f||(f=!0,"function"==typeof e.destroy&&e.destroy())}function s(e){if(u(),0===n.listenerCount(this,"error"))throw e}function u(){l.removeListener("data",r),e.removeListener("drain",i),l.removeListener("end",o),l.removeListener("close",a),l.removeListener("error",s),e.removeListener("error",s),l.removeListener("end",u),l.removeListener("close",u),e.removeListener("close",u)}var l=this;l.on("data",r),e.on("drain",i),e._isStdio||t&&t.end===!1||(l.on("end",o),l.on("close",a));var f=!1;return l.on("error",s),e.on("error",s),l.on("end",u),l.on("close",u),e.on("close",u),e.emit("pipe",l),e}},{events:31,inherits:37,"readable-stream/duplex.js":44,"readable-stream/passthrough.js":53,"readable-stream/readable.js":54,"readable-stream/transform.js":55,"readable-stream/writable.js":56}],58:[function(e,t,r){function n(){this.protocol=null,this.slashes=null,this.auth=null,this.host=null,this.port=null,this.hostname=null,this.hash=null,this.search=null,this.query=null,this.pathname=null,this.path=null,this.href=null}function i(e,t,r){if(e&&l(e)&&e instanceof n)return e;var i=new n;return i.parse(e,t,r),i}function o(e){return u(e)&&(e=i(e)),e instanceof n?e.format():n.prototype.format.call(e)}function a(e,t){return i(e,!1,!0).resolve(t)}function s(e,t){return e?i(e,!1,!0).resolveObject(t):t}function u(e){return"string"==typeof e}function l(e){return"object"==typeof e&&null!==e}function f(e){return null===e}function c(e){return null==e}var h=e("punycode");r.parse=i,r.resolve=a,r.resolveObject=s,r.format=o,r.Url=n;var d=/^([a-z0-9.+-]+:)/i,p=/:[0-9]*$/,g=["<",">",'"',"`"," ","\r","\n"," "],m=["{","}","|","\\","^","`"].concat(g),v=["'"].concat(m),b=["%","/","?",";","#"].concat(v),y=["/","?","#"],w=255,x=/^[a-z0-9A-Z_-]{0,63}$/,k=/^([a-z0-9A-Z_-]{0,63})(.*)$/,_={javascript:!0,"javascript:":!0},O={javascript:!0,"javascript:":!0},E={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},S=e("querystring");n.prototype.parse=function(e,t,r){if(!u(e))throw new TypeError("Parameter 'url' must be a string, not "+typeof e);var n=e;n=n.trim();var i=d.exec(n);if(i){i=i[0];var o=i.toLowerCase();this.protocol=o,n=n.substr(i.length)}if(r||i||n.match(/^\/\/[^@\/]+@[^@\/]+/)){var a="//"===n.substr(0,2);!a||i&&O[i]||(n=n.substr(2),this.slashes=!0)}if(!O[i]&&(a||i&&!E[i])){for(var s=-1,l=0;lf)&&(s=f)}var c,p;p=-1===s?n.lastIndexOf("@"):n.lastIndexOf("@",s),-1!==p&&(c=n.slice(0,p),n=n.slice(p+1),this.auth=decodeURIComponent(c)),s=-1;for(var l=0;lf)&&(s=f)}-1===s&&(s=n.length),this.host=n.slice(0,s),n=n.slice(s),this.parseHost(),this.hostname=this.hostname||"";var g="["===this.hostname[0]&&"]"===this.hostname[this.hostname.length-1];if(!g)for(var m=this.hostname.split(/\./),l=0,I=m.length;I>l;l++){var A=m[l];if(A&&!A.match(x)){for(var j="",C=0,L=A.length;L>C;C++)j+=A.charCodeAt(C)>127?"x":A[C];if(!j.match(x)){var B=m.slice(0,l),R=m.slice(l+1),V=A.match(k);V&&(B.push(V[1]),R.unshift(V[2])),R.length&&(n="/"+R.join(".")+n),this.hostname=B.join(".");break}}}if(this.hostname=this.hostname.length>w?"":this.hostname.toLowerCase(),!g){for(var T=this.hostname.split("."),M=[],l=0;ll;l++){var q=v[l],F=encodeURIComponent(q);F===q&&(F=escape(q)),n=n.split(q).join(F)}var P=n.indexOf("#");-1!==P&&(this.hash=n.substr(P),n=n.slice(0,P));var N=n.indexOf("?");if(-1!==N?(this.search=n.substr(N),this.query=n.substr(N+1),t&&(this.query=S.parse(this.query)),n=n.slice(0,N)):t&&(this.search="",this.query={}),n&&(this.pathname=n),E[o]&&this.hostname&&!this.pathname&&(this.pathname="/"),this.pathname||this.search){var z=this.pathname||"",U=this.search||"";this.path=z+U}return this.href=this.format(),this},n.prototype.format=function(){var e=this.auth||"";e&&(e=encodeURIComponent(e),e=e.replace(/%3A/i,":"),e+="@");var t=this.protocol||"",r=this.pathname||"",n=this.hash||"",i=!1,o="";this.host?i=e+this.host:this.hostname&&(i=e+(-1===this.hostname.indexOf(":")?this.hostname:"["+this.hostname+"]"),this.port&&(i+=":"+this.port)),this.query&&l(this.query)&&Object.keys(this.query).length&&(o=S.stringify(this.query));var a=this.search||o&&"?"+o||"";return t&&":"!==t.substr(-1)&&(t+=":"),this.slashes||(!t||E[t])&&i!==!1?(i="//"+(i||""),r&&"/"!==r.charAt(0)&&(r="/"+r)):i||(i=""),n&&"#"!==n.charAt(0)&&(n="#"+n),a&&"?"!==a.charAt(0)&&(a="?"+a),r=r.replace(/[?#]/g,function(e){return encodeURIComponent(e)}),a=a.replace("#","%23"),t+i+r+a+n},n.prototype.resolve=function(e){return this.resolveObject(i(e,!1,!0)).format()},n.prototype.resolveObject=function(e){if(u(e)){var t=new n;t.parse(e,!1,!0),e=t}var r=new n;if(Object.keys(this).forEach(function(e){r[e]=this[e]},this),r.hash=e.hash,""===e.href)return r.href=r.format(),r;if(e.slashes&&!e.protocol)return Object.keys(e).forEach(function(t){"protocol"!==t&&(r[t]=e[t])}),E[r.protocol]&&r.hostname&&!r.pathname&&(r.path=r.pathname="/"),r.href=r.format(),r;if(e.protocol&&e.protocol!==r.protocol){if(!E[e.protocol])return Object.keys(e).forEach(function(t){r[t]=e[t]}),r.href=r.format(),r;if(r.protocol=e.protocol,e.host||O[e.protocol])r.pathname=e.pathname;else{for(var i=(e.pathname||"").split("/");i.length&&!(e.host=i.shift()););e.host||(e.host=""),e.hostname||(e.hostname=""),""!==i[0]&&i.unshift(""),i.length<2&&i.unshift(""),r.pathname=i.join("/")}if(r.search=e.search,r.query=e.query,r.host=e.host||"",r.auth=e.auth,r.hostname=e.hostname||e.host,r.port=e.port,r.pathname||r.search){var o=r.pathname||"",a=r.search||"";r.path=o+a}return r.slashes=r.slashes||e.slashes,r.href=r.format(),r}var s=r.pathname&&"/"===r.pathname.charAt(0),l=e.host||e.pathname&&"/"===e.pathname.charAt(0),h=l||s||r.host&&e.pathname,d=h,p=r.pathname&&r.pathname.split("/")||[],i=e.pathname&&e.pathname.split("/")||[],g=r.protocol&&!E[r.protocol];if(g&&(r.hostname="",r.port=null,r.host&&(""===p[0]?p[0]=r.host:p.unshift(r.host)),r.host="",e.protocol&&(e.hostname=null,e.port=null,e.host&&(""===i[0]?i[0]=e.host:i.unshift(e.host)),e.host=null),h=h&&(""===i[0]||""===p[0])),l)r.host=e.host||""===e.host?e.host:r.host,r.hostname=e.hostname||""===e.hostname?e.hostname:r.hostname,r.search=e.search,r.query=e.query,p=i;else if(i.length)p||(p=[]),p.pop(),p=p.concat(i),r.search=e.search,r.query=e.query;else if(!c(e.search)){if(g){r.hostname=r.host=p.shift();var m=r.host&&r.host.indexOf("@")>0?r.host.split("@"):!1;m&&(r.auth=m.shift(),r.host=r.hostname=m.shift())}return r.search=e.search,r.query=e.query,f(r.pathname)&&f(r.search)||(r.path=(r.pathname?r.pathname:"")+(r.search?r.search:"")),r.href=r.format(),r}if(!p.length)return r.pathname=null,r.path=r.search?"/"+r.search:null,r.href=r.format(),r;for(var v=p.slice(-1)[0],b=(r.host||e.host)&&("."===v||".."===v)||""===v,y=0,w=p.length;w>=0;w--)v=p[w],"."==v?p.splice(w,1):".."===v?(p.splice(w,1),y++):y&&(p.splice(w,1),y--);if(!h&&!d)for(;y--;y)p.unshift("..");!h||""===p[0]||p[0]&&"/"===p[0].charAt(0)||p.unshift(""),b&&"/"!==p.join("/").substr(-1)&&p.push("");var x=""===p[0]||p[0]&&"/"===p[0].charAt(0);if(g){r.hostname=r.host=x?"":p.length?p.shift():"";var m=r.host&&r.host.indexOf("@")>0?r.host.split("@"):!1;m&&(r.auth=m.shift(),r.host=r.hostname=m.shift())}return h=h||r.host&&p.length,h&&!x&&p.unshift(""),p.length?r.pathname=p.join("/"):(r.pathname=null,r.path=null),f(r.pathname)&&f(r.search)||(r.path=(r.pathname?r.pathname:"")+(r.search?r.search:"")),r.auth=e.auth||r.auth,r.slashes=r.slashes||e.slashes,r.href=r.format(),r},n.prototype.parseHost=function(){var e=this.host,t=p.exec(e);t&&(t=t[0],":"!==t&&(this.port=t.substr(1)),e=e.substr(0,e.length-t.length)),e&&(this.hostname=e)}},{punycode:40,querystring:43}],59:[function(e,t){t.exports=function(e){return e&&"object"==typeof e&&"function"==typeof e.copy&&"function"==typeof e.fill&&"function"==typeof e.readUInt8}},{}],60:[function(e,t,r){(function(t,n){function i(e,t){var n={seen:[],stylize:a};return arguments.length>=3&&(n.depth=arguments[2]),arguments.length>=4&&(n.colors=arguments[3]),g(t)?n.showHidden=t:t&&r._extend(n,t),x(n.showHidden)&&(n.showHidden=!1),x(n.depth)&&(n.depth=2),x(n.colors)&&(n.colors=!1),x(n.customInspect)&&(n.customInspect=!0),n.colors&&(n.stylize=o),u(n,e,n.depth)}function o(e,t){var r=i.styles[t];return r?"["+i.colors[r][0]+"m"+e+"["+i.colors[r][1]+"m":e}function a(e){return e}function s(e){var t={};return e.forEach(function(e){t[e]=!0}),t}function u(e,t,n){if(e.customInspect&&t&&S(t.inspect)&&t.inspect!==r.inspect&&(!t.constructor||t.constructor.prototype!==t)){var i=t.inspect(n,e);return y(i)||(i=u(e,i,n)),i}var o=l(e,t);if(o)return o;var a=Object.keys(t),g=s(a);if(e.showHidden&&(a=Object.getOwnPropertyNames(t)),E(t)&&(a.indexOf("message")>=0||a.indexOf("description")>=0))return f(t);if(0===a.length){if(S(t)){var m=t.name?": "+t.name:"";return e.stylize("[Function"+m+"]","special")}if(k(t))return e.stylize(RegExp.prototype.toString.call(t),"regexp");if(O(t))return e.stylize(Date.prototype.toString.call(t),"date");if(E(t))return f(t)}var v="",b=!1,w=["{","}"];if(p(t)&&(b=!0,w=["[","]"]),S(t)){var x=t.name?": "+t.name:"";v=" [Function"+x+"]"}if(k(t)&&(v=" "+RegExp.prototype.toString.call(t)),O(t)&&(v=" "+Date.prototype.toUTCString.call(t)),E(t)&&(v=" "+f(t)),0===a.length&&(!b||0==t.length))return w[0]+v+w[1];if(0>n)return k(t)?e.stylize(RegExp.prototype.toString.call(t),"regexp"):e.stylize("[Object]","special");e.seen.push(t);var _;return _=b?c(e,t,n,g,a):a.map(function(r){return h(e,t,n,g,r,b)}),e.seen.pop(),d(_,v,w)}function l(e,t){if(x(t))return e.stylize("undefined","undefined");if(y(t)){var r="'"+JSON.stringify(t).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return e.stylize(r,"string")}return b(t)?e.stylize(""+t,"number"):g(t)?e.stylize(""+t,"boolean"):m(t)?e.stylize("null","null"):void 0}function f(e){return"["+Error.prototype.toString.call(e)+"]"}function c(e,t,r,n,i){for(var o=[],a=0,s=t.length;s>a;++a)o.push(L(t,String(a))?h(e,t,r,n,String(a),!0):"");return i.forEach(function(i){i.match(/^\d+$/)||o.push(h(e,t,r,n,i,!0))}),o}function h(e,t,r,n,i,o){var a,s,l;if(l=Object.getOwnPropertyDescriptor(t,i)||{value:t[i]},l.get?s=l.set?e.stylize("[Getter/Setter]","special"):e.stylize("[Getter]","special"):l.set&&(s=e.stylize("[Setter]","special")),L(n,i)||(a="["+i+"]"),s||(e.seen.indexOf(l.value)<0?(s=m(r)?u(e,l.value,null):u(e,l.value,r-1),s.indexOf("\n")>-1&&(s=o?s.split("\n").map(function(e){return" "+e}).join("\n").substr(2):"\n"+s.split("\n").map(function(e){return" "+e}).join("\n"))):s=e.stylize("[Circular]","special")),x(a)){if(o&&i.match(/^\d+$/))return s;a=JSON.stringify(""+i),a.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(a=a.substr(1,a.length-2),a=e.stylize(a,"name")):(a=a.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),a=e.stylize(a,"string"))}return a+": "+s}function d(e,t,r){var n=0,i=e.reduce(function(e,t){return n++,t.indexOf("\n")>=0&&n++,e+t.replace(/\u001b\[\d\d?m/g,"").length+1},0);return i>60?r[0]+(""===t?"":t+"\n ")+" "+e.join(",\n ")+" "+r[1]:r[0]+t+" "+e.join(", ")+" "+r[1]}function p(e){return Array.isArray(e)}function g(e){return"boolean"==typeof e}function m(e){return null===e}function v(e){return null==e}function b(e){return"number"==typeof e}function y(e){return"string"==typeof e}function w(e){return"symbol"==typeof e}function x(e){return void 0===e}function k(e){return _(e)&&"[object RegExp]"===A(e)}function _(e){return"object"==typeof e&&null!==e}function O(e){return _(e)&&"[object Date]"===A(e)}function E(e){return _(e)&&("[object Error]"===A(e)||e instanceof Error)}function S(e){return"function"==typeof e}function I(e){return null===e||"boolean"==typeof e||"number"==typeof e||"string"==typeof e||"symbol"==typeof e||"undefined"==typeof e}function A(e){return Object.prototype.toString.call(e)}function j(e){return 10>e?"0"+e.toString(10):e.toString(10)}function C(){var e=new Date,t=[j(e.getHours()),j(e.getMinutes()),j(e.getSeconds())].join(":");return[e.getDate(),T[e.getMonth()],t].join(" ")}function L(e,t){return Object.prototype.hasOwnProperty.call(e,t)}var B=/%[sdj%]/g;r.format=function(e){if(!y(e)){for(var t=[],r=0;r=o)return e;switch(e){case"%s":return String(n[r++]);case"%d":return Number(n[r++]);case"%j":try{return JSON.stringify(n[r++])}catch(t){return"[Circular]"}default:return e}}),s=n[r];o>r;s=n[++r])a+=m(s)||!_(s)?" "+s:" "+i(s);return a},r.deprecate=function(e,i){function o(){if(!a){if(t.throwDeprecation)throw new Error(i);t.traceDeprecation?console.trace(i):console.error(i),a=!0}return e.apply(this,arguments)}if(x(n.process))return function(){return r.deprecate(e,i).apply(this,arguments)};if(t.noDeprecation===!0)return e;var a=!1;return o};var R,V={};r.debuglog=function(e){if(x(R)&&(R=t.env.NODE_DEBUG||""),e=e.toUpperCase(),!V[e])if(new RegExp("\\b"+e+"\\b","i").test(R)){var n=t.pid;V[e]=function(){var t=r.format.apply(r,arguments);console.error("%s %d: %s",e,n,t)}}else V[e]=function(){};return V[e]},r.inspect=i,i.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},i.styles={special:"cyan",number:"yellow","boolean":"yellow",undefined:"grey","null":"bold",string:"green",date:"magenta",regexp:"red"},r.isArray=p,r.isBoolean=g,r.isNull=m,r.isNullOrUndefined=v,r.isNumber=b,r.isString=y,r.isSymbol=w,r.isUndefined=x,r.isRegExp=k,r.isObject=_,r.isDate=O,r.isError=E,r.isFunction=S,r.isPrimitive=I,r.isBuffer=e("./support/isBuffer");var T=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];r.log=function(){console.log("%s - %s",C(),r.format.apply(r,arguments))},r.inherits=e("inherits"),r._extend=function(e,t){if(!t||!_(t))return e;for(var r=Object.keys(t),n=r.length;n--;)e[r[n]]=t[r[n]];return e}}).call(this,e("Zbi7gb"),"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./support/isBuffer":59,Zbi7gb:39,inherits:37}]},{},[1])(1)}); \ No newline at end of file -- 2.34.1