ololog
Version:
Platform-agnostic logging with colors in terminals & browsers / shows call locations / pretty prints objects and stacktraces / smart newline and indentation handling
1,652 lines (1,317 loc) • 591 kB
JavaScript
(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);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
"use strict";
/* ------------------------------------------------------------------------ */
var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
function _defineEnumerableProperties(obj, descs) { for (var key in descs) { var desc = descs[key]; desc.configurable = desc.enumerable = true; if ("value" in desc) desc.writable = true; Object.defineProperty(obj, key, desc); } return obj; }
function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
function _toArray(arr) { return Array.isArray(arr) ? arr : Array.from(arr); }
var O = Object,
StackTracey = require('stacktracey'),
ansi = require('ansicolor'),
bullet = require('string.bullet'),
pipez = require('pipez');
/* ------------------------------------------------------------------------ */
var _stringify = require('string.ify').configure({
formatter: function formatter(x) {
if (x instanceof Error && !(typeof Symbol !== 'undefined' && x[Symbol.for('String.ify')])) {
var why = _stringify.limit((x.message || '').replace(/\r|\n/g, '').trim(), 120),
stack = new StackTracey(x).pretty,
stackIndented = stack.split('\n').map(function (x) {
return ' ' + x;
}).join('\n');
return '[EXCEPTION] ' + why + '\n\n' + stackIndented + '\n';
}
}
});
/* ------------------------------------------------------------------------ */
var _require = require('printable-characters'),
isBlank = _require.isBlank,
blank = _require.blank,
changeLastNonemptyLine = function changeLastNonemptyLine(lines, fn) {
for (var i = lines.length - 1; i >= 0; i--) {
if (i === 0 || !isBlank(lines[i])) {
lines[i] = fn(lines[i]);
break;
}
}
return lines;
};
/* ------------------------------------------------------------------------ */
var log = pipez({
/* ------------------------------------------------------------------------ */
stringify: function stringify(args, cfg) {
var print = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : _stringify.configure(cfg);
return args.map(function (arg) {
return typeof arg === 'string' ? arg : print(arg);
});
},
trim: function trim(tokens, _ref) {
var _ref$max = _ref.max,
max = _ref$max === undefined ? undefined : _ref$max;
return !max ? tokens : tokens.map(function (t) {
return _stringify.limit(t, max);
});
},
lines: function lines(tokens, _ref2) {
var _ref2$linebreak = _ref2.linebreak,
linebreak = _ref2$linebreak === undefined ? '\n' : _ref2$linebreak;
var lines = [[]];
var leftPad = [];
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = tokens[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var t = _step.value;
var _t$split = t.split(linebreak),
_t$split2 = _toArray(_t$split),
first = _t$split2[0],
rest = _t$split2.slice(1);
lines[lines.length - 1].push(first);
lines = [].concat(_toConsumableArray(lines), _toConsumableArray(rest.map(function (t) {
return t ? [].concat(leftPad, [t]) : [];
})));
var pad = blank(!rest.length ? t : rest[rest.length - 1]);
if (pad) {
leftPad.push(pad);
}
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
return lines;
},
concat: function concat(lines, _ref3) {
var _ref3$separator = _ref3.separator,
separator = _ref3$separator === undefined ? ' ' : _ref3$separator;
return lines.map(function (tokens) {
return tokens.join(separator);
});
},
indent: function indent(lines, _ref4) {
var _ref4$level = _ref4.level,
level = _ref4$level === undefined ? 0 : _ref4$level,
_ref4$pattern = _ref4.pattern,
pattern = _ref4$pattern === undefined ? '\t' : _ref4$pattern;
return lines.map(function (line) {
return pattern.repeat(level) + line;
});
},
time: function time(lines, _ref5) {
var _ref5$when = _ref5.when,
when = _ref5$when === undefined ? new Date() : _ref5$when,
_ref5$print = _ref5.print,
print = _ref5$print === undefined ? function (when) {
return ansi.dim(when.toISOString()) + '\t';
} : _ref5$print;
return bullet(print(when), lines);
},
locate: function locate(lines, _ref6) {
var _ref6$shift = _ref6.shift,
shift = _ref6$shift === undefined ? 0 : _ref6$shift,
_ref6$where = _ref6.where,
where = _ref6$where === undefined ? new StackTracey().clean.at(2 + shift) : _ref6$where,
_ref6$join = _ref6.join,
join = _ref6$join === undefined ? function (a, sep, b) {
return a && b ? a + sep + b : a || b;
} : _ref6$join,
_ref6$print = _ref6.print,
print = _ref6$print === undefined ? function (_ref7) {
var calleeShort = _ref7.calleeShort,
_ref7$fileName = _ref7.fileName,
fileName = _ref7$fileName === undefined ? [] : _ref7$fileName,
_ref7$line = _ref7.line,
line = _ref7$line === undefined ? [] : _ref7$line;
return ansi.dim('(' + join(calleeShort, ' @ ', join(fileName, ':', line)) + ')');
} : _ref6$print;
return changeLastNonemptyLine(lines, function (line) {
return join(line, ' ', print(where));
});
},
join: function join(lines, _ref8) {
var _ref8$linebreak = _ref8.linebreak,
linebreak = _ref8$linebreak === undefined ? '\n' : _ref8$linebreak;
return lines.join(linebreak);
},
render: function render(text, _ref9) {
var _ref9$engine = _ref9.engine,
engine = _ref9$engine === undefined ? typeof window !== 'undefined' && window.window === window && window.navigator ? navigator.userAgent.indexOf('Chrome') >= 0 ? 'chrome' : 'generic' : 'ansi' : _ref9$engine,
_ref9$engines = _ref9.engines,
engines = _ref9$engines === undefined ? {/* configurable */} : _ref9$engines,
_ref9$consoleMethod = _ref9.consoleMethod,
consoleMethod = _ref9$consoleMethod === undefined ? 'log' : _ref9$consoleMethod,
_ref9$defaults = _ref9.defaults,
defaults = _ref9$defaults === undefined ? {
ansi: function ansi(s) {
return console[consoleMethod](s);
},
chrome: function chrome(s) {
var _console;
return (_console = console)[consoleMethod].apply(_console, _toConsumableArray(ansi.parse(s).asChromeConsoleLogArguments));
},
generic: function generic(s) {
return console[consoleMethod](ansi.strip(s));
}
} : _ref9$defaults;
return text && O.assign(defaults, engines)[engine](text), text;
},
returnValue: function returnValue(__, _ref10) {
var _ref10$initialArgumen = _slicedToArray(_ref10.initialArguments, 1),
firstArgument = _ref10$initialArgumen[0];
return firstArgument;
}
/* ------------------------------------------------------------------------ */
}).configure({
time: false // disables 'time' step (until enabled back explicitly)
/* ------------------------------------------------------------------------ */
}).methods({
indent: function indent(level) {
return this.configure({ indent: { level: level } });
},
get error() {
return this.configure({ render: { consoleMethod: 'error' } });
},
get warn() {
return this.configure({ render: { consoleMethod: 'warn' } });
},
get info() {
return this.configure({ render: { consoleMethod: 'info' } });
},
maxArrayLength: function maxArrayLength(n) {
return this.configure({ stringify: { maxArrayLength: n } });
},
maxDepth: function maxDepth(n) {
return this.configure({ stringify: { maxDepth: n } });
},
get unlimited() {
return this.configure({ stringify: { maxArrayLength: Number.MAX_VALUE, maxDepth: Number.MAX_VALUE } });
},
get noPretty() {
return this.configure({ stringify: { pretty: false } });
},
get serialize() {
return this.before('render');
},
get deserialize() {
return this.from('render');
},
newline: function newline() {
return this.from('join')(['']);
}
});
/* ------------------------------------------------------------------------ */
ansi.names.forEach(function (color) {
var _log$methods, _mutatorMap;
log.methods((_log$methods = {}, _mutatorMap = {}, _mutatorMap[color] = _mutatorMap[color] || {}, _mutatorMap[color].get = function () {
return this.configure({ 'concat+': function concat(lines) {
return lines.map(ansi[color]);
} });
}, _defineEnumerableProperties(_log$methods, _mutatorMap), _log$methods));
});
/* ------------------------------------------------------------------------ */
module.exports = log;
/* ------------------------------------------------------------------------ */
},{"ansicolor":2,"pipez":12,"printable-characters":13,"stacktracey":27,"string.bullet":28,"string.ify":29}],2:[function(require,module,exports){
"use strict";
/* ------------------------------------------------------------------------ */
const O = Object
/* ------------------------------------------------------------------------ */
const
colorCodes = ['black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white', '', 'default'],
styleCodes = ['', 'bright', 'dim', 'italic', 'underline', '', '', 'inverse'],
types = { 0: 'style',
2: 'unstyle',
3: 'color',
4: 'bgColor',
10: 'bgColorBright' },
subtypes = { color: colorCodes,
bgColor: colorCodes,
bgColorBright: colorCodes,
style: styleCodes,
unstyle: styleCodes }
/* ------------------------------------------------------------------------ */
const clean = obj => {
for (const k in obj) { if (!obj[k]) { delete obj[k] } }
return (O.keys (obj).length === 0) ? undefined : obj
}
/* ------------------------------------------------------------------------ */
class Color {
constructor (background, name, brightness) {
this.background = background
this.name = name
this.brightness = brightness
}
get inverse () {
return new Color (!this.background, this.name || (this.background ? 'black' : 'white'), this.brightness)
}
get clean () {
return clean ({ name: this.name === 'default' ? '' : this.name,
bright: this.brightness === Code.bright,
dim: this.brightness === Code.dim })
}
defaultBrightness (value) {
return new Color (this.background, this.name, this.brightness || value)
}
css (inverted) {
const color = inverted ? this.inverse : this
const prop = (color.background ? 'background:' : 'color:'),
rgb = ((this.brightness === Code.bright) ? Colors.rgbBright : Colors.rgb)[color.name]
const alpha = (this.brightness === Code.dim) ? 0.5 : 1
return rgb
? (prop + 'rgba(' + [...rgb, alpha].join (',') + ');')
: ((!color.background && (alpha < 1)) ? 'color:rgba(0,0,0,0.5);' : '') // Chrome does not support 'opacity' property...
}
}
/* ------------------------------------------------------------------------ */
class Code {
constructor (n) {
if (n !== undefined) { this.value = Number (n) } }
get type () {
return types[Math.floor (this.value / 10)] }
get subtype () {
return subtypes[this.type][this.value % 10] }
get str () {
return (this.value ? ('\u001b\[' + this.value + 'm') : '') }
static str (x) {
return new Code (x).str }
get isBrightness () {
return (this.value === Code.noBrightness) || (this.value === Code.bright) || (this.value === Code.dim) }
}
/* ------------------------------------------------------------------------ */
O.assign (Code, {
bright: 1,
dim: 2,
inverse: 7,
noBrightness: 22,
noItalic: 23,
noUnderline: 24,
noInverse: 27,
noColor: 39,
noBgColor: 49
})
/* ------------------------------------------------------------------------ */
const camel = (a, b) => a + b.charAt (0).toUpperCase () + b.slice (1)
const replaceAll = (str, a, b) => str.split (a).join (b)
/* ANSI brightness codes do not overlap, e.g. "{bright}{dim}foo" will be rendered bright (not dim).
So we fix it by adding brightness canceling before each brightness code, so the former example gets
converted to "{noBrightness}{bright}{noBrightness}{dim}foo" – this way it gets rendered as expected.
*/
const denormalizeBrightness = s => s.replace (/(\u001b\[(1|2)m)/g, '\u001b[22m$1')
const normalizeBrightness = s => s.replace (/\u001b\[22m(\u001b\[(1|2)m)/g, '$1')
const wrap = (x, openCode, closeCode) => {
const open = Code.str (openCode),
close = Code.str (closeCode)
return String (x)
.split ('\n')
.map (line => denormalizeBrightness (open + replaceAll (normalizeBrightness (line), close, open) + close))
.join ('\n')
}
/* ------------------------------------------------------------------------ */
const stringWrappingMethods = (() => [
...colorCodes.map ((k, i) => !k ? [] : [ // color methods
[k, 30 + i, Code.noColor],
[camel ('bg', k), 40 + i, Code.noBgColor],
[camel ('bgBright', k), 100 + i, Code.noBgColor]
]),
...styleCodes.map ((k, i) => !k ? [] : [ // style methods
[k, i, ((k === 'bright') || (k === 'dim')) ? Code.noBrightness : (20 + i)]
])
]
.reduce ((a, b) => a.concat (b))
) ();
/* ------------------------------------------------------------------------ */
const assignStringWrappingAPI = (target, wrapBefore = target) =>
stringWrappingMethods.reduce ((memo, [k, open, close]) =>
O.defineProperty (memo, k, {
get: () => assignStringWrappingAPI (str => wrapBefore (wrap (str, open, close)))
}),
target)
/* ------------------------------------------------------------------------ */
/**
* Represents an ANSI-escaped string.
*/
class Colors {
/**
* @param {string} s a string containing ANSI escape codes.
*/
constructor (s) {
if (s) {
const r = /\u001b\[(\d+)m/g
const spans = s.split (/\u001b\[\d+m/)
const codes = []
for (let match; match = r.exec (s);) codes.push (match[1])
this.spans = spans.map ((s, i) => ({ text: s, code: new Code (codes[i]) }))
}
else {
this.spans = []
}
}
get str () {
return this.spans.reduce ((str, p) => str + p.text + p.code.str, '')
}
get parsed () {
var color = new Color (),
bgColor = new Color (true /* background */),
brightness = undefined,
styles = new Set ()
return O.assign (new Colors (), {
spans: this.spans.map (span => {
const c = span.code
const inverted = styles.has ('inverse'),
underline = styles.has ('underline') ? 'text-decoration: underline;' : '',
italic = styles.has ('italic') ? 'font-style: italic;' : '',
bold = brightness === Code.bright ? 'font-weight: bold;' : ''
const foreColor = color.defaultBrightness (brightness)
const styledSpan = O.assign (
{ css: bold + italic + underline + foreColor.css (inverted) + bgColor.css (inverted) },
clean ({ bold: !!bold, color: foreColor.clean, bgColor: bgColor.clean }),
span)
for (const k of styles) { styledSpan[k] = true }
if (c.isBrightness) {
brightness = c.value
} else {
switch (span.code.type) {
case 'color' : color = new Color (false, c.subtype); break
case 'bgColor' : bgColor = new Color (true, c.subtype); break
case 'bgColorBright': bgColor = new Color (true, c.subtype, Code.bright); break
case 'style' : styles.add (c.subtype); break
case 'unstyle': styles.delete (c.subtype); break
}
}
return styledSpan
}).filter (s => s.text.length > 0)
})
}
/* Outputs with Chrome DevTools-compatible format */
get asChromeConsoleLogArguments () {
const spans = this.parsed.spans
return [spans.map (s => ('%c' + s.text)).join (''),
...spans.map (s => s.css)]
}
get browserConsoleArguments () /* LEGACY, DEPRECATED */ { return this.asChromeConsoleLogArguments }
/**
* @desc installs String prototype extensions
* @example
* require ('ansicolor').nice
* console.log ('foo'.bright.red)
*/
static get nice () {
Colors.names.forEach (k => {
if (!(k in String.prototype)) {
O.defineProperty (String.prototype, k, { get: function () { return Colors[k] (this) } })
}
})
return Colors
}
/**
* @desc parses a string containing ANSI escape codes
* @return {Colors} parsed representation.
*/
static parse (s) {
return new Colors (s).parsed
}
/**
* @desc strips ANSI codes from a string
* @param {string} s a string containing ANSI escape codes.
* @return {string} clean string.
*/
static strip (s) {
return s.replace (/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-PRZcf-nqry=><]/g, '') // hope V8 caches the regexp
}
/**
* @example
* const spans = [...ansi.parse ('\u001b[7m\u001b[7mfoo\u001b[7mbar\u001b[27m')]
*/
[Symbol.iterator] () {
return this.spans[Symbol.iterator] ()
}
}
/* ------------------------------------------------------------------------ */
assignStringWrappingAPI (Colors, str => str)
/* ------------------------------------------------------------------------ */
Colors.names = stringWrappingMethods.map (([k]) => k)
/* ------------------------------------------------------------------------ */
Colors.rgb = {
black: [0, 0, 0],
red: [204, 0, 0],
green: [0, 204, 0],
yellow: [204, 102, 0],
blue: [0, 0, 255],
magenta: [204, 0, 204],
cyan: [0, 153, 255],
white: [255, 255, 255]
}
Colors.rgbBright = {
black: [0, 0, 0],
red: [255, 51, 0],
green: [51, 204, 51],
yellow: [255, 153, 51],
blue: [26, 140, 255],
magenta: [255, 0, 255],
cyan: [0, 204, 255],
white: [255, 255, 255]
}
/* ------------------------------------------------------------------------ */
module.exports = Colors
/* ------------------------------------------------------------------------ */
},{}],3:[function(require,module,exports){
"use strict";
const
O = Object,
{ first, strlen } = require ('printable-characters'), // handles ANSI codes and invisible characters
limit = (s, n) => (first (s, n - 1) + '…'),
asColumns = (rows, cfg_) => {
const
zip = (arrs, f) => arrs.reduce ((a, b) => b.map ((b, i) => [...a[i] || [], b]), []).map (args => f (...args)),
/* Convert cell data to string (converting multiline text to singleline) */
cells = rows.map (r => r.map (c => (c === undefined) ? '' : cfg_.print (c).replace (/\n/g, '\\n'))),
/* Compute column widths (per row) and max widths (per column) */
cellWidths = cells.map (r => r.map (strlen)),
maxWidths = zip (cellWidths, Math.max),
/* Default config */
cfg = O.assign ({
delimiter: ' ',
minColumnWidths: maxWidths.map (x => 0),
maxTotalWidth: 0 }, cfg_),
delimiterLength = strlen (cfg.delimiter),
/* Project desired column widths, taking maxTotalWidth and minColumnWidths in account. */
totalWidth = maxWidths.reduce ((a, b) => a + b, 0),
relativeWidths = maxWidths.map (w => w / totalWidth),
maxTotalWidth = cfg.maxTotalWidth - (delimiterLength * (maxWidths.length - 1)),
excessWidth = Math.max (0, totalWidth - maxTotalWidth),
computedWidths = zip ([cfg.minColumnWidths, maxWidths, relativeWidths],
(min, max, relative) => Math.max (min, Math.floor (max - excessWidth * relative))),
/* This is how many symbols we should pad or cut (per column). */
restCellWidths = cellWidths.map (widths => zip ([computedWidths, widths], (a, b) => a - b))
/* Perform final composition. */
return zip ([cells, restCellWidths], (a, b) =>
zip ([a, b], (str, w) => (w >= 0)
? (str + ' '.repeat (w))
: (limit (str, strlen (str) + w))).join (cfg.delimiter))
},
asTable = cfg => O.assign (arr => {
/* Print arrays */
if (arr[0] && Array.isArray (arr[0]))
return asColumns (arr, cfg).join ('\n')
/* Print objects */
const colNames = [...new Set ([].concat (...arr.map (O.keys)))],
columns = [colNames.map (cfg.title), ...arr.map (o => colNames.map (key => o[key]))],
lines = asColumns (columns, cfg)
return [lines[0], cfg.dash.repeat (strlen (lines[0])), ...lines.slice (1)].join ('\n')
}, cfg, {
configure: newConfig => asTable (O.assign ({}, cfg, newConfig)),
})
module.exports = asTable ({
maxTotalWidth: Number.MAX_SAFE_INTEGER,
print: String,
title: String,
dash: '-'
})
},{"printable-characters":13}],4:[function(require,module,exports){
'use strict'
exports.byteLength = byteLength
exports.toByteArray = toByteArray
exports.fromByteArray = fromByteArray
var lookup = []
var revLookup = []
var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
for (var i = 0, len = code.length; i < len; ++i) {
lookup[i] = code[i]
revLookup[code.charCodeAt(i)] = i
}
revLookup['-'.charCodeAt(0)] = 62
revLookup['_'.charCodeAt(0)] = 63
function placeHoldersCount (b64) {
var len = b64.length
if (len % 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
return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0
}
function byteLength (b64) {
// base64 is 4/3 + up to two characters of the original data
return (b64.length * 3 / 4) - placeHoldersCount(b64)
}
function toByteArray (b64) {
var i, l, tmp, placeHolders, arr
var len = b64.length
placeHolders = placeHoldersCount(b64)
arr = new Arr((len * 3 / 4) - placeHolders)
// if there are placeholders, only get up to the last complete 4 chars
l = placeHolders > 0 ? len - 4 : len
var L = 0
for (i = 0; i < l; i += 4) {
tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]
arr[L++] = (tmp >> 16) & 0xFF
arr[L++] = (tmp >> 8) & 0xFF
arr[L++] = tmp & 0xFF
}
if (placeHolders === 2) {
tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4)
arr[L++] = tmp & 0xFF
} else if (placeHolders === 1) {
tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2)
arr[L++] = (tmp >> 8) & 0xFF
arr[L++] = tmp & 0xFF
}
return arr
}
function tripletToBase64 (num) {
return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]
}
function encodeChunk (uint8, start, end) {
var tmp
var output = []
for (var i = start; i < end; i += 3) {
tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2])
output.push(tripletToBase64(tmp))
}
return output.join('')
}
function fromByteArray (uint8) {
var tmp
var len = uint8.length
var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
var output = ''
var parts = []
var maxChunkLength = 16383 // must be multiple of 3
// go through the array every three bytes, we'll deal with trailing stuff later
for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))
}
// pad the end with zeros, but make sure to not forget the extra bytes
if (extraBytes === 1) {
tmp = uint8[len - 1]
output += lookup[tmp >> 2]
output += lookup[(tmp << 4) & 0x3F]
output += '=='
} else if (extraBytes === 2) {
tmp = (uint8[len - 2] << 8) + (uint8[len - 1])
output += lookup[tmp >> 10]
output += lookup[(tmp >> 4) & 0x3F]
output += lookup[(tmp << 2) & 0x3F]
output += '='
}
parts.push(output)
return parts.join('')
}
},{}],5:[function(require,module,exports){
},{}],6:[function(require,module,exports){
/*!
* The buffer module from node.js, for the browser.
*
* @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
* @license MIT
*/
/* eslint-disable no-proto */
'use strict'
var base64 = require('base64-js')
var ieee754 = require('ieee754')
exports.Buffer = Buffer
exports.SlowBuffer = SlowBuffer
exports.INSPECT_MAX_BYTES = 50
var K_MAX_LENGTH = 0x7fffffff
exports.kMaxLength = K_MAX_LENGTH
/**
* If `Buffer.TYPED_ARRAY_SUPPORT`:
* === true Use Uint8Array implementation (fastest)
* === false Print warning and recommend using `buffer` v4.x which has an Object
* implementation (most compatible, even IE6)
*
* Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
* Opera 11.6+, iOS 4.2+.
*
* We report that the browser does not support typed arrays if the are not subclassable
* using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
* (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
* for __proto__ and has a buggy typed array implementation.
*/
Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport()
if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&
typeof console.error === 'function') {
console.error(
'This browser lacks typed array (Uint8Array) support which is required by ' +
'`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'
)
}
function typedArraySupport () {
// Can typed array instances can be augmented?
try {
var arr = new Uint8Array(1)
arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }}
return arr.foo() === 42
} catch (e) {
return false
}
}
function createBuffer (length) {
if (length > K_MAX_LENGTH) {
throw new RangeError('Invalid typed array length')
}
// Return an augmented `Uint8Array` instance
var buf = new Uint8Array(length)
buf.__proto__ = Buffer.prototype
return buf
}
/**
* The Buffer constructor returns instances of `Uint8Array` that have their
* prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
* `Uint8Array`, so the returned instances will have all the node `Buffer` methods
* and the `Uint8Array` methods. Square bracket notation works as expected -- it
* returns a single octet.
*
* The `Uint8Array` prototype remains unmodified.
*/
function Buffer (arg, encodingOrOffset, length) {
// Common case.
if (typeof arg === 'number') {
if (typeof encodingOrOffset === 'string') {
throw new Error(
'If encoding is specified then the first argument must be a string'
)
}
return allocUnsafe(arg)
}
return from(arg, encodingOrOffset, length)
}
// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
if (typeof Symbol !== 'undefined' && Symbol.species &&
Buffer[Symbol.species] === Buffer) {
Object.defineProperty(Buffer, Symbol.species, {
value: null,
configurable: true,
enumerable: false,
writable: false
})
}
Buffer.poolSize = 8192 // not used by this implementation
function from (value, encodingOrOffset, length) {
if (typeof value === 'number') {
throw new TypeError('"value" argument must not be a number')
}
if (value instanceof ArrayBuffer) {
return fromArrayBuffer(value, encodingOrOffset, length)
}
if (typeof value === 'string') {
return fromString(value, encodingOrOffset)
}
return fromObject(value)
}
/**
* Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
* if value is a number.
* Buffer.from(str[, encoding])
* Buffer.from(array)
* Buffer.from(buffer)
* Buffer.from(arrayBuffer[, byteOffset[, length]])
**/
Buffer.from = function (value, encodingOrOffset, length) {
return from(value, encodingOrOffset, length)
}
// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
// https://github.com/feross/buffer/pull/148
Buffer.prototype.__proto__ = Uint8Array.prototype
Buffer.__proto__ = Uint8Array
function assertSize (size) {
if (typeof size !== 'number') {
throw new TypeError('"size" argument must be a number')
} else if (size < 0) {
throw new RangeError('"size" argument must not be negative')
}
}
function alloc (size, fill, encoding) {
assertSize(size)
if (size <= 0) {
return createBuffer(size)
}
if (fill !== undefined) {
// Only pay attention to encoding if it's a string. This
// prevents accidentally sending in a number that would
// be interpretted as a start offset.
return typeof encoding === 'string'
? createBuffer(size).fill(fill, encoding)
: createBuffer(size).fill(fill)
}
return createBuffer(size)
}
/**
* Creates a new filled Buffer instance.
* alloc(size[, fill[, encoding]])
**/
Buffer.alloc = function (size, fill, encoding) {
return alloc(size, fill, encoding)
}
function allocUnsafe (size) {
assertSize(size)
return createBuffer(size < 0 ? 0 : checked(size) | 0)
}
/**
* Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
* */
Buffer.allocUnsafe = function (size) {
return allocUnsafe(size)
}
/**
* Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
*/
Buffer.allocUnsafeSlow = function (size) {
return allocUnsafe(size)
}
function fromString (string, encoding) {
if (typeof encoding !== 'string' || encoding === '') {
encoding = 'utf8'
}
if (!Buffer.isEncoding(encoding)) {
throw new TypeError('"encoding" must be a valid string encoding')
}
var length = byteLength(string, encoding) | 0
var buf = createBuffer(length)
var actual = buf.write(string, encoding)
if (actual !== length) {
// Writing a hex string, for example, that contains invalid characters will
// cause everything after the first invalid character to be ignored. (e.g.
// 'abxxcd' will be treated as 'ab')
buf = buf.slice(0, actual)
}
return buf
}
function fromArrayLike (array) {
var length = array.length < 0 ? 0 : checked(array.length) | 0
var buf = createBuffer(length)
for (var i = 0; i < length; i += 1) {
buf[i] = array[i] & 255
}
return buf
}
function fromArrayBuffer (array, byteOffset, length) {
if (byteOffset < 0 || array.byteLength < byteOffset) {
throw new RangeError('\'offset\' is out of bounds')
}
if (array.byteLength < byteOffset + (length || 0)) {
throw new RangeError('\'length\' is out of bounds')
}
var buf
if (byteOffset === undefined && length === undefined) {
buf = new Uint8Array(array)
} else if (length === undefined) {
buf = new Uint8Array(array, byteOffset)
} else {
buf = new Uint8Array(array, byteOffset, length)
}
// Return an augmented `Uint8Array` instance
buf.__proto__ = Buffer.prototype
return buf
}
function fromObject (obj) {
if (Buffer.isBuffer(obj)) {
var len = checked(obj.length) | 0
var buf = createBuffer(len)
if (buf.length === 0) {
return buf
}
obj.copy(buf, 0, 0, len)
return buf
}
if (obj) {
if (isArrayBufferView(obj) || 'length' in obj) {
if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
return createBuffer(0)
}
return fromArrayLike(obj)
}
if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
return fromArrayLike(obj.data)
}
}
throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')
}
function checked (length) {
// Note: cannot use `length < K_MAX_LENGTH` here because that fails when
// length is NaN (which is otherwise coerced to zero.)
if (length >= K_MAX_LENGTH) {
throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')
}
return length | 0
}
function SlowBuffer (length) {
if (+length != length) { // eslint-disable-line eqeqeq
length = 0
}
return Buffer.alloc(+length)
}
Buffer.isBuffer = function isBuffer (b) {
return b != null && b._isBuffer === true
}
Buffer.compare = function compare (a, b) {
if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
throw new TypeError('Arguments must be Buffers')
}
if (a === b) return 0
var x = a.length
var y = b.length
for (var i = 0, len = Math.min(x, y); i < len; ++i) {
if (a[i] !== b[i]) {
x = a[i]
y = b[i]
break
}
}
if (x < y) return -1
if (y < x) return 1
return 0
}
Buffer.isEncoding = function isEncoding (encoding) {
switch (String(encoding).toLowerCase()) {
case 'hex':
case 'utf8':
case 'utf-8':
case 'ascii':
case 'latin1':
case 'binary':
case 'base64':
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return true
default:
return false
}
}
Buffer.concat = function concat (list, length) {
if (!Array.isArray(list)) {
throw new TypeError('"list" argument must be an Array of Buffers')
}
if (list.length === 0) {
return Buffer.alloc(0)
}
var i
if (length === undefined) {
length = 0
for (i = 0; i < list.length; ++i) {
length += list[i].length
}
}
var buffer = Buffer.allocUnsafe(length)
var pos = 0
for (i = 0; i < list.length; ++i) {
var buf = list[i]
if (!Buffer.isBuffer(buf)) {
throw new TypeError('"list" argument must be an Array of Buffers')
}
buf.copy(buffer, pos)
pos += buf.length
}
return buffer
}
function byteLength (string, encoding) {
if (Buffer.isBuffer(string)) {
return string.length
}
if (isArrayBufferView(string) || string instanceof ArrayBuffer) {
return string.byteLength
}
if (typeof string !== 'string') {
string = '' + string
}
var len = string.length
if (len === 0) return 0
// Use a for loop to avoid recursion
var loweredCase = false
for (;;) {
switch (encoding) {
case 'ascii':
case 'latin1':
case 'binary':
return len
case 'utf8':
case 'utf-8':
case undefined:
return utf8ToBytes(string).length
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return len * 2
case 'hex':
return len >>> 1
case 'base64':
return base64ToBytes(string).length
default:
if (loweredCase) return utf8ToBytes(string).length // assume utf8
encoding = ('' + encoding).toLowerCase()
loweredCase = true
}
}
}
Buffer.byteLength = byteLength
function slowToString (encoding, start, end) {
var loweredCase = false
// No need to verify that "this.length <= MAX_UINT32" since it's a read-only
// property of a typed array.
// This behaves neither like String nor Uint8Array in that we set start/end
// to their upper/lower bounds if the value passed is out of range.
// undefined is handled specially as per ECMA-262 6th Edition,
// Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
if (start === undefined || start < 0) {
start = 0
}
// Return early if start > this.length. Done here to prevent potential uint32
// coercion fail below.
if (start > this.length) {
return ''
}
if (end === undefined || end > this.length) {
end = this.length
}
if (end <= 0) {
return ''
}
// Force coersion to uint32. This will also coerce falsey/NaN values to 0.
end >>>= 0
start >>>= 0
if (end <= start) {
return ''
}
if (!encoding) encoding = 'utf8'
while (true) {
switch (encoding) {
case 'hex':
return hexSlice(this, start, end)
case 'utf8':
case 'utf-8':
return utf8Slice(this, start, end)
case 'ascii':
return asciiSlice(this, start, end)
case 'latin1':
case 'binary':
return latin1Slice(this, start, end)
case 'base64':
return base64Slice(this, start, end)
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return utf16leSlice(this, start, end)
default:
if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
encoding = (encoding + '').toLowerCase()
loweredCase = true
}
}
}
// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
// to detect a Buffer instance. It's not possible to use `instanceof Buffer`
// reliably in a browserify context because there could be multiple different
// copies of the 'buffer' package in use. This method works even for Buffer
// instances that were created from another copy of the `buffer` package.
// See: https://github.com/feross/buffer/issues/154
Buffer.prototype._isBuffer = true
function swap (b, n, m) {
var i = b[n]
b[n] = b[m]
b[m] = i
}
Buffer.prototype.swap16 = function swap16 () {
var len = this.length
if (len % 2 !== 0) {
throw new RangeError('Buffer size must be a multiple of 16-bits')
}
for (var i = 0; i < len; i += 2) {
swap(this, i, i + 1)
}
return this
}
Buffer.prototype.swap32 = function swap32 () {
var len = this.length
if (len % 4 !== 0) {
throw new RangeError('Buffer size must be a multiple of 32-bits')
}
for (var i = 0; i < len; i += 4) {
swap(this, i, i + 3)
swap(this, i + 1, i + 2)
}
return this
}
Buffer.prototype.swap64 = function swap64 () {
var len = this.length
if (len % 8 !== 0) {
throw new RangeError('Buffer size must be a multiple of 64-bits')
}
for (var i = 0; i < len; i += 8) {
swap(this, i, i + 7)
swap(this, i + 1, i + 6)
swap(this, i + 2, i + 5)
swap(this, i + 3, i + 4)
}
return this
}
Buffer.prototype.toString = function toString () {
var length = this.length
if (length === 0) return ''
if (arguments.length === 0) return utf8Slice(this, 0, length)
return slowToString.apply(this, arguments)
}
Buffer.prototype.equals = function equals (b) {
if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
if (this === b) return true
return Buffer.compare(this, b) === 0
}
Buffer.prototype.inspect = function inspect () {
var str = ''
var max = exports.INSPECT_MAX_BYTES
if (this.length > 0) {
str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')
if (this.length > max) str += ' ... '
}
return '<Buffer ' + str + '>'
}
Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
if (!Buffer.isBuffer(target)) {
throw new TypeError('Argument must be a Buffer')
}
if (start === undefined) {
start = 0
}
if (end === undefined) {
end = target ? target.length : 0
}
if (thisStart === undefined) {
thisStart = 0
}
if (thisEnd === undefined) {
thisEnd = this.length
}
if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
throw new RangeError('out of range index')
}
if (thisStart >= thisEnd && start >= end) {
return 0
}
if (thisStart >= thisEnd) {
return -1
}
if (start >= end) {
return 1
}
start >>>= 0
end >>>= 0
thisStart >>>= 0
thisEnd >>>= 0
if (this === target) return 0
var x = thisEnd - thisStart
var y = end - start
var len = Math.min(x, y)
var thisCopy = this.slice(thisStart, thisEnd)
var targetCopy = target.slice(start, end)
for (var i = 0; i < len; ++i) {
if (thisCopy[i] !== targetCopy[i]) {
x = thisCopy[i]
y = targetCopy[i]
break
}
}
if (x < y) return -1
if (y < x) return 1
return 0
}
// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
// OR the last index of `val` in `buffer` at offset <= `byteOffset`.
//
// Arguments:
// - buffer - a Buffer to search
// - val - a string, Buffer, or number
// - byteOffset - an index into `buffer`; will be clamped to an int32
// - encoding - an optional encoding, relevant is val is a string
// - dir - true for indexOf, false for lastIndexOf
function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
// Empty buffer means no match
if (buffer.length === 0) return -1
// Normalize byteOffset
if (typeof byteOffset === 'string') {
encoding = byteOffset
byteOffset = 0
} else if (byteOffset > 0x7fffffff) {
byteOffset = 0x7fffffff
} else if (byteOffset < -0x80000000) {
byteOffset = -0x80000000
}
byteOffset = +byteOffset // Coerce to Number.
if (numberIsNaN(byteOffset)) {
// byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
byteOffset = dir ? 0 : (buffer.length - 1)
}
// Normalize byteOffset: negative offsets start from the end of the buffer
if (byteOffset < 0) byteOffset = buffer.length + byteOffset
if (byteOffset >= buffer.length) {
if (dir) return -1
else byteOffset = buffer.length - 1
} else if (byteOffset < 0) {
if (dir) byteOffset = 0
else return -1
}
// Normalize val
if (typeof val === 'string') {
val = Buffer.from(val, encoding)
}
// Finally, search either indexOf (if dir is true) or lastIndexOf
if (Buffer.isBuffer(val)) {
// Special case: looking for empty string/buffer always fails
if (val.length === 0) {
return -1
}
return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
} else if (typeof val === 'number') {
val = val & 0xFF // Search for a byte value [0-255]
if (typeof Uint8Array.prototype.indexOf === 'function') {
if (dir) {
return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
} else {
return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
}
}
return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
}
throw new TypeError('val must be string, number or Buffer')
}
function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
var indexSize = 1
var arrLength = arr.length
var valLength = val.length
if (encoding !== undefined) {
encoding = String(encoding).toLowerCase()
if (encoding === 'ucs2' || encoding === 'ucs-2' ||
encoding === 'utf16le' || encoding === 'utf-16le') {
if (arr.length < 2 || val.length < 2) {
return -1
}
indexSize = 2
arrLength /= 2
valLength /= 2
byteOffset /= 2
}
}
function read (buf, i) {
if (indexSize === 1) {
return buf[i]
} else {
return buf.readUInt16BE(i * indexSize)
}
}
var i
if (dir) {
var foundIndex = -1
for (i = byteOffset; i < arrLength; i++) {
if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
if (foundIndex === -1) foundIndex = i
if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
} else {
if (foundIndex !== -1) i -= i - foundIndex
foundIndex = -1
}
}
} else {
if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
for (i = byteOffset; i >= 0; i--) {
var found = true
for (var j = 0; j < valLength; j++) {
if (read(arr, i + j) !== read(val, j)) {
found = false
break
}
}
if (found) return i
}
}
return -1
}
Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
return this.indexOf(val, byteOffset, encoding) !== -1
}
Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
}
Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
}
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
if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')
if (length > strLen / 2) {
length = strLen / 2
}
for (var i = 0; i < length; ++i) {
var parsed = parseInt(string.substr(i * 2, 2), 16)
if (numberIsNaN(parsed)) return i
buf[offset + i] = parsed
}
return i
}
function utf8Write (buf, string, offset, length) {
return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
}
function asciiWrite (buf, string, offset, length) {
return blitBuffer(asciiToBytes(string), buf, offset, length)
}
function latin1Write (buf, string, offset, length) {
return asciiWrite(buf, string, offset, length)
}
function base64Write (buf, string, offset, length) {
return blitBuffer(base64ToBytes(string), buf, offset, length)
}
function ucs2Write (buf, string, offset, length) {
return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
}
Buffer.prototype.write = function write (string, offset, length, encoding) {
// Buffer#write(string)
if (offset === undefined) {
encoding = 'utf8'
length = this.length
offset = 0
// Buffer#write(string, encoding)
} else if (length === undefined && typeof offset === 'string') {
encoding = offset
length = this.length
offset = 0
// Buffer#write(string, offset[, length][, encoding])
} else if (isFinite(offset)) {
offset = offset >>> 0
if (isFinite(length)) {
length = length >>> 0
if (encoding === undefined) encoding = 'utf8'
} else {
encoding = length
length = undefined
}
} else {
throw new Error(
'Buffer.write(string, encoding, offset[, length]) is