Skip to content

Instantly share code, notes, and snippets.

@mustafa-colakoglu
Created February 17, 2017 18:30
Show Gist options
  • Save mustafa-colakoglu/08116c6b748d0c307b97fe0d759616b3 to your computer and use it in GitHub Desktop.
Save mustafa-colakoglu/08116c6b748d0c307b97fe0d759616b3 to your computer and use it in GitHub Desktop.
This gist exceeds the recommended number of files (~10). To access all files, please clone this gist.
<?xml version="1.0" encoding="UTF-8"?>
<module type="WEB_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$">
<excludeFolder url="file://$MODULE_DIR$/.tmp" />
<excludeFolder url="file://$MODULE_DIR$/temp" />
<excludeFolder url="file://$MODULE_DIR$/tmp" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/cafe.iml" filepath="$PROJECT_DIR$/.idea/cafe.iml" />
</modules>
</component>
</project>
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project>
nodemon cafe.js
var express = require("express");
var md5 = require('md5');
var app = express();
var ip = require('ip');
app.use("/js",express.static(__dirname+"/js"));
app.use("/css",express.static(__dirname+"/css"));
app.use("/pages",express.static(__dirname+"/pages"));
var server = app.listen(83);
var io = require("socket.io").listen(server);
var mysql = require("mysql");
var connect = mysql.createConnection({
"host":"127.0.0.1", // localhost olmaz
"user":"root",
"password":"",
"database":"cafe",
"port":3306
});
connect.connect();
function masaNode(){
this.masaNo = "";
this.socketId = "";
this.ip = "";
this.next = undefined;
}
function masaBl(socket){
this.socket = socket;
this.root = undefined;
this.last = undefined;
this.insert = function(masaNo,socketId,ip){
var newMasaNode = new masaNode();
newMasaNode.masaNo = masaNo;
newMasaNode.socketId = socketId;
newMasaNode.ip = ip;
if(this.root == undefined){
this.root = newMasaNode;
this.last = newMasaNode;
}
else{
this.last.next = newMasaNode;
this.last = newMasaNode;
}
}
this.del = function(socketId){
if(this.root.socketId == socketId){
this.root = this.root.next;
}
else{
var temp = this.root.next;
var prev = this.root;
while(temp != undefined){
if(temp.socketId == socketId){
prev.next = temp.next;
}
prev = temp;
temp = temp.next;
}
}
}
this.edit = function(socketId,newSocketId){
var temp = this.root;
while(temp != undefined){
if(temp.socketId == socketId){
temp.socketId = newSocketId;
break;
}
temp = temp.next;
}
}
this.sendAll = function(variableName,data){
var temp = this.root;
while(temp != undefined){
this.socket.to(temp.socketId).emit(variableName,data);
temp = temp.next;
}
}
}
function garsonNode(){
this.username = "";
this.socketId = "";
this.ip = "";
this.next = undefined;
}
function garsonBl(socket){
this.socket = socket;
this.root = undefined;
this.last = undefined;
this.insert = function(username,socketId,ip){
var newGarsonNode = new garsonNode();
newGarsonNode.username = username;
newGarsonNode.socketId = socketId;
newGarsonNode.ip = ip;
if(this.root == undefined){
this.root = newGarsonNode;
this.last = newGarsonNode;
}
else{
this.last.next = newGarsonNode;
this.last = newGarsonNode;
}
}
this.del = function(socketId){
if(this.root.socketId == socketId){
this.root = this.root.next;
}
else{
var temp = this.root.next;
var prev = this.root;
while(temp != undefined){
if(temp.socketId == socketId){
prev.next = temp.next;
}
prev = temp;
temp = temp.next;
}
}
}
this.edit = function(socketId,newSocketId){
var temp = this.root;
while(temp != undefined){
if(temp.socketId == socketId){
temp.socketId = newSocketId;
break;
}
temp = temp.next;
}
}
this.sendAll = function(variableName,data){
var temp = this.root;
while(temp != undefined){
this.socket.to(temp.socketId).emit(variableName,data);
temp = temp.next;
}
}
}
var masaBl = new masaBl(io);
var garsonBl = new garsonBl(io);
io.sockets.on("connection",function(socket){
socket.on("firstLogin",function(data){
var ip = socket.handshake.address;
connect.query("SELECT * FROM masalar WHERE doluMu='1' and ip="+mysql.escape(ip),function(error,result){
if(error == null){
if(result.length > 0){
io.to(socket.id).emit("listenFirstLogin",{"login":true});
}
else{
io.to(socket.id).emit("listenFirstLogin",{"login":false});
}
}
else{
console.log(error);
}
});
});
socket.on("garsonFirstLogin",function(data){
var ip = socket.handshake.address;
connect.query("SELECT * FROM garsonlar WHERE ip="+mysql.escape(ip),function(error,result){
if(error == null){
if(result.length > 0){
io.to(socket.id).emit("listenGarsonFirstLogin",{"login":true});
}
else{
io.to(socket.id).emit("listenGarsonFirstLogin",{"login":false});
}
}
else{
console.log(error);
}
});
});
socket.on("garsonLogin",function(data){
console.log(data);
var ip = socket.handshake.address;
var username = mysql.escape(data.username);
var password = mysql.escape(md5(data.password));
connect.query("SELECT * FROM garsonlar WHERE username="+username+" and password="+password,function (error,result) {
console.log(result.length)
});
});
});
app.get("/garson",function(req,res){
res.sendFile(__dirname+"/pages/garson.html");
});
app.get("/",function(req,res){
res.sendFile(__dirname+"/pages/use.html");
});
/* Sıfırlamalar */
body,html{
width:100%;
height:100%;
margin:0;
padding:0;
}
p,h1,h2,h3,h4,h5,h6,ul,li,div,nav,img,textarea,header,footer,section,video,audio,canvas,textarea,menu,iframe{
display:block;
margin:0;
padding:0;
position:relative;
float:left;
border:0;
list-style-type:none;
}
a{
text-decoration:none;
}
:focus{
outline:0;
}
*::-moz-selection{
background:#74cff9;
}
var socket = io.connect();
socket.emit("garsonFirstLogin",true);
socket.on("listenGarsonFirstLogin",function(data){
if(data.login == true){
$(document).ready(function(){
$("title").html("Giriş Başarılı");
$(".garsonGiris").hide();
$(".garson").show();
});
}
else{
$(document).ready(function(){
$("title").html("Giriş Yapın");
$(".garsonGiris").show();
$(".garson").hide();
});
}
});
function login(){
$(document).ready(function(){
var username = $("input[name='username']").val();
var password = $("input[name='password']").val();
socket.emit("garsonLogin",{"username":username,"password":password});
});
}
/*! jQuery v1.11.0 | (c) 2005, 2014 jQuery Foundation, Inc. | jquery.org/license */
!function(a,b){"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}("undefined"!=typeof window?window:this,function(a,b){var c=[],d=c.slice,e=c.concat,f=c.push,g=c.indexOf,h={},i=h.toString,j=h.hasOwnProperty,k="".trim,l={},m="1.11.0",n=function(a,b){return new n.fn.init(a,b)},o=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,p=/^-ms-/,q=/-([\da-z])/gi,r=function(a,b){return b.toUpperCase()};n.fn=n.prototype={jquery:m,constructor:n,selector:"",length:0,toArray:function(){return d.call(this)},get:function(a){return null!=a?0>a?this[a+this.length]:this[a]:d.call(this)},pushStack:function(a){var b=n.merge(this.constructor(),a);return b.prevObject=this,b.context=this.context,b},each:function(a,b){return n.each(this,a,b)},map:function(a){return this.pushStack(n.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(d.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(0>a?b:0);return this.pushStack(c>=0&&b>c?[this[c]]:[])},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:c.sort,splice:c.splice},n.extend=n.fn.extend=function(){var a,b,c,d,e,f,g=arguments[0]||{},h=1,i=arguments.length,j=!1;for("boolean"==typeof g&&(j=g,g=arguments[h]||{},h++),"object"==typeof g||n.isFunction(g)||(g={}),h===i&&(g=this,h--);i>h;h++)if(null!=(e=arguments[h]))for(d in e)a=g[d],c=e[d],g!==c&&(j&&c&&(n.isPlainObject(c)||(b=n.isArray(c)))?(b?(b=!1,f=a&&n.isArray(a)?a:[]):f=a&&n.isPlainObject(a)?a:{},g[d]=n.extend(j,f,c)):void 0!==c&&(g[d]=c));return g},n.extend({expando:"jQuery"+(m+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===n.type(a)},isArray:Array.isArray||function(a){return"array"===n.type(a)},isWindow:function(a){return null!=a&&a==a.window},isNumeric:function(a){return a-parseFloat(a)>=0},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},isPlainObject:function(a){var b;if(!a||"object"!==n.type(a)||a.nodeType||n.isWindow(a))return!1;try{if(a.constructor&&!j.call(a,"constructor")&&!j.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}if(l.ownLast)for(b in a)return j.call(a,b);for(b in a);return void 0===b||j.call(a,b)},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?h[i.call(a)]||"object":typeof a},globalEval:function(b){b&&n.trim(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(p,"ms-").replace(q,r)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,b,c){var d,e=0,f=a.length,g=s(a);if(c){if(g){for(;f>e;e++)if(d=b.apply(a[e],c),d===!1)break}else for(e in a)if(d=b.apply(a[e],c),d===!1)break}else if(g){for(;f>e;e++)if(d=b.call(a[e],e,a[e]),d===!1)break}else for(e in a)if(d=b.call(a[e],e,a[e]),d===!1)break;return a},trim:k&&!k.call("\ufeff\xa0")?function(a){return null==a?"":k.call(a)}:function(a){return null==a?"":(a+"").replace(o,"")},makeArray:function(a,b){var c=b||[];return null!=a&&(s(Object(a))?n.merge(c,"string"==typeof a?[a]:a):f.call(c,a)),c},inArray:function(a,b,c){var d;if(b){if(g)return g.call(b,a,c);for(d=b.length,c=c?0>c?Math.max(0,d+c):c:0;d>c;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,b){var c=+b.length,d=0,e=a.length;while(c>d)a[e++]=b[d++];if(c!==c)while(void 0!==b[d])a[e++]=b[d++];return a.length=e,a},grep:function(a,b,c){for(var d,e=[],f=0,g=a.length,h=!c;g>f;f++)d=!b(a[f],f),d!==h&&e.push(a[f]);return e},map:function(a,b,c){var d,f=0,g=a.length,h=s(a),i=[];if(h)for(;g>f;f++)d=b(a[f],f,c),null!=d&&i.push(d);else for(f in a)d=b(a[f],f,c),null!=d&&i.push(d);return e.apply([],i)},guid:1,proxy:function(a,b){var c,e,f;return"string"==typeof b&&(f=a[b],b=a,a=f),n.isFunction(a)?(c=d.call(arguments,2),e=function(){return a.apply(b||this,c.concat(d.call(arguments)))},e.guid=a.guid=a.guid||n.guid++,e):void 0},now:function(){return+new Date},support:l}),n.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(a,b){h["[object "+b+"]"]=b.toLowerCase()});function s(a){var b=a.length,c=n.type(a);return"function"===c||n.isWindow(a)?!1:1===a.nodeType&&b?!0:"array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a}var t=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s="sizzle"+-new Date,t=a.document,u=0,v=0,w=eb(),x=eb(),y=eb(),z=function(a,b){return a===b&&(j=!0),0},A="undefined",B=1<<31,C={}.hasOwnProperty,D=[],E=D.pop,F=D.push,G=D.push,H=D.slice,I=D.indexOf||function(a){for(var b=0,c=this.length;c>b;b++)if(this[b]===a)return b;return-1},J="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",K="[\\x20\\t\\r\\n\\f]",L="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",M=L.replace("w","w#"),N="\\["+K+"*("+L+")"+K+"*(?:([*^$|!~]?=)"+K+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+M+")|)|)"+K+"*\\]",O=":("+L+")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|"+N.replace(3,8)+")*)|.*)\\)|)",P=new RegExp("^"+K+"+|((?:^|[^\\\\])(?:\\\\.)*)"+K+"+$","g"),Q=new RegExp("^"+K+"*,"+K+"*"),R=new RegExp("^"+K+"*([>+~]|"+K+")"+K+"*"),S=new RegExp("="+K+"*([^\\]'\"]*?)"+K+"*\\]","g"),T=new RegExp(O),U=new RegExp("^"+M+"$"),V={ID:new RegExp("^#("+L+")"),CLASS:new RegExp("^\\.("+L+")"),TAG:new RegExp("^("+L.replace("w","w*")+")"),ATTR:new RegExp("^"+N),PSEUDO:new RegExp("^"+O),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+K+"*(even|odd|(([+-]|)(\\d*)n|)"+K+"*(?:([+-]|)"+K+"*(\\d+)|))"+K+"*\\)|)","i"),bool:new RegExp("^(?:"+J+")$","i"),needsContext:new RegExp("^"+K+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+K+"*((?:-\\d)?\\d*)"+K+"*\\)|)(?=[^-]|$)","i")},W=/^(?:input|select|textarea|button)$/i,X=/^h\d$/i,Y=/^[^{]+\{\s*\[native \w/,Z=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,$=/[+~]/,_=/'|\\/g,ab=new RegExp("\\\\([\\da-f]{1,6}"+K+"?|("+K+")|.)","ig"),bb=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:0>d?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)};try{G.apply(D=H.call(t.childNodes),t.childNodes),D[t.childNodes.length].nodeType}catch(cb){G={apply:D.length?function(a,b){F.apply(a,H.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function db(a,b,d,e){var f,g,h,i,j,m,p,q,u,v;if((b?b.ownerDocument||b:t)!==l&&k(b),b=b||l,d=d||[],!a||"string"!=typeof a)return d;if(1!==(i=b.nodeType)&&9!==i)return[];if(n&&!e){if(f=Z.exec(a))if(h=f[1]){if(9===i){if(g=b.getElementById(h),!g||!g.parentNode)return d;if(g.id===h)return d.push(g),d}else if(b.ownerDocument&&(g=b.ownerDocument.getElementById(h))&&r(b,g)&&g.id===h)return d.push(g),d}else{if(f[2])return G.apply(d,b.getElementsByTagName(a)),d;if((h=f[3])&&c.getElementsByClassName&&b.getElementsByClassName)return G.apply(d,b.getElementsByClassName(h)),d}if(c.qsa&&(!o||!o.test(a))){if(q=p=s,u=b,v=9===i&&a,1===i&&"object"!==b.nodeName.toLowerCase()){m=ob(a),(p=b.getAttribute("id"))?q=p.replace(_,"\\$&"):b.setAttribute("id",q),q="[id='"+q+"'] ",j=m.length;while(j--)m[j]=q+pb(m[j]);u=$.test(a)&&mb(b.parentNode)||b,v=m.join(",")}if(v)try{return G.apply(d,u.querySelectorAll(v)),d}catch(w){}finally{p||b.removeAttribute("id")}}}return xb(a.replace(P,"$1"),b,d,e)}function eb(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function fb(a){return a[s]=!0,a}function gb(a){var b=l.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function hb(a,b){var c=a.split("|"),e=a.length;while(e--)d.attrHandle[c[e]]=b}function ib(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&(~b.sourceIndex||B)-(~a.sourceIndex||B);if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function jb(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function kb(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function lb(a){return fb(function(b){return b=+b,fb(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function mb(a){return a&&typeof a.getElementsByTagName!==A&&a}c=db.support={},f=db.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},k=db.setDocument=function(a){var b,e=a?a.ownerDocument||a:t,g=e.defaultView;return e!==l&&9===e.nodeType&&e.documentElement?(l=e,m=e.documentElement,n=!f(e),g&&g!==g.top&&(g.addEventListener?g.addEventListener("unload",function(){k()},!1):g.attachEvent&&g.attachEvent("onunload",function(){k()})),c.attributes=gb(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=gb(function(a){return a.appendChild(e.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=Y.test(e.getElementsByClassName)&&gb(function(a){return a.innerHTML="<div class='a'></div><div class='a i'></div>",a.firstChild.className="i",2===a.getElementsByClassName("i").length}),c.getById=gb(function(a){return m.appendChild(a).id=s,!e.getElementsByName||!e.getElementsByName(s).length}),c.getById?(d.find.ID=function(a,b){if(typeof b.getElementById!==A&&n){var c=b.getElementById(a);return c&&c.parentNode?[c]:[]}},d.filter.ID=function(a){var b=a.replace(ab,bb);return function(a){return a.getAttribute("id")===b}}):(delete d.find.ID,d.filter.ID=function(a){var b=a.replace(ab,bb);return function(a){var c=typeof a.getAttributeNode!==A&&a.getAttributeNode("id");return c&&c.value===b}}),d.find.TAG=c.getElementsByTagName?function(a,b){return typeof b.getElementsByTagName!==A?b.getElementsByTagName(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){while(c=f[e++])1===c.nodeType&&d.push(c);return d}return f},d.find.CLASS=c.getElementsByClassName&&function(a,b){return typeof b.getElementsByClassName!==A&&n?b.getElementsByClassName(a):void 0},p=[],o=[],(c.qsa=Y.test(e.querySelectorAll))&&(gb(function(a){a.innerHTML="<select t=''><option selected=''></option></select>",a.querySelectorAll("[t^='']").length&&o.push("[*^$]="+K+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||o.push("\\["+K+"*(?:value|"+J+")"),a.querySelectorAll(":checked").length||o.push(":checked")}),gb(function(a){var b=e.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&o.push("name"+K+"*[*^$|!~]?="),a.querySelectorAll(":enabled").length||o.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),o.push(",.*:")})),(c.matchesSelector=Y.test(q=m.webkitMatchesSelector||m.mozMatchesSelector||m.oMatchesSelector||m.msMatchesSelector))&&gb(function(a){c.disconnectedMatch=q.call(a,"div"),q.call(a,"[s!='']:x"),p.push("!=",O)}),o=o.length&&new RegExp(o.join("|")),p=p.length&&new RegExp(p.join("|")),b=Y.test(m.compareDocumentPosition),r=b||Y.test(m.contains)?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)while(b=b.parentNode)if(b===a)return!0;return!1},z=b?function(a,b){if(a===b)return j=!0,0;var d=!a.compareDocumentPosition-!b.compareDocumentPosition;return d?d:(d=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&d||!c.sortDetached&&b.compareDocumentPosition(a)===d?a===e||a.ownerDocument===t&&r(t,a)?-1:b===e||b.ownerDocument===t&&r(t,b)?1:i?I.call(i,a)-I.call(i,b):0:4&d?-1:1)}:function(a,b){if(a===b)return j=!0,0;var c,d=0,f=a.parentNode,g=b.parentNode,h=[a],k=[b];if(!f||!g)return a===e?-1:b===e?1:f?-1:g?1:i?I.call(i,a)-I.call(i,b):0;if(f===g)return ib(a,b);c=a;while(c=c.parentNode)h.unshift(c);c=b;while(c=c.parentNode)k.unshift(c);while(h[d]===k[d])d++;return d?ib(h[d],k[d]):h[d]===t?-1:k[d]===t?1:0},e):l},db.matches=function(a,b){return db(a,null,null,b)},db.matchesSelector=function(a,b){if((a.ownerDocument||a)!==l&&k(a),b=b.replace(S,"='$1']"),!(!c.matchesSelector||!n||p&&p.test(b)||o&&o.test(b)))try{var d=q.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return db(b,l,null,[a]).length>0},db.contains=function(a,b){return(a.ownerDocument||a)!==l&&k(a),r(a,b)},db.attr=function(a,b){(a.ownerDocument||a)!==l&&k(a);var e=d.attrHandle[b.toLowerCase()],f=e&&C.call(d.attrHandle,b.toLowerCase())?e(a,b,!n):void 0;return void 0!==f?f:c.attributes||!n?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},db.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},db.uniqueSort=function(a){var b,d=[],e=0,f=0;if(j=!c.detectDuplicates,i=!c.sortStable&&a.slice(0),a.sort(z),j){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return i=null,a},e=db.getText=function(a){var b,c="",d=0,f=a.nodeType;if(f){if(1===f||9===f||11===f){if("string"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=e(a)}else if(3===f||4===f)return a.nodeValue}else while(b=a[d++])c+=e(b);return c},d=db.selectors={cacheLength:50,createPseudo:fb,match:V,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(ab,bb),a[3]=(a[4]||a[5]||"").replace(ab,bb),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1].slice(0,3)?(a[3]||db.error(a[0]),a[4]=+(a[4]?a[5]+(a[6]||1):2*("even"===a[3]||"odd"===a[3])),a[5]=+(a[7]+a[8]||"odd"===a[3])):a[3]&&db.error(a[0]),a},PSEUDO:function(a){var b,c=!a[5]&&a[2];return V.CHILD.test(a[0])?null:(a[3]&&void 0!==a[4]?a[2]=a[4]:c&&T.test(c)&&(b=ob(c,!0))&&(b=c.indexOf(")",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(ab,bb).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=w[a+" "];return b||(b=new RegExp("(^|"+K+")"+a+"("+K+"|$)"))&&w(a,function(a){return b.test("string"==typeof a.className&&a.className||typeof a.getAttribute!==A&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=db.attr(d,a);return null==e?"!="===b:b?(e+="","="===b?e===c:"!="===b?e!==c:"^="===b?c&&0===e.indexOf(c):"*="===b?c&&e.indexOf(c)>-1:"$="===b?c&&e.slice(-c.length)===c:"~="===b?(" "+e+" ").indexOf(c)>-1:"|="===b?e===c||e.slice(0,c.length+1)===c+"-":!1):!0}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),t=!i&&!h;if(q){if(f){while(p){l=b;while(l=l[p])if(h?l.nodeName.toLowerCase()===r:1===l.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&t){k=q[s]||(q[s]={}),j=k[a]||[],n=j[0]===u&&j[1],m=j[0]===u&&j[2],l=n&&q.childNodes[n];while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if(1===l.nodeType&&++m&&l===b){k[a]=[u,n,m];break}}else if(t&&(j=(b[s]||(b[s]={}))[a])&&j[0]===u)m=j[1];else while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if((h?l.nodeName.toLowerCase()===r:1===l.nodeType)&&++m&&(t&&((l[s]||(l[s]={}))[a]=[u,m]),l===b))break;return m-=e,m===d||m%d===0&&m/d>=0}}},PSEUDO:function(a,b){var c,e=d.pseudos[a]||d.setFilters[a.toLowerCase()]||db.error("unsupported pseudo: "+a);return e[s]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?fb(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=I.call(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:fb(function(a){var b=[],c=[],d=g(a.replace(P,"$1"));return d[s]?fb(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),!c.pop()}}),has:fb(function(a){return function(b){return db(a,b).length>0}}),contains:fb(function(a){return function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:fb(function(a){return U.test(a||"")||db.error("unsupported lang: "+a),a=a.replace(ab,bb).toLowerCase(),function(b){var c;do if(c=n?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===m},focus:function(a){return a===l.activeElement&&(!l.hasFocus||l.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!d.pseudos.empty(a)},header:function(a){return X.test(a.nodeName)},input:function(a){return W.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||"text"===b.toLowerCase())},first:lb(function(){return[0]}),last:lb(function(a,b){return[b-1]}),eq:lb(function(a,b,c){return[0>c?c+b:c]}),even:lb(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:lb(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:lb(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:lb(function(a,b,c){for(var d=0>c?c+b:c;++d<b;)a.push(d);return a})}},d.pseudos.nth=d.pseudos.eq;for(b in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})d.pseudos[b]=jb(b);for(b in{submit:!0,reset:!0})d.pseudos[b]=kb(b);function nb(){}nb.prototype=d.filters=d.pseudos,d.setFilters=new nb;function ob(a,b){var c,e,f,g,h,i,j,k=x[a+" "];if(k)return b?0:k.slice(0);h=a,i=[],j=d.preFilter;while(h){(!c||(e=Q.exec(h)))&&(e&&(h=h.slice(e[0].length)||h),i.push(f=[])),c=!1,(e=R.exec(h))&&(c=e.shift(),f.push({value:c,type:e[0].replace(P," ")}),h=h.slice(c.length));for(g in d.filter)!(e=V[g].exec(h))||j[g]&&!(e=j[g](e))||(c=e.shift(),f.push({value:c,type:g,matches:e}),h=h.slice(c.length));if(!c)break}return b?h.length:h?db.error(a):x(a,i).slice(0)}function pb(a){for(var b=0,c=a.length,d="";c>b;b++)d+=a[b].value;return d}function qb(a,b,c){var d=b.dir,e=c&&"parentNode"===d,f=v++;return b.first?function(b,c,f){while(b=b[d])if(1===b.nodeType||e)return a(b,c,f)}:function(b,c,g){var h,i,j=[u,f];if(g){while(b=b[d])if((1===b.nodeType||e)&&a(b,c,g))return!0}else while(b=b[d])if(1===b.nodeType||e){if(i=b[s]||(b[s]={}),(h=i[d])&&h[0]===u&&h[1]===f)return j[2]=h[2];if(i[d]=j,j[2]=a(b,c,g))return!0}}}function rb(a){return a.length>1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function sb(a,b,c,d,e){for(var f,g=[],h=0,i=a.length,j=null!=b;i>h;h++)(f=a[h])&&(!c||c(f,d,e))&&(g.push(f),j&&b.push(h));return g}function tb(a,b,c,d,e,f){return d&&!d[s]&&(d=tb(d)),e&&!e[s]&&(e=tb(e,f)),fb(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||wb(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:sb(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=sb(r,n),d(j,[],h,i),k=j.length;while(k--)(l=j[k])&&(r[n[k]]=!(q[n[k]]=l))}if(f){if(e||a){if(e){j=[],k=r.length;while(k--)(l=r[k])&&j.push(q[k]=l);e(null,r=[],j,i)}k=r.length;while(k--)(l=r[k])&&(j=e?I.call(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=sb(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):G.apply(g,r)})}function ub(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],i=g||d.relative[" "],j=g?1:0,k=qb(function(a){return a===b},i,!0),l=qb(function(a){return I.call(b,a)>-1},i,!0),m=[function(a,c,d){return!g&&(d||c!==h)||((b=c).nodeType?k(a,c,d):l(a,c,d))}];f>j;j++)if(c=d.relative[a[j].type])m=[qb(rb(m),c)];else{if(c=d.filter[a[j].type].apply(null,a[j].matches),c[s]){for(e=++j;f>e;e++)if(d.relative[a[e].type])break;return tb(j>1&&rb(m),j>1&&pb(a.slice(0,j-1).concat({value:" "===a[j-2].type?"*":""})).replace(P,"$1"),c,e>j&&ub(a.slice(j,e)),f>e&&ub(a=a.slice(e)),f>e&&pb(a))}m.push(c)}return rb(m)}function vb(a,b){var c=b.length>0,e=a.length>0,f=function(f,g,i,j,k){var m,n,o,p=0,q="0",r=f&&[],s=[],t=h,v=f||e&&d.find.TAG("*",k),w=u+=null==t?1:Math.random()||.1,x=v.length;for(k&&(h=g!==l&&g);q!==x&&null!=(m=v[q]);q++){if(e&&m){n=0;while(o=a[n++])if(o(m,g,i)){j.push(m);break}k&&(u=w)}c&&((m=!o&&m)&&p--,f&&r.push(m))}if(p+=q,c&&q!==p){n=0;while(o=b[n++])o(r,s,g,i);if(f){if(p>0)while(q--)r[q]||s[q]||(s[q]=E.call(j));s=sb(s)}G.apply(j,s),k&&!f&&s.length>0&&p+b.length>1&&db.uniqueSort(j)}return k&&(u=w,h=t),r};return c?fb(f):f}g=db.compile=function(a,b){var c,d=[],e=[],f=y[a+" "];if(!f){b||(b=ob(a)),c=b.length;while(c--)f=ub(b[c]),f[s]?d.push(f):e.push(f);f=y(a,vb(e,d))}return f};function wb(a,b,c){for(var d=0,e=b.length;e>d;d++)db(a,b[d],c);return c}function xb(a,b,e,f){var h,i,j,k,l,m=ob(a);if(!f&&1===m.length){if(i=m[0]=m[0].slice(0),i.length>2&&"ID"===(j=i[0]).type&&c.getById&&9===b.nodeType&&n&&d.relative[i[1].type]){if(b=(d.find.ID(j.matches[0].replace(ab,bb),b)||[])[0],!b)return e;a=a.slice(i.shift().value.length)}h=V.needsContext.test(a)?0:i.length;while(h--){if(j=i[h],d.relative[k=j.type])break;if((l=d.find[k])&&(f=l(j.matches[0].replace(ab,bb),$.test(i[0].type)&&mb(b.parentNode)||b))){if(i.splice(h,1),a=f.length&&pb(i),!a)return G.apply(e,f),e;break}}}return g(a,m)(f,b,!n,e,$.test(a)&&mb(b.parentNode)||b),e}return c.sortStable=s.split("").sort(z).join("")===s,c.detectDuplicates=!!j,k(),c.sortDetached=gb(function(a){return 1&a.compareDocumentPosition(l.createElement("div"))}),gb(function(a){return a.innerHTML="<a href='#'></a>","#"===a.firstChild.getAttribute("href")})||hb("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&gb(function(a){return a.innerHTML="<input/>",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||hb("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),gb(function(a){return null==a.getAttribute("disabled")})||hb(J,function(a,b,c){var d;return c?void 0:a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),db}(a);n.find=t,n.expr=t.selectors,n.expr[":"]=n.expr.pseudos,n.unique=t.uniqueSort,n.text=t.getText,n.isXMLDoc=t.isXML,n.contains=t.contains;var u=n.expr.match.needsContext,v=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,w=/^.[^:#\[\.,]*$/;function x(a,b,c){if(n.isFunction(b))return n.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return n.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(w.test(b))return n.filter(b,a,c);b=n.filter(b,a)}return n.grep(a,function(a){return n.inArray(a,b)>=0!==c})}n.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?n.find.matchesSelector(d,a)?[d]:[]:n.find.matches(a,n.grep(b,function(a){return 1===a.nodeType}))},n.fn.extend({find:function(a){var b,c=[],d=this,e=d.length;if("string"!=typeof a)return this.pushStack(n(a).filter(function(){for(b=0;e>b;b++)if(n.contains(d[b],this))return!0}));for(b=0;e>b;b++)n.find(a,d[b],c);return c=this.pushStack(e>1?n.unique(c):c),c.selector=this.selector?this.selector+" "+a:a,c},filter:function(a){return this.pushStack(x(this,a||[],!1))},not:function(a){return this.pushStack(x(this,a||[],!0))},is:function(a){return!!x(this,"string"==typeof a&&u.test(a)?n(a):a||[],!1).length}});var y,z=a.document,A=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,B=n.fn.init=function(a,b){var c,d;if(!a)return this;if("string"==typeof a){if(c="<"===a.charAt(0)&&">"===a.charAt(a.length-1)&&a.length>=3?[null,a,null]:A.exec(a),!c||!c[1]&&b)return!b||b.jquery?(b||y).find(a):this.constructor(b).find(a);if(c[1]){if(b=b instanceof n?b[0]:b,n.merge(this,n.parseHTML(c[1],b&&b.nodeType?b.ownerDocument||b:z,!0)),v.test(c[1])&&n.isPlainObject(b))for(c in b)n.isFunction(this[c])?this[c](b[c]):this.attr(c,b[c]);return this}if(d=z.getElementById(c[2]),d&&d.parentNode){if(d.id!==c[2])return y.find(a);this.length=1,this[0]=d}return this.context=z,this.selector=a,this}return a.nodeType?(this.context=this[0]=a,this.length=1,this):n.isFunction(a)?"undefined"!=typeof y.ready?y.ready(a):a(n):(void 0!==a.selector&&(this.selector=a.selector,this.context=a.context),n.makeArray(a,this))};B.prototype=n.fn,y=n(z);var C=/^(?:parents|prev(?:Until|All))/,D={children:!0,contents:!0,next:!0,prev:!0};n.extend({dir:function(a,b,c){var d=[],e=a[b];while(e&&9!==e.nodeType&&(void 0===c||1!==e.nodeType||!n(e).is(c)))1===e.nodeType&&d.push(e),e=e[b];return d},sibling:function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c}}),n.fn.extend({has:function(a){var b,c=n(a,this),d=c.length;return this.filter(function(){for(b=0;d>b;b++)if(n.contains(this,c[b]))return!0})},closest:function(a,b){for(var c,d=0,e=this.length,f=[],g=u.test(a)||"string"!=typeof a?n(a,b||this.context):0;e>d;d++)for(c=this[d];c&&c!==b;c=c.parentNode)if(c.nodeType<11&&(g?g.index(c)>-1:1===c.nodeType&&n.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?n.unique(f):f)},index:function(a){return a?"string"==typeof a?n.inArray(this[0],n(a)):n.inArray(a.jquery?a[0]:a,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(n.unique(n.merge(this.get(),n(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function E(a,b){do a=a[b];while(a&&1!==a.nodeType);return a}n.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return n.dir(a,"parentNode")},parentsUntil:function(a,b,c){return n.dir(a,"parentNode",c)},next:function(a){return E(a,"nextSibling")},prev:function(a){return E(a,"previousSibling")},nextAll:function(a){return n.dir(a,"nextSibling")},prevAll:function(a){return n.dir(a,"previousSibling")},nextUntil:function(a,b,c){return n.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return n.dir(a,"previousSibling",c)},siblings:function(a){return n.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return n.sibling(a.firstChild)},contents:function(a){return n.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:n.merge([],a.childNodes)}},function(a,b){n.fn[a]=function(c,d){var e=n.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=n.filter(d,e)),this.length>1&&(D[a]||(e=n.unique(e)),C.test(a)&&(e=e.reverse())),this.pushStack(e)}});var F=/\S+/g,G={};function H(a){var b=G[a]={};return n.each(a.match(F)||[],function(a,c){b[c]=!0}),b}n.Callbacks=function(a){a="string"==typeof a?G[a]||H(a):n.extend({},a);var b,c,d,e,f,g,h=[],i=!a.once&&[],j=function(l){for(c=a.memory&&l,d=!0,f=g||0,g=0,e=h.length,b=!0;h&&e>f;f++)if(h[f].apply(l[0],l[1])===!1&&a.stopOnFalse){c=!1;break}b=!1,h&&(i?i.length&&j(i.shift()):c?h=[]:k.disable())},k={add:function(){if(h){var d=h.length;!function f(b){n.each(b,function(b,c){var d=n.type(c);"function"===d?a.unique&&k.has(c)||h.push(c):c&&c.length&&"string"!==d&&f(c)})}(arguments),b?e=h.length:c&&(g=d,j(c))}return this},remove:function(){return h&&n.each(arguments,function(a,c){var d;while((d=n.inArray(c,h,d))>-1)h.splice(d,1),b&&(e>=d&&e--,f>=d&&f--)}),this},has:function(a){return a?n.inArray(a,h)>-1:!(!h||!h.length)},empty:function(){return h=[],e=0,this},disable:function(){return h=i=c=void 0,this},disabled:function(){return!h},lock:function(){return i=void 0,c||k.disable(),this},locked:function(){return!i},fireWith:function(a,c){return!h||d&&!i||(c=c||[],c=[a,c.slice?c.slice():c],b?i.push(c):j(c)),this},fire:function(){return k.fireWith(this,arguments),this},fired:function(){return!!d}};return k},n.extend({Deferred:function(a){var b=[["resolve","done",n.Callbacks("once memory"),"resolved"],["reject","fail",n.Callbacks("once memory"),"rejected"],["notify","progress",n.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return n.Deferred(function(c){n.each(b,function(b,f){var g=n.isFunction(a[b])&&a[b];e[f[1]](function(){var a=g&&g.apply(this,arguments);a&&n.isFunction(a.promise)?a.promise().done(c.resolve).fail(c.reject).progress(c.notify):c[f[0]+"With"](this===d?c.promise():this,g?[a]:arguments)})}),a=null}).promise()},promise:function(a){return null!=a?n.extend(a,d):d}},e={};return d.pipe=d.then,n.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[1^a][2].disable,b[2][2].lock),e[f[0]]=function(){return e[f[0]+"With"](this===e?d:this,arguments),this},e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=d.call(arguments),e=c.length,f=1!==e||a&&n.isFunction(a.promise)?e:0,g=1===f?a:n.Deferred(),h=function(a,b,c){return function(e){b[a]=this,c[a]=arguments.length>1?d.call(arguments):e,c===i?g.notifyWith(b,c):--f||g.resolveWith(b,c)}},i,j,k;if(e>1)for(i=new Array(e),j=new Array(e),k=new Array(e);e>b;b++)c[b]&&n.isFunction(c[b].promise)?c[b].promise().done(h(b,k,c)).fail(g.reject).progress(h(b,j,i)):--f;return f||g.resolveWith(k,c),g.promise()}});var I;n.fn.ready=function(a){return n.ready.promise().done(a),this},n.extend({isReady:!1,readyWait:1,holdReady:function(a){a?n.readyWait++:n.ready(!0)},ready:function(a){if(a===!0?!--n.readyWait:!n.isReady){if(!z.body)return setTimeout(n.ready);n.isReady=!0,a!==!0&&--n.readyWait>0||(I.resolveWith(z,[n]),n.fn.trigger&&n(z).trigger("ready").off("ready"))}}});function J(){z.addEventListener?(z.removeEventListener("DOMContentLoaded",K,!1),a.removeEventListener("load",K,!1)):(z.detachEvent("onreadystatechange",K),a.detachEvent("onload",K))}function K(){(z.addEventListener||"load"===event.type||"complete"===z.readyState)&&(J(),n.ready())}n.ready.promise=function(b){if(!I)if(I=n.Deferred(),"complete"===z.readyState)setTimeout(n.ready);else if(z.addEventListener)z.addEventListener("DOMContentLoaded",K,!1),a.addEventListener("load",K,!1);else{z.attachEvent("onreadystatechange",K),a.attachEvent("onload",K);var c=!1;try{c=null==a.frameElement&&z.documentElement}catch(d){}c&&c.doScroll&&!function e(){if(!n.isReady){try{c.doScroll("left")}catch(a){return setTimeout(e,50)}J(),n.ready()}}()}return I.promise(b)};var L="undefined",M;for(M in n(l))break;l.ownLast="0"!==M,l.inlineBlockNeedsLayout=!1,n(function(){var a,b,c=z.getElementsByTagName("body")[0];c&&(a=z.createElement("div"),a.style.cssText="border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px",b=z.createElement("div"),c.appendChild(a).appendChild(b),typeof b.style.zoom!==L&&(b.style.cssText="border:0;margin:0;width:1px;padding:1px;display:inline;zoom:1",(l.inlineBlockNeedsLayout=3===b.offsetWidth)&&(c.style.zoom=1)),c.removeChild(a),a=b=null)}),function(){var a=z.createElement("div");if(null==l.deleteExpando){l.deleteExpando=!0;try{delete a.test}catch(b){l.deleteExpando=!1}}a=null}(),n.acceptData=function(a){var b=n.noData[(a.nodeName+" ").toLowerCase()],c=+a.nodeType||1;return 1!==c&&9!==c?!1:!b||b!==!0&&a.getAttribute("classid")===b};var N=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,O=/([A-Z])/g;function P(a,b,c){if(void 0===c&&1===a.nodeType){var d="data-"+b.replace(O,"-$1").toLowerCase();if(c=a.getAttribute(d),"string"==typeof c){try{c="true"===c?!0:"false"===c?!1:"null"===c?null:+c+""===c?+c:N.test(c)?n.parseJSON(c):c}catch(e){}n.data(a,b,c)}else c=void 0}return c}function Q(a){var b;for(b in a)if(("data"!==b||!n.isEmptyObject(a[b]))&&"toJSON"!==b)return!1;return!0}function R(a,b,d,e){if(n.acceptData(a)){var f,g,h=n.expando,i=a.nodeType,j=i?n.cache:a,k=i?a[h]:a[h]&&h;if(k&&j[k]&&(e||j[k].data)||void 0!==d||"string"!=typeof b)return k||(k=i?a[h]=c.pop()||n.guid++:h),j[k]||(j[k]=i?{}:{toJSON:n.noop}),("object"==typeof b||"function"==typeof b)&&(e?j[k]=n.extend(j[k],b):j[k].data=n.extend(j[k].data,b)),g=j[k],e||(g.data||(g.data={}),g=g.data),void 0!==d&&(g[n.camelCase(b)]=d),"string"==typeof b?(f=g[b],null==f&&(f=g[n.camelCase(b)])):f=g,f
}}function S(a,b,c){if(n.acceptData(a)){var d,e,f=a.nodeType,g=f?n.cache:a,h=f?a[n.expando]:n.expando;if(g[h]){if(b&&(d=c?g[h]:g[h].data)){n.isArray(b)?b=b.concat(n.map(b,n.camelCase)):b in d?b=[b]:(b=n.camelCase(b),b=b in d?[b]:b.split(" ")),e=b.length;while(e--)delete d[b[e]];if(c?!Q(d):!n.isEmptyObject(d))return}(c||(delete g[h].data,Q(g[h])))&&(f?n.cleanData([a],!0):l.deleteExpando||g!=g.window?delete g[h]:g[h]=null)}}}n.extend({cache:{},noData:{"applet ":!0,"embed ":!0,"object ":"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(a){return a=a.nodeType?n.cache[a[n.expando]]:a[n.expando],!!a&&!Q(a)},data:function(a,b,c){return R(a,b,c)},removeData:function(a,b){return S(a,b)},_data:function(a,b,c){return R(a,b,c,!0)},_removeData:function(a,b){return S(a,b,!0)}}),n.fn.extend({data:function(a,b){var c,d,e,f=this[0],g=f&&f.attributes;if(void 0===a){if(this.length&&(e=n.data(f),1===f.nodeType&&!n._data(f,"parsedAttrs"))){c=g.length;while(c--)d=g[c].name,0===d.indexOf("data-")&&(d=n.camelCase(d.slice(5)),P(f,d,e[d]));n._data(f,"parsedAttrs",!0)}return e}return"object"==typeof a?this.each(function(){n.data(this,a)}):arguments.length>1?this.each(function(){n.data(this,a,b)}):f?P(f,a,n.data(f,a)):void 0},removeData:function(a){return this.each(function(){n.removeData(this,a)})}}),n.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=n._data(a,b),c&&(!d||n.isArray(c)?d=n._data(a,b,n.makeArray(c)):d.push(c)),d||[]):void 0},dequeue:function(a,b){b=b||"fx";var c=n.queue(a,b),d=c.length,e=c.shift(),f=n._queueHooks(a,b),g=function(){n.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return n._data(a,c)||n._data(a,c,{empty:n.Callbacks("once memory").add(function(){n._removeData(a,b+"queue"),n._removeData(a,c)})})}}),n.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.length<c?n.queue(this[0],a):void 0===b?this:this.each(function(){var c=n.queue(this,a,b);n._queueHooks(this,a),"fx"===a&&"inprogress"!==c[0]&&n.dequeue(this,a)})},dequeue:function(a){return this.each(function(){n.dequeue(this,a)})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,b){var c,d=1,e=n.Deferred(),f=this,g=this.length,h=function(){--d||e.resolveWith(f,[f])};"string"!=typeof a&&(b=a,a=void 0),a=a||"fx";while(g--)c=n._data(f[g],a+"queueHooks"),c&&c.empty&&(d++,c.empty.add(h));return h(),e.promise(b)}});var T=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,U=["Top","Right","Bottom","Left"],V=function(a,b){return a=b||a,"none"===n.css(a,"display")||!n.contains(a.ownerDocument,a)},W=n.access=function(a,b,c,d,e,f,g){var h=0,i=a.length,j=null==c;if("object"===n.type(c)){e=!0;for(h in c)n.access(a,b,h,c[h],!0,f,g)}else if(void 0!==d&&(e=!0,n.isFunction(d)||(g=!0),j&&(g?(b.call(a,d),b=null):(j=b,b=function(a,b,c){return j.call(n(a),c)})),b))for(;i>h;h++)b(a[h],c,g?d:d.call(a[h],h,b(a[h],c)));return e?a:j?b.call(a):i?b(a[0],c):f},X=/^(?:checkbox|radio)$/i;!function(){var a=z.createDocumentFragment(),b=z.createElement("div"),c=z.createElement("input");if(b.setAttribute("className","t"),b.innerHTML=" <link/><table></table><a href='/a'>a</a>",l.leadingWhitespace=3===b.firstChild.nodeType,l.tbody=!b.getElementsByTagName("tbody").length,l.htmlSerialize=!!b.getElementsByTagName("link").length,l.html5Clone="<:nav></:nav>"!==z.createElement("nav").cloneNode(!0).outerHTML,c.type="checkbox",c.checked=!0,a.appendChild(c),l.appendChecked=c.checked,b.innerHTML="<textarea>x</textarea>",l.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue,a.appendChild(b),b.innerHTML="<input type='radio' checked='checked' name='t'/>",l.checkClone=b.cloneNode(!0).cloneNode(!0).lastChild.checked,l.noCloneEvent=!0,b.attachEvent&&(b.attachEvent("onclick",function(){l.noCloneEvent=!1}),b.cloneNode(!0).click()),null==l.deleteExpando){l.deleteExpando=!0;try{delete b.test}catch(d){l.deleteExpando=!1}}a=b=c=null}(),function(){var b,c,d=z.createElement("div");for(b in{submit:!0,change:!0,focusin:!0})c="on"+b,(l[b+"Bubbles"]=c in a)||(d.setAttribute(c,"t"),l[b+"Bubbles"]=d.attributes[c].expando===!1);d=null}();var Y=/^(?:input|select|textarea)$/i,Z=/^key/,$=/^(?:mouse|contextmenu)|click/,_=/^(?:focusinfocus|focusoutblur)$/,ab=/^([^.]*)(?:\.(.+)|)$/;function bb(){return!0}function cb(){return!1}function db(){try{return z.activeElement}catch(a){}}n.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,o,p,q,r=n._data(a);if(r){c.handler&&(i=c,c=i.handler,e=i.selector),c.guid||(c.guid=n.guid++),(g=r.events)||(g=r.events={}),(k=r.handle)||(k=r.handle=function(a){return typeof n===L||a&&n.event.triggered===a.type?void 0:n.event.dispatch.apply(k.elem,arguments)},k.elem=a),b=(b||"").match(F)||[""],h=b.length;while(h--)f=ab.exec(b[h])||[],o=q=f[1],p=(f[2]||"").split(".").sort(),o&&(j=n.event.special[o]||{},o=(e?j.delegateType:j.bindType)||o,j=n.event.special[o]||{},l=n.extend({type:o,origType:q,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&n.expr.match.needsContext.test(e),namespace:p.join(".")},i),(m=g[o])||(m=g[o]=[],m.delegateCount=0,j.setup&&j.setup.call(a,d,p,k)!==!1||(a.addEventListener?a.addEventListener(o,k,!1):a.attachEvent&&a.attachEvent("on"+o,k))),j.add&&(j.add.call(a,l),l.handler.guid||(l.handler.guid=c.guid)),e?m.splice(m.delegateCount++,0,l):m.push(l),n.event.global[o]=!0);a=null}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,o,p,q,r=n.hasData(a)&&n._data(a);if(r&&(k=r.events)){b=(b||"").match(F)||[""],j=b.length;while(j--)if(h=ab.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o){l=n.event.special[o]||{},o=(d?l.delegateType:l.bindType)||o,m=k[o]||[],h=h[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),i=f=m.length;while(f--)g=m[f],!e&&q!==g.origType||c&&c.guid!==g.guid||h&&!h.test(g.namespace)||d&&d!==g.selector&&("**"!==d||!g.selector)||(m.splice(f,1),g.selector&&m.delegateCount--,l.remove&&l.remove.call(a,g));i&&!m.length&&(l.teardown&&l.teardown.call(a,p,r.handle)!==!1||n.removeEvent(a,o,r.handle),delete k[o])}else for(o in k)n.event.remove(a,o+b[j],c,d,!0);n.isEmptyObject(k)&&(delete r.handle,n._removeData(a,"events"))}},trigger:function(b,c,d,e){var f,g,h,i,k,l,m,o=[d||z],p=j.call(b,"type")?b.type:b,q=j.call(b,"namespace")?b.namespace.split("."):[];if(h=l=d=d||z,3!==d.nodeType&&8!==d.nodeType&&!_.test(p+n.event.triggered)&&(p.indexOf(".")>=0&&(q=p.split("."),p=q.shift(),q.sort()),g=p.indexOf(":")<0&&"on"+p,b=b[n.expando]?b:new n.Event(p,"object"==typeof b&&b),b.isTrigger=e?2:3,b.namespace=q.join("."),b.namespace_re=b.namespace?new RegExp("(^|\\.)"+q.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=d),c=null==c?[b]:n.makeArray(c,[b]),k=n.event.special[p]||{},e||!k.trigger||k.trigger.apply(d,c)!==!1)){if(!e&&!k.noBubble&&!n.isWindow(d)){for(i=k.delegateType||p,_.test(i+p)||(h=h.parentNode);h;h=h.parentNode)o.push(h),l=h;l===(d.ownerDocument||z)&&o.push(l.defaultView||l.parentWindow||a)}m=0;while((h=o[m++])&&!b.isPropagationStopped())b.type=m>1?i:k.bindType||p,f=(n._data(h,"events")||{})[b.type]&&n._data(h,"handle"),f&&f.apply(h,c),f=g&&h[g],f&&f.apply&&n.acceptData(h)&&(b.result=f.apply(h,c),b.result===!1&&b.preventDefault());if(b.type=p,!e&&!b.isDefaultPrevented()&&(!k._default||k._default.apply(o.pop(),c)===!1)&&n.acceptData(d)&&g&&d[p]&&!n.isWindow(d)){l=d[g],l&&(d[g]=null),n.event.triggered=p;try{d[p]()}catch(r){}n.event.triggered=void 0,l&&(d[g]=l)}return b.result}},dispatch:function(a){a=n.event.fix(a);var b,c,e,f,g,h=[],i=d.call(arguments),j=(n._data(this,"events")||{})[a.type]||[],k=n.event.special[a.type]||{};if(i[0]=a,a.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,a)!==!1){h=n.event.handlers.call(this,a,j),b=0;while((f=h[b++])&&!a.isPropagationStopped()){a.currentTarget=f.elem,g=0;while((e=f.handlers[g++])&&!a.isImmediatePropagationStopped())(!a.namespace_re||a.namespace_re.test(e.namespace))&&(a.handleObj=e,a.data=e.data,c=((n.event.special[e.origType]||{}).handle||e.handler).apply(f.elem,i),void 0!==c&&(a.result=c)===!1&&(a.preventDefault(),a.stopPropagation()))}return k.postDispatch&&k.postDispatch.call(this,a),a.result}},handlers:function(a,b){var c,d,e,f,g=[],h=b.delegateCount,i=a.target;if(h&&i.nodeType&&(!a.button||"click"!==a.type))for(;i!=this;i=i.parentNode||this)if(1===i.nodeType&&(i.disabled!==!0||"click"!==a.type)){for(e=[],f=0;h>f;f++)d=b[f],c=d.selector+" ",void 0===e[c]&&(e[c]=d.needsContext?n(c,this).index(i)>=0:n.find(c,this,null,[i]).length),e[c]&&e.push(d);e.length&&g.push({elem:i,handlers:e})}return h<b.length&&g.push({elem:this,handlers:b.slice(h)}),g},fix:function(a){if(a[n.expando])return a;var b,c,d,e=a.type,f=a,g=this.fixHooks[e];g||(this.fixHooks[e]=g=$.test(e)?this.mouseHooks:Z.test(e)?this.keyHooks:{}),d=g.props?this.props.concat(g.props):this.props,a=new n.Event(f),b=d.length;while(b--)c=d[b],a[c]=f[c];return a.target||(a.target=f.srcElement||z),3===a.target.nodeType&&(a.target=a.target.parentNode),a.metaKey=!!a.metaKey,g.filter?g.filter(a,f):a},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(a,b){return null==a.which&&(a.which=null!=b.charCode?b.charCode:b.keyCode),a}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,b){var c,d,e,f=b.button,g=b.fromElement;return null==a.pageX&&null!=b.clientX&&(d=a.target.ownerDocument||z,e=d.documentElement,c=d.body,a.pageX=b.clientX+(e&&e.scrollLeft||c&&c.scrollLeft||0)-(e&&e.clientLeft||c&&c.clientLeft||0),a.pageY=b.clientY+(e&&e.scrollTop||c&&c.scrollTop||0)-(e&&e.clientTop||c&&c.clientTop||0)),!a.relatedTarget&&g&&(a.relatedTarget=g===a.target?b.toElement:g),a.which||void 0===f||(a.which=1&f?1:2&f?3:4&f?2:0),a}},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==db()&&this.focus)try{return this.focus(),!1}catch(a){}},delegateType:"focusin"},blur:{trigger:function(){return this===db()&&this.blur?(this.blur(),!1):void 0},delegateType:"focusout"},click:{trigger:function(){return n.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):void 0},_default:function(a){return n.nodeName(a.target,"a")}},beforeunload:{postDispatch:function(a){void 0!==a.result&&(a.originalEvent.returnValue=a.result)}}},simulate:function(a,b,c,d){var e=n.extend(new n.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?n.event.trigger(e,null,b):n.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},n.removeEvent=z.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)}:function(a,b,c){var d="on"+b;a.detachEvent&&(typeof a[d]===L&&(a[d]=null),a.detachEvent(d,c))},n.Event=function(a,b){return this instanceof n.Event?(a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||void 0===a.defaultPrevented&&(a.returnValue===!1||a.getPreventDefault&&a.getPreventDefault())?bb:cb):this.type=a,b&&n.extend(this,b),this.timeStamp=a&&a.timeStamp||n.now(),void(this[n.expando]=!0)):new n.Event(a,b)},n.Event.prototype={isDefaultPrevented:cb,isPropagationStopped:cb,isImmediatePropagationStopped:cb,preventDefault:function(){var a=this.originalEvent;this.isDefaultPrevented=bb,a&&(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){var a=this.originalEvent;this.isPropagationStopped=bb,a&&(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=bb,this.stopPropagation()}},n.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){n.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c,d=this,e=a.relatedTarget,f=a.handleObj;return(!e||e!==d&&!n.contains(d,e))&&(a.type=f.origType,c=f.handler.apply(this,arguments),a.type=b),c}}}),l.submitBubbles||(n.event.special.submit={setup:function(){return n.nodeName(this,"form")?!1:void n.event.add(this,"click._submit keypress._submit",function(a){var b=a.target,c=n.nodeName(b,"input")||n.nodeName(b,"button")?b.form:void 0;c&&!n._data(c,"submitBubbles")&&(n.event.add(c,"submit._submit",function(a){a._submit_bubble=!0}),n._data(c,"submitBubbles",!0))})},postDispatch:function(a){a._submit_bubble&&(delete a._submit_bubble,this.parentNode&&!a.isTrigger&&n.event.simulate("submit",this.parentNode,a,!0))},teardown:function(){return n.nodeName(this,"form")?!1:void n.event.remove(this,"._submit")}}),l.changeBubbles||(n.event.special.change={setup:function(){return Y.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(n.event.add(this,"propertychange._change",function(a){"checked"===a.originalEvent.propertyName&&(this._just_changed=!0)}),n.event.add(this,"click._change",function(a){this._just_changed&&!a.isTrigger&&(this._just_changed=!1),n.event.simulate("change",this,a,!0)})),!1):void n.event.add(this,"beforeactivate._change",function(a){var b=a.target;Y.test(b.nodeName)&&!n._data(b,"changeBubbles")&&(n.event.add(b,"change._change",function(a){!this.parentNode||a.isSimulated||a.isTrigger||n.event.simulate("change",this.parentNode,a,!0)}),n._data(b,"changeBubbles",!0))})},handle:function(a){var b=a.target;return this!==b||a.isSimulated||a.isTrigger||"radio"!==b.type&&"checkbox"!==b.type?a.handleObj.handler.apply(this,arguments):void 0},teardown:function(){return n.event.remove(this,"._change"),!Y.test(this.nodeName)}}),l.focusinBubbles||n.each({focus:"focusin",blur:"focusout"},function(a,b){var c=function(a){n.event.simulate(b,a.target,n.event.fix(a),!0)};n.event.special[b]={setup:function(){var d=this.ownerDocument||this,e=n._data(d,b);e||d.addEventListener(a,c,!0),n._data(d,b,(e||0)+1)},teardown:function(){var d=this.ownerDocument||this,e=n._data(d,b)-1;e?n._data(d,b,e):(d.removeEventListener(a,c,!0),n._removeData(d,b))}}}),n.fn.extend({on:function(a,b,c,d,e){var f,g;if("object"==typeof a){"string"!=typeof b&&(c=c||b,b=void 0);for(f in a)this.on(f,b,c,a[f],e);return this}if(null==c&&null==d?(d=b,c=b=void 0):null==d&&("string"==typeof b?(d=c,c=void 0):(d=c,c=b,b=void 0)),d===!1)d=cb;else if(!d)return this;return 1===e&&(g=d,d=function(a){return n().off(a),g.apply(this,arguments)},d.guid=g.guid||(g.guid=n.guid++)),this.each(function(){n.event.add(this,a,d,c,b)})},one:function(a,b,c,d){return this.on(a,b,c,d,1)},off:function(a,b,c){var d,e;if(a&&a.preventDefault&&a.handleObj)return d=a.handleObj,n(a.delegateTarget).off(d.namespace?d.origType+"."+d.namespace:d.origType,d.selector,d.handler),this;if("object"==typeof a){for(e in a)this.off(e,b,a[e]);return this}return(b===!1||"function"==typeof b)&&(c=b,b=void 0),c===!1&&(c=cb),this.each(function(){n.event.remove(this,a,c,b)})},trigger:function(a,b){return this.each(function(){n.event.trigger(a,b,this)})},triggerHandler:function(a,b){var c=this[0];return c?n.event.trigger(a,b,c,!0):void 0}});function eb(a){var b=fb.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}var fb="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",gb=/ jQuery\d+="(?:null|\d+)"/g,hb=new RegExp("<(?:"+fb+")[\\s/>]","i"),ib=/^\s+/,jb=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,kb=/<([\w:]+)/,lb=/<tbody/i,mb=/<|&#?\w+;/,nb=/<(?:script|style|link)/i,ob=/checked\s*(?:[^=]|=\s*.checked.)/i,pb=/^$|\/(?:java|ecma)script/i,qb=/^true\/(.*)/,rb=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,sb={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],area:[1,"<map>","</map>"],param:[1,"<object>","</object>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:l.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},tb=eb(z),ub=tb.appendChild(z.createElement("div"));sb.optgroup=sb.option,sb.tbody=sb.tfoot=sb.colgroup=sb.caption=sb.thead,sb.th=sb.td;function vb(a,b){var c,d,e=0,f=typeof a.getElementsByTagName!==L?a.getElementsByTagName(b||"*"):typeof a.querySelectorAll!==L?a.querySelectorAll(b||"*"):void 0;if(!f)for(f=[],c=a.childNodes||a;null!=(d=c[e]);e++)!b||n.nodeName(d,b)?f.push(d):n.merge(f,vb(d,b));return void 0===b||b&&n.nodeName(a,b)?n.merge([a],f):f}function wb(a){X.test(a.type)&&(a.defaultChecked=a.checked)}function xb(a,b){return n.nodeName(a,"table")&&n.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function yb(a){return a.type=(null!==n.find.attr(a,"type"))+"/"+a.type,a}function zb(a){var b=qb.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function Ab(a,b){for(var c,d=0;null!=(c=a[d]);d++)n._data(c,"globalEval",!b||n._data(b[d],"globalEval"))}function Bb(a,b){if(1===b.nodeType&&n.hasData(a)){var c,d,e,f=n._data(a),g=n._data(b,f),h=f.events;if(h){delete g.handle,g.events={};for(c in h)for(d=0,e=h[c].length;e>d;d++)n.event.add(b,c,h[c][d])}g.data&&(g.data=n.extend({},g.data))}}function Cb(a,b){var c,d,e;if(1===b.nodeType){if(c=b.nodeName.toLowerCase(),!l.noCloneEvent&&b[n.expando]){e=n._data(b);for(d in e.events)n.removeEvent(b,d,e.handle);b.removeAttribute(n.expando)}"script"===c&&b.text!==a.text?(yb(b).text=a.text,zb(b)):"object"===c?(b.parentNode&&(b.outerHTML=a.outerHTML),l.html5Clone&&a.innerHTML&&!n.trim(b.innerHTML)&&(b.innerHTML=a.innerHTML)):"input"===c&&X.test(a.type)?(b.defaultChecked=b.checked=a.checked,b.value!==a.value&&(b.value=a.value)):"option"===c?b.defaultSelected=b.selected=a.defaultSelected:("input"===c||"textarea"===c)&&(b.defaultValue=a.defaultValue)}}n.extend({clone:function(a,b,c){var d,e,f,g,h,i=n.contains(a.ownerDocument,a);if(l.html5Clone||n.isXMLDoc(a)||!hb.test("<"+a.nodeName+">")?f=a.cloneNode(!0):(ub.innerHTML=a.outerHTML,ub.removeChild(f=ub.firstChild)),!(l.noCloneEvent&&l.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||n.isXMLDoc(a)))for(d=vb(f),h=vb(a),g=0;null!=(e=h[g]);++g)d[g]&&Cb(e,d[g]);if(b)if(c)for(h=h||vb(a),d=d||vb(f),g=0;null!=(e=h[g]);g++)Bb(e,d[g]);else Bb(a,f);return d=vb(f,"script"),d.length>0&&Ab(d,!i&&vb(a,"script")),d=h=e=null,f},buildFragment:function(a,b,c,d){for(var e,f,g,h,i,j,k,m=a.length,o=eb(b),p=[],q=0;m>q;q++)if(f=a[q],f||0===f)if("object"===n.type(f))n.merge(p,f.nodeType?[f]:f);else if(mb.test(f)){h=h||o.appendChild(b.createElement("div")),i=(kb.exec(f)||["",""])[1].toLowerCase(),k=sb[i]||sb._default,h.innerHTML=k[1]+f.replace(jb,"<$1></$2>")+k[2],e=k[0];while(e--)h=h.lastChild;if(!l.leadingWhitespace&&ib.test(f)&&p.push(b.createTextNode(ib.exec(f)[0])),!l.tbody){f="table"!==i||lb.test(f)?"<table>"!==k[1]||lb.test(f)?0:h:h.firstChild,e=f&&f.childNodes.length;while(e--)n.nodeName(j=f.childNodes[e],"tbody")&&!j.childNodes.length&&f.removeChild(j)}n.merge(p,h.childNodes),h.textContent="";while(h.firstChild)h.removeChild(h.firstChild);h=o.lastChild}else p.push(b.createTextNode(f));h&&o.removeChild(h),l.appendChecked||n.grep(vb(p,"input"),wb),q=0;while(f=p[q++])if((!d||-1===n.inArray(f,d))&&(g=n.contains(f.ownerDocument,f),h=vb(o.appendChild(f),"script"),g&&Ab(h),c)){e=0;while(f=h[e++])pb.test(f.type||"")&&c.push(f)}return h=null,o},cleanData:function(a,b){for(var d,e,f,g,h=0,i=n.expando,j=n.cache,k=l.deleteExpando,m=n.event.special;null!=(d=a[h]);h++)if((b||n.acceptData(d))&&(f=d[i],g=f&&j[f])){if(g.events)for(e in g.events)m[e]?n.event.remove(d,e):n.removeEvent(d,e,g.handle);j[f]&&(delete j[f],k?delete d[i]:typeof d.removeAttribute!==L?d.removeAttribute(i):d[i]=null,c.push(f))}}}),n.fn.extend({text:function(a){return W(this,function(a){return void 0===a?n.text(this):this.empty().append((this[0]&&this[0].ownerDocument||z).createTextNode(a))},null,a,arguments.length)},append:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=xb(this,a);b.appendChild(a)}})},prepend:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=xb(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},remove:function(a,b){for(var c,d=a?n.filter(a,this):this,e=0;null!=(c=d[e]);e++)b||1!==c.nodeType||n.cleanData(vb(c)),c.parentNode&&(b&&n.contains(c.ownerDocument,c)&&Ab(vb(c,"script")),c.parentNode.removeChild(c));return this},empty:function(){for(var a,b=0;null!=(a=this[b]);b++){1===a.nodeType&&n.cleanData(vb(a,!1));while(a.firstChild)a.removeChild(a.firstChild);a.options&&n.nodeName(a,"select")&&(a.options.length=0)}return this},clone:function(a,b){return a=null==a?!1:a,b=null==b?a:b,this.map(function(){return n.clone(this,a,b)})},html:function(a){return W(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a)return 1===b.nodeType?b.innerHTML.replace(gb,""):void 0;if(!("string"!=typeof a||nb.test(a)||!l.htmlSerialize&&hb.test(a)||!l.leadingWhitespace&&ib.test(a)||sb[(kb.exec(a)||["",""])[1].toLowerCase()])){a=a.replace(jb,"<$1></$2>");try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(n.cleanData(vb(b,!1)),b.innerHTML=a);b=0}catch(e){}}b&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(){var a=arguments[0];return this.domManip(arguments,function(b){a=this.parentNode,n.cleanData(vb(this)),a&&a.replaceChild(b,this)}),a&&(a.length||a.nodeType)?this:this.remove()},detach:function(a){return this.remove(a,!0)},domManip:function(a,b){a=e.apply([],a);var c,d,f,g,h,i,j=0,k=this.length,m=this,o=k-1,p=a[0],q=n.isFunction(p);if(q||k>1&&"string"==typeof p&&!l.checkClone&&ob.test(p))return this.each(function(c){var d=m.eq(c);q&&(a[0]=p.call(this,c,d.html())),d.domManip(a,b)});if(k&&(i=n.buildFragment(a,this[0].ownerDocument,!1,this),c=i.firstChild,1===i.childNodes.length&&(i=c),c)){for(g=n.map(vb(i,"script"),yb),f=g.length;k>j;j++)d=i,j!==o&&(d=n.clone(d,!0,!0),f&&n.merge(g,vb(d,"script"))),b.call(this[j],d,j);if(f)for(h=g[g.length-1].ownerDocument,n.map(g,zb),j=0;f>j;j++)d=g[j],pb.test(d.type||"")&&!n._data(d,"globalEval")&&n.contains(h,d)&&(d.src?n._evalUrl&&n._evalUrl(d.src):n.globalEval((d.text||d.textContent||d.innerHTML||"").replace(rb,"")));i=c=null}return this}}),n.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){n.fn[a]=function(a){for(var c,d=0,e=[],g=n(a),h=g.length-1;h>=d;d++)c=d===h?this:this.clone(!0),n(g[d])[b](c),f.apply(e,c.get());return this.pushStack(e)}});var Db,Eb={};function Fb(b,c){var d=n(c.createElement(b)).appendTo(c.body),e=a.getDefaultComputedStyle?a.getDefaultComputedStyle(d[0]).display:n.css(d[0],"display");return d.detach(),e}function Gb(a){var b=z,c=Eb[a];return c||(c=Fb(a,b),"none"!==c&&c||(Db=(Db||n("<iframe frameborder='0' width='0' height='0'/>")).appendTo(b.documentElement),b=(Db[0].contentWindow||Db[0].contentDocument).document,b.write(),b.close(),c=Fb(a,b),Db.detach()),Eb[a]=c),c}!function(){var a,b,c=z.createElement("div"),d="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;padding:0;margin:0;border:0";c.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",a=c.getElementsByTagName("a")[0],a.style.cssText="float:left;opacity:.5",l.opacity=/^0.5/.test(a.style.opacity),l.cssFloat=!!a.style.cssFloat,c.style.backgroundClip="content-box",c.cloneNode(!0).style.backgroundClip="",l.clearCloneStyle="content-box"===c.style.backgroundClip,a=c=null,l.shrinkWrapBlocks=function(){var a,c,e,f;if(null==b){if(a=z.getElementsByTagName("body")[0],!a)return;f="border:0;width:0;height:0;position:absolute;top:0;left:-9999px",c=z.createElement("div"),e=z.createElement("div"),a.appendChild(c).appendChild(e),b=!1,typeof e.style.zoom!==L&&(e.style.cssText=d+";width:1px;padding:1px;zoom:1",e.innerHTML="<div></div>",e.firstChild.style.width="5px",b=3!==e.offsetWidth),a.removeChild(c),a=c=e=null}return b}}();var Hb=/^margin/,Ib=new RegExp("^("+T+")(?!px)[a-z%]+$","i"),Jb,Kb,Lb=/^(top|right|bottom|left)$/;a.getComputedStyle?(Jb=function(a){return a.ownerDocument.defaultView.getComputedStyle(a,null)},Kb=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Jb(a),g=c?c.getPropertyValue(b)||c[b]:void 0,c&&(""!==g||n.contains(a.ownerDocument,a)||(g=n.style(a,b)),Ib.test(g)&&Hb.test(b)&&(d=h.width,e=h.minWidth,f=h.maxWidth,h.minWidth=h.maxWidth=h.width=g,g=c.width,h.width=d,h.minWidth=e,h.maxWidth=f)),void 0===g?g:g+""}):z.documentElement.currentStyle&&(Jb=function(a){return a.currentStyle},Kb=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Jb(a),g=c?c[b]:void 0,null==g&&h&&h[b]&&(g=h[b]),Ib.test(g)&&!Lb.test(b)&&(d=h.left,e=a.runtimeStyle,f=e&&e.left,f&&(e.left=a.currentStyle.left),h.left="fontSize"===b?"1em":g,g=h.pixelLeft+"px",h.left=d,f&&(e.left=f)),void 0===g?g:g+""||"auto"});function Mb(a,b){return{get:function(){var c=a();if(null!=c)return c?void delete this.get:(this.get=b).apply(this,arguments)}}}!function(){var b,c,d,e,f,g,h=z.createElement("div"),i="border:0;width:0;height:0;position:absolute;top:0;left:-9999px",j="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;padding:0;margin:0;border:0";h.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",b=h.getElementsByTagName("a")[0],b.style.cssText="float:left;opacity:.5",l.opacity=/^0.5/.test(b.style.opacity),l.cssFloat=!!b.style.cssFloat,h.style.backgroundClip="content-box",h.cloneNode(!0).style.backgroundClip="",l.clearCloneStyle="content-box"===h.style.backgroundClip,b=h=null,n.extend(l,{reliableHiddenOffsets:function(){if(null!=c)return c;var a,b,d,e=z.createElement("div"),f=z.getElementsByTagName("body")[0];if(f)return e.setAttribute("className","t"),e.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",a=z.createElement("div"),a.style.cssText=i,f.appendChild(a).appendChild(e),e.innerHTML="<table><tr><td></td><td>t</td></tr></table>",b=e.getElementsByTagName("td"),b[0].style.cssText="padding:0;margin:0;border:0;display:none",d=0===b[0].offsetHeight,b[0].style.display="",b[1].style.display="none",c=d&&0===b[0].offsetHeight,f.removeChild(a),e=f=null,c},boxSizing:function(){return null==d&&k(),d},boxSizingReliable:function(){return null==e&&k(),e},pixelPosition:function(){return null==f&&k(),f},reliableMarginRight:function(){var b,c,d,e;if(null==g&&a.getComputedStyle){if(b=z.getElementsByTagName("body")[0],!b)return;c=z.createElement("div"),d=z.createElement("div"),c.style.cssText=i,b.appendChild(c).appendChild(d),e=d.appendChild(z.createElement("div")),e.style.cssText=d.style.cssText=j,e.style.marginRight=e.style.width="0",d.style.width="1px",g=!parseFloat((a.getComputedStyle(e,null)||{}).marginRight),b.removeChild(c)}return g}});function k(){var b,c,h=z.getElementsByTagName("body")[0];h&&(b=z.createElement("div"),c=z.createElement("div"),b.style.cssText=i,h.appendChild(b).appendChild(c),c.style.cssText="-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;position:absolute;display:block;padding:1px;border:1px;width:4px;margin-top:1%;top:1%",n.swap(h,null!=h.style.zoom?{zoom:1}:{},function(){d=4===c.offsetWidth}),e=!0,f=!1,g=!0,a.getComputedStyle&&(f="1%"!==(a.getComputedStyle(c,null)||{}).top,e="4px"===(a.getComputedStyle(c,null)||{width:"4px"}).width),h.removeChild(b),c=h=null)}}(),n.swap=function(a,b,c,d){var e,f,g={};for(f in b)g[f]=a.style[f],a.style[f]=b[f];e=c.apply(a,d||[]);for(f in b)a.style[f]=g[f];return e};var Nb=/alpha\([^)]*\)/i,Ob=/opacity\s*=\s*([^)]*)/,Pb=/^(none|table(?!-c[ea]).+)/,Qb=new RegExp("^("+T+")(.*)$","i"),Rb=new RegExp("^([+-])=("+T+")","i"),Sb={position:"absolute",visibility:"hidden",display:"block"},Tb={letterSpacing:0,fontWeight:400},Ub=["Webkit","O","Moz","ms"];function Vb(a,b){if(b in a)return b;var c=b.charAt(0).toUpperCase()+b.slice(1),d=b,e=Ub.length;while(e--)if(b=Ub[e]+c,b in a)return b;return d}function Wb(a,b){for(var c,d,e,f=[],g=0,h=a.length;h>g;g++)d=a[g],d.style&&(f[g]=n._data(d,"olddisplay"),c=d.style.display,b?(f[g]||"none"!==c||(d.style.display=""),""===d.style.display&&V(d)&&(f[g]=n._data(d,"olddisplay",Gb(d.nodeName)))):f[g]||(e=V(d),(c&&"none"!==c||!e)&&n._data(d,"olddisplay",e?c:n.css(d,"display"))));for(g=0;h>g;g++)d=a[g],d.style&&(b&&"none"!==d.style.display&&""!==d.style.display||(d.style.display=b?f[g]||"":"none"));return a}function Xb(a,b,c){var d=Qb.exec(b);return d?Math.max(0,d[1]-(c||0))+(d[2]||"px"):b}function Yb(a,b,c,d,e){for(var f=c===(d?"border":"content")?4:"width"===b?1:0,g=0;4>f;f+=2)"margin"===c&&(g+=n.css(a,c+U[f],!0,e)),d?("content"===c&&(g-=n.css(a,"padding"+U[f],!0,e)),"margin"!==c&&(g-=n.css(a,"border"+U[f]+"Width",!0,e))):(g+=n.css(a,"padding"+U[f],!0,e),"padding"!==c&&(g+=n.css(a,"border"+U[f]+"Width",!0,e)));return g}function Zb(a,b,c){var d=!0,e="width"===b?a.offsetWidth:a.offsetHeight,f=Jb(a),g=l.boxSizing()&&"border-box"===n.css(a,"boxSizing",!1,f);if(0>=e||null==e){if(e=Kb(a,b,f),(0>e||null==e)&&(e=a.style[b]),Ib.test(e))return e;d=g&&(l.boxSizingReliable()||e===a.style[b]),e=parseFloat(e)||0}return e+Yb(a,b,c||(g?"border":"content"),d,f)+"px"}n.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=Kb(a,"opacity");return""===c?"1":c}}}},cssNumber:{columnCount:!0,fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":l.cssFloat?"cssFloat":"styleFloat"},style:function(a,b,c,d){if(a&&3!==a.nodeType&&8!==a.nodeType&&a.style){var e,f,g,h=n.camelCase(b),i=a.style;if(b=n.cssProps[h]||(n.cssProps[h]=Vb(i,h)),g=n.cssHooks[b]||n.cssHooks[h],void 0===c)return g&&"get"in g&&void 0!==(e=g.get(a,!1,d))?e:i[b];if(f=typeof c,"string"===f&&(e=Rb.exec(c))&&(c=(e[1]+1)*e[2]+parseFloat(n.css(a,b)),f="number"),null!=c&&c===c&&("number"!==f||n.cssNumber[h]||(c+="px"),l.clearCloneStyle||""!==c||0!==b.indexOf("background")||(i[b]="inherit"),!(g&&"set"in g&&void 0===(c=g.set(a,c,d)))))try{i[b]="",i[b]=c}catch(j){}}},css:function(a,b,c,d){var e,f,g,h=n.camelCase(b);return b=n.cssProps[h]||(n.cssProps[h]=Vb(a.style,h)),g=n.cssHooks[b]||n.cssHooks[h],g&&"get"in g&&(f=g.get(a,!0,c)),void 0===f&&(f=Kb(a,b,d)),"normal"===f&&b in Tb&&(f=Tb[b]),""===c||c?(e=parseFloat(f),c===!0||n.isNumeric(e)?e||0:f):f}}),n.each(["height","width"],function(a,b){n.cssHooks[b]={get:function(a,c,d){return c?0===a.offsetWidth&&Pb.test(n.css(a,"display"))?n.swap(a,Sb,function(){return Zb(a,b,d)}):Zb(a,b,d):void 0},set:function(a,c,d){var e=d&&Jb(a);return Xb(a,c,d?Yb(a,b,d,l.boxSizing()&&"border-box"===n.css(a,"boxSizing",!1,e),e):0)}}}),l.opacity||(n.cssHooks.opacity={get:function(a,b){return Ob.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=n.isNumeric(b)?"alpha(opacity="+100*b+")":"",f=d&&d.filter||c.filter||"";c.zoom=1,(b>=1||""===b)&&""===n.trim(f.replace(Nb,""))&&c.removeAttribute&&(c.removeAttribute("filter"),""===b||d&&!d.filter)||(c.filter=Nb.test(f)?f.replace(Nb,e):f+" "+e)}}),n.cssHooks.marginRight=Mb(l.reliableMarginRight,function(a,b){return b?n.swap(a,{display:"inline-block"},Kb,[a,"marginRight"]):void 0}),n.each({margin:"",padding:"",border:"Width"},function(a,b){n.cssHooks[a+b]={expand:function(c){for(var d=0,e={},f="string"==typeof c?c.split(" "):[c];4>d;d++)e[a+U[d]+b]=f[d]||f[d-2]||f[0];return e}},Hb.test(a)||(n.cssHooks[a+b].set=Xb)}),n.fn.extend({css:function(a,b){return W(this,function(a,b,c){var d,e,f={},g=0;if(n.isArray(b)){for(d=Jb(a),e=b.length;e>g;g++)f[b[g]]=n.css(a,b[g],!1,d);return f}return void 0!==c?n.style(a,b,c):n.css(a,b)
},a,b,arguments.length>1)},show:function(){return Wb(this,!0)},hide:function(){return Wb(this)},toggle:function(a){return"boolean"==typeof a?a?this.show():this.hide():this.each(function(){V(this)?n(this).show():n(this).hide()})}});function $b(a,b,c,d,e){return new $b.prototype.init(a,b,c,d,e)}n.Tween=$b,$b.prototype={constructor:$b,init:function(a,b,c,d,e,f){this.elem=a,this.prop=c,this.easing=e||"swing",this.options=b,this.start=this.now=this.cur(),this.end=d,this.unit=f||(n.cssNumber[c]?"":"px")},cur:function(){var a=$b.propHooks[this.prop];return a&&a.get?a.get(this):$b.propHooks._default.get(this)},run:function(a){var b,c=$b.propHooks[this.prop];return this.pos=b=this.options.duration?n.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration):a,this.now=(this.end-this.start)*b+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),c&&c.set?c.set(this):$b.propHooks._default.set(this),this}},$b.prototype.init.prototype=$b.prototype,$b.propHooks={_default:{get:function(a){var b;return null==a.elem[a.prop]||a.elem.style&&null!=a.elem.style[a.prop]?(b=n.css(a.elem,a.prop,""),b&&"auto"!==b?b:0):a.elem[a.prop]},set:function(a){n.fx.step[a.prop]?n.fx.step[a.prop](a):a.elem.style&&(null!=a.elem.style[n.cssProps[a.prop]]||n.cssHooks[a.prop])?n.style(a.elem,a.prop,a.now+a.unit):a.elem[a.prop]=a.now}}},$b.propHooks.scrollTop=$b.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}},n.easing={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2}},n.fx=$b.prototype.init,n.fx.step={};var _b,ac,bc=/^(?:toggle|show|hide)$/,cc=new RegExp("^(?:([+-])=|)("+T+")([a-z%]*)$","i"),dc=/queueHooks$/,ec=[jc],fc={"*":[function(a,b){var c=this.createTween(a,b),d=c.cur(),e=cc.exec(b),f=e&&e[3]||(n.cssNumber[a]?"":"px"),g=(n.cssNumber[a]||"px"!==f&&+d)&&cc.exec(n.css(c.elem,a)),h=1,i=20;if(g&&g[3]!==f){f=f||g[3],e=e||[],g=+d||1;do h=h||".5",g/=h,n.style(c.elem,a,g+f);while(h!==(h=c.cur()/d)&&1!==h&&--i)}return e&&(g=c.start=+g||+d||0,c.unit=f,c.end=e[1]?g+(e[1]+1)*e[2]:+e[2]),c}]};function gc(){return setTimeout(function(){_b=void 0}),_b=n.now()}function hc(a,b){var c,d={height:a},e=0;for(b=b?1:0;4>e;e+=2-b)c=U[e],d["margin"+c]=d["padding"+c]=a;return b&&(d.opacity=d.width=a),d}function ic(a,b,c){for(var d,e=(fc[b]||[]).concat(fc["*"]),f=0,g=e.length;g>f;f++)if(d=e[f].call(c,b,a))return d}function jc(a,b,c){var d,e,f,g,h,i,j,k,m=this,o={},p=a.style,q=a.nodeType&&V(a),r=n._data(a,"fxshow");c.queue||(h=n._queueHooks(a,"fx"),null==h.unqueued&&(h.unqueued=0,i=h.empty.fire,h.empty.fire=function(){h.unqueued||i()}),h.unqueued++,m.always(function(){m.always(function(){h.unqueued--,n.queue(a,"fx").length||h.empty.fire()})})),1===a.nodeType&&("height"in b||"width"in b)&&(c.overflow=[p.overflow,p.overflowX,p.overflowY],j=n.css(a,"display"),k=Gb(a.nodeName),"none"===j&&(j=k),"inline"===j&&"none"===n.css(a,"float")&&(l.inlineBlockNeedsLayout&&"inline"!==k?p.zoom=1:p.display="inline-block")),c.overflow&&(p.overflow="hidden",l.shrinkWrapBlocks()||m.always(function(){p.overflow=c.overflow[0],p.overflowX=c.overflow[1],p.overflowY=c.overflow[2]}));for(d in b)if(e=b[d],bc.exec(e)){if(delete b[d],f=f||"toggle"===e,e===(q?"hide":"show")){if("show"!==e||!r||void 0===r[d])continue;q=!0}o[d]=r&&r[d]||n.style(a,d)}if(!n.isEmptyObject(o)){r?"hidden"in r&&(q=r.hidden):r=n._data(a,"fxshow",{}),f&&(r.hidden=!q),q?n(a).show():m.done(function(){n(a).hide()}),m.done(function(){var b;n._removeData(a,"fxshow");for(b in o)n.style(a,b,o[b])});for(d in o)g=ic(q?r[d]:0,d,m),d in r||(r[d]=g.start,q&&(g.end=g.start,g.start="width"===d||"height"===d?1:0))}}function kc(a,b){var c,d,e,f,g;for(c in a)if(d=n.camelCase(c),e=b[d],f=a[c],n.isArray(f)&&(e=f[1],f=a[c]=f[0]),c!==d&&(a[d]=f,delete a[c]),g=n.cssHooks[d],g&&"expand"in g){f=g.expand(f),delete a[d];for(c in f)c in a||(a[c]=f[c],b[c]=e)}else b[d]=e}function lc(a,b,c){var d,e,f=0,g=ec.length,h=n.Deferred().always(function(){delete i.elem}),i=function(){if(e)return!1;for(var b=_b||gc(),c=Math.max(0,j.startTime+j.duration-b),d=c/j.duration||0,f=1-d,g=0,i=j.tweens.length;i>g;g++)j.tweens[g].run(f);return h.notifyWith(a,[j,f,c]),1>f&&i?c:(h.resolveWith(a,[j]),!1)},j=h.promise({elem:a,props:n.extend({},b),opts:n.extend(!0,{specialEasing:{}},c),originalProperties:b,originalOptions:c,startTime:_b||gc(),duration:c.duration,tweens:[],createTween:function(b,c){var d=n.Tween(a,j.opts,b,c,j.opts.specialEasing[b]||j.opts.easing);return j.tweens.push(d),d},stop:function(b){var c=0,d=b?j.tweens.length:0;if(e)return this;for(e=!0;d>c;c++)j.tweens[c].run(1);return b?h.resolveWith(a,[j,b]):h.rejectWith(a,[j,b]),this}}),k=j.props;for(kc(k,j.opts.specialEasing);g>f;f++)if(d=ec[f].call(j,a,k,j.opts))return d;return n.map(k,ic,j),n.isFunction(j.opts.start)&&j.opts.start.call(a,j),n.fx.timer(n.extend(i,{elem:a,anim:j,queue:j.opts.queue})),j.progress(j.opts.progress).done(j.opts.done,j.opts.complete).fail(j.opts.fail).always(j.opts.always)}n.Animation=n.extend(lc,{tweener:function(a,b){n.isFunction(a)?(b=a,a=["*"]):a=a.split(" ");for(var c,d=0,e=a.length;e>d;d++)c=a[d],fc[c]=fc[c]||[],fc[c].unshift(b)},prefilter:function(a,b){b?ec.unshift(a):ec.push(a)}}),n.speed=function(a,b,c){var d=a&&"object"==typeof a?n.extend({},a):{complete:c||!c&&b||n.isFunction(a)&&a,duration:a,easing:c&&b||b&&!n.isFunction(b)&&b};return d.duration=n.fx.off?0:"number"==typeof d.duration?d.duration:d.duration in n.fx.speeds?n.fx.speeds[d.duration]:n.fx.speeds._default,(null==d.queue||d.queue===!0)&&(d.queue="fx"),d.old=d.complete,d.complete=function(){n.isFunction(d.old)&&d.old.call(this),d.queue&&n.dequeue(this,d.queue)},d},n.fn.extend({fadeTo:function(a,b,c,d){return this.filter(V).css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){var e=n.isEmptyObject(a),f=n.speed(b,c,d),g=function(){var b=lc(this,n.extend({},a),f);(e||n._data(this,"finish"))&&b.stop(!0)};return g.finish=g,e||f.queue===!1?this.each(g):this.queue(f.queue,g)},stop:function(a,b,c){var d=function(a){var b=a.stop;delete a.stop,b(c)};return"string"!=typeof a&&(c=b,b=a,a=void 0),b&&a!==!1&&this.queue(a||"fx",[]),this.each(function(){var b=!0,e=null!=a&&a+"queueHooks",f=n.timers,g=n._data(this);if(e)g[e]&&g[e].stop&&d(g[e]);else for(e in g)g[e]&&g[e].stop&&dc.test(e)&&d(g[e]);for(e=f.length;e--;)f[e].elem!==this||null!=a&&f[e].queue!==a||(f[e].anim.stop(c),b=!1,f.splice(e,1));(b||!c)&&n.dequeue(this,a)})},finish:function(a){return a!==!1&&(a=a||"fx"),this.each(function(){var b,c=n._data(this),d=c[a+"queue"],e=c[a+"queueHooks"],f=n.timers,g=d?d.length:0;for(c.finish=!0,n.queue(this,a,[]),e&&e.stop&&e.stop.call(this,!0),b=f.length;b--;)f[b].elem===this&&f[b].queue===a&&(f[b].anim.stop(!0),f.splice(b,1));for(b=0;g>b;b++)d[b]&&d[b].finish&&d[b].finish.call(this);delete c.finish})}}),n.each(["toggle","show","hide"],function(a,b){var c=n.fn[b];n.fn[b]=function(a,d,e){return null==a||"boolean"==typeof a?c.apply(this,arguments):this.animate(hc(b,!0),a,d,e)}}),n.each({slideDown:hc("show"),slideUp:hc("hide"),slideToggle:hc("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){n.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),n.timers=[],n.fx.tick=function(){var a,b=n.timers,c=0;for(_b=n.now();c<b.length;c++)a=b[c],a()||b[c]!==a||b.splice(c--,1);b.length||n.fx.stop(),_b=void 0},n.fx.timer=function(a){n.timers.push(a),a()?n.fx.start():n.timers.pop()},n.fx.interval=13,n.fx.start=function(){ac||(ac=setInterval(n.fx.tick,n.fx.interval))},n.fx.stop=function(){clearInterval(ac),ac=null},n.fx.speeds={slow:600,fast:200,_default:400},n.fn.delay=function(a,b){return a=n.fx?n.fx.speeds[a]||a:a,b=b||"fx",this.queue(b,function(b,c){var d=setTimeout(b,a);c.stop=function(){clearTimeout(d)}})},function(){var a,b,c,d,e=z.createElement("div");e.setAttribute("className","t"),e.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",a=e.getElementsByTagName("a")[0],c=z.createElement("select"),d=c.appendChild(z.createElement("option")),b=e.getElementsByTagName("input")[0],a.style.cssText="top:1px",l.getSetAttribute="t"!==e.className,l.style=/top/.test(a.getAttribute("style")),l.hrefNormalized="/a"===a.getAttribute("href"),l.checkOn=!!b.value,l.optSelected=d.selected,l.enctype=!!z.createElement("form").enctype,c.disabled=!0,l.optDisabled=!d.disabled,b=z.createElement("input"),b.setAttribute("value",""),l.input=""===b.getAttribute("value"),b.value="t",b.setAttribute("type","radio"),l.radioValue="t"===b.value,a=b=c=d=e=null}();var mc=/\r/g;n.fn.extend({val:function(a){var b,c,d,e=this[0];{if(arguments.length)return d=n.isFunction(a),this.each(function(c){var e;1===this.nodeType&&(e=d?a.call(this,c,n(this).val()):a,null==e?e="":"number"==typeof e?e+="":n.isArray(e)&&(e=n.map(e,function(a){return null==a?"":a+""})),b=n.valHooks[this.type]||n.valHooks[this.nodeName.toLowerCase()],b&&"set"in b&&void 0!==b.set(this,e,"value")||(this.value=e))});if(e)return b=n.valHooks[e.type]||n.valHooks[e.nodeName.toLowerCase()],b&&"get"in b&&void 0!==(c=b.get(e,"value"))?c:(c=e.value,"string"==typeof c?c.replace(mc,""):null==c?"":c)}}}),n.extend({valHooks:{option:{get:function(a){var b=n.find.attr(a,"value");return null!=b?b:n.text(a)}},select:{get:function(a){for(var b,c,d=a.options,e=a.selectedIndex,f="select-one"===a.type||0>e,g=f?null:[],h=f?e+1:d.length,i=0>e?h:f?e:0;h>i;i++)if(c=d[i],!(!c.selected&&i!==e||(l.optDisabled?c.disabled:null!==c.getAttribute("disabled"))||c.parentNode.disabled&&n.nodeName(c.parentNode,"optgroup"))){if(b=n(c).val(),f)return b;g.push(b)}return g},set:function(a,b){var c,d,e=a.options,f=n.makeArray(b),g=e.length;while(g--)if(d=e[g],n.inArray(n.valHooks.option.get(d),f)>=0)try{d.selected=c=!0}catch(h){d.scrollHeight}else d.selected=!1;return c||(a.selectedIndex=-1),e}}}}),n.each(["radio","checkbox"],function(){n.valHooks[this]={set:function(a,b){return n.isArray(b)?a.checked=n.inArray(n(a).val(),b)>=0:void 0}},l.checkOn||(n.valHooks[this].get=function(a){return null===a.getAttribute("value")?"on":a.value})});var nc,oc,pc=n.expr.attrHandle,qc=/^(?:checked|selected)$/i,rc=l.getSetAttribute,sc=l.input;n.fn.extend({attr:function(a,b){return W(this,n.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){n.removeAttr(this,a)})}}),n.extend({attr:function(a,b,c){var d,e,f=a.nodeType;if(a&&3!==f&&8!==f&&2!==f)return typeof a.getAttribute===L?n.prop(a,b,c):(1===f&&n.isXMLDoc(a)||(b=b.toLowerCase(),d=n.attrHooks[b]||(n.expr.match.bool.test(b)?oc:nc)),void 0===c?d&&"get"in d&&null!==(e=d.get(a,b))?e:(e=n.find.attr(a,b),null==e?void 0:e):null!==c?d&&"set"in d&&void 0!==(e=d.set(a,c,b))?e:(a.setAttribute(b,c+""),c):void n.removeAttr(a,b))},removeAttr:function(a,b){var c,d,e=0,f=b&&b.match(F);if(f&&1===a.nodeType)while(c=f[e++])d=n.propFix[c]||c,n.expr.match.bool.test(c)?sc&&rc||!qc.test(c)?a[d]=!1:a[n.camelCase("default-"+c)]=a[d]=!1:n.attr(a,c,""),a.removeAttribute(rc?c:d)},attrHooks:{type:{set:function(a,b){if(!l.radioValue&&"radio"===b&&n.nodeName(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}}}}),oc={set:function(a,b,c){return b===!1?n.removeAttr(a,c):sc&&rc||!qc.test(c)?a.setAttribute(!rc&&n.propFix[c]||c,c):a[n.camelCase("default-"+c)]=a[c]=!0,c}},n.each(n.expr.match.bool.source.match(/\w+/g),function(a,b){var c=pc[b]||n.find.attr;pc[b]=sc&&rc||!qc.test(b)?function(a,b,d){var e,f;return d||(f=pc[b],pc[b]=e,e=null!=c(a,b,d)?b.toLowerCase():null,pc[b]=f),e}:function(a,b,c){return c?void 0:a[n.camelCase("default-"+b)]?b.toLowerCase():null}}),sc&&rc||(n.attrHooks.value={set:function(a,b,c){return n.nodeName(a,"input")?void(a.defaultValue=b):nc&&nc.set(a,b,c)}}),rc||(nc={set:function(a,b,c){var d=a.getAttributeNode(c);return d||a.setAttributeNode(d=a.ownerDocument.createAttribute(c)),d.value=b+="","value"===c||b===a.getAttribute(c)?b:void 0}},pc.id=pc.name=pc.coords=function(a,b,c){var d;return c?void 0:(d=a.getAttributeNode(b))&&""!==d.value?d.value:null},n.valHooks.button={get:function(a,b){var c=a.getAttributeNode(b);return c&&c.specified?c.value:void 0},set:nc.set},n.attrHooks.contenteditable={set:function(a,b,c){nc.set(a,""===b?!1:b,c)}},n.each(["width","height"],function(a,b){n.attrHooks[b]={set:function(a,c){return""===c?(a.setAttribute(b,"auto"),c):void 0}}})),l.style||(n.attrHooks.style={get:function(a){return a.style.cssText||void 0},set:function(a,b){return a.style.cssText=b+""}});var tc=/^(?:input|select|textarea|button|object)$/i,uc=/^(?:a|area)$/i;n.fn.extend({prop:function(a,b){return W(this,n.prop,a,b,arguments.length>1)},removeProp:function(a){return a=n.propFix[a]||a,this.each(function(){try{this[a]=void 0,delete this[a]}catch(b){}})}}),n.extend({propFix:{"for":"htmlFor","class":"className"},prop:function(a,b,c){var d,e,f,g=a.nodeType;if(a&&3!==g&&8!==g&&2!==g)return f=1!==g||!n.isXMLDoc(a),f&&(b=n.propFix[b]||b,e=n.propHooks[b]),void 0!==c?e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:a[b]=c:e&&"get"in e&&null!==(d=e.get(a,b))?d:a[b]},propHooks:{tabIndex:{get:function(a){var b=n.find.attr(a,"tabindex");return b?parseInt(b,10):tc.test(a.nodeName)||uc.test(a.nodeName)&&a.href?0:-1}}}}),l.hrefNormalized||n.each(["href","src"],function(a,b){n.propHooks[b]={get:function(a){return a.getAttribute(b,4)}}}),l.optSelected||(n.propHooks.selected={get:function(a){var b=a.parentNode;return b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex),null}}),n.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){n.propFix[this.toLowerCase()]=this}),l.enctype||(n.propFix.enctype="encoding");var vc=/[\t\r\n\f]/g;n.fn.extend({addClass:function(a){var b,c,d,e,f,g,h=0,i=this.length,j="string"==typeof a&&a;if(n.isFunction(a))return this.each(function(b){n(this).addClass(a.call(this,b,this.className))});if(j)for(b=(a||"").match(F)||[];i>h;h++)if(c=this[h],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(vc," "):" ")){f=0;while(e=b[f++])d.indexOf(" "+e+" ")<0&&(d+=e+" ");g=n.trim(d),c.className!==g&&(c.className=g)}return this},removeClass:function(a){var b,c,d,e,f,g,h=0,i=this.length,j=0===arguments.length||"string"==typeof a&&a;if(n.isFunction(a))return this.each(function(b){n(this).removeClass(a.call(this,b,this.className))});if(j)for(b=(a||"").match(F)||[];i>h;h++)if(c=this[h],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(vc," "):"")){f=0;while(e=b[f++])while(d.indexOf(" "+e+" ")>=0)d=d.replace(" "+e+" "," ");g=a?n.trim(d):"",c.className!==g&&(c.className=g)}return this},toggleClass:function(a,b){var c=typeof a;return"boolean"==typeof b&&"string"===c?b?this.addClass(a):this.removeClass(a):this.each(n.isFunction(a)?function(c){n(this).toggleClass(a.call(this,c,this.className,b),b)}:function(){if("string"===c){var b,d=0,e=n(this),f=a.match(F)||[];while(b=f[d++])e.hasClass(b)?e.removeClass(b):e.addClass(b)}else(c===L||"boolean"===c)&&(this.className&&n._data(this,"__className__",this.className),this.className=this.className||a===!1?"":n._data(this,"__className__")||"")})},hasClass:function(a){for(var b=" "+a+" ",c=0,d=this.length;d>c;c++)if(1===this[c].nodeType&&(" "+this[c].className+" ").replace(vc," ").indexOf(b)>=0)return!0;return!1}}),n.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(a,b){n.fn[b]=function(a,c){return arguments.length>0?this.on(b,null,a,c):this.trigger(b)}}),n.fn.extend({hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)},bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return 1===arguments.length?this.off(a,"**"):this.off(b,a||"**",c)}});var wc=n.now(),xc=/\?/,yc=/(,)|(\[|{)|(}|])|"(?:[^"\\\r\n]|\\["\\\/bfnrt]|\\u[\da-fA-F]{4})*"\s*:?|true|false|null|-?(?!0\d)\d+(?:\.\d+|)(?:[eE][+-]?\d+|)/g;n.parseJSON=function(b){if(a.JSON&&a.JSON.parse)return a.JSON.parse(b+"");var c,d=null,e=n.trim(b+"");return e&&!n.trim(e.replace(yc,function(a,b,e,f){return c&&b&&(d=0),0===d?a:(c=e||b,d+=!f-!e,"")}))?Function("return "+e)():n.error("Invalid JSON: "+b)},n.parseXML=function(b){var c,d;if(!b||"string"!=typeof b)return null;try{a.DOMParser?(d=new DOMParser,c=d.parseFromString(b,"text/xml")):(c=new ActiveXObject("Microsoft.XMLDOM"),c.async="false",c.loadXML(b))}catch(e){c=void 0}return c&&c.documentElement&&!c.getElementsByTagName("parsererror").length||n.error("Invalid XML: "+b),c};var zc,Ac,Bc=/#.*$/,Cc=/([?&])_=[^&]*/,Dc=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Ec=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Fc=/^(?:GET|HEAD)$/,Gc=/^\/\//,Hc=/^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,Ic={},Jc={},Kc="*/".concat("*");try{Ac=location.href}catch(Lc){Ac=z.createElement("a"),Ac.href="",Ac=Ac.href}zc=Hc.exec(Ac.toLowerCase())||[];function Mc(a){return function(b,c){"string"!=typeof b&&(c=b,b="*");var d,e=0,f=b.toLowerCase().match(F)||[];if(n.isFunction(c))while(d=f[e++])"+"===d.charAt(0)?(d=d.slice(1)||"*",(a[d]=a[d]||[]).unshift(c)):(a[d]=a[d]||[]).push(c)}}function Nc(a,b,c,d){var e={},f=a===Jc;function g(h){var i;return e[h]=!0,n.each(a[h]||[],function(a,h){var j=h(b,c,d);return"string"!=typeof j||f||e[j]?f?!(i=j):void 0:(b.dataTypes.unshift(j),g(j),!1)}),i}return g(b.dataTypes[0])||!e["*"]&&g("*")}function Oc(a,b){var c,d,e=n.ajaxSettings.flatOptions||{};for(d in b)void 0!==b[d]&&((e[d]?a:c||(c={}))[d]=b[d]);return c&&n.extend(!0,a,c),a}function Pc(a,b,c){var d,e,f,g,h=a.contents,i=a.dataTypes;while("*"===i[0])i.shift(),void 0===e&&(e=a.mimeType||b.getResponseHeader("Content-Type"));if(e)for(g in h)if(h[g]&&h[g].test(e)){i.unshift(g);break}if(i[0]in c)f=i[0];else{for(g in c){if(!i[0]||a.converters[g+" "+i[0]]){f=g;break}d||(d=g)}f=f||d}return f?(f!==i[0]&&i.unshift(f),c[f]):void 0}function Qc(a,b,c,d){var e,f,g,h,i,j={},k=a.dataTypes.slice();if(k[1])for(g in a.converters)j[g.toLowerCase()]=a.converters[g];f=k.shift();while(f)if(a.responseFields[f]&&(c[a.responseFields[f]]=b),!i&&d&&a.dataFilter&&(b=a.dataFilter(b,a.dataType)),i=f,f=k.shift())if("*"===f)f=i;else if("*"!==i&&i!==f){if(g=j[i+" "+f]||j["* "+f],!g)for(e in j)if(h=e.split(" "),h[1]===f&&(g=j[i+" "+h[0]]||j["* "+h[0]])){g===!0?g=j[e]:j[e]!==!0&&(f=h[0],k.unshift(h[1]));break}if(g!==!0)if(g&&a["throws"])b=g(b);else try{b=g(b)}catch(l){return{state:"parsererror",error:g?l:"No conversion from "+i+" to "+f}}}return{state:"success",data:b}}n.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:Ac,type:"GET",isLocal:Ec.test(zc[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Kc,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":n.parseJSON,"text xml":n.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(a,b){return b?Oc(Oc(a,n.ajaxSettings),b):Oc(n.ajaxSettings,a)},ajaxPrefilter:Mc(Ic),ajaxTransport:Mc(Jc),ajax:function(a,b){"object"==typeof a&&(b=a,a=void 0),b=b||{};var c,d,e,f,g,h,i,j,k=n.ajaxSetup({},b),l=k.context||k,m=k.context&&(l.nodeType||l.jquery)?n(l):n.event,o=n.Deferred(),p=n.Callbacks("once memory"),q=k.statusCode||{},r={},s={},t=0,u="canceled",v={readyState:0,getResponseHeader:function(a){var b;if(2===t){if(!j){j={};while(b=Dc.exec(f))j[b[1].toLowerCase()]=b[2]}b=j[a.toLowerCase()]}return null==b?null:b},getAllResponseHeaders:function(){return 2===t?f:null},setRequestHeader:function(a,b){var c=a.toLowerCase();return t||(a=s[c]=s[c]||a,r[a]=b),this},overrideMimeType:function(a){return t||(k.mimeType=a),this},statusCode:function(a){var b;if(a)if(2>t)for(b in a)q[b]=[q[b],a[b]];else v.always(a[v.status]);return this},abort:function(a){var b=a||u;return i&&i.abort(b),x(0,b),this}};if(o.promise(v).complete=p.add,v.success=v.done,v.error=v.fail,k.url=((a||k.url||Ac)+"").replace(Bc,"").replace(Gc,zc[1]+"//"),k.type=b.method||b.type||k.method||k.type,k.dataTypes=n.trim(k.dataType||"*").toLowerCase().match(F)||[""],null==k.crossDomain&&(c=Hc.exec(k.url.toLowerCase()),k.crossDomain=!(!c||c[1]===zc[1]&&c[2]===zc[2]&&(c[3]||("http:"===c[1]?"80":"443"))===(zc[3]||("http:"===zc[1]?"80":"443")))),k.data&&k.processData&&"string"!=typeof k.data&&(k.data=n.param(k.data,k.traditional)),Nc(Ic,k,b,v),2===t)return v;h=k.global,h&&0===n.active++&&n.event.trigger("ajaxStart"),k.type=k.type.toUpperCase(),k.hasContent=!Fc.test(k.type),e=k.url,k.hasContent||(k.data&&(e=k.url+=(xc.test(e)?"&":"?")+k.data,delete k.data),k.cache===!1&&(k.url=Cc.test(e)?e.replace(Cc,"$1_="+wc++):e+(xc.test(e)?"&":"?")+"_="+wc++)),k.ifModified&&(n.lastModified[e]&&v.setRequestHeader("If-Modified-Since",n.lastModified[e]),n.etag[e]&&v.setRequestHeader("If-None-Match",n.etag[e])),(k.data&&k.hasContent&&k.contentType!==!1||b.contentType)&&v.setRequestHeader("Content-Type",k.contentType),v.setRequestHeader("Accept",k.dataTypes[0]&&k.accepts[k.dataTypes[0]]?k.accepts[k.dataTypes[0]]+("*"!==k.dataTypes[0]?", "+Kc+"; q=0.01":""):k.accepts["*"]);for(d in k.headers)v.setRequestHeader(d,k.headers[d]);if(k.beforeSend&&(k.beforeSend.call(l,v,k)===!1||2===t))return v.abort();u="abort";for(d in{success:1,error:1,complete:1})v[d](k[d]);if(i=Nc(Jc,k,b,v)){v.readyState=1,h&&m.trigger("ajaxSend",[v,k]),k.async&&k.timeout>0&&(g=setTimeout(function(){v.abort("timeout")},k.timeout));try{t=1,i.send(r,x)}catch(w){if(!(2>t))throw w;x(-1,w)}}else x(-1,"No Transport");function x(a,b,c,d){var j,r,s,u,w,x=b;2!==t&&(t=2,g&&clearTimeout(g),i=void 0,f=d||"",v.readyState=a>0?4:0,j=a>=200&&300>a||304===a,c&&(u=Pc(k,v,c)),u=Qc(k,u,v,j),j?(k.ifModified&&(w=v.getResponseHeader("Last-Modified"),w&&(n.lastModified[e]=w),w=v.getResponseHeader("etag"),w&&(n.etag[e]=w)),204===a||"HEAD"===k.type?x="nocontent":304===a?x="notmodified":(x=u.state,r=u.data,s=u.error,j=!s)):(s=x,(a||!x)&&(x="error",0>a&&(a=0))),v.status=a,v.statusText=(b||x)+"",j?o.resolveWith(l,[r,x,v]):o.rejectWith(l,[v,x,s]),v.statusCode(q),q=void 0,h&&m.trigger(j?"ajaxSuccess":"ajaxError",[v,k,j?r:s]),p.fireWith(l,[v,x]),h&&(m.trigger("ajaxComplete",[v,k]),--n.active||n.event.trigger("ajaxStop")))}return v},getJSON:function(a,b,c){return n.get(a,b,c,"json")},getScript:function(a,b){return n.get(a,void 0,b,"script")}}),n.each(["get","post"],function(a,b){n[b]=function(a,c,d,e){return n.isFunction(c)&&(e=e||d,d=c,c=void 0),n.ajax({url:a,type:b,dataType:e,data:c,success:d})}}),n.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(a,b){n.fn[b]=function(a){return this.on(b,a)}}),n._evalUrl=function(a){return n.ajax({url:a,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})},n.fn.extend({wrapAll:function(a){if(n.isFunction(a))return this.each(function(b){n(this).wrapAll(a.call(this,b))});if(this[0]){var b=n(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&1===a.firstChild.nodeType)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){return this.each(n.isFunction(a)?function(b){n(this).wrapInner(a.call(this,b))}:function(){var b=n(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=n.isFunction(a);return this.each(function(c){n(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){n.nodeName(this,"body")||n(this).replaceWith(this.childNodes)}).end()}}),n.expr.filters.hidden=function(a){return a.offsetWidth<=0&&a.offsetHeight<=0||!l.reliableHiddenOffsets()&&"none"===(a.style&&a.style.display||n.css(a,"display"))},n.expr.filters.visible=function(a){return!n.expr.filters.hidden(a)};var Rc=/%20/g,Sc=/\[\]$/,Tc=/\r?\n/g,Uc=/^(?:submit|button|image|reset|file)$/i,Vc=/^(?:input|select|textarea|keygen)/i;function Wc(a,b,c,d){var e;if(n.isArray(b))n.each(b,function(b,e){c||Sc.test(a)?d(a,e):Wc(a+"["+("object"==typeof e?b:"")+"]",e,c,d)});else if(c||"object"!==n.type(b))d(a,b);else for(e in b)Wc(a+"["+e+"]",b[e],c,d)}n.param=function(a,b){var c,d=[],e=function(a,b){b=n.isFunction(b)?b():null==b?"":b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};if(void 0===b&&(b=n.ajaxSettings&&n.ajaxSettings.traditional),n.isArray(a)||a.jquery&&!n.isPlainObject(a))n.each(a,function(){e(this.name,this.value)});else for(c in a)Wc(c,a[c],b,e);return d.join("&").replace(Rc,"+")},n.fn.extend({serialize:function(){return n.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var a=n.prop(this,"elements");return a?n.makeArray(a):this}).filter(function(){var a=this.type;return this.name&&!n(this).is(":disabled")&&Vc.test(this.nodeName)&&!Uc.test(a)&&(this.checked||!X.test(a))}).map(function(a,b){var c=n(this).val();return null==c?null:n.isArray(c)?n.map(c,function(a){return{name:b.name,value:a.replace(Tc,"\r\n")}}):{name:b.name,value:c.replace(Tc,"\r\n")}}).get()}}),n.ajaxSettings.xhr=void 0!==a.ActiveXObject?function(){return!this.isLocal&&/^(get|post|head|put|delete|options)$/i.test(this.type)&&$c()||_c()}:$c;var Xc=0,Yc={},Zc=n.ajaxSettings.xhr();a.ActiveXObject&&n(a).on("unload",function(){for(var a in Yc)Yc[a](void 0,!0)}),l.cors=!!Zc&&"withCredentials"in Zc,Zc=l.ajax=!!Zc,Zc&&n.ajaxTransport(function(a){if(!a.crossDomain||l.cors){var b;return{send:function(c,d){var e,f=a.xhr(),g=++Xc;if(f.open(a.type,a.url,a.async,a.username,a.password),a.xhrFields)for(e in a.xhrFields)f[e]=a.xhrFields[e];a.mimeType&&f.overrideMimeType&&f.overrideMimeType(a.mimeType),a.crossDomain||c["X-Requested-With"]||(c["X-Requested-With"]="XMLHttpRequest");for(e in c)void 0!==c[e]&&f.setRequestHeader(e,c[e]+"");f.send(a.hasContent&&a.data||null),b=function(c,e){var h,i,j;if(b&&(e||4===f.readyState))if(delete Yc[g],b=void 0,f.onreadystatechange=n.noop,e)4!==f.readyState&&f.abort();else{j={},h=f.status,"string"==typeof f.responseText&&(j.text=f.responseText);try{i=f.statusText}catch(k){i=""}h||!a.isLocal||a.crossDomain?1223===h&&(h=204):h=j.text?200:404}j&&d(h,i,j,f.getAllResponseHeaders())},a.async?4===f.readyState?setTimeout(b):f.onreadystatechange=Yc[g]=b:b()},abort:function(){b&&b(void 0,!0)}}}});function $c(){try{return new a.XMLHttpRequest}catch(b){}}function _c(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}n.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(a){return n.globalEval(a),a}}}),n.ajaxPrefilter("script",function(a){void 0===a.cache&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),n.ajaxTransport("script",function(a){if(a.crossDomain){var b,c=z.head||n("head")[0]||z.documentElement;return{send:function(d,e){b=z.createElement("script"),b.async=!0,a.scriptCharset&&(b.charset=a.scriptCharset),b.src=a.url,b.onload=b.onreadystatechange=function(a,c){(c||!b.readyState||/loaded|complete/.test(b.readyState))&&(b.onload=b.onreadystatechange=null,b.parentNode&&b.parentNode.removeChild(b),b=null,c||e(200,"success"))},c.insertBefore(b,c.firstChild)},abort:function(){b&&b.onload(void 0,!0)}}}});var ad=[],bd=/(=)\?(?=&|$)|\?\?/;n.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=ad.pop()||n.expando+"_"+wc++;return this[a]=!0,a}}),n.ajaxPrefilter("json jsonp",function(b,c,d){var e,f,g,h=b.jsonp!==!1&&(bd.test(b.url)?"url":"string"==typeof b.data&&!(b.contentType||"").indexOf("application/x-www-form-urlencoded")&&bd.test(b.data)&&"data");return h||"jsonp"===b.dataTypes[0]?(e=b.jsonpCallback=n.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,h?b[h]=b[h].replace(bd,"$1"+e):b.jsonp!==!1&&(b.url+=(xc.test(b.url)?"&":"?")+b.jsonp+"="+e),b.converters["script json"]=function(){return g||n.error(e+" was not called"),g[0]},b.dataTypes[0]="json",f=a[e],a[e]=function(){g=arguments},d.always(function(){a[e]=f,b[e]&&(b.jsonpCallback=c.jsonpCallback,ad.push(e)),g&&n.isFunction(f)&&f(g[0]),g=f=void 0}),"script"):void 0}),n.parseHTML=function(a,b,c){if(!a||"string"!=typeof a)return null;"boolean"==typeof b&&(c=b,b=!1),b=b||z;var d=v.exec(a),e=!c&&[];return d?[b.createElement(d[1])]:(d=n.buildFragment([a],b,e),e&&e.length&&n(e).remove(),n.merge([],d.childNodes))};var cd=n.fn.load;n.fn.load=function(a,b,c){if("string"!=typeof a&&cd)return cd.apply(this,arguments);var d,e,f,g=this,h=a.indexOf(" ");return h>=0&&(d=a.slice(h,a.length),a=a.slice(0,h)),n.isFunction(b)?(c=b,b=void 0):b&&"object"==typeof b&&(f="POST"),g.length>0&&n.ajax({url:a,type:f,dataType:"html",data:b}).done(function(a){e=arguments,g.html(d?n("<div>").append(n.parseHTML(a)).find(d):a)}).complete(c&&function(a,b){g.each(c,e||[a.responseText,b,a])}),this},n.expr.filters.animated=function(a){return n.grep(n.timers,function(b){return a===b.elem}).length};var dd=a.document.documentElement;function ed(a){return n.isWindow(a)?a:9===a.nodeType?a.defaultView||a.parentWindow:!1}n.offset={setOffset:function(a,b,c){var d,e,f,g,h,i,j,k=n.css(a,"position"),l=n(a),m={};"static"===k&&(a.style.position="relative"),h=l.offset(),f=n.css(a,"top"),i=n.css(a,"left"),j=("absolute"===k||"fixed"===k)&&n.inArray("auto",[f,i])>-1,j?(d=l.position(),g=d.top,e=d.left):(g=parseFloat(f)||0,e=parseFloat(i)||0),n.isFunction(b)&&(b=b.call(a,c,h)),null!=b.top&&(m.top=b.top-h.top+g),null!=b.left&&(m.left=b.left-h.left+e),"using"in b?b.using.call(a,m):l.css(m)}},n.fn.extend({offset:function(a){if(arguments.length)return void 0===a?this:this.each(function(b){n.offset.setOffset(this,a,b)});var b,c,d={top:0,left:0},e=this[0],f=e&&e.ownerDocument;if(f)return b=f.documentElement,n.contains(b,e)?(typeof e.getBoundingClientRect!==L&&(d=e.getBoundingClientRect()),c=ed(f),{top:d.top+(c.pageYOffset||b.scrollTop)-(b.clientTop||0),left:d.left+(c.pageXOffset||b.scrollLeft)-(b.clientLeft||0)}):d},position:function(){if(this[0]){var a,b,c={top:0,left:0},d=this[0];return"fixed"===n.css(d,"position")?b=d.getBoundingClientRect():(a=this.offsetParent(),b=this.offset(),n.nodeName(a[0],"html")||(c=a.offset()),c.top+=n.css(a[0],"borderTopWidth",!0),c.left+=n.css(a[0],"borderLeftWidth",!0)),{top:b.top-c.top-n.css(d,"marginTop",!0),left:b.left-c.left-n.css(d,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||dd;while(a&&!n.nodeName(a,"html")&&"static"===n.css(a,"position"))a=a.offsetParent;return a||dd})}}),n.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,b){var c=/Y/.test(b);n.fn[a]=function(d){return W(this,function(a,d,e){var f=ed(a);return void 0===e?f?b in f?f[b]:f.document.documentElement[d]:a[d]:void(f?f.scrollTo(c?n(f).scrollLeft():e,c?e:n(f).scrollTop()):a[d]=e)},a,d,arguments.length,null)}}),n.each(["top","left"],function(a,b){n.cssHooks[b]=Mb(l.pixelPosition,function(a,c){return c?(c=Kb(a,b),Ib.test(c)?n(a).position()[b]+"px":c):void 0})}),n.each({Height:"height",Width:"width"},function(a,b){n.each({padding:"inner"+a,content:b,"":"outer"+a},function(c,d){n.fn[d]=function(d,e){var f=arguments.length&&(c||"boolean"!=typeof d),g=c||(d===!0||e===!0?"margin":"border");return W(this,function(b,c,d){var e;return n.isWindow(b)?b.document.documentElement["client"+a]:9===b.nodeType?(e=b.documentElement,Math.max(b.body["scroll"+a],e["scroll"+a],b.body["offset"+a],e["offset"+a],e["client"+a])):void 0===d?n.css(b,c,g):n.style(b,c,d,g)},b,f?d:void 0,f,null)}})}),n.fn.size=function(){return this.length},n.fn.andSelf=n.fn.addBack,"function"==typeof define&&define.amd&&define("jquery",[],function(){return n});var fd=a.jQuery,gd=a.$;return n.noConflict=function(b){return a.$===n&&(a.$=gd),b&&a.jQuery===n&&(a.jQuery=fd),n},typeof b===L&&(a.jQuery=a.$=n),n});
var socket = io.connect();
function session(){
this.siparisler = new Array();
}
var session = new session();
socket.emit("firstLogin",true);
socket.on("listenFirstLogin",function(data){
if(data.login == true){
$(document).ready(function(){
$("title").html("Sipariş verebilirsiniz");
$(".giris").hide();
$(".siparis").show();
});
}
else{
$(document).ready(function(){
$("title").html("Sipariş verebilmek için giriş yapın");
$(".giris").show();
$(".siparis").hide();
});
}
});
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*) basedir=`cygpath -w "$basedir"`;;
esac
if [ -x "$basedir/node" ]; then
"$basedir/node" "$basedir/../mime/cli.js" "$@"
ret=$?
else
node "$basedir/../mime/cli.js" "$@"
ret=$?
fi
exit $ret
@IF EXIST "%~dp0\node.exe" (
"%~dp0\node.exe" "%~dp0\..\mime\cli.js" %*
) ELSE (
@SETLOCAL
@SET PATHEXT=%PATHEXT:;.JS;=;%
node "%~dp0\..\mime\cli.js" %*
)
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*) basedir=`cygpath -w "$basedir"`;;
esac
if [ -x "$basedir/node" ]; then
"$basedir/node" "$basedir/../vows/bin/vows" "$@"
ret=$?
else
node "$basedir/../vows/bin/vows" "$@"
ret=$?
fi
exit $ret
@IF EXIST "%~dp0\node.exe" (
"%~dp0\node.exe" "%~dp0\..\vows\bin\vows" %*
) ELSE (
@SETLOCAL
@SET PATHEXT=%PATHEXT:;.JS;=;%
node "%~dp0\..\vows\bin\vows" %*
)

1.3.3 / 2016-05-02

  • deps: mime-types@~2.1.11
    • deps: mime-db@~1.23.0
  • deps: negotiator@0.6.1
    • perf: improve Accept parsing speed
    • perf: improve Accept-Charset parsing speed
    • perf: improve Accept-Encoding parsing speed
    • perf: improve Accept-Language parsing speed

1.3.2 / 2016-03-08

  • deps: mime-types@~2.1.10
    • Fix extension of application/dash+xml
    • Update primary extension for audio/mp4
    • deps: mime-db@~1.22.0

1.3.1 / 2016-01-19

  • deps: mime-types@~2.1.9
    • deps: mime-db@~1.21.0

1.3.0 / 2015-09-29

  • deps: mime-types@~2.1.7
    • deps: mime-db@~1.19.0
  • deps: negotiator@0.6.0
    • Fix including type extensions in parameters in Accept parsing
    • Fix parsing Accept parameters with quoted equals
    • Fix parsing Accept parameters with quoted semicolons
    • Lazy-load modules from main entry point
    • perf: delay type concatenation until needed
    • perf: enable strict mode
    • perf: hoist regular expressions
    • perf: remove closures getting spec properties
    • perf: remove a closure from media type parsing
    • perf: remove property delete from media type parsing

1.2.13 / 2015-09-06

  • deps: mime-types@~2.1.6
    • deps: mime-db@~1.18.0

1.2.12 / 2015-07-30

  • deps: mime-types@~2.1.4
    • deps: mime-db@~1.16.0

1.2.11 / 2015-07-16

  • deps: mime-types@~2.1.3
    • deps: mime-db@~1.15.0

1.2.10 / 2015-07-01

  • deps: mime-types@~2.1.2
    • deps: mime-db@~1.14.0

1.2.9 / 2015-06-08

  • deps: mime-types@~2.1.1
    • perf: fix deopt during mapping

1.2.8 / 2015-06-07

  • deps: mime-types@~2.1.0
    • deps: mime-db@~1.13.0
  • perf: avoid argument reassignment & argument slice
  • perf: avoid negotiator recursive construction
  • perf: enable strict mode
  • perf: remove unnecessary bitwise operator

1.2.7 / 2015-05-10

  • deps: negotiator@0.5.3
    • Fix media type parameter matching to be case-insensitive

1.2.6 / 2015-05-07

  • deps: mime-types@~2.0.11
    • deps: mime-db@~1.9.1
  • deps: negotiator@0.5.2
    • Fix comparing media types with quoted values
    • Fix splitting media types with quoted commas

1.2.5 / 2015-03-13

  • deps: mime-types@~2.0.10
    • deps: mime-db@~1.8.0

1.2.4 / 2015-02-14

  • Support Node.js 0.6
  • deps: mime-types@~2.0.9
    • deps: mime-db@~1.7.0
  • deps: negotiator@0.5.1
    • Fix preference sorting to be stable for long acceptable lists

1.2.3 / 2015-01-31

  • deps: mime-types@~2.0.8
    • deps: mime-db@~1.6.0

1.2.2 / 2014-12-30

  • deps: mime-types@~2.0.7
    • deps: mime-db@~1.5.0

1.2.1 / 2014-12-30

  • deps: mime-types@~2.0.5
    • deps: mime-db@~1.3.1

1.2.0 / 2014-12-19

  • deps: negotiator@0.5.0
    • Fix list return order when large accepted list
    • Fix missing identity encoding when q=0 exists
    • Remove dynamic building of Negotiator class

1.1.4 / 2014-12-10

  • deps: mime-types@~2.0.4
    • deps: mime-db@~1.3.0

1.1.3 / 2014-11-09

  • deps: mime-types@~2.0.3
    • deps: mime-db@~1.2.0

1.1.2 / 2014-10-14

  • deps: negotiator@0.4.9
    • Fix error when media type has invalid parameter

1.1.1 / 2014-09-28

  • deps: mime-types@~2.0.2
    • deps: mime-db@~1.1.0
  • deps: negotiator@0.4.8
    • Fix all negotiations to be case-insensitive
    • Stable sort preferences of same quality according to client order

1.1.0 / 2014-09-02

  • update mime-types

1.0.7 / 2014-07-04

  • Fix wrong type returned from type when match after unknown extension

1.0.6 / 2014-06-24

  • deps: negotiator@0.4.7

1.0.5 / 2014-06-20

  • fix crash when unknown extension given

1.0.4 / 2014-06-19

  • use mime-types

1.0.3 / 2014-06-11

  • deps: negotiator@0.4.6
    • Order by specificity when quality is the same

1.0.2 / 2014-05-29

  • Fix interpretation when header not in request
  • deps: pin negotiator@0.4.5

1.0.1 / 2014-01-18

  • Identity encoding isn't always acceptable
  • deps: negotiator@~0.4.0

1.0.0 / 2013-12-27

  • Genesis
/*!
* accepts
* Copyright(c) 2014 Jonathan Ong
* Copyright(c) 2015 Douglas Christopher Wilson
* MIT Licensed
*/
'use strict'
/**
* Module dependencies.
* @private
*/
var Negotiator = require('negotiator')
var mime = require('mime-types')
/**
* Module exports.
* @public
*/
module.exports = Accepts
/**
* Create a new Accepts object for the given req.
*
* @param {object} req
* @public
*/
function Accepts(req) {
if (!(this instanceof Accepts))
return new Accepts(req)
this.headers = req.headers
this.negotiator = new Negotiator(req)
}
/**
* Check if the given `type(s)` is acceptable, returning
* the best match when true, otherwise `undefined`, in which
* case you should respond with 406 "Not Acceptable".
*
* The `type` value may be a single mime type string
* such as "application/json", the extension name
* such as "json" or an array `["json", "html", "text/plain"]`. When a list
* or array is given the _best_ match, if any is returned.
*
* Examples:
*
* // Accept: text/html
* this.types('html');
* // => "html"
*
* // Accept: text/*, application/json
* this.types('html');
* // => "html"
* this.types('text/html');
* // => "text/html"
* this.types('json', 'text');
* // => "json"
* this.types('application/json');
* // => "application/json"
*
* // Accept: text/*, application/json
* this.types('image/png');
* this.types('png');
* // => undefined
*
* // Accept: text/*;q=.5, application/json
* this.types(['html', 'json']);
* this.types('html', 'json');
* // => "json"
*
* @param {String|Array} types...
* @return {String|Array|Boolean}
* @public
*/
Accepts.prototype.type =
Accepts.prototype.types = function (types_) {
var types = types_
// support flattened arguments
if (types && !Array.isArray(types)) {
types = new Array(arguments.length)
for (var i = 0; i < types.length; i++) {
types[i] = arguments[i]
}
}
// no types, return all requested types
if (!types || types.length === 0) {
return this.negotiator.mediaTypes()
}
if (!this.headers.accept) return types[0];
var mimes = types.map(extToMime);
var accepts = this.negotiator.mediaTypes(mimes.filter(validMime));
var first = accepts[0];
if (!first) return false;
return types[mimes.indexOf(first)];
}
/**
* Return accepted encodings or best fit based on `encodings`.
*
* Given `Accept-Encoding: gzip, deflate`
* an array sorted by quality is returned:
*
* ['gzip', 'deflate']
*
* @param {String|Array} encodings...
* @return {String|Array}
* @public
*/
Accepts.prototype.encoding =
Accepts.prototype.encodings = function (encodings_) {
var encodings = encodings_
// support flattened arguments
if (encodings && !Array.isArray(encodings)) {
encodings = new Array(arguments.length)
for (var i = 0; i < encodings.length; i++) {
encodings[i] = arguments[i]
}
}
// no encodings, return all requested encodings
if (!encodings || encodings.length === 0) {
return this.negotiator.encodings()
}
return this.negotiator.encodings(encodings)[0] || false
}
/**
* Return accepted charsets or best fit based on `charsets`.
*
* Given `Accept-Charset: utf-8, iso-8859-1;q=0.2, utf-7;q=0.5`
* an array sorted by quality is returned:
*
* ['utf-8', 'utf-7', 'iso-8859-1']
*
* @param {String|Array} charsets...
* @return {String|Array}
* @public
*/
Accepts.prototype.charset =
Accepts.prototype.charsets = function (charsets_) {
var charsets = charsets_
// support flattened arguments
if (charsets && !Array.isArray(charsets)) {
charsets = new Array(arguments.length)
for (var i = 0; i < charsets.length; i++) {
charsets[i] = arguments[i]
}
}
// no charsets, return all requested charsets
if (!charsets || charsets.length === 0) {
return this.negotiator.charsets()
}
return this.negotiator.charsets(charsets)[0] || false
}
/**
* Return accepted languages or best fit based on `langs`.
*
* Given `Accept-Language: en;q=0.8, es, pt`
* an array sorted by quality is returned:
*
* ['es', 'pt', 'en']
*
* @param {String|Array} langs...
* @return {Array|String}
* @public
*/
Accepts.prototype.lang =
Accepts.prototype.langs =
Accepts.prototype.language =
Accepts.prototype.languages = function (languages_) {
var languages = languages_
// support flattened arguments
if (languages && !Array.isArray(languages)) {
languages = new Array(arguments.length)
for (var i = 0; i < languages.length; i++) {
languages[i] = arguments[i]
}
}
// no languages, return all requested languages
if (!languages || languages.length === 0) {
return this.negotiator.languages()
}
return this.negotiator.languages(languages)[0] || false
}
/**
* Convert extnames to mime.
*
* @param {String} type
* @return {String}
* @private
*/
function extToMime(type) {
return type.indexOf('/') === -1
? mime.lookup(type)
: type
}
/**
* Check if mime is valid.
*
* @param {String} type
* @return {String}
* @private
*/
function validMime(type) {
return typeof type === 'string';
}
(The MIT License)
Copyright (c) 2014 Jonathan Ong <me@jongleberry.com>
Copyright (c) 2015 Douglas Christopher Wilson <doug@somethingdoug.com>
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.
{
"_args": [
[
{
"raw": "accepts@~1.3.3",
"scope": null,
"escapedName": "accepts",
"name": "accepts",
"rawSpec": "~1.3.3",
"spec": ">=1.3.3 <1.4.0",
"type": "range"
},
"C:\\xampp\\htdocs\\cafe\\node_modules\\express"
]
],
"_from": "accepts@>=1.3.3 <1.4.0",
"_id": "accepts@1.3.3",
"_inCache": true,
"_location": "/accepts",
"_nodeVersion": "4.4.3",
"_npmOperationalInternal": {
"host": "packages-16-east.internal.npmjs.com",
"tmp": "tmp/accepts-1.3.3.tgz_1462251932032_0.7092335098423064"
},
"_npmUser": {
"name": "dougwilson",
"email": "doug@somethingdoug.com"
},
"_npmVersion": "2.15.1",
"_phantomChildren": {},
"_requested": {
"raw": "accepts@~1.3.3",
"scope": null,
"escapedName": "accepts",
"name": "accepts",
"rawSpec": "~1.3.3",
"spec": ">=1.3.3 <1.4.0",
"type": "range"
},
"_requiredBy": [
"/express"
],
"_resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.3.tgz",
"_shasum": "c3ca7434938648c3e0d9c1e328dd68b622c284ca",
"_shrinkwrap": null,
"_spec": "accepts@~1.3.3",
"_where": "C:\\xampp\\htdocs\\cafe\\node_modules\\express",
"bugs": {
"url": "https://github.com/jshttp/accepts/issues"
},
"contributors": [
{
"name": "Douglas Christopher Wilson",
"email": "doug@somethingdoug.com"
},
{
"name": "Jonathan Ong",
"email": "me@jongleberry.com",
"url": "http://jongleberry.com"
}
],
"dependencies": {
"mime-types": "~2.1.11",
"negotiator": "0.6.1"
},
"description": "Higher-level content negotiation",
"devDependencies": {
"istanbul": "0.4.3",
"mocha": "~1.21.5"
},
"directories": {},
"dist": {
"shasum": "c3ca7434938648c3e0d9c1e328dd68b622c284ca",
"tarball": "https://registry.npmjs.org/accepts/-/accepts-1.3.3.tgz"
},
"engines": {
"node": ">= 0.6"
},
"files": [
"LICENSE",
"HISTORY.md",
"index.js"
],
"gitHead": "3e925b1e65ed7da2798849683d49814680dfa426",
"homepage": "https://github.com/jshttp/accepts#readme",
"keywords": [
"content",
"negotiation",
"accept",
"accepts"
],
"license": "MIT",
"maintainers": [
{
"name": "dougwilson",
"email": "doug@somethingdoug.com"
}
],
"name": "accepts",
"optionalDependencies": {},
"readme": "ERROR: No README data found!",
"repository": {
"type": "git",
"url": "git+https://github.com/jshttp/accepts.git"
},
"scripts": {
"test": "mocha --reporter spec --check-leaks --bail test/",
"test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/",
"test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/"
},
"version": "1.3.3"
}

accepts

NPM Version NPM Downloads Node.js Version Build Status Test Coverage

Higher level content negotiation based on negotiator. Extracted from koa for general use.

In addition to negotiator, it allows:

  • Allows types as an array or arguments list, ie (['text/html', 'application/json']) as well as ('text/html', 'application/json').
  • Allows type shorthands such as json.
  • Returns false when no types match
  • Treats non-existent headers as *

Installation

npm install accepts

API

var accepts = require('accepts')

accepts(req)

Create a new Accepts object for the given req.

.charset(charsets)

Return the first accepted charset. If nothing in charsets is accepted, then false is returned.

.charsets()

Return the charsets that the request accepts, in the order of the client's preference (most preferred first).

.encoding(encodings)

Return the first accepted encoding. If nothing in encodings is accepted, then false is returned.

.encodings()

Return the encodings that the request accepts, in the order of the client's preference (most preferred first).

.language(languages)

Return the first accepted language. If nothing in languages is accepted, then false is returned.

.languages()

Return the languages that the request accepts, in the order of the client's preference (most preferred first).

.type(types)

Return the first accepted type (and it is returned as the same text as what appears in the types array). If nothing in types is accepted, then false is returned.

The types array can contain full MIME types or file extensions. Any value that is not a full MIME types is passed to require('mime-types').lookup.

.types()

Return the types that the request accepts, in the order of the client's preference (most preferred first).

Examples

Simple type negotiation

This simple example shows how to use accepts to return a different typed respond body based on what the client wants to accept. The server lists it's preferences in order and will get back the best match between the client and server.

var accepts = require('accepts')
var http = require('http')

function app(req, res) {
  var accept = accepts(req)

  // the order of this list is significant; should be server preferred order
  switch(accept.type(['json', 'html'])) {
    case 'json':
      res.setHeader('Content-Type', 'application/json')
      res.write('{"hello":"world!"}')
      break
    case 'html':
      res.setHeader('Content-Type', 'text/html')
      res.write('<b>hello, world!</b>')
      break
    default:
      // the fallback is text/plain, so no need to specify it above
      res.setHeader('Content-Type', 'text/plain')
      res.write('hello, world!')
      break
  }

  res.end()
}

http.createServer(app).listen(3000)

You can test this out with the cURL program:

curl -I -H'Accept: text/html' http://localhost:3000/

License

MIT

language: node_js
node_js:
- 0.6
- 0.8
- 0.9
- 0.10
- 0.12
- 4.2.4
- 5.4.1
- iojs-1
- iojs-2
- iojs-3
module.exports = after
function after(count, callback, err_cb) {
var bail = false
err_cb = err_cb || noop
proxy.count = count
return (count === 0) ? callback() : proxy
function proxy(err, result) {
if (proxy.count <= 0) {
throw new Error('after called too many times')
}
--proxy.count
// after first error, rest are passed to err_cb
if (err) {
bail = true
callback(err)
// future error callbacks will go to error handler
callback = err_cb
} else if (proxy.count === 0 && !bail) {
callback(null, result)
}
}
}
function noop() {}
Copyright (c) 2011 Raynos.
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.
{
"_args": [
[
{
"raw": "after@0.8.2",
"scope": null,
"escapedName": "after",
"name": "after",
"rawSpec": "0.8.2",
"spec": "0.8.2",
"type": "version"
},
"C:\\xampp\\htdocs\\cafe\\node_modules\\engine.io-parser"
]
],
"_from": "after@0.8.2",
"_id": "after@0.8.2",
"_inCache": true,
"_location": "/after",
"_nodeVersion": "0.10.32",
"_npmOperationalInternal": {
"host": "packages-12-west.internal.npmjs.com",
"tmp": "tmp/after-0.8.2.tgz_1471308639186_0.9132961586583406"
},
"_npmUser": {
"name": "raynos",
"email": "raynos2@gmail.com"
},
"_npmVersion": "2.15.9",
"_phantomChildren": {},
"_requested": {
"raw": "after@0.8.2",
"scope": null,
"escapedName": "after",
"name": "after",
"rawSpec": "0.8.2",
"spec": "0.8.2",
"type": "version"
},
"_requiredBy": [
"/engine.io-parser"
],
"_resolved": "https://registry.npmjs.org/after/-/after-0.8.2.tgz",
"_shasum": "fedb394f9f0e02aa9768e702bda23b505fae7e1f",
"_shrinkwrap": null,
"_spec": "after@0.8.2",
"_where": "C:\\xampp\\htdocs\\cafe\\node_modules\\engine.io-parser",
"author": {
"name": "Raynos",
"email": "raynos2@gmail.com"
},
"bugs": {
"url": "https://github.com/Raynos/after/issues"
},
"contributors": [
{
"name": "Raynos",
"email": "raynos2@gmail.com",
"url": "http://raynos.org"
}
],
"dependencies": {},
"description": "after - tiny flow control",
"devDependencies": {
"mocha": "~1.8.1"
},
"directories": {},
"dist": {
"shasum": "fedb394f9f0e02aa9768e702bda23b505fae7e1f",
"tarball": "https://registry.npmjs.org/after/-/after-0.8.2.tgz"
},
"gitHead": "e8c26046f36962b90e68dc5df33a9672a54b25f5",
"homepage": "https://github.com/Raynos/after#readme",
"keywords": [
"flowcontrol",
"after",
"flow",
"control",
"arch"
],
"license": "MIT",
"maintainers": [
{
"name": "raynos",
"email": "raynos2@gmail.com"
},
{
"name": "defunctzombie",
"email": "shtylman@gmail.com"
}
],
"name": "after",
"optionalDependencies": {},
"readme": "ERROR: No README data found!",
"repository": {
"type": "git",
"url": "git://github.com/Raynos/after.git"
},
"scripts": {
"test": "mocha --ui tdd --reporter spec test/*.js"
},
"version": "0.8.2"
}

After Build Status

Invoke callback after n calls

Status: production ready

Example

var after = require("after")
var db = require("./db") // some db.

var updateUser = function (req, res) {
  // use after to run two tasks in parallel,
  // namely get request body and get session
  // then run updateUser with the results
  var next = after(2, updateUser)
  var results = {}
  
  getJSONBody(req, res, function (err, body) {
    if (err) return next(err)
    
    results.body = body
    next(null, results)
  })
  
  getSessionUser(req, res, function (err, user) {
    if (err) return next(err)
    
    results.user = user
    next(null, results)
  })
  
  // now do the thing!
  function updateUser(err, result) {
    if (err) {
      res.statusCode = 500
      return res.end("Unexpected Error")
    }
    
    if (!result.user || result.user.role !== "admin") {
      res.statusCode = 403
      return res.end("Permission Denied")
    }
    
    db.put("users:" + req.params.userId, result.body, function (err) {
      if (err) {
        res.statusCode = 500
        return res.end("Unexpected Error")
      }
      
      res.statusCode = 200
      res.end("Ok")  
    })   
  }
}

Naive Example

var after = require("after")
    , next = after(3, logItWorks)

next()
next()
next() // it works

function logItWorks() {
    console.log("it works!")
}

Example with error handling

var after = require("after")
    , next = after(3, logError)

next()
next(new Error("oops")) // logs oops
next() // does nothing

// This callback is only called once.
// If there is an error the callback gets called immediately
// this avoids the situation where errors get lost.
function logError(err) {
    console.log(err)
}

Installation

npm install after

Tests

npm test

Contributors

  • Raynos
  • defunctzombie

MIT Licenced

/*global suite, test*/
var assert = require("assert")
, after = require("../")
test("exists", function () {
assert(typeof after === "function", "after is not a function")
})
test("after when called with 0 invokes", function (done) {
after(0, done)
});
test("after 1", function (done) {
var next = after(1, done)
next()
})
test("after 5", function (done) {
var next = after(5, done)
, i = 5
while (i--) {
next()
}
})
test("manipulate count", function (done) {
var next = after(1, done)
, i = 5
next.count = i
while (i--) {
next()
}
})
test("after terminates on error", function (done) {
var next = after(2, function(err) {
assert.equal(err.message, 'test');
done();
})
next(new Error('test'))
next(new Error('test2'))
})
test('gee', function(done) {
done = after(2, done)
function cb(err) {
assert.equal(err.message, 1);
done()
}
var next = after(3, cb, function(err) {
assert.equal(err.message, 2)
done()
});
next()
next(new Error(1))
next(new Error(2))
})
test('eee', function(done) {
done = after(3, done)
function cb(err) {
assert.equal(err.message, 1);
done()
}
var next = after(3, cb, function(err) {
assert.equal(err.message, 2)
done()
});
next(new Error(1))
next(new Error(2))
next(new Error(2))
})
test('gge', function(done) {
function cb(err) {
assert.equal(err.message, 1);
done()
}
var next = after(3, cb, function(err) {
// should not happen
assert.ok(false);
});
next()
next()
next(new Error(1))
})
test('egg', function(done) {
function cb(err) {
assert.equal(err.message, 1);
done()
}
var next = after(3, cb, function(err) {
// should not happen
assert.ok(false);
});
next(new Error(1))
next()
next()
})
test('throws on too many calls', function(done) {
var next = after(1, done);
next()
assert.throws(next, /after called too many times/);
});
'use strict'
/**
* Expose `arrayFlatten`.
*/
module.exports = arrayFlatten
/**
* Recursive flatten function with depth.
*
* @param {Array} array
* @param {Array} result
* @param {Number} depth
* @return {Array}
*/
function flattenWithDepth (array, result, depth) {
for (var i = 0; i < array.length; i++) {
var value = array[i]
if (depth > 0 && Array.isArray(value)) {
flattenWithDepth(value, result, depth - 1)
} else {
result.push(value)
}
}
return result
}
/**
* Recursive flatten function. Omitting depth is slightly faster.
*
* @param {Array} array
* @param {Array} result
* @return {Array}
*/
function flattenForever (array, result) {
for (var i = 0; i < array.length; i++) {
var value = array[i]
if (Array.isArray(value)) {
flattenForever(value, result)
} else {
result.push(value)
}
}
return result
}
/**
* Flatten an array, with the ability to define a depth.
*
* @param {Array} array
* @param {Number} depth
* @return {Array}
*/
function arrayFlatten (array, depth) {
if (depth == null) {
return flattenForever(array, [])
}
return flattenWithDepth(array, [], depth)
}
The MIT License (MIT)
Copyright (c) 2014 Blake Embrey (hello@blakeembrey.com)
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.
{
"_args": [
[
{
"raw": "array-flatten@1.1.1",
"scope": null,
"escapedName": "array-flatten",
"name": "array-flatten",
"rawSpec": "1.1.1",
"spec": "1.1.1",
"type": "version"
},
"C:\\xampp\\htdocs\\cafe\\node_modules\\express"
]
],
"_from": "array-flatten@1.1.1",
"_id": "array-flatten@1.1.1",
"_inCache": true,
"_location": "/array-flatten",
"_nodeVersion": "2.3.3",
"_npmUser": {
"name": "blakeembrey",
"email": "hello@blakeembrey.com"
},
"_npmVersion": "2.11.3",
"_phantomChildren": {},
"_requested": {
"raw": "array-flatten@1.1.1",
"scope": null,
"escapedName": "array-flatten",
"name": "array-flatten",
"rawSpec": "1.1.1",
"spec": "1.1.1",
"type": "version"
},
"_requiredBy": [
"/express"
],
"_resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz",
"_shasum": "9a5f699051b1e7073328f2a008968b64ea2955d2",
"_shrinkwrap": null,
"_spec": "array-flatten@1.1.1",
"_where": "C:\\xampp\\htdocs\\cafe\\node_modules\\express",
"author": {
"name": "Blake Embrey",
"email": "hello@blakeembrey.com",
"url": "http://blakeembrey.me"
},
"bugs": {
"url": "https://github.com/blakeembrey/array-flatten/issues"
},
"dependencies": {},
"description": "Flatten an array of nested arrays into a single flat array",
"devDependencies": {
"istanbul": "^0.3.13",
"mocha": "^2.2.4",
"pre-commit": "^1.0.7",
"standard": "^3.7.3"
},
"directories": {},
"dist": {
"shasum": "9a5f699051b1e7073328f2a008968b64ea2955d2",
"tarball": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz"
},
"files": [
"array-flatten.js",
"LICENSE"
],
"gitHead": "1963a9189229d408e1e8f585a00c8be9edbd1803",
"homepage": "https://github.com/blakeembrey/array-flatten",
"keywords": [
"array",
"flatten",
"arguments",
"depth"
],
"license": "MIT",
"main": "array-flatten.js",
"maintainers": [
{
"name": "blakeembrey",
"email": "hello@blakeembrey.com"
}
],
"name": "array-flatten",
"optionalDependencies": {},
"readme": "ERROR: No README data found!",
"repository": {
"type": "git",
"url": "git://github.com/blakeembrey/array-flatten.git"
},
"scripts": {
"test": "istanbul cover _mocha -- -R spec"
},
"version": "1.1.1"
}

Array Flatten

NPM version NPM downloads Build status Test coverage

Flatten an array of nested arrays into a single flat array. Accepts an optional depth.

Installation

npm install array-flatten --save

Usage

var flatten = require('array-flatten')

flatten([1, [2, [3, [4, [5], 6], 7], 8], 9])
//=> [1, 2, 3, 4, 5, 6, 7, 8, 9]

flatten([1, [2, [3, [4, [5], 6], 7], 8], 9], 2)
//=> [1, 2, 3, [4, [5], 6], 7, 8, 9]

(function () {
  flatten(arguments) //=> [1, 2, 3]
})(1, [2, 3])

License

MIT

lib-cov
lcov.info
*.seed
*.log
*.csv
*.dat
*.out
*.pid
*.gz
pids
logs
results
build
.grunt
node_modules
/**
* An abstraction for slicing an arraybuffer even when
* ArrayBuffer.prototype.slice is not supported
*
* @api public
*/
module.exports = function(arraybuffer, start, end) {
var bytes = arraybuffer.byteLength;
start = start || 0;
end = end || bytes;
if (arraybuffer.slice) { return arraybuffer.slice(start, end); }
if (start < 0) { start += bytes; }
if (end < 0) { end += bytes; }
if (end > bytes) { end = bytes; }
if (start >= bytes || start >= end || bytes === 0) {
return new ArrayBuffer(0);
}
var abv = new Uint8Array(arraybuffer);
var result = new Uint8Array(end - start);
for (var i = start, ii = 0; i < end; i++, ii++) {
result[ii] = abv[i];
}
return result.buffer;
};
REPORTER = dot
test:
@./node_modules/.bin/mocha \
--reporter $(REPORTER)
.PHONY: test
{
"_args": [
[
{
"raw": "arraybuffer.slice@0.0.6",
"scope": null,
"escapedName": "arraybuffer.slice",
"name": "arraybuffer.slice",
"rawSpec": "0.0.6",
"spec": "0.0.6",
"type": "version"
},
"C:\\xampp\\htdocs\\cafe\\node_modules\\engine.io-parser"
]
],
"_from": "arraybuffer.slice@0.0.6",
"_id": "arraybuffer.slice@0.0.6",
"_inCache": true,
"_location": "/arraybuffer.slice",
"_npmUser": {
"name": "rase-",
"email": "tonykovanen@hotmail.com"
},
"_npmVersion": "1.3.5",
"_phantomChildren": {},
"_requested": {
"raw": "arraybuffer.slice@0.0.6",
"scope": null,
"escapedName": "arraybuffer.slice",
"name": "arraybuffer.slice",
"rawSpec": "0.0.6",
"spec": "0.0.6",
"type": "version"
},
"_requiredBy": [
"/engine.io-parser"
],
"_resolved": "https://registry.npmjs.org/arraybuffer.slice/-/arraybuffer.slice-0.0.6.tgz",
"_shasum": "f33b2159f0532a3f3107a272c0ccfbd1ad2979ca",
"_shrinkwrap": null,
"_spec": "arraybuffer.slice@0.0.6",
"_where": "C:\\xampp\\htdocs\\cafe\\node_modules\\engine.io-parser",
"bugs": {
"url": "https://github.com/rase-/arraybuffer.slice/issues"
},
"dependencies": {},
"description": "Exports a function for slicing ArrayBuffers (no polyfilling)",
"devDependencies": {
"expect.js": "0.2.0",
"mocha": "1.17.1"
},
"directories": {},
"dist": {
"shasum": "f33b2159f0532a3f3107a272c0ccfbd1ad2979ca",
"tarball": "https://registry.npmjs.org/arraybuffer.slice/-/arraybuffer.slice-0.0.6.tgz"
},
"homepage": "https://github.com/rase-/arraybuffer.slice",
"maintainers": [
{
"name": "rase-",
"email": "tonykovanen@hotmail.com"
}
],
"name": "arraybuffer.slice",
"optionalDependencies": {},
"readme": "ERROR: No README data found!",
"repository": {
"type": "git",
"url": "git+ssh://git@github.com/rase-/arraybuffer.slice.git"
},
"version": "0.0.6"
}

How to

var sliceBuffer = require('arraybuffer.slice');
var ab = (new Int8Array(5)).buffer;
var sliced = sliceBuffer(ab, 1, 3);
sliced = sliceBuffer(ab, 1);

Licence (MIT)

Copyright (C) 2013 Rase-

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.

/*
* Test dependencies
*/
var sliceBuffer = require('../index.js');
var expect = require('expect.js');
/**
* Tests
*/
describe('sliceBuffer', function() {
describe('using standard slice', function() {
it('should slice correctly with only start provided', function() {
var abv = new Uint8Array(10);
for (var i = 0; i < abv.length; i++) {
abv[i] = i;
}
var sliced = sliceBuffer(abv.buffer, 3);
var sabv = new Uint8Array(sliced);
for (var i = 3, ii = 0; i < abv.length; i++, ii++) {
expect(abv[i]).to.equal(sabv[ii]);
}
});
it('should slice correctly with start and end provided', function() {
var abv = new Uint8Array(10);
for (var i = 0; i < abv.length; i++) {
abv[i] = i;
}
var sliced = sliceBuffer(abv.buffer, 3, 8);
var sabv = new Uint8Array(sliced);
for (var i = 3, ii = 0; i < 8; i++, ii++) {
expect(abv[i]).to.equal(sabv[ii]);
}
});
it('should slice correctly with negative start', function() {
var abv = new Uint8Array(10);
for (var i = 0; i < abv.length; i++) {
abv[i] = i;
}
var sliced = sliceBuffer(abv.buffer, -3);
var sabv = new Uint8Array(sliced);
for (var i = abv.length - 3, ii = 0; i < abv.length; i++, ii++) {
expect(abv[i]).to.equal(sabv[ii]);
}
});
it('should slice correctly with negative end', function() {
var abv = new Uint8Array(10);
for (var i = 0; i < abv.length; i++) {
abv[i] = i;
}
var sliced = sliceBuffer(abv.buffer, 0, -3);
var sabv = new Uint8Array(sliced);
for (var i = 0, ii = 0; i < abv.length - 3; i++, ii++) {
expect(abv[i]).to.equal(sabv[ii]);
}
});
it('should slice correctly with negative start and end', function() {
var abv = new Uint8Array(10);
for (var i = 0; i < abv.length; i++) {
abv[i] = i;
}
var sliced = sliceBuffer(abv.buffer, -6, -3);
var sabv = new Uint8Array(sliced);
for (var i = abv.length - 6, ii = 0; i < abv.length - 3; i++, ii++) {
expect(abv[i]).to.equal(sabv[ii]);
}
});
it('should slice correctly with equal start and end', function() {
var abv = new Uint8Array(10);
for (var i = 0; i < abv.length; i++) {
abv[i] = i;
}
var sliced = sliceBuffer(abv.buffer, 1, 1);
expect(sliced.byteLength).to.equal(0);
});
it('should slice correctly when end larger than buffer', function() {
var abv = new Uint8Array(10);
for (var i = 0; i < abv.length; i++) {
abv[i] = i;
}
var sliced = sliceBuffer(abv.buffer, 0, 100);
expect(new Uint8Array(sliced)).to.eql(abv);
});
it('shoud slice correctly when start larger than end', function() {
var abv = new Uint8Array(10);
for (var i = 0; i < abv.length; i++) {
abv[i] = i;
}
var sliced = sliceBuffer(abv.buffer, 6, 5);
expect(sliced.byteLength).to.equal(0);
});
});
describe('using fallback', function() {
it('should slice correctly with only start provided', function() {
var abv = new Uint8Array(10);
for (var i = 0; i < abv.length; i++) {
abv[i] = i;
}
var ab = abv.buffer;
ab.slice = undefined;
var sliced = sliceBuffer(ab, 3);
var sabv = new Uint8Array(sliced);
for (var i = 3, ii = 0; i < abv.length; i++, ii++) {
expect(abv[i]).to.equal(sabv[ii]);
}
});
it('should slice correctly with start and end provided', function() {
var abv = new Uint8Array(10);
for (var i = 0; i < abv.length; i++) {
abv[i] = i;
}
var ab = abv.buffer;
ab.slice = undefined;
var sliced = sliceBuffer(ab, 3, 8);
var sabv = new Uint8Array(sliced);
for (var i = 3, ii = 0; i < 8; i++, ii++) {
expect(abv[i]).to.equal(sabv[ii]);
}
});
it('should slice correctly with negative start', function() {
var abv = new Uint8Array(10);
for (var i = 0; i < abv.length; i++) {
abv[i] = i;
}
var ab = abv.buffer;
ab.slice = undefined;
var sliced = sliceBuffer(ab, -3);
var sabv = new Uint8Array(sliced);
for (var i = abv.length - 3, ii = 0; i < abv.length; i++, ii++) {
expect(abv[i]).to.equal(sabv[ii]);
}
});
it('should slice correctly with negative end', function() {
var abv = new Uint8Array(10);
for (var i = 0; i < abv.length; i++) {
abv[i] = i;
}
var ab = abv.buffer;
ab.slice = undefined;
var sliced = sliceBuffer(ab, 0, -3);
var sabv = new Uint8Array(sliced);
for (var i = 0, ii = 0; i < abv.length - 3; i++, ii++) {
expect(abv[i]).to.equal(sabv[ii]);
}
});
it('should slice correctly with negative start and end', function() {
var abv = new Uint8Array(10);
for (var i = 0; i < abv.length; i++) {
abv[i] = i;
}
var ab = abv.buffer;
ab.slice = undefined;
var sliced = sliceBuffer(ab, -6, -3);
var sabv = new Uint8Array(sliced);
for (var i = abv.length - 6, ii = 0; i < abv.length - 3; i++, ii++) {
expect(abv[i]).to.equal(sabv[ii]);
}
});
it('should slice correctly with equal start and end', function() {
var abv = new Uint8Array(10);
for (var i = 0; i < abv.length; i++) {
abv[i] = i;
}
var ab = abv.buffer;
ab.slice = undefined;
var sliced = sliceBuffer(ab, 1, 1);
expect(sliced.byteLength).to.equal(0);
});
it('should slice correctly when end larger than buffer', function() {
var abv = new Uint8Array(10);
for (var i = 0; i < abv.length; i++) {
abv[i] = i;
}
var ab = abv.buffer;
ab.slice = undefined;
var sliced = sliceBuffer(ab, 0, 100);
var sabv = new Uint8Array(sliced);
for (var i = 0; i < abv.length; i++) {
expect(abv[i]).to.equal(sabv[i]);
}
});
it('shoud slice correctly when start larger than end', function() {
var abv = new Uint8Array(10);
for (var i = 0; i < abv.length; i++) {
abv[i] = i;
}
var ab = abv.buffer;
ab.slice = undefined;
var sliced = sliceBuffer(ab, 6, 5);
expect(sliced.byteLength).to.equal(0);
});
});
});
{
"name": "backo",
"repo": "segmentio/backo",
"dependencies": {},
"version": "1.0.1",
"description": "simple backoff without the weird abstractions",
"keywords": ["backoff"],
"license": "MIT",
"scripts": ["index.js"],
"main": "index.js"
}

1.0.1 / 2014-02-17

  • go away decimal point
  • history

1.0.0 / 2014-02-17

  • add jitter option
  • Initial commit
/**
* Expose `Backoff`.
*/
module.exports = Backoff;
/**
* Initialize backoff timer with `opts`.
*
* - `min` initial timeout in milliseconds [100]
* - `max` max timeout [10000]
* - `jitter` [0]
* - `factor` [2]
*
* @param {Object} opts
* @api public
*/
function Backoff(opts) {
opts = opts || {};
this.ms = opts.min || 100;
this.max = opts.max || 10000;
this.factor = opts.factor || 2;
this.jitter = opts.jitter > 0 && opts.jitter <= 1 ? opts.jitter : 0;
this.attempts = 0;
}
/**
* Return the backoff duration.
*
* @return {Number}
* @api public
*/
Backoff.prototype.duration = function(){
var ms = this.ms * Math.pow(this.factor, this.attempts++);
if (this.jitter) {
var rand = Math.random();
var deviation = Math.floor(rand * this.jitter * ms);
ms = (Math.floor(rand * 10) & 1) == 0 ? ms - deviation : ms + deviation;
}
return Math.min(ms, this.max) | 0;
};
/**
* Reset the number of attempts.
*
* @api public
*/
Backoff.prototype.reset = function(){
this.attempts = 0;
};
/**
* Set the minimum duration
*
* @api public
*/
Backoff.prototype.setMin = function(min){
this.ms = min;
};
/**
* Set the maximum duration
*
* @api public
*/
Backoff.prototype.setMax = function(max){
this.max = max;
};
/**
* Set the jitter
*
* @api public
*/
Backoff.prototype.setJitter = function(jitter){
this.jitter = jitter;
};
test:
@./node_modules/.bin/mocha \
--require should \
--reporter dot \
--bail
.PHONY: test
{
"_args": [
[
{
"raw": "backo2@1.0.2",
"scope": null,
"escapedName": "backo2",
"name": "backo2",
"rawSpec": "1.0.2",
"spec": "1.0.2",
"type": "version"
},
"C:\\xampp\\htdocs\\cafe\\node_modules\\socket.io-client"
]
],
"_from": "backo2@1.0.2",
"_id": "backo2@1.0.2",
"_inCache": true,
"_location": "/backo2",
"_npmUser": {
"name": "mokesmokes",
"email": "mokesmokes@gmail.com"
},
"_npmVersion": "1.4.28",
"_phantomChildren": {},
"_requested": {
"raw": "backo2@1.0.2",
"scope": null,
"escapedName": "backo2",
"name": "backo2",
"rawSpec": "1.0.2",
"spec": "1.0.2",
"type": "version"
},
"_requiredBy": [
"/socket.io-client"
],
"_resolved": "https://registry.npmjs.org/backo2/-/backo2-1.0.2.tgz",
"_shasum": "31ab1ac8b129363463e35b3ebb69f4dfcfba7947",
"_shrinkwrap": null,
"_spec": "backo2@1.0.2",
"_where": "C:\\xampp\\htdocs\\cafe\\node_modules\\socket.io-client",
"bugs": {
"url": "https://github.com/mokesmokes/backo/issues"
},
"dependencies": {},
"description": "simple backoff based on segmentio/backo",
"devDependencies": {
"mocha": "*",
"should": "*"
},
"directories": {},
"dist": {
"shasum": "31ab1ac8b129363463e35b3ebb69f4dfcfba7947",
"tarball": "https://registry.npmjs.org/backo2/-/backo2-1.0.2.tgz"
},
"gitHead": "3e695bade7756fef2295e8883bf3570a06e5d9ec",
"homepage": "https://github.com/mokesmokes/backo",
"keywords": [
"backoff"
],
"license": "MIT",
"maintainers": [
{
"name": "mokesmokes",
"email": "mokesmokes@gmail.com"
}
],
"name": "backo2",
"optionalDependencies": {},
"readme": "ERROR: No README data found!",
"repository": {
"type": "git",
"url": "git+https://github.com/mokesmokes/backo.git"
},
"scripts": {},
"version": "1.0.2"
}

backo

Simple exponential backoff because the others seem to have weird abstractions.

Installation

$ npm install backo

Options

  • min initial timeout in milliseconds [100]
  • max max timeout [10000]
  • jitter [0]
  • factor [2]

Example

var Backoff = require('backo');
var backoff = new Backoff({ min: 100, max: 20000 });

setTimeout(function(){
  something.reconnect();
}, backoff.duration());

// later when something works
backoff.reset()

License

MIT

var Backoff = require('..');
var assert = require('assert');
describe('.duration()', function(){
it('should increase the backoff', function(){
var b = new Backoff;
assert(100 == b.duration());
assert(200 == b.duration());
assert(400 == b.duration());
assert(800 == b.duration());
b.reset();
assert(100 == b.duration());
assert(200 == b.duration());
})
})
language: node_js
node_js:
- '0.12'
- iojs-1
- iojs-2
- iojs-3
- '4.1'
before_script:
- npm install
before_install: npm install -g npm@'>=2.13.5'
deploy:
provider: npm
email: niklasvh@gmail.com
api_key:
secure: oHV9ArprTj5WOk7MP1UF7QMJ70huXw+y7xXb5wF4+V2H8Hyfa5TfE0DiOmqrube1WXTeH1FLgq54shp/sJWi47Hkg/GyeoB5NnsPhYEaJkaON9UG5blML+ODiNVsEnq/1kNBQ8e0+0JItMPLGySKyFmuZ3yflulXKS8O88mfINo=
on:
tags: true
branch: master
repo: niklasvh/base64-arraybuffer
/*
* base64-arraybuffer
* https://github.com/niklasvh/base64-arraybuffer
*
* Copyright (c) 2012 Niklas von Hertzen
* Licensed under the MIT license.
*/
(function(){
"use strict";
var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
// Use a lookup table to find the index.
var lookup = new Uint8Array(256);
for (var i = 0; i < chars.length; i++) {
lookup[chars.charCodeAt(i)] = i;
}
exports.encode = function(arraybuffer) {
var bytes = new Uint8Array(arraybuffer),
i, len = bytes.length, base64 = "";
for (i = 0; i < len; i+=3) {
base64 += chars[bytes[i] >> 2];
base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];
base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];
base64 += chars[bytes[i + 2] & 63];
}
if ((len % 3) === 2) {
base64 = base64.substring(0, base64.length - 1) + "=";
} else if (len % 3 === 1) {
base64 = base64.substring(0, base64.length - 2) + "==";
}
return base64;
};
exports.decode = function(base64) {
var bufferLength = base64.length * 0.75,
len = base64.length, i, p = 0,
encoded1, encoded2, encoded3, encoded4;
if (base64[base64.length - 1] === "=") {
bufferLength--;
if (base64[base64.length - 2] === "=") {
bufferLength--;
}
}
var arraybuffer = new ArrayBuffer(bufferLength),
bytes = new Uint8Array(arraybuffer);
for (i = 0; i < len; i+=4) {
encoded1 = lookup[base64.charCodeAt(i)];
encoded2 = lookup[base64.charCodeAt(i+1)];
encoded3 = lookup[base64.charCodeAt(i+2)];
encoded4 = lookup[base64.charCodeAt(i+3)];
bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);
bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);
bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);
}
return arraybuffer;
};
})();
Copyright (c) 2012 Niklas von Hertzen
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.
{
"_args": [
[
{
"raw": "base64-arraybuffer@0.1.5",
"scope": null,
"escapedName": "base64-arraybuffer",
"name": "base64-arraybuffer",
"rawSpec": "0.1.5",
"spec": "0.1.5",
"type": "version"
},
"C:\\xampp\\htdocs\\cafe\\node_modules\\engine.io-parser"
]
],
"_from": "base64-arraybuffer@0.1.5",
"_id": "base64-arraybuffer@0.1.5",
"_inCache": true,
"_location": "/base64-arraybuffer",
"_nodeVersion": "2.5.0",
"_npmUser": {
"name": "niklasvh",
"email": "niklasvh@gmail.com"
},
"_npmVersion": "3.4.0",
"_phantomChildren": {},
"_requested": {
"raw": "base64-arraybuffer@0.1.5",
"scope": null,
"escapedName": "base64-arraybuffer",
"name": "base64-arraybuffer",
"rawSpec": "0.1.5",
"spec": "0.1.5",
"type": "version"
},
"_requiredBy": [
"/engine.io-parser"
],
"_resolved": "https://registry.npmjs.org/base64-arraybuffer/-/base64-arraybuffer-0.1.5.tgz",
"_shasum": "73926771923b5a19747ad666aa5cd4bf9c6e9ce8",
"_shrinkwrap": null,
"_spec": "base64-arraybuffer@0.1.5",
"_where": "C:\\xampp\\htdocs\\cafe\\node_modules\\engine.io-parser",
"author": {
"name": "Niklas von Hertzen",
"email": "niklasvh@gmail.com",
"url": "http://hertzen.com"
},
"bugs": {
"url": "https://github.com/niklasvh/base64-arraybuffer/issues"
},
"dependencies": {},
"description": "Encode/decode base64 data into ArrayBuffers",
"devDependencies": {
"grunt": "^0.4.5",
"grunt-cli": "^0.1.13",
"grunt-contrib-jshint": "^0.11.2",
"grunt-contrib-nodeunit": "^0.4.1",
"grunt-contrib-watch": "^0.6.1"
},
"directories": {},
"dist": {
"shasum": "73926771923b5a19747ad666aa5cd4bf9c6e9ce8",
"tarball": "https://registry.npmjs.org/base64-arraybuffer/-/base64-arraybuffer-0.1.5.tgz"
},
"engines": {
"node": ">= 0.6.0"
},
"gitHead": "e9457ccb7b140f5ae54a2880c8e9b967ffb03a7d",
"homepage": "https://github.com/niklasvh/base64-arraybuffer",
"keywords": [],
"licenses": [
{
"type": "MIT",
"url": "https://github.com/niklasvh/base64-arraybuffer/blob/master/LICENSE-MIT"
}
],
"main": "lib/base64-arraybuffer",
"maintainers": [
{
"name": "niklasvh",
"email": "niklasvh@gmail.com"
}
],
"name": "base64-arraybuffer",
"optionalDependencies": {},
"readme": "ERROR: No README data found!",
"repository": {
"type": "git",
"url": "git+https://github.com/niklasvh/base64-arraybuffer.git"
},
"scripts": {
"test": "grunt nodeunit"
},
"version": "0.1.5"
}

base64-arraybuffer

Build Status NPM Downloads NPM Version

Encode/decode base64 data into ArrayBuffers

Getting Started

Install the module with: npm install base64-arraybuffer

API

The library encodes and decodes base64 to and from ArrayBuffers

  • encode(buffer) - Encodes ArrayBuffer into base64 string
  • decode(str) - Decodes base64 string to ArrayBuffer

License

Copyright (c) 2012 Niklas von Hertzen Licensed under the MIT license.

'use strict';
var base64url = module.exports;
base64url.unescape = function unescape (str) {
return (str + '==='.slice((str.length + 3) % 4))
.replace(/\-/g, '+')
.replace(/_/g, '/');
};
base64url.escape = function escape (str) {
return str.replace(/\+/g, '-')
.replace(/\//g, '_')
.replace(/=/g, '');
};
base64url.encode = function encode (str) {
return this.escape(new Buffer(str).toString('base64'));
};
base64url.decode = function decode (str) {
return new Buffer(this.unescape(str), 'base64').toString();
};
The ISC License
Copyright (c) 2014, Joaquim José F. Serafim
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
{
"_args": [
[
{
"raw": "base64-url@1.3.3",
"scope": null,
"escapedName": "base64-url",
"name": "base64-url",
"rawSpec": "1.3.3",
"spec": "1.3.3",
"type": "version"
},
"C:\\xampp\\htdocs\\cafe\\node_modules\\uid-safe"
]
],
"_from": "base64-url@1.3.3",
"_id": "base64-url@1.3.3",
"_inCache": true,
"_location": "/base64-url",
"_nodeVersion": "6.9.1",
"_npmOperationalInternal": {
"host": "packages-12-west.internal.npmjs.com",
"tmp": "tmp/base64-url-1.3.3.tgz_1477648995978_0.048048977041617036"
},
"_npmUser": {
"name": "quim",
"email": "joaquim.serafim@gmail.com"
},
"_npmVersion": "4.0.0",
"_phantomChildren": {},
"_requested": {
"raw": "base64-url@1.3.3",
"scope": null,
"escapedName": "base64-url",
"name": "base64-url",
"rawSpec": "1.3.3",
"spec": "1.3.3",
"type": "version"
},
"_requiredBy": [
"/uid-safe"
],
"_resolved": "https://registry.npmjs.org/base64-url/-/base64-url-1.3.3.tgz",
"_shasum": "f8b6c537f09a4fc58c99cb86e0b0e9c61461a20f",
"_shrinkwrap": null,
"_spec": "base64-url@1.3.3",
"_where": "C:\\xampp\\htdocs\\cafe\\node_modules\\uid-safe",
"author": {
"name": "@joaquimserafim"
},
"bugs": {
"url": "https://github.com/joaquimserafim/base64-url/issues"
},
"dependencies": {},
"description": "Base64 encode, decode, escape and unescape for URL applications",
"devDependencies": {
"istanbul": "^0.3.5",
"jscs": "^1.9.0",
"jshint": "^2.5.11",
"pre-commit": "^1.1.3",
"tape": "^4.6.0"
},
"directories": {},
"dist": {
"shasum": "f8b6c537f09a4fc58c99cb86e0b0e9c61461a20f",
"tarball": "https://registry.npmjs.org/base64-url/-/base64-url-1.3.3.tgz"
},
"files": [
"LICENSE",
"README.md",
"index.js"
],
"gitHead": "fb100b8397f24b1066016cf09369a7b2be4e1a32",
"homepage": "https://github.com/joaquimserafim/base64-url",
"keywords": [
"base64",
"base64url"
],
"license": "ISC",
"main": "index.js",
"maintainers": [
{
"name": "quim",
"email": "joaquim.serafim@gmail.com"
}
],
"name": "base64-url",
"optionalDependencies": {},
"pre-commit": [
"lint",
"style",
"test",
"coverage:check"
],
"readme": "ERROR: No README data found!",
"repository": {
"type": "git",
"url": "git://github.com/joaquimserafim/base64-url.git"
},
"scripts": {
"coverage": "open coverage/lcov-report/index.html",
"coverage:check": "istanbul check-coverage --statements 100 --functions 100 --lines 100 --branches 100",
"lint": "jshint -c .jshintrc *.js",
"style": "jscs -p google *.js",
"test": "istanbul cover tape test.js"
},
"version": "1.3.3"
}

base64-url

Base64 encode, decode, escape and unescape for URL applications.

Build Status

API

var base64url = require('base64-url');

base64url.encode('Node.js is awesome.');
// returns Tm9kZS5qcyBpcyBhd2Vzb21lLg

base64url.decode('Tm9kZS5qcyBpcyBhd2Vzb21lLg');
// returns Node.js is awesome.

base64url.escape('This+is/goingto+escape==');
// returns This-is_goingto-escape

base64url.unescape('This-is_goingto-escape');
// returns This+is/goingto+escape==

Development

this project has been set up with a precommit that forces you to follow a code style, no jshint issues and 100% of code coverage before commit

to run test

npm test

to run lint

npm run lint

to run code style

npm run style

to check code coverage

npm run coverage:check
/*!
* base64id v0.1.0
*/
/**
* Module dependencies
*/
var crypto = require('crypto');
/**
* Constructor
*/
var Base64Id = function() { };
/**
* Get random bytes
*
* Uses a buffer if available, falls back to crypto.randomBytes
*/
Base64Id.prototype.getRandomBytes = function(bytes) {
var BUFFER_SIZE = 4096
var self = this;
bytes = bytes || 12;
if (bytes > BUFFER_SIZE) {
return crypto.randomBytes(bytes);
}
var bytesInBuffer = parseInt(BUFFER_SIZE/bytes);
var threshold = parseInt(bytesInBuffer*0.85);
if (!threshold) {
return crypto.randomBytes(bytes);
}
if (this.bytesBufferIndex == null) {
this.bytesBufferIndex = -1;
}
if (this.bytesBufferIndex == bytesInBuffer) {
this.bytesBuffer = null;
this.bytesBufferIndex = -1;
}
// No buffered bytes available or index above threshold
if (this.bytesBufferIndex == -1 || this.bytesBufferIndex > threshold) {
if (!this.isGeneratingBytes) {
this.isGeneratingBytes = true;
crypto.randomBytes(BUFFER_SIZE, function(err, bytes) {
self.bytesBuffer = bytes;
self.bytesBufferIndex = 0;
self.isGeneratingBytes = false;
});
}
// Fall back to sync call when no buffered bytes are available
if (this.bytesBufferIndex == -1) {
return crypto.randomBytes(bytes);
}
}
var result = this.bytesBuffer.slice(bytes*this.bytesBufferIndex, bytes*(this.bytesBufferIndex+1));
this.bytesBufferIndex++;
return result;
}
/**
* Generates a base64 id
*
* (Original version from socket.io <http://socket.io>)
*/
Base64Id.prototype.generateId = function () {
var rand = new Buffer(15); // multiple of 3 for base64
if (!rand.writeInt32BE) {
return Math.abs(Math.random() * Math.random() * Date.now() | 0).toString()
+ Math.abs(Math.random() * Math.random() * Date.now() | 0).toString();
}
this.sequenceNumber = (this.sequenceNumber + 1) | 0;
rand.writeInt32BE(this.sequenceNumber, 11);
if (crypto.randomBytes) {
this.getRandomBytes(12).copy(rand);
} else {
// not secure for node 0.4
[0, 4, 8].forEach(function(i) {
rand.writeInt32BE(Math.random() * Math.pow(2, 32) | 0, i);
});
}
return rand.toString('base64').replace(/\//g, '_').replace(/\+/g, '-');
};
/**
* Export
*/
exports = module.exports = new Base64Id();
(The MIT License)
Copyright (c) 2012-2016 Kristian Faeldt <faeldt_kristian@cyberagent.co.jp>
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.
{
"_args": [
[
{
"raw": "base64id@1.0.0",
"scope": null,
"escapedName": "base64id",
"name": "base64id",
"rawSpec": "1.0.0",
"spec": "1.0.0",
"type": "version"
},
"C:\\xampp\\htdocs\\cafe\\node_modules\\engine.io"
]
],
"_from": "base64id@1.0.0",
"_id": "base64id@1.0.0",
"_inCache": true,
"_location": "/base64id",
"_nodeVersion": "4.4.7",
"_npmOperationalInternal": {
"host": "packages-18-east.internal.npmjs.com",
"tmp": "tmp/base64id-1.0.0.tgz_1480551701495_0.042360062478110194"
},
"_npmUser": {
"name": "darrachequesne",
"email": "damien.arrachequesne@gmail.com"
},
"_npmVersion": "2.15.8",
"_phantomChildren": {},
"_requested": {
"raw": "base64id@1.0.0",
"scope": null,
"escapedName": "base64id",
"name": "base64id",
"rawSpec": "1.0.0",
"spec": "1.0.0",
"type": "version"
},
"_requiredBy": [
"/engine.io"
],
"_resolved": "https://registry.npmjs.org/base64id/-/base64id-1.0.0.tgz",
"_shasum": "47688cb99bb6804f0e06d3e763b1c32e57d8e6b6",
"_shrinkwrap": null,
"_spec": "base64id@1.0.0",
"_where": "C:\\xampp\\htdocs\\cafe\\node_modules\\engine.io",
"author": {
"name": "Kristian Faeldt",
"email": "faeldt_kristian@cyberagent.co.jp"
},
"bugs": {
"url": "https://github.com/faeldt/base64id/issues"
},
"dependencies": {},
"description": "Generates a base64 id",
"devDependencies": {},
"directories": {},
"dist": {
"shasum": "47688cb99bb6804f0e06d3e763b1c32e57d8e6b6",
"tarball": "https://registry.npmjs.org/base64id/-/base64id-1.0.0.tgz"
},
"engines": {
"node": ">= 0.4.0"
},
"gitHead": "3c846f0818ff88b683ad39fde2f8e015ce0f9807",
"homepage": "https://github.com/faeldt/base64id#readme",
"license": "MIT",
"main": "./lib/base64id.js",
"maintainers": [
{
"name": "darrachequesne",
"email": "damien.arrachequesne@gmail.com"
},
{
"name": "faeldt_kristian",
"email": "kristian.faeldt@gmail.com"
}
],
"name": "base64id",
"optionalDependencies": {},
"readme": "ERROR: No README data found!",
"repository": {
"type": "git",
"url": "git+https://github.com/faeldt/base64id.git"
},
"scripts": {},
"version": "1.0.0"
}

base64id

Node.js module that generates a base64 id.

Uses crypto.randomBytes when available, falls back to unsafe methods for node.js <= 0.4.

To increase performance, random bytes are buffered to minimize the number of synchronous calls to crypto.randomBytes.

Installation

$ npm install base64id

Usage

var base64id = require('base64id');

var id = base64id.generateId();

var assert = require('./');
test();
function test() {
var user = { name: 'tobi' };
assert('tobi' == user.name);
assert('number' == typeof user.age);
}

1.0.0 / 2013-02-03

  • Stop using the removed magic __stack global getter

0.1.0 / 2012-10-04

  • add throwing of AssertionError for test frameworks etc

0.0.1 / 2010-01-03

  • Initial release
/**
* Module dependencies.
*/
var AssertionError = require('assert').AssertionError
, callsite = require('callsite')
, fs = require('fs')
/**
* Expose `assert`.
*/
module.exports = process.env.NO_ASSERT
? function(){}
: assert;
/**
* Assert the given `expr`.
*/
function assert(expr) {
if (expr) return;
var stack = callsite();
var call = stack[1];
var file = call.getFileName();
var lineno = call.getLineNumber();
var src = fs.readFileSync(file, 'utf8');
var line = src.split('\n')[lineno-1];
var src = line.match(/assert\((.*)\)/)[1];
var err = new AssertionError({
message: src,
stackStartFunction: stack[0].getFunction()
});
throw err;
}
test:
@echo "populate me"
.PHONY: test
{
"_args": [
[
{
"raw": "better-assert@~1.0.0",
"scope": null,
"escapedName": "better-assert",
"name": "better-assert",
"rawSpec": "~1.0.0",
"spec": ">=1.0.0 <1.1.0",
"type": "range"
},
"C:\\xampp\\htdocs\\cafe\\node_modules\\parsejson"
]
],
"_from": "better-assert@>=1.0.0 <1.1.0",
"_id": "better-assert@1.0.2",
"_inCache": true,
"_location": "/better-assert",
"_npmUser": {
"name": "tony_ado",
"email": "coolhzb@163.com"
},
"_npmVersion": "1.4.9",
"_phantomChildren": {},
"_requested": {
"raw": "better-assert@~1.0.0",
"scope": null,
"escapedName": "better-assert",
"name": "better-assert",
"rawSpec": "~1.0.0",
"spec": ">=1.0.0 <1.1.0",
"type": "range"
},
"_requiredBy": [
"/parsejson",
"/parseqs",
"/parseuri"
],
"_resolved": "https://registry.npmjs.org/better-assert/-/better-assert-1.0.2.tgz",
"_shasum": "40866b9e1b9e0b55b481894311e68faffaebc522",
"_shrinkwrap": null,
"_spec": "better-assert@~1.0.0",
"_where": "C:\\xampp\\htdocs\\cafe\\node_modules\\parsejson",
"author": {
"name": "TJ Holowaychuk",
"email": "tj@vision-media.ca"
},
"bugs": {
"url": "https://github.com/visionmedia/better-assert/issues"
},
"contributors": [
{
"name": "TonyHe",
"email": "coolhzb@163.com"
},
{
"name": "ForbesLindesay"
}
],
"dependencies": {
"callsite": "1.0.0"
},
"description": "Better assertions for node, reporting the expr, filename, lineno etc",
"devDependencies": {},
"directories": {},
"dist": {
"shasum": "40866b9e1b9e0b55b481894311e68faffaebc522",
"tarball": "https://registry.npmjs.org/better-assert/-/better-assert-1.0.2.tgz"
},
"engines": {
"node": "*"
},
"homepage": "https://github.com/visionmedia/better-assert",
"keywords": [
"assert",
"stack",
"trace",
"debug"
],
"main": "index",
"maintainers": [
{
"name": "tjholowaychuk",
"email": "tj@vision-media.ca"
},
{
"name": "tony_ado",
"email": "coolhzb@163.com"
}
],
"name": "better-assert",
"optionalDependencies": {},
"readme": "ERROR: No README data found!",
"repository": {
"type": "git",
"url": "git+https://github.com/visionmedia/better-assert.git"
},
"version": "1.0.2"
}

better-assert

Better c-style assertions using callsite for self-documenting failure messages.

Installation

$ npm install better-assert

Example

By default assertions are enabled, however the NO_ASSERT environment variable will deactivate them when truthy.

var assert = require('better-assert');

test();

function test() {
  var user = { name: 'tobi' };
  assert('tobi' == user.name);
  assert('number' == typeof user.age);
}

AssertionError: 'number' == typeof user.age
    at test (/Users/tj/projects/better-assert/example.js:9:3)
    at Object.<anonymous> (/Users/tj/projects/better-assert/example.js:4:1)
    at Module._compile (module.js:449:26)
    at Object.Module._extensions..js (module.js:467:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Module.runMain (module.js:492:10)
    at process.startup.processNextTick.process._tickCallback (node.js:244:9)

License

(The MIT License)

Copyright (c) 2012 TJ Holowaychuk <tj@vision-media.ca>

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.

/*! bignumber.js v3.1.2 https://github.com/MikeMcl/bignumber.js/LICENCE */
;(function (globalObj) {
'use strict';
/*
bignumber.js v3.1.2
A JavaScript library for arbitrary-precision arithmetic.
https://github.com/MikeMcl/bignumber.js
Copyright (c) 2016 Michael Mclaughlin <M8ch88l@gmail.com>
MIT Expat Licence
*/
var BigNumber,
isNumeric = /^-?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,
mathceil = Math.ceil,
mathfloor = Math.floor,
notBool = ' not a boolean or binary digit',
roundingMode = 'rounding mode',
tooManyDigits = 'number type has more than 15 significant digits',
ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_',
BASE = 1e14,
LOG_BASE = 14,
MAX_SAFE_INTEGER = 0x1fffffffffffff, // 2^53 - 1
// MAX_INT32 = 0x7fffffff, // 2^31 - 1
POWS_TEN = [1, 10, 100, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13],
SQRT_BASE = 1e7,
/*
* The limit on the value of DECIMAL_PLACES, TO_EXP_NEG, TO_EXP_POS, MIN_EXP, MAX_EXP, and
* the arguments to toExponential, toFixed, toFormat, and toPrecision, beyond which an
* exception is thrown (if ERRORS is true).
*/
MAX = 1E9; // 0 to MAX_INT32
/*
* Create and return a BigNumber constructor.
*/
function constructorFactory(configObj) {
var div, parseNumeric,
// id tracks the caller function, so its name can be included in error messages.
id = 0,
P = BigNumber.prototype,
ONE = new BigNumber(1),
/********************************* EDITABLE DEFAULTS **********************************/
/*
* The default values below must be integers within the inclusive ranges stated.
* The values can also be changed at run-time using BigNumber.config.
*/
// The maximum number of decimal places for operations involving division.
DECIMAL_PLACES = 20, // 0 to MAX
/*
* The rounding mode used when rounding to the above decimal places, and when using
* toExponential, toFixed, toFormat and toPrecision, and round (default value).
* UP 0 Away from zero.
* DOWN 1 Towards zero.
* CEIL 2 Towards +Infinity.
* FLOOR 3 Towards -Infinity.
* HALF_UP 4 Towards nearest neighbour. If equidistant, up.
* HALF_DOWN 5 Towards nearest neighbour. If equidistant, down.
* HALF_EVEN 6 Towards nearest neighbour. If equidistant, towards even neighbour.
* HALF_CEIL 7 Towards nearest neighbour. If equidistant, towards +Infinity.
* HALF_FLOOR 8 Towards nearest neighbour. If equidistant, towards -Infinity.
*/
ROUNDING_MODE = 4, // 0 to 8
// EXPONENTIAL_AT : [TO_EXP_NEG , TO_EXP_POS]
// The exponent value at and beneath which toString returns exponential notation.
// Number type: -7
TO_EXP_NEG = -7, // 0 to -MAX
// The exponent value at and above which toString returns exponential notation.
// Number type: 21
TO_EXP_POS = 21, // 0 to MAX
// RANGE : [MIN_EXP, MAX_EXP]
// The minimum exponent value, beneath which underflow to zero occurs.
// Number type: -324 (5e-324)
MIN_EXP = -1e7, // -1 to -MAX
// The maximum exponent value, above which overflow to Infinity occurs.
// Number type: 308 (1.7976931348623157e+308)
// For MAX_EXP > 1e7, e.g. new BigNumber('1e100000000').plus(1) may be slow.
MAX_EXP = 1e7, // 1 to MAX
// Whether BigNumber Errors are ever thrown.
ERRORS = true, // true or false
// Change to intValidatorNoErrors if ERRORS is false.
isValidInt = intValidatorWithErrors, // intValidatorWithErrors/intValidatorNoErrors
// Whether to use cryptographically-secure random number generation, if available.
CRYPTO = false, // true or false
/*
* The modulo mode used when calculating the modulus: a mod n.
* The quotient (q = a / n) is calculated according to the corresponding rounding mode.
* The remainder (r) is calculated as: r = a - n * q.
*
* UP 0 The remainder is positive if the dividend is negative, else is negative.
* DOWN 1 The remainder has the same sign as the dividend.
* This modulo mode is commonly known as 'truncated division' and is
* equivalent to (a % n) in JavaScript.
* FLOOR 3 The remainder has the same sign as the divisor (Python %).
* HALF_EVEN 6 This modulo mode implements the IEEE 754 remainder function.
* EUCLID 9 Euclidian division. q = sign(n) * floor(a / abs(n)).
* The remainder is always positive.
*
* The truncated division, floored division, Euclidian division and IEEE 754 remainder
* modes are commonly used for the modulus operation.
* Although the other rounding modes can also be used, they may not give useful results.
*/
MODULO_MODE = 1, // 0 to 9
// The maximum number of significant digits of the result of the toPower operation.
// If POW_PRECISION is 0, there will be unlimited significant digits.
POW_PRECISION = 0, // 0 to MAX
// The format specification used by the BigNumber.prototype.toFormat method.
FORMAT = {
decimalSeparator: '.',
groupSeparator: ',',
groupSize: 3,
secondaryGroupSize: 0,
fractionGroupSeparator: '\xA0', // non-breaking space
fractionGroupSize: 0
};
/******************************************************************************************/
// CONSTRUCTOR
/*
* The BigNumber constructor and exported function.
* Create and return a new instance of a BigNumber object.
*
* n {number|string|BigNumber} A numeric value.
* [b] {number} The base of n. Integer, 2 to 64 inclusive.
*/
function BigNumber( n, b ) {
var c, e, i, num, len, str,
x = this;
// Enable constructor usage without new.
if ( !( x instanceof BigNumber ) ) {
// 'BigNumber() constructor call without new: {n}'
if (ERRORS) raise( 26, 'constructor call without new', n );
return new BigNumber( n, b );
}
// 'new BigNumber() base not an integer: {b}'
// 'new BigNumber() base out of range: {b}'
if ( b == null || !isValidInt( b, 2, 64, id, 'base' ) ) {
// Duplicate.
if ( n instanceof BigNumber ) {
x.s = n.s;
x.e = n.e;
x.c = ( n = n.c ) ? n.slice() : n;
id = 0;
return;
}
if ( ( num = typeof n == 'number' ) && n * 0 == 0 ) {
x.s = 1 / n < 0 ? ( n = -n, -1 ) : 1;
// Fast path for integers.
if ( n === ~~n ) {
for ( e = 0, i = n; i >= 10; i /= 10, e++ );
x.e = e;
x.c = [n];
id = 0;
return;
}
str = n + '';
} else {
if ( !isNumeric.test( str = n + '' ) ) return parseNumeric( x, str, num );
x.s = str.charCodeAt(0) === 45 ? ( str = str.slice(1), -1 ) : 1;
}
} else {
b = b | 0;
str = n + '';
// Ensure return value is rounded to DECIMAL_PLACES as with other bases.
// Allow exponential notation to be used with base 10 argument.
if ( b == 10 ) {
x = new BigNumber( n instanceof BigNumber ? n : str );
return round( x, DECIMAL_PLACES + x.e + 1, ROUNDING_MODE );
}
// Avoid potential interpretation of Infinity and NaN as base 44+ values.
// Any number in exponential form will fail due to the [Ee][+-].
if ( ( num = typeof n == 'number' ) && n * 0 != 0 ||
!( new RegExp( '^-?' + ( c = '[' + ALPHABET.slice( 0, b ) + ']+' ) +
'(?:\\.' + c + ')?$',b < 37 ? 'i' : '' ) ).test(str) ) {
return parseNumeric( x, str, num, b );
}
if (num) {
x.s = 1 / n < 0 ? ( str = str.slice(1), -1 ) : 1;
if ( ERRORS && str.replace( /^0\.0*|\./, '' ).length > 15 ) {
// 'new BigNumber() number type has more than 15 significant digits: {n}'
raise( id, tooManyDigits, n );
}
// Prevent later check for length on converted number.
num = false;
} else {
x.s = str.charCodeAt(0) === 45 ? ( str = str.slice(1), -1 ) : 1;
}
str = convertBase( str, 10, b, x.s );
}
// Decimal point?
if ( ( e = str.indexOf('.') ) > -1 ) str = str.replace( '.', '' );
// Exponential form?
if ( ( i = str.search( /e/i ) ) > 0 ) {
// Determine exponent.
if ( e < 0 ) e = i;
e += +str.slice( i + 1 );
str = str.substring( 0, i );
} else if ( e < 0 ) {
// Integer.
e = str.length;
}
// Determine leading zeros.
for ( i = 0; str.charCodeAt(i) === 48; i++ );
// Determine trailing zeros.
for ( len = str.length; str.charCodeAt(--len) === 48; );
str = str.slice( i, len + 1 );
if (str) {
len = str.length;
// Disallow numbers with over 15 significant digits if number type.
// 'new BigNumber() number type has more than 15 significant digits: {n}'
if ( num && ERRORS && len > 15 && ( n > MAX_SAFE_INTEGER || n !== mathfloor(n) ) ) {
raise( id, tooManyDigits, x.s * n );
}
e = e - i - 1;
// Overflow?
if ( e > MAX_EXP ) {
// Infinity.
x.c = x.e = null;
// Underflow?
} else if ( e < MIN_EXP ) {
// Zero.
x.c = [ x.e = 0 ];
} else {
x.e = e;
x.c = [];
// Transform base
// e is the base 10 exponent.
// i is where to slice str to get the first element of the coefficient array.
i = ( e + 1 ) % LOG_BASE;
if ( e < 0 ) i += LOG_BASE;
if ( i < len ) {
if (i) x.c.push( +str.slice( 0, i ) );
for ( len -= LOG_BASE; i < len; ) {
x.c.push( +str.slice( i, i += LOG_BASE ) );
}
str = str.slice(i);
i = LOG_BASE - str.length;
} else {
i -= len;
}
for ( ; i--; str += '0' );
x.c.push( +str );
}
} else {
// Zero.
x.c = [ x.e = 0 ];
}
id = 0;
}
// CONSTRUCTOR PROPERTIES
BigNumber.another = constructorFactory;
BigNumber.ROUND_UP = 0;
BigNumber.ROUND_DOWN = 1;
BigNumber.ROUND_CEIL = 2;
BigNumber.ROUND_FLOOR = 3;
BigNumber.ROUND_HALF_UP = 4;
BigNumber.ROUND_HALF_DOWN = 5;
BigNumber.ROUND_HALF_EVEN = 6;
BigNumber.ROUND_HALF_CEIL = 7;
BigNumber.ROUND_HALF_FLOOR = 8;
BigNumber.EUCLID = 9;
/*
* Configure infrequently-changing library-wide settings.
*
* Accept an object or an argument list, with one or many of the following properties or
* parameters respectively:
*
* DECIMAL_PLACES {number} Integer, 0 to MAX inclusive
* ROUNDING_MODE {number} Integer, 0 to 8 inclusive
* EXPONENTIAL_AT {number|number[]} Integer, -MAX to MAX inclusive or
* [integer -MAX to 0 incl., 0 to MAX incl.]
* RANGE {number|number[]} Non-zero integer, -MAX to MAX inclusive or
* [integer -MAX to -1 incl., integer 1 to MAX incl.]
* ERRORS {boolean|number} true, false, 1 or 0
* CRYPTO {boolean|number} true, false, 1 or 0
* MODULO_MODE {number} 0 to 9 inclusive
* POW_PRECISION {number} 0 to MAX inclusive
* FORMAT {object} See BigNumber.prototype.toFormat
* decimalSeparator {string}
* groupSeparator {string}
* groupSize {number}
* secondaryGroupSize {number}
* fractionGroupSeparator {string}
* fractionGroupSize {number}
*
* (The values assigned to the above FORMAT object properties are not checked for validity.)
*
* E.g.
* BigNumber.config(20, 4) is equivalent to
* BigNumber.config({ DECIMAL_PLACES : 20, ROUNDING_MODE : 4 })
*
* Ignore properties/parameters set to null or undefined.
* Return an object with the properties current values.
*/
BigNumber.config = BigNumber.set = function () {
var v, p,
i = 0,
r = {},
a = arguments,
o = a[0],
has = o && typeof o == 'object'
? function () { if ( o.hasOwnProperty(p) ) return ( v = o[p] ) != null; }
: function () { if ( a.length > i ) return ( v = a[i++] ) != null; };
// DECIMAL_PLACES {number} Integer, 0 to MAX inclusive.
// 'config() DECIMAL_PLACES not an integer: {v}'
// 'config() DECIMAL_PLACES out of range: {v}'
if ( has( p = 'DECIMAL_PLACES' ) && isValidInt( v, 0, MAX, 2, p ) ) {
DECIMAL_PLACES = v | 0;
}
r[p] = DECIMAL_PLACES;
// ROUNDING_MODE {number} Integer, 0 to 8 inclusive.
// 'config() ROUNDING_MODE not an integer: {v}'
// 'config() ROUNDING_MODE out of range: {v}'
if ( has( p = 'ROUNDING_MODE' ) && isValidInt( v, 0, 8, 2, p ) ) {
ROUNDING_MODE = v | 0;
}
r[p] = ROUNDING_MODE;
// EXPONENTIAL_AT {number|number[]}
// Integer, -MAX to MAX inclusive or [integer -MAX to 0 inclusive, 0 to MAX inclusive].
// 'config() EXPONENTIAL_AT not an integer: {v}'
// 'config() EXPONENTIAL_AT out of range: {v}'
if ( has( p = 'EXPONENTIAL_AT' ) ) {
if ( isArray(v) ) {
if ( isValidInt( v[0], -MAX, 0, 2, p ) && isValidInt( v[1], 0, MAX, 2, p ) ) {
TO_EXP_NEG = v[0] | 0;
TO_EXP_POS = v[1] | 0;
}
} else if ( isValidInt( v, -MAX, MAX, 2, p ) ) {
TO_EXP_NEG = -( TO_EXP_POS = ( v < 0 ? -v : v ) | 0 );
}
}
r[p] = [ TO_EXP_NEG, TO_EXP_POS ];
// RANGE {number|number[]} Non-zero integer, -MAX to MAX inclusive or
// [integer -MAX to -1 inclusive, integer 1 to MAX inclusive].
// 'config() RANGE not an integer: {v}'
// 'config() RANGE cannot be zero: {v}'
// 'config() RANGE out of range: {v}'
if ( has( p = 'RANGE' ) ) {
if ( isArray(v) ) {
if ( isValidInt( v[0], -MAX, -1, 2, p ) && isValidInt( v[1], 1, MAX, 2, p ) ) {
MIN_EXP = v[0] | 0;
MAX_EXP = v[1] | 0;
}
} else if ( isValidInt( v, -MAX, MAX, 2, p ) ) {
if ( v | 0 ) MIN_EXP = -( MAX_EXP = ( v < 0 ? -v : v ) | 0 );
else if (ERRORS) raise( 2, p + ' cannot be zero', v );
}
}
r[p] = [ MIN_EXP, MAX_EXP ];
// ERRORS {boolean|number} true, false, 1 or 0.
// 'config() ERRORS not a boolean or binary digit: {v}'
if ( has( p = 'ERRORS' ) ) {
if ( v === !!v || v === 1 || v === 0 ) {
id = 0;
isValidInt = ( ERRORS = !!v ) ? intValidatorWithErrors : intValidatorNoErrors;
} else if (ERRORS) {
raise( 2, p + notBool, v );
}
}
r[p] = ERRORS;
// CRYPTO {boolean|number} true, false, 1 or 0.
// 'config() CRYPTO not a boolean or binary digit: {v}'
// 'config() crypto unavailable: {crypto}'
if ( has( p = 'CRYPTO' ) ) {
if ( v === true || v === false || v === 1 || v === 0 ) {
if (v) {
v = typeof crypto == 'undefined';
if ( !v && crypto && (crypto.getRandomValues || crypto.randomBytes)) {
CRYPTO = true;
} else if (ERRORS) {
raise( 2, 'crypto unavailable', v ? void 0 : crypto );
} else {
CRYPTO = false;
}
} else {
CRYPTO = false;
}
} else if (ERRORS) {
raise( 2, p + notBool, v );
}
}
r[p] = CRYPTO;
// MODULO_MODE {number} Integer, 0 to 9 inclusive.
// 'config() MODULO_MODE not an integer: {v}'
// 'config() MODULO_MODE out of range: {v}'
if ( has( p = 'MODULO_MODE' ) && isValidInt( v, 0, 9, 2, p ) ) {
MODULO_MODE = v | 0;
}
r[p] = MODULO_MODE;
// POW_PRECISION {number} Integer, 0 to MAX inclusive.
// 'config() POW_PRECISION not an integer: {v}'
// 'config() POW_PRECISION out of range: {v}'
if ( has( p = 'POW_PRECISION' ) && isValidInt( v, 0, MAX, 2, p ) ) {
POW_PRECISION = v | 0;
}
r[p] = POW_PRECISION;
// FORMAT {object}
// 'config() FORMAT not an object: {v}'
if ( has( p = 'FORMAT' ) ) {
if ( typeof v == 'object' ) {
FORMAT = v;
} else if (ERRORS) {
raise( 2, p + ' not an object', v );
}
}
r[p] = FORMAT;
return r;
};
/*
* Return true if value v is a BigNumber instance, otherwise return false.
*
* v {any} A value that may or may not be a BigNumber instance.
*/
BigNumber.isBigNumber = isBigNumber;
/*
* Return a new BigNumber whose value is the maximum of the arguments.
*
* arguments {number|string|BigNumber}
*/
BigNumber.max = function () { return maxOrMin( arguments, P.lt ); };
/*
* Return a new BigNumber whose value is the minimum of the arguments.
*
* arguments {number|string|BigNumber}
*/
BigNumber.min = function () { return maxOrMin( arguments, P.gt ); };
/*
* Return a new BigNumber with a random value equal to or greater than 0 and less than 1,
* and with dp, or DECIMAL_PLACES if dp is omitted, decimal places (or less if trailing
* zeros are produced).
*
* [dp] {number} Decimal places. Integer, 0 to MAX inclusive.
*
* 'random() decimal places not an integer: {dp}'
* 'random() decimal places out of range: {dp}'
* 'random() crypto unavailable: {crypto}'
*/
BigNumber.random = (function () {
var pow2_53 = 0x20000000000000;
// Return a 53 bit integer n, where 0 <= n < 9007199254740992.
// Check if Math.random() produces more than 32 bits of randomness.
// If it does, assume at least 53 bits are produced, otherwise assume at least 30 bits.
// 0x40000000 is 2^30, 0x800000 is 2^23, 0x1fffff is 2^21 - 1.
var random53bitInt = (Math.random() * pow2_53) & 0x1fffff
? function () { return mathfloor( Math.random() * pow2_53 ); }
: function () { return ((Math.random() * 0x40000000 | 0) * 0x800000) +
(Math.random() * 0x800000 | 0); };
return function (dp) {
var a, b, e, k, v,
i = 0,
c = [],
rand = new BigNumber(ONE);
dp = dp == null || !isValidInt( dp, 0, MAX, 14 ) ? DECIMAL_PLACES : dp | 0;
k = mathceil( dp / LOG_BASE );
if (CRYPTO) {
// Browsers supporting crypto.getRandomValues.
if (crypto.getRandomValues) {
a = crypto.getRandomValues( new Uint32Array( k *= 2 ) );
for ( ; i < k; ) {
// 53 bits:
// ((Math.pow(2, 32) - 1) * Math.pow(2, 21)).toString(2)
// 11111 11111111 11111111 11111111 11100000 00000000 00000000
// ((Math.pow(2, 32) - 1) >>> 11).toString(2)
// 11111 11111111 11111111
// 0x20000 is 2^21.
v = a[i] * 0x20000 + (a[i + 1] >>> 11);
// Rejection sampling:
// 0 <= v < 9007199254740992
// Probability that v >= 9e15, is
// 7199254740992 / 9007199254740992 ~= 0.0008, i.e. 1 in 1251
if ( v >= 9e15 ) {
b = crypto.getRandomValues( new Uint32Array(2) );
a[i] = b[0];
a[i + 1] = b[1];
} else {
// 0 <= v <= 8999999999999999
// 0 <= (v % 1e14) <= 99999999999999
c.push( v % 1e14 );
i += 2;
}
}
i = k / 2;
// Node.js supporting crypto.randomBytes.
} else if (crypto.randomBytes) {
// buffer
a = crypto.randomBytes( k *= 7 );
for ( ; i < k; ) {
// 0x1000000000000 is 2^48, 0x10000000000 is 2^40
// 0x100000000 is 2^32, 0x1000000 is 2^24
// 11111 11111111 11111111 11111111 11111111 11111111 11111111
// 0 <= v < 9007199254740992
v = ( ( a[i] & 31 ) * 0x1000000000000 ) + ( a[i + 1] * 0x10000000000 ) +
( a[i + 2] * 0x100000000 ) + ( a[i + 3] * 0x1000000 ) +
( a[i + 4] << 16 ) + ( a[i + 5] << 8 ) + a[i + 6];
if ( v >= 9e15 ) {
crypto.randomBytes(7).copy( a, i );
} else {
// 0 <= (v % 1e14) <= 99999999999999
c.push( v % 1e14 );
i += 7;
}
}
i = k / 7;
} else {
CRYPTO = false;
if (ERRORS) raise( 14, 'crypto unavailable', crypto );
}
}
// Use Math.random.
if (!CRYPTO) {
for ( ; i < k; ) {
v = random53bitInt();
if ( v < 9e15 ) c[i++] = v % 1e14;
}
}
k = c[--i];
dp %= LOG_BASE;
// Convert trailing digits to zeros according to dp.
if ( k && dp ) {
v = POWS_TEN[LOG_BASE - dp];
c[i] = mathfloor( k / v ) * v;
}
// Remove trailing elements which are zero.
for ( ; c[i] === 0; c.pop(), i-- );
// Zero?
if ( i < 0 ) {
c = [ e = 0 ];
} else {
// Remove leading elements which are zero and adjust exponent accordingly.
for ( e = -1 ; c[0] === 0; c.shift(), e -= LOG_BASE);
// Count the digits of the first element of c to determine leading zeros, and...
for ( i = 1, v = c[0]; v >= 10; v /= 10, i++);
// adjust the exponent accordingly.
if ( i < LOG_BASE ) e -= LOG_BASE - i;
}
rand.e = e;
rand.c = c;
return rand;
};
})();
// PRIVATE FUNCTIONS
// Convert a numeric string of baseIn to a numeric string of baseOut.
function convertBase( str, baseOut, baseIn, sign ) {
var d, e, k, r, x, xc, y,
i = str.indexOf( '.' ),
dp = DECIMAL_PLACES,
rm = ROUNDING_MODE;
if ( baseIn < 37 ) str = str.toLowerCase();
// Non-integer.
if ( i >= 0 ) {
k = POW_PRECISION;
// Unlimited precision.
POW_PRECISION = 0;
str = str.replace( '.', '' );
y = new BigNumber(baseIn);
x = y.pow( str.length - i );
POW_PRECISION = k;
// Convert str as if an integer, then restore the fraction part by dividing the
// result by its base raised to a power.
y.c = toBaseOut( toFixedPoint( coeffToString( x.c ), x.e ), 10, baseOut );
y.e = y.c.length;
}
// Convert the number as integer.
xc = toBaseOut( str, baseIn, baseOut );
e = k = xc.length;
// Remove trailing zeros.
for ( ; xc[--k] == 0; xc.pop() );
if ( !xc[0] ) return '0';
if ( i < 0 ) {
--e;
} else {
x.c = xc;
x.e = e;
// sign is needed for correct rounding.
x.s = sign;
x = div( x, y, dp, rm, baseOut );
xc = x.c;
r = x.r;
e = x.e;
}
d = e + dp + 1;
// The rounding digit, i.e. the digit to the right of the digit that may be rounded up.
i = xc[d];
k = baseOut / 2;
r = r || d < 0 || xc[d + 1] != null;
r = rm < 4 ? ( i != null || r ) && ( rm == 0 || rm == ( x.s < 0 ? 3 : 2 ) )
: i > k || i == k &&( rm == 4 || r || rm == 6 && xc[d - 1] & 1 ||
rm == ( x.s < 0 ? 8 : 7 ) );
if ( d < 1 || !xc[0] ) {
// 1^-dp or 0.
str = r ? toFixedPoint( '1', -dp ) : '0';
} else {
xc.length = d;
if (r) {
// Rounding up may mean the previous digit has to be rounded up and so on.
for ( --baseOut; ++xc[--d] > baseOut; ) {
xc[d] = 0;
if ( !d ) {
++e;
xc.unshift(1);
}
}
}
// Determine trailing zeros.
for ( k = xc.length; !xc[--k]; );
// E.g. [4, 11, 15] becomes 4bf.
for ( i = 0, str = ''; i <= k; str += ALPHABET.charAt( xc[i++] ) );
str = toFixedPoint( str, e );
}
// The caller will add the sign.
return str;
}
// Perform division in the specified base. Called by div and convertBase.
div = (function () {
// Assume non-zero x and k.
function multiply( x, k, base ) {
var m, temp, xlo, xhi,
carry = 0,
i = x.length,
klo = k % SQRT_BASE,
khi = k / SQRT_BASE | 0;
for ( x = x.slice(); i--; ) {
xlo = x[i] % SQRT_BASE;
xhi = x[i] / SQRT_BASE | 0;
m = khi * xlo + xhi * klo;
temp = klo * xlo + ( ( m % SQRT_BASE ) * SQRT_BASE ) + carry;
carry = ( temp / base | 0 ) + ( m / SQRT_BASE | 0 ) + khi * xhi;
x[i] = temp % base;
}
if (carry) x.unshift(carry);
return x;
}
function compare( a, b, aL, bL ) {
var i, cmp;
if ( aL != bL ) {
cmp = aL > bL ? 1 : -1;
} else {
for ( i = cmp = 0; i < aL; i++ ) {
if ( a[i] != b[i] ) {
cmp = a[i] > b[i] ? 1 : -1;
break;
}
}
}
return cmp;
}
function subtract( a, b, aL, base ) {
var i = 0;
// Subtract b from a.
for ( ; aL--; ) {
a[aL] -= i;
i = a[aL] < b[aL] ? 1 : 0;
a[aL] = i * base + a[aL] - b[aL];
}
// Remove leading zeros.
for ( ; !a[0] && a.length > 1; a.shift() );
}
// x: dividend, y: divisor.
return function ( x, y, dp, rm, base ) {
var cmp, e, i, more, n, prod, prodL, q, qc, rem, remL, rem0, xi, xL, yc0,
yL, yz,
s = x.s == y.s ? 1 : -1,
xc = x.c,
yc = y.c;
// Either NaN, Infinity or 0?
if ( !xc || !xc[0] || !yc || !yc[0] ) {
return new BigNumber(
// Return NaN if either NaN, or both Infinity or 0.
!x.s || !y.s || ( xc ? yc && xc[0] == yc[0] : !yc ) ? NaN :
// Return ±0 if x is ±0 or y is ±Infinity, or return ±Infinity as y is ±0.
xc && xc[0] == 0 || !yc ? s * 0 : s / 0
);
}
q = new BigNumber(s);
qc = q.c = [];
e = x.e - y.e;
s = dp + e + 1;
if ( !base ) {
base = BASE;
e = bitFloor( x.e / LOG_BASE ) - bitFloor( y.e / LOG_BASE );
s = s / LOG_BASE | 0;
}
// Result exponent may be one less then the current value of e.
// The coefficients of the BigNumbers from convertBase may have trailing zeros.
for ( i = 0; yc[i] == ( xc[i] || 0 ); i++ );
if ( yc[i] > ( xc[i] || 0 ) ) e--;
if ( s < 0 ) {
qc.push(1);
more = true;
} else {
xL = xc.length;
yL = yc.length;
i = 0;
s += 2;
// Normalise xc and yc so highest order digit of yc is >= base / 2.
n = mathfloor( base / ( yc[0] + 1 ) );
// Not necessary, but to handle odd bases where yc[0] == ( base / 2 ) - 1.
// if ( n > 1 || n++ == 1 && yc[0] < base / 2 ) {
if ( n > 1 ) {
yc = multiply( yc, n, base );
xc = multiply( xc, n, base );
yL = yc.length;
xL = xc.length;
}
xi = yL;
rem = xc.slice( 0, yL );
remL = rem.length;
// Add zeros to make remainder as long as divisor.
for ( ; remL < yL; rem[remL++] = 0 );
yz = yc.slice();
yz.unshift(0);
yc0 = yc[0];
if ( yc[1] >= base / 2 ) yc0++;
// Not necessary, but to prevent trial digit n > base, when using base 3.
// else if ( base == 3 && yc0 == 1 ) yc0 = 1 + 1e-15;
do {
n = 0;
// Compare divisor and remainder.
cmp = compare( yc, rem, yL, remL );
// If divisor < remainder.
if ( cmp < 0 ) {
// Calculate trial digit, n.
rem0 = rem[0];
if ( yL != remL ) rem0 = rem0 * base + ( rem[1] || 0 );
// n is how many times the divisor goes into the current remainder.
n = mathfloor( rem0 / yc0 );
// Algorithm:
// 1. product = divisor * trial digit (n)
// 2. if product > remainder: product -= divisor, n--
// 3. remainder -= product
// 4. if product was < remainder at 2:
// 5. compare new remainder and divisor
// 6. If remainder > divisor: remainder -= divisor, n++
if ( n > 1 ) {
// n may be > base only when base is 3.
if (n >= base) n = base - 1;
// product = divisor * trial digit.
prod = multiply( yc, n, base );
prodL = prod.length;
remL = rem.length;
// Compare product and remainder.
// If product > remainder.
// Trial digit n too high.
// n is 1 too high about 5% of the time, and is not known to have
// ever been more than 1 too high.
while ( compare( prod, rem, prodL, remL ) == 1 ) {
n--;
// Subtract divisor from product.
subtract( prod, yL < prodL ? yz : yc, prodL, base );
prodL = prod.length;
cmp = 1;
}
} else {
// n is 0 or 1, cmp is -1.
// If n is 0, there is no need to compare yc and rem again below,
// so change cmp to 1 to avoid it.
// If n is 1, leave cmp as -1, so yc and rem are compared again.
if ( n == 0 ) {
// divisor < remainder, so n must be at least 1.
cmp = n = 1;
}
// product = divisor
prod = yc.slice();
prodL = prod.length;
}
if ( prodL < remL ) prod.unshift(0);
// Subtract product from remainder.
subtract( rem, prod, remL, base );
remL = rem.length;
// If product was < remainder.
if ( cmp == -1 ) {
// Compare divisor and new remainder.
// If divisor < new remainder, subtract divisor from remainder.
// Trial digit n too low.
// n is 1 too low about 5% of the time, and very rarely 2 too low.
while ( compare( yc, rem, yL, remL ) < 1 ) {
n++;
// Subtract divisor from remainder.
subtract( rem, yL < remL ? yz : yc, remL, base );
remL = rem.length;
}
}
} else if ( cmp === 0 ) {
n++;
rem = [0];
} // else cmp === 1 and n will be 0
// Add the next digit, n, to the result array.
qc[i++] = n;
// Update the remainder.
if ( rem[0] ) {
rem[remL++] = xc[xi] || 0;
} else {
rem = [ xc[xi] ];
remL = 1;
}
} while ( ( xi++ < xL || rem[0] != null ) && s-- );
more = rem[0] != null;
// Leading zero?
if ( !qc[0] ) qc.shift();
}
if ( base == BASE ) {
// To calculate q.e, first get the number of digits of qc[0].
for ( i = 1, s = qc[0]; s >= 10; s /= 10, i++ );
round( q, dp + ( q.e = i + e * LOG_BASE - 1 ) + 1, rm, more );
// Caller is convertBase.
} else {
q.e = e;
q.r = +more;
}
return q;
};
})();
/*
* Return a string representing the value of BigNumber n in fixed-point or exponential
* notation rounded to the specified decimal places or significant digits.
*
* n is a BigNumber.
* i is the index of the last digit required (i.e. the digit that may be rounded up).
* rm is the rounding mode.
* caller is caller id: toExponential 19, toFixed 20, toFormat 21, toPrecision 24.
*/
function format( n, i, rm, caller ) {
var c0, e, ne, len, str;
rm = rm != null && isValidInt( rm, 0, 8, caller, roundingMode )
? rm | 0 : ROUNDING_MODE;
if ( !n.c ) return n.toString();
c0 = n.c[0];
ne = n.e;
if ( i == null ) {
str = coeffToString( n.c );
str = caller == 19 || caller == 24 && ne <= TO_EXP_NEG
? toExponential( str, ne )
: toFixedPoint( str, ne );
} else {
n = round( new BigNumber(n), i, rm );
// n.e may have changed if the value was rounded up.
e = n.e;
str = coeffToString( n.c );
len = str.length;
// toPrecision returns exponential notation if the number of significant digits
// specified is less than the number of digits necessary to represent the integer
// part of the value in fixed-point notation.
// Exponential notation.
if ( caller == 19 || caller == 24 && ( i <= e || e <= TO_EXP_NEG ) ) {
// Append zeros?
for ( ; len < i; str += '0', len++ );
str = toExponential( str, e );
// Fixed-point notation.
} else {
i -= ne;
str = toFixedPoint( str, e );
// Append zeros?
if ( e + 1 > len ) {
if ( --i > 0 ) for ( str += '.'; i--; str += '0' );
} else {
i += e - len;
if ( i > 0 ) {
if ( e + 1 == len ) str += '.';
for ( ; i--; str += '0' );
}
}
}
}
return n.s < 0 && c0 ? '-' + str : str;
}
// Handle BigNumber.max and BigNumber.min.
function maxOrMin( args, method ) {
var m, n,
i = 0;
if ( isArray( args[0] ) ) args = args[0];
m = new BigNumber( args[0] );
for ( ; ++i < args.length; ) {
n = new BigNumber( args[i] );
// If any number is NaN, return NaN.
if ( !n.s ) {
m = n;
break;
} else if ( method.call( m, n ) ) {
m = n;
}
}
return m;
}
/*
* Return true if n is an integer in range, otherwise throw.
* Use for argument validation when ERRORS is true.
*/
function intValidatorWithErrors( n, min, max, caller, name ) {
if ( n < min || n > max || n != truncate(n) ) {
raise( caller, ( name || 'decimal places' ) +
( n < min || n > max ? ' out of range' : ' not an integer' ), n );
}
return true;
}
/*
* Strip trailing zeros, calculate base 10 exponent and check against MIN_EXP and MAX_EXP.
* Called by minus, plus and times.
*/
function normalise( n, c, e ) {
var i = 1,
j = c.length;
// Remove trailing zeros.
for ( ; !c[--j]; c.pop() );
// Calculate the base 10 exponent. First get the number of digits of c[0].
for ( j = c[0]; j >= 10; j /= 10, i++ );
// Overflow?
if ( ( e = i + e * LOG_BASE - 1 ) > MAX_EXP ) {
// Infinity.
n.c = n.e = null;
// Underflow?
} else if ( e < MIN_EXP ) {
// Zero.
n.c = [ n.e = 0 ];
} else {
n.e = e;
n.c = c;
}
return n;
}
// Handle values that fail the validity test in BigNumber.
parseNumeric = (function () {
var basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i,
dotAfter = /^([^.]+)\.$/,
dotBefore = /^\.([^.]+)$/,
isInfinityOrNaN = /^-?(Infinity|NaN)$/,
whitespaceOrPlus = /^\s*\+(?=[\w.])|^\s+|\s+$/g;
return function ( x, str, num, b ) {
var base,
s = num ? str : str.replace( whitespaceOrPlus, '' );
// No exception on ±Infinity or NaN.
if ( isInfinityOrNaN.test(s) ) {
x.s = isNaN(s) ? null : s < 0 ? -1 : 1;
} else {
if ( !num ) {
// basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i
s = s.replace( basePrefix, function ( m, p1, p2 ) {
base = ( p2 = p2.toLowerCase() ) == 'x' ? 16 : p2 == 'b' ? 2 : 8;
return !b || b == base ? p1 : m;
});
if (b) {
base = b;
// E.g. '1.' to '1', '.1' to '0.1'
s = s.replace( dotAfter, '$1' ).replace( dotBefore, '0.$1' );
}
if ( str != s ) return new BigNumber( s, base );
}
// 'new BigNumber() not a number: {n}'
// 'new BigNumber() not a base {b} number: {n}'
if (ERRORS) raise( id, 'not a' + ( b ? ' base ' + b : '' ) + ' number', str );
x.s = null;
}
x.c = x.e = null;
id = 0;
}
})();
// Throw a BigNumber Error.
function raise( caller, msg, val ) {
var error = new Error( [
'new BigNumber', // 0
'cmp', // 1
'config', // 2
'div', // 3
'divToInt', // 4
'eq', // 5
'gt', // 6
'gte', // 7
'lt', // 8
'lte', // 9
'minus', // 10
'mod', // 11
'plus', // 12
'precision', // 13
'random', // 14
'round', // 15
'shift', // 16
'times', // 17
'toDigits', // 18
'toExponential', // 19
'toFixed', // 20
'toFormat', // 21
'toFraction', // 22
'pow', // 23
'toPrecision', // 24
'toString', // 25
'BigNumber' // 26
][caller] + '() ' + msg + ': ' + val );
error.name = 'BigNumber Error';
id = 0;
throw error;
}
/*
* Round x to sd significant digits using rounding mode rm. Check for over/under-flow.
* If r is truthy, it is known that there are more digits after the rounding digit.
*/
function round( x, sd, rm, r ) {
var d, i, j, k, n, ni, rd,
xc = x.c,
pows10 = POWS_TEN;
// if x is not Infinity or NaN...
if (xc) {
// rd is the rounding digit, i.e. the digit after the digit that may be rounded up.
// n is a base 1e14 number, the value of the element of array x.c containing rd.
// ni is the index of n within x.c.
// d is the number of digits of n.
// i is the index of rd within n including leading zeros.
// j is the actual index of rd within n (if < 0, rd is a leading zero).
out: {
// Get the number of digits of the first element of xc.
for ( d = 1, k = xc[0]; k >= 10; k /= 10, d++ );
i = sd - d;
// If the rounding digit is in the first element of xc...
if ( i < 0 ) {
i += LOG_BASE;
j = sd;
n = xc[ ni = 0 ];
// Get the rounding digit at index j of n.
rd = n / pows10[ d - j - 1 ] % 10 | 0;
} else {
ni = mathceil( ( i + 1 ) / LOG_BASE );
if ( ni >= xc.length ) {
if (r) {
// Needed by sqrt.
for ( ; xc.length <= ni; xc.push(0) );
n = rd = 0;
d = 1;
i %= LOG_BASE;
j = i - LOG_BASE + 1;
} else {
break out;
}
} else {
n = k = xc[ni];
// Get the number of digits of n.
for ( d = 1; k >= 10; k /= 10, d++ );
// Get the index of rd within n.
i %= LOG_BASE;
// Get the index of rd within n, adjusted for leading zeros.
// The number of leading zeros of n is given by LOG_BASE - d.
j = i - LOG_BASE + d;
// Get the rounding digit at index j of n.
rd = j < 0 ? 0 : n / pows10[ d - j - 1 ] % 10 | 0;
}
}
r = r || sd < 0 ||
// Are there any non-zero digits after the rounding digit?
// The expression n % pows10[ d - j - 1 ] returns all digits of n to the right
// of the digit at j, e.g. if n is 908714 and j is 2, the expression gives 714.
xc[ni + 1] != null || ( j < 0 ? n : n % pows10[ d - j - 1 ] );
r = rm < 4
? ( rd || r ) && ( rm == 0 || rm == ( x.s < 0 ? 3 : 2 ) )
: rd > 5 || rd == 5 && ( rm == 4 || r || rm == 6 &&
// Check whether the digit to the left of the rounding digit is odd.
( ( i > 0 ? j > 0 ? n / pows10[ d - j ] : 0 : xc[ni - 1] ) % 10 ) & 1 ||
rm == ( x.s < 0 ? 8 : 7 ) );
if ( sd < 1 || !xc[0] ) {
xc.length = 0;
if (r) {
// Convert sd to decimal places.
sd -= x.e + 1;
// 1, 0.1, 0.01, 0.001, 0.0001 etc.
xc[0] = pows10[ ( LOG_BASE - sd % LOG_BASE ) % LOG_BASE ];
x.e = -sd || 0;
} else {
// Zero.
xc[0] = x.e = 0;
}
return x;
}
// Remove excess digits.
if ( i == 0 ) {
xc.length = ni;
k = 1;
ni--;
} else {
xc.length = ni + 1;
k = pows10[ LOG_BASE - i ];
// E.g. 56700 becomes 56000 if 7 is the rounding digit.
// j > 0 means i > number of leading zeros of n.
xc[ni] = j > 0 ? mathfloor( n / pows10[ d - j ] % pows10[j] ) * k : 0;
}
// Round up?
if (r) {
for ( ; ; ) {
// If the digit to be rounded up is in the first element of xc...
if ( ni == 0 ) {
// i will be the length of xc[0] before k is added.
for ( i = 1, j = xc[0]; j >= 10; j /= 10, i++ );
j = xc[0] += k;
for ( k = 1; j >= 10; j /= 10, k++ );
// if i != k the length has increased.
if ( i != k ) {
x.e++;
if ( xc[0] == BASE ) xc[0] = 1;
}
break;
} else {
xc[ni] += k;
if ( xc[ni] != BASE ) break;
xc[ni--] = 0;
k = 1;
}
}
}
// Remove trailing zeros.
for ( i = xc.length; xc[--i] === 0; xc.pop() );
}
// Overflow? Infinity.
if ( x.e > MAX_EXP ) {
x.c = x.e = null;
// Underflow? Zero.
} else if ( x.e < MIN_EXP ) {
x.c = [ x.e = 0 ];
}
}
return x;
}
// PROTOTYPE/INSTANCE METHODS
/*
* Return a new BigNumber whose value is the absolute value of this BigNumber.
*/
P.absoluteValue = P.abs = function () {
var x = new BigNumber(this);
if ( x.s < 0 ) x.s = 1;
return x;
};
/*
* Return a new BigNumber whose value is the value of this BigNumber rounded to a whole
* number in the direction of Infinity.
*/
P.ceil = function () {
return round( new BigNumber(this), this.e + 1, 2 );
};
/*
* Return
* 1 if the value of this BigNumber is greater than the value of BigNumber(y, b),
* -1 if the value of this BigNumber is less than the value of BigNumber(y, b),
* 0 if they have the same value,
* or null if the value of either is NaN.
*/
P.comparedTo = P.cmp = function ( y, b ) {
id = 1;
return compare( this, new BigNumber( y, b ) );
};
/*
* Return the number of decimal places of the value of this BigNumber, or null if the value
* of this BigNumber is ±Infinity or NaN.
*/
P.decimalPlaces = P.dp = function () {
var n, v,
c = this.c;
if ( !c ) return null;
n = ( ( v = c.length - 1 ) - bitFloor( this.e / LOG_BASE ) ) * LOG_BASE;
// Subtract the number of trailing zeros of the last number.
if ( v = c[v] ) for ( ; v % 10 == 0; v /= 10, n-- );
if ( n < 0 ) n = 0;
return n;
};
/*
* n / 0 = I
* n / N = N
* n / I = 0
* 0 / n = 0
* 0 / 0 = N
* 0 / N = N
* 0 / I = 0
* N / n = N
* N / 0 = N
* N / N = N
* N / I = N
* I / n = I
* I / 0 = I
* I / N = N
* I / I = N
*
* Return a new BigNumber whose value is the value of this BigNumber divided by the value of
* BigNumber(y, b), rounded according to DECIMAL_PLACES and ROUNDING_MODE.
*/
P.dividedBy = P.div = function ( y, b ) {
id = 3;
return div( this, new BigNumber( y, b ), DECIMAL_PLACES, ROUNDING_MODE );
};
/*
* Return a new BigNumber whose value is the integer part of dividing the value of this
* BigNumber by the value of BigNumber(y, b).
*/
P.dividedToIntegerBy = P.divToInt = function ( y, b ) {
id = 4;
return div( this, new BigNumber( y, b ), 0, 1 );
};
/*
* Return true if the value of this BigNumber is equal to the value of BigNumber(y, b),
* otherwise returns false.
*/
P.equals = P.eq = function ( y, b ) {
id = 5;
return compare( this, new BigNumber( y, b ) ) === 0;
};
/*
* Return a new BigNumber whose value is the value of this BigNumber rounded to a whole
* number in the direction of -Infinity.
*/
P.floor = function () {
return round( new BigNumber(this), this.e + 1, 3 );
};
/*
* Return true if the value of this BigNumber is greater than the value of BigNumber(y, b),
* otherwise returns false.
*/
P.greaterThan = P.gt = function ( y, b ) {
id = 6;
return compare( this, new BigNumber( y, b ) ) > 0;
};
/*
* Return true if the value of this BigNumber is greater than or equal to the value of
* BigNumber(y, b), otherwise returns false.
*/
P.greaterThanOrEqualTo = P.gte = function ( y, b ) {
id = 7;
return ( b = compare( this, new BigNumber( y, b ) ) ) === 1 || b === 0;
};
/*
* Return true if the value of this BigNumber is a finite number, otherwise returns false.
*/
P.isFinite = function () {
return !!this.c;
};
/*
* Return true if the value of this BigNumber is an integer, otherwise return false.
*/
P.isInteger = P.isInt = function () {
return !!this.c && bitFloor( this.e / LOG_BASE ) > this.c.length - 2;
};
/*
* Return true if the value of this BigNumber is NaN, otherwise returns false.
*/
P.isNaN = function () {
return !this.s;
};
/*
* Return true if the value of this BigNumber is negative, otherwise returns false.
*/
P.isNegative = P.isNeg = function () {
return this.s < 0;
};
/*
* Return true if the value of this BigNumber is 0 or -0, otherwise returns false.
*/
P.isZero = function () {
return !!this.c && this.c[0] == 0;
};
/*
* Return true if the value of this BigNumber is less than the value of BigNumber(y, b),
* otherwise returns false.
*/
P.lessThan = P.lt = function ( y, b ) {
id = 8;
return compare( this, new BigNumber( y, b ) ) < 0;
};
/*
* Return true if the value of this BigNumber is less than or equal to the value of
* BigNumber(y, b), otherwise returns false.
*/
P.lessThanOrEqualTo = P.lte = function ( y, b ) {
id = 9;
return ( b = compare( this, new BigNumber( y, b ) ) ) === -1 || b === 0;
};
/*
* n - 0 = n
* n - N = N
* n - I = -I
* 0 - n = -n
* 0 - 0 = 0
* 0 - N = N
* 0 - I = -I
* N - n = N
* N - 0 = N
* N - N = N
* N - I = N
* I - n = I
* I - 0 = I
* I - N = N
* I - I = N
*
* Return a new BigNumber whose value is the value of this BigNumber minus the value of
* BigNumber(y, b).
*/
P.minus = P.sub = function ( y, b ) {
var i, j, t, xLTy,
x = this,
a = x.s;
id = 10;
y = new BigNumber( y, b );
b = y.s;
// Either NaN?
if ( !a || !b ) return new BigNumber(NaN);
// Signs differ?
if ( a != b ) {
y.s = -b;
return x.plus(y);
}
var xe = x.e / LOG_BASE,
ye = y.e / LOG_BASE,
xc = x.c,
yc = y.c;
if ( !xe || !ye ) {
// Either Infinity?
if ( !xc || !yc ) return xc ? ( y.s = -b, y ) : new BigNumber( yc ? x : NaN );
// Either zero?
if ( !xc[0] || !yc[0] ) {
// Return y if y is non-zero, x if x is non-zero, or zero if both are zero.
return yc[0] ? ( y.s = -b, y ) : new BigNumber( xc[0] ? x :
// IEEE 754 (2008) 6.3: n - n = -0 when rounding to -Infinity
ROUNDING_MODE == 3 ? -0 : 0 );
}
}
xe = bitFloor(xe);
ye = bitFloor(ye);
xc = xc.slice();
// Determine which is the bigger number.
if ( a = xe - ye ) {
if ( xLTy = a < 0 ) {
a = -a;
t = xc;
} else {
ye = xe;
t = yc;
}
t.reverse();
// Prepend zeros to equalise exponents.
for ( b = a; b--; t.push(0) );
t.reverse();
} else {
// Exponents equal. Check digit by digit.
j = ( xLTy = ( a = xc.length ) < ( b = yc.length ) ) ? a : b;
for ( a = b = 0; b < j; b++ ) {
if ( xc[b] != yc[b] ) {
xLTy = xc[b] < yc[b];
break;
}
}
}
// x < y? Point xc to the array of the bigger number.
if (xLTy) t = xc, xc = yc, yc = t, y.s = -y.s;
b = ( j = yc.length ) - ( i = xc.length );
// Append zeros to xc if shorter.
// No need to add zeros to yc if shorter as subtract only needs to start at yc.length.
if ( b > 0 ) for ( ; b--; xc[i++] = 0 );
b = BASE - 1;
// Subtract yc from xc.
for ( ; j > a; ) {
if ( xc[--j] < yc[j] ) {
for ( i = j; i && !xc[--i]; xc[i] = b );
--xc[i];
xc[j] += BASE;
}
xc[j] -= yc[j];
}
// Remove leading zeros and adjust exponent accordingly.
for ( ; xc[0] == 0; xc.shift(), --ye );
// Zero?
if ( !xc[0] ) {
// Following IEEE 754 (2008) 6.3,
// n - n = +0 but n - n = -0 when rounding towards -Infinity.
y.s = ROUNDING_MODE == 3 ? -1 : 1;
y.c = [ y.e = 0 ];
return y;
}
// No need to check for Infinity as +x - +y != Infinity && -x - -y != Infinity
// for finite x and y.
return normalise( y, xc, ye );
};
/*
* n % 0 = N
* n % N = N
* n % I = n
* 0 % n = 0
* -0 % n = -0
* 0 % 0 = N
* 0 % N = N
* 0 % I = 0
* N % n = N
* N % 0 = N
* N % N = N
* N % I = N
* I % n = N
* I % 0 = N
* I % N = N
* I % I = N
*
* Return a new BigNumber whose value is the value of this BigNumber modulo the value of
* BigNumber(y, b). The result depends on the value of MODULO_MODE.
*/
P.modulo = P.mod = function ( y, b ) {
var q, s,
x = this;
id = 11;
y = new BigNumber( y, b );
// Return NaN if x is Infinity or NaN, or y is NaN or zero.
if ( !x.c || !y.s || y.c && !y.c[0] ) {
return new BigNumber(NaN);
// Return x if y is Infinity or x is zero.
} else if ( !y.c || x.c && !x.c[0] ) {
return new BigNumber(x);
}
if ( MODULO_MODE == 9 ) {
// Euclidian division: q = sign(y) * floor(x / abs(y))
// r = x - qy where 0 <= r < abs(y)
s = y.s;
y.s = 1;
q = div( x, y, 0, 3 );
y.s = s;
q.s *= s;
} else {
q = div( x, y, 0, MODULO_MODE );
}
return x.minus( q.times(y) );
};
/*
* Return a new BigNumber whose value is the value of this BigNumber negated,
* i.e. multiplied by -1.
*/
P.negated = P.neg = function () {
var x = new BigNumber(this);
x.s = -x.s || null;
return x;
};
/*
* n + 0 = n
* n + N = N
* n + I = I
* 0 + n = n
* 0 + 0 = 0
* 0 + N = N
* 0 + I = I
* N + n = N
* N + 0 = N
* N + N = N
* N + I = N
* I + n = I
* I + 0 = I
* I + N = N
* I + I = I
*
* Return a new BigNumber whose value is the value of this BigNumber plus the value of
* BigNumber(y, b).
*/
P.plus = P.add = function ( y, b ) {
var t,
x = this,
a = x.s;
id = 12;
y = new BigNumber( y, b );
b = y.s;
// Either NaN?
if ( !a || !b ) return new BigNumber(NaN);
// Signs differ?
if ( a != b ) {
y.s = -b;
return x.minus(y);
}
var xe = x.e / LOG_BASE,
ye = y.e / LOG_BASE,
xc = x.c,
yc = y.c;
if ( !xe || !ye ) {
// Return ±Infinity if either ±Infinity.
if ( !xc || !yc ) return new BigNumber( a / 0 );
// Either zero?
// Return y if y is non-zero, x if x is non-zero, or zero if both are zero.
if ( !xc[0] || !yc[0] ) return yc[0] ? y : new BigNumber( xc[0] ? x : a * 0 );
}
xe = bitFloor(xe);
ye = bitFloor(ye);
xc = xc.slice();
// Prepend zeros to equalise exponents. Faster to use reverse then do unshifts.
if ( a = xe - ye ) {
if ( a > 0 ) {
ye = xe;
t = yc;
} else {
a = -a;
t = xc;
}
t.reverse();
for ( ; a--; t.push(0) );
t.reverse();
}
a = xc.length;
b = yc.length;
// Point xc to the longer array, and b to the shorter length.
if ( a - b < 0 ) t = yc, yc = xc, xc = t, b = a;
// Only start adding at yc.length - 1 as the further digits of xc can be ignored.
for ( a = 0; b; ) {
a = ( xc[--b] = xc[b] + yc[b] + a ) / BASE | 0;
xc[b] = BASE === xc[b] ? 0 : xc[b] % BASE;
}
if (a) {
xc.unshift(a);
++ye;
}
// No need to check for zero, as +x + +y != 0 && -x + -y != 0
// ye = MAX_EXP + 1 possible
return normalise( y, xc, ye );
};
/*
* Return the number of significant digits of the value of this BigNumber.
*
* [z] {boolean|number} Whether to count integer-part trailing zeros: true, false, 1 or 0.
*/
P.precision = P.sd = function (z) {
var n, v,
x = this,
c = x.c;
// 'precision() argument not a boolean or binary digit: {z}'
if ( z != null && z !== !!z && z !== 1 && z !== 0 ) {
if (ERRORS) raise( 13, 'argument' + notBool, z );
if ( z != !!z ) z = null;
}
if ( !c ) return null;
v = c.length - 1;
n = v * LOG_BASE + 1;
if ( v = c[v] ) {
// Subtract the number of trailing zeros of the last element.
for ( ; v % 10 == 0; v /= 10, n-- );
// Add the number of digits of the first element.
for ( v = c[0]; v >= 10; v /= 10, n++ );
}
if ( z && x.e + 1 > n ) n = x.e + 1;
return n;
};
/*
* Return a new BigNumber whose value is the value of this BigNumber rounded to a maximum of
* dp decimal places using rounding mode rm, or to 0 and ROUNDING_MODE respectively if
* omitted.
*
* [dp] {number} Decimal places. Integer, 0 to MAX inclusive.
* [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
*
* 'round() decimal places out of range: {dp}'
* 'round() decimal places not an integer: {dp}'
* 'round() rounding mode not an integer: {rm}'
* 'round() rounding mode out of range: {rm}'
*/
P.round = function ( dp, rm ) {
var n = new BigNumber(this);
if ( dp == null || isValidInt( dp, 0, MAX, 15 ) ) {
round( n, ~~dp + this.e + 1, rm == null ||
!isValidInt( rm, 0, 8, 15, roundingMode ) ? ROUNDING_MODE : rm | 0 );
}
return n;
};
/*
* Return a new BigNumber whose value is the value of this BigNumber shifted by k places
* (powers of 10). Shift to the right if n > 0, and to the left if n < 0.
*
* k {number} Integer, -MAX_SAFE_INTEGER to MAX_SAFE_INTEGER inclusive.
*
* If k is out of range and ERRORS is false, the result will be ±0 if k < 0, or ±Infinity
* otherwise.
*
* 'shift() argument not an integer: {k}'
* 'shift() argument out of range: {k}'
*/
P.shift = function (k) {
var n = this;
return isValidInt( k, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER, 16, 'argument' )
// k < 1e+21, or truncate(k) will produce exponential notation.
? n.times( '1e' + truncate(k) )
: new BigNumber( n.c && n.c[0] && ( k < -MAX_SAFE_INTEGER || k > MAX_SAFE_INTEGER )
? n.s * ( k < 0 ? 0 : 1 / 0 )
: n );
};
/*
* sqrt(-n) = N
* sqrt( N) = N
* sqrt(-I) = N
* sqrt( I) = I
* sqrt( 0) = 0
* sqrt(-0) = -0
*
* Return a new BigNumber whose value is the square root of the value of this BigNumber,
* rounded according to DECIMAL_PLACES and ROUNDING_MODE.
*/
P.squareRoot = P.sqrt = function () {
var m, n, r, rep, t,
x = this,
c = x.c,
s = x.s,
e = x.e,
dp = DECIMAL_PLACES + 4,
half = new BigNumber('0.5');
// Negative/NaN/Infinity/zero?
if ( s !== 1 || !c || !c[0] ) {
return new BigNumber( !s || s < 0 && ( !c || c[0] ) ? NaN : c ? x : 1 / 0 );
}
// Initial estimate.
s = Math.sqrt( +x );
// Math.sqrt underflow/overflow?
// Pass x to Math.sqrt as integer, then adjust the exponent of the result.
if ( s == 0 || s == 1 / 0 ) {
n = coeffToString(c);
if ( ( n.length + e ) % 2 == 0 ) n += '0';
s = Math.sqrt(n);
e = bitFloor( ( e + 1 ) / 2 ) - ( e < 0 || e % 2 );
if ( s == 1 / 0 ) {
n = '1e' + e;
} else {
n = s.toExponential();
n = n.slice( 0, n.indexOf('e') + 1 ) + e;
}
r = new BigNumber(n);
} else {
r = new BigNumber( s + '' );
}
// Check for zero.
// r could be zero if MIN_EXP is changed after the this value was created.
// This would cause a division by zero (x/t) and hence Infinity below, which would cause
// coeffToString to throw.
if ( r.c[0] ) {
e = r.e;
s = e + dp;
if ( s < 3 ) s = 0;
// Newton-Raphson iteration.
for ( ; ; ) {
t = r;
r = half.times( t.plus( div( x, t, dp, 1 ) ) );
if ( coeffToString( t.c ).slice( 0, s ) === ( n =
coeffToString( r.c ) ).slice( 0, s ) ) {
// The exponent of r may here be one less than the final result exponent,
// e.g 0.0009999 (e-4) --> 0.001 (e-3), so adjust s so the rounding digits
// are indexed correctly.
if ( r.e < e ) --s;
n = n.slice( s - 3, s + 1 );
// The 4th rounding digit may be in error by -1 so if the 4 rounding digits
// are 9999 or 4999 (i.e. approaching a rounding boundary) continue the
// iteration.
if ( n == '9999' || !rep && n == '4999' ) {
// On the first iteration only, check to see if rounding up gives the
// exact result as the nines may infinitely repeat.
if ( !rep ) {
round( t, t.e + DECIMAL_PLACES + 2, 0 );
if ( t.times(t).eq(x) ) {
r = t;
break;
}
}
dp += 4;
s += 4;
rep = 1;
} else {
// If rounding digits are null, 0{0,4} or 50{0,3}, check for exact
// result. If not, then there are further digits and m will be truthy.
if ( !+n || !+n.slice(1) && n.charAt(0) == '5' ) {
// Truncate to the first rounding digit.
round( r, r.e + DECIMAL_PLACES + 2, 1 );
m = !r.times(r).eq(x);
}
break;
}
}
}
}
return round( r, r.e + DECIMAL_PLACES + 1, ROUNDING_MODE, m );
};
/*
* n * 0 = 0
* n * N = N
* n * I = I
* 0 * n = 0
* 0 * 0 = 0
* 0 * N = N
* 0 * I = N
* N * n = N
* N * 0 = N
* N * N = N
* N * I = N
* I * n = I
* I * 0 = N
* I * N = N
* I * I = I
*
* Return a new BigNumber whose value is the value of this BigNumber times the value of
* BigNumber(y, b).
*/
P.times = P.mul = function ( y, b ) {
var c, e, i, j, k, m, xcL, xlo, xhi, ycL, ylo, yhi, zc,
base, sqrtBase,
x = this,
xc = x.c,
yc = ( id = 17, y = new BigNumber( y, b ) ).c;
// Either NaN, ±Infinity or ±0?
if ( !xc || !yc || !xc[0] || !yc[0] ) {
// Return NaN if either is NaN, or one is 0 and the other is Infinity.
if ( !x.s || !y.s || xc && !xc[0] && !yc || yc && !yc[0] && !xc ) {
y.c = y.e = y.s = null;
} else {
y.s *= x.s;
// Return ±Infinity if either is ±Infinity.
if ( !xc || !yc ) {
y.c = y.e = null;
// Return ±0 if either is ±0.
} else {
y.c = [0];
y.e = 0;
}
}
return y;
}
e = bitFloor( x.e / LOG_BASE ) + bitFloor( y.e / LOG_BASE );
y.s *= x.s;
xcL = xc.length;
ycL = yc.length;
// Ensure xc points to longer array and xcL to its length.
if ( xcL < ycL ) zc = xc, xc = yc, yc = zc, i = xcL, xcL = ycL, ycL = i;
// Initialise the result array with zeros.
for ( i = xcL + ycL, zc = []; i--; zc.push(0) );
base = BASE;
sqrtBase = SQRT_BASE;
for ( i = ycL; --i >= 0; ) {
c = 0;
ylo = yc[i] % sqrtBase;
yhi = yc[i] / sqrtBase | 0;
for ( k = xcL, j = i + k; j > i; ) {
xlo = xc[--k] % sqrtBase;
xhi = xc[k] / sqrtBase | 0;
m = yhi * xlo + xhi * ylo;
xlo = ylo * xlo + ( ( m % sqrtBase ) * sqrtBase ) + zc[j] + c;
c = ( xlo / base | 0 ) + ( m / sqrtBase | 0 ) + yhi * xhi;
zc[j--] = xlo % base;
}
zc[j] = c;
}
if (c) {
++e;
} else {
zc.shift();
}
return normalise( y, zc, e );
};
/*
* Return a new BigNumber whose value is the value of this BigNumber rounded to a maximum of
* sd significant digits using rounding mode rm, or ROUNDING_MODE if rm is omitted.
*
* [sd] {number} Significant digits. Integer, 1 to MAX inclusive.
* [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
*
* 'toDigits() precision out of range: {sd}'
* 'toDigits() precision not an integer: {sd}'
* 'toDigits() rounding mode not an integer: {rm}'
* 'toDigits() rounding mode out of range: {rm}'
*/
P.toDigits = function ( sd, rm ) {
var n = new BigNumber(this);
sd = sd == null || !isValidInt( sd, 1, MAX, 18, 'precision' ) ? null : sd | 0;
rm = rm == null || !isValidInt( rm, 0, 8, 18, roundingMode ) ? ROUNDING_MODE : rm | 0;
return sd ? round( n, sd, rm ) : n;
};
/*
* Return a string representing the value of this BigNumber in exponential notation and
* rounded using ROUNDING_MODE to dp fixed decimal places.
*
* [dp] {number} Decimal places. Integer, 0 to MAX inclusive.
* [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
*
* 'toExponential() decimal places not an integer: {dp}'
* 'toExponential() decimal places out of range: {dp}'
* 'toExponential() rounding mode not an integer: {rm}'
* 'toExponential() rounding mode out of range: {rm}'
*/
P.toExponential = function ( dp, rm ) {
return format( this,
dp != null && isValidInt( dp, 0, MAX, 19 ) ? ~~dp + 1 : null, rm, 19 );
};
/*
* Return a string representing the value of this BigNumber in fixed-point notation rounding
* to dp fixed decimal places using rounding mode rm, or ROUNDING_MODE if rm is omitted.
*
* Note: as with JavaScript's number type, (-0).toFixed(0) is '0',
* but e.g. (-0.00001).toFixed(0) is '-0'.
*
* [dp] {number} Decimal places. Integer, 0 to MAX inclusive.
* [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
*
* 'toFixed() decimal places not an integer: {dp}'
* 'toFixed() decimal places out of range: {dp}'
* 'toFixed() rounding mode not an integer: {rm}'
* 'toFixed() rounding mode out of range: {rm}'
*/
P.toFixed = function ( dp, rm ) {
return format( this, dp != null && isValidInt( dp, 0, MAX, 20 )
? ~~dp + this.e + 1 : null, rm, 20 );
};
/*
* Return a string representing the value of this BigNumber in fixed-point notation rounded
* using rm or ROUNDING_MODE to dp decimal places, and formatted according to the properties
* of the FORMAT object (see BigNumber.config).
*
* FORMAT = {
* decimalSeparator : '.',
* groupSeparator : ',',
* groupSize : 3,
* secondaryGroupSize : 0,
* fractionGroupSeparator : '\xA0', // non-breaking space
* fractionGroupSize : 0
* };
*
* [dp] {number} Decimal places. Integer, 0 to MAX inclusive.
* [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
*
* 'toFormat() decimal places not an integer: {dp}'
* 'toFormat() decimal places out of range: {dp}'
* 'toFormat() rounding mode not an integer: {rm}'
* 'toFormat() rounding mode out of range: {rm}'
*/
P.toFormat = function ( dp, rm ) {
var str = format( this, dp != null && isValidInt( dp, 0, MAX, 21 )
? ~~dp + this.e + 1 : null, rm, 21 );
if ( this.c ) {
var i,
arr = str.split('.'),
g1 = +FORMAT.groupSize,
g2 = +FORMAT.secondaryGroupSize,
groupSeparator = FORMAT.groupSeparator,
intPart = arr[0],
fractionPart = arr[1],
isNeg = this.s < 0,
intDigits = isNeg ? intPart.slice(1) : intPart,
len = intDigits.length;
if (g2) i = g1, g1 = g2, g2 = i, len -= i;
if ( g1 > 0 && len > 0 ) {
i = len % g1 || g1;
intPart = intDigits.substr( 0, i );
for ( ; i < len; i += g1 ) {
intPart += groupSeparator + intDigits.substr( i, g1 );
}
if ( g2 > 0 ) intPart += groupSeparator + intDigits.slice(i);
if (isNeg) intPart = '-' + intPart;
}
str = fractionPart
? intPart + FORMAT.decimalSeparator + ( ( g2 = +FORMAT.fractionGroupSize )
? fractionPart.replace( new RegExp( '\\d{' + g2 + '}\\B', 'g' ),
'$&' + FORMAT.fractionGroupSeparator )
: fractionPart )
: intPart;
}
return str;
};
/*
* Return a string array representing the value of this BigNumber as a simple fraction with
* an integer numerator and an integer denominator. The denominator will be a positive
* non-zero value less than or equal to the specified maximum denominator. If a maximum
* denominator is not specified, the denominator will be the lowest value necessary to
* represent the number exactly.
*
* [md] {number|string|BigNumber} Integer >= 1 and < Infinity. The maximum denominator.
*
* 'toFraction() max denominator not an integer: {md}'
* 'toFraction() max denominator out of range: {md}'
*/
P.toFraction = function (md) {
var arr, d0, d2, e, exp, n, n0, q, s,
k = ERRORS,
x = this,
xc = x.c,
d = new BigNumber(ONE),
n1 = d0 = new BigNumber(ONE),
d1 = n0 = new BigNumber(ONE);
if ( md != null ) {
ERRORS = false;
n = new BigNumber(md);
ERRORS = k;
if ( !( k = n.isInt() ) || n.lt(ONE) ) {
if (ERRORS) {
raise( 22,
'max denominator ' + ( k ? 'out of range' : 'not an integer' ), md );
}
// ERRORS is false:
// If md is a finite non-integer >= 1, round it to an integer and use it.
md = !k && n.c && round( n, n.e + 1, 1 ).gte(ONE) ? n : null;
}
}
if ( !xc ) return x.toString();
s = coeffToString(xc);
// Determine initial denominator.
// d is a power of 10 and the minimum max denominator that specifies the value exactly.
e = d.e = s.length - x.e - 1;
d.c[0] = POWS_TEN[ ( exp = e % LOG_BASE ) < 0 ? LOG_BASE + exp : exp ];
md = !md || n.cmp(d) > 0 ? ( e > 0 ? d : n1 ) : n;
exp = MAX_EXP;
MAX_EXP = 1 / 0;
n = new BigNumber(s);
// n0 = d1 = 0
n0.c[0] = 0;
for ( ; ; ) {
q = div( n, d, 0, 1 );
d2 = d0.plus( q.times(d1) );
if ( d2.cmp(md) == 1 ) break;
d0 = d1;
d1 = d2;
n1 = n0.plus( q.times( d2 = n1 ) );
n0 = d2;
d = n.minus( q.times( d2 = d ) );
n = d2;
}
d2 = div( md.minus(d0), d1, 0, 1 );
n0 = n0.plus( d2.times(n1) );
d0 = d0.plus( d2.times(d1) );
n0.s = n1.s = x.s;
e *= 2;
// Determine which fraction is closer to x, n0/d0 or n1/d1
arr = div( n1, d1, e, ROUNDING_MODE ).minus(x).abs().cmp(
div( n0, d0, e, ROUNDING_MODE ).minus(x).abs() ) < 1
? [ n1.toString(), d1.toString() ]
: [ n0.toString(), d0.toString() ];
MAX_EXP = exp;
return arr;
};
/*
* Return the value of this BigNumber converted to a number primitive.
*/
P.toNumber = function () {
return +this;
};
/*
* Return a BigNumber whose value is the value of this BigNumber raised to the power n.
* If m is present, return the result modulo m.
* If n is negative round according to DECIMAL_PLACES and ROUNDING_MODE.
* If POW_PRECISION is non-zero and m is not present, round to POW_PRECISION using
* ROUNDING_MODE.
*
* The modular power operation works efficiently when x, n, and m are positive integers,
* otherwise it is equivalent to calculating x.toPower(n).modulo(m) (with POW_PRECISION 0).
*
* n {number} Integer, -MAX_SAFE_INTEGER to MAX_SAFE_INTEGER inclusive.
* [m] {number|string|BigNumber} The modulus.
*
* 'pow() exponent not an integer: {n}'
* 'pow() exponent out of range: {n}'
*
* Performs 54 loop iterations for n of 9007199254740991.
*/
P.toPower = P.pow = function ( n, m ) {
var k, y, z,
i = mathfloor( n < 0 ? -n : +n ),
x = this;
if ( m != null ) {
id = 23;
m = new BigNumber(m);
}
// Pass ±Infinity to Math.pow if exponent is out of range.
if ( !isValidInt( n, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER, 23, 'exponent' ) &&
( !isFinite(n) || i > MAX_SAFE_INTEGER && ( n /= 0 ) ||
parseFloat(n) != n && !( n = NaN ) ) || n == 0 ) {
k = Math.pow( +x, n );
return new BigNumber( m ? k % m : k );
}
if (m) {
if ( n > 1 && x.gt(ONE) && x.isInt() && m.gt(ONE) && m.isInt() ) {
x = x.mod(m);
} else {
z = m;
// Nullify m so only a single mod operation is performed at the end.
m = null;
}
} else if (POW_PRECISION) {
// Truncating each coefficient array to a length of k after each multiplication
// equates to truncating significant digits to POW_PRECISION + [28, 41],
// i.e. there will be a minimum of 28 guard digits retained.
// (Using + 1.5 would give [9, 21] guard digits.)
k = mathceil( POW_PRECISION / LOG_BASE + 2 );
}
y = new BigNumber(ONE);
for ( ; ; ) {
if ( i % 2 ) {
y = y.times(x);
if ( !y.c ) break;
if (k) {
if ( y.c.length > k ) y.c.length = k;
} else if (m) {
y = y.mod(m);
}
}
i = mathfloor( i / 2 );
if ( !i ) break;
x = x.times(x);
if (k) {
if ( x.c && x.c.length > k ) x.c.length = k;
} else if (m) {
x = x.mod(m);
}
}
if (m) return y;
if ( n < 0 ) y = ONE.div(y);
return z ? y.mod(z) : k ? round( y, POW_PRECISION, ROUNDING_MODE ) : y;
};
/*
* Return a string representing the value of this BigNumber rounded to sd significant digits
* using rounding mode rm or ROUNDING_MODE. If sd is less than the number of digits
* necessary to represent the integer part of the value in fixed-point notation, then use
* exponential notation.
*
* [sd] {number} Significant digits. Integer, 1 to MAX inclusive.
* [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
*
* 'toPrecision() precision not an integer: {sd}'
* 'toPrecision() precision out of range: {sd}'
* 'toPrecision() rounding mode not an integer: {rm}'
* 'toPrecision() rounding mode out of range: {rm}'
*/
P.toPrecision = function ( sd, rm ) {
return format( this, sd != null && isValidInt( sd, 1, MAX, 24, 'precision' )
? sd | 0 : null, rm, 24 );
};
/*
* Return a string representing the value of this BigNumber in base b, or base 10 if b is
* omitted. If a base is specified, including base 10, round according to DECIMAL_PLACES and
* ROUNDING_MODE. If a base is not specified, and this BigNumber has a positive exponent
* that is equal to or greater than TO_EXP_POS, or a negative exponent equal to or less than
* TO_EXP_NEG, return exponential notation.
*
* [b] {number} Integer, 2 to 64 inclusive.
*
* 'toString() base not an integer: {b}'
* 'toString() base out of range: {b}'
*/
P.toString = function (b) {
var str,
n = this,
s = n.s,
e = n.e;
// Infinity or NaN?
if ( e === null ) {
if (s) {
str = 'Infinity';
if ( s < 0 ) str = '-' + str;
} else {
str = 'NaN';
}
} else {
str = coeffToString( n.c );
if ( b == null || !isValidInt( b, 2, 64, 25, 'base' ) ) {
str = e <= TO_EXP_NEG || e >= TO_EXP_POS
? toExponential( str, e )
: toFixedPoint( str, e );
} else {
str = convertBase( toFixedPoint( str, e ), b | 0, 10, s );
}
if ( s < 0 && n.c[0] ) str = '-' + str;
}
return str;
};
/*
* Return a new BigNumber whose value is the value of this BigNumber truncated to a whole
* number.
*/
P.truncated = P.trunc = function () {
return round( new BigNumber(this), this.e + 1, 1 );
};
/*
* Return as toString, but do not accept a base argument, and include the minus sign for
* negative zero.
*/
P.valueOf = P.toJSON = function () {
var str,
n = this,
e = n.e;
if ( e === null ) return n.toString();
str = coeffToString( n.c );
str = e <= TO_EXP_NEG || e >= TO_EXP_POS
? toExponential( str, e )
: toFixedPoint( str, e );
return n.s < 0 ? '-' + str : str;
};
if ( configObj != null ) BigNumber.config(configObj);
return BigNumber;
}
// PRIVATE HELPER FUNCTIONS
function bitFloor(n) {
var i = n | 0;
return n > 0 || n === i ? i : i - 1;
}
// Return a coefficient array as a string of base 10 digits.
function coeffToString(a) {
var s, z,
i = 1,
j = a.length,
r = a[0] + '';
for ( ; i < j; ) {
s = a[i++] + '';
z = LOG_BASE - s.length;
for ( ; z--; s = '0' + s );
r += s;
}
// Determine trailing zeros.
for ( j = r.length; r.charCodeAt(--j) === 48; );
return r.slice( 0, j + 1 || 1 );
}
// Compare the value of BigNumbers x and y.
function compare( x, y ) {
var a, b,
xc = x.c,
yc = y.c,
i = x.s,
j = y.s,
k = x.e,
l = y.e;
// Either NaN?
if ( !i || !j ) return null;
a = xc && !xc[0];
b = yc && !yc[0];
// Either zero?
if ( a || b ) return a ? b ? 0 : -j : i;
// Signs differ?
if ( i != j ) return i;
a = i < 0;
b = k == l;
// Either Infinity?
if ( !xc || !yc ) return b ? 0 : !xc ^ a ? 1 : -1;
// Compare exponents.
if ( !b ) return k > l ^ a ? 1 : -1;
j = ( k = xc.length ) < ( l = yc.length ) ? k : l;
// Compare digit by digit.
for ( i = 0; i < j; i++ ) if ( xc[i] != yc[i] ) return xc[i] > yc[i] ^ a ? 1 : -1;
// Compare lengths.
return k == l ? 0 : k > l ^ a ? 1 : -1;
}
/*
* Return true if n is a valid number in range, otherwise false.
* Use for argument validation when ERRORS is false.
* Note: parseInt('1e+1') == 1 but parseFloat('1e+1') == 10.
*/
function intValidatorNoErrors( n, min, max ) {
return ( n = truncate(n) ) >= min && n <= max;
}
function isArray(obj) {
return Object.prototype.toString.call(obj) == '[object Array]';
}
function isBigNumber(v) {
return !!( v && v.constructor && v.constructor.isBigNumber === isBigNumber );
}
/*
* Convert string of baseIn to an array of numbers of baseOut.
* Eg. convertBase('255', 10, 16) returns [15, 15].
* Eg. convertBase('ff', 16, 10) returns [2, 5, 5].
*/
function toBaseOut( str, baseIn, baseOut ) {
var j,
arr = [0],
arrL,
i = 0,
len = str.length;
for ( ; i < len; ) {
for ( arrL = arr.length; arrL--; arr[arrL] *= baseIn );
arr[ j = 0 ] += ALPHABET.indexOf( str.charAt( i++ ) );
for ( ; j < arr.length; j++ ) {
if ( arr[j] > baseOut - 1 ) {
if ( arr[j + 1] == null ) arr[j + 1] = 0;
arr[j + 1] += arr[j] / baseOut | 0;
arr[j] %= baseOut;
}
}
}
return arr.reverse();
}
function toExponential( str, e ) {
return ( str.length > 1 ? str.charAt(0) + '.' + str.slice(1) : str ) +
( e < 0 ? 'e' : 'e+' ) + e;
}
function toFixedPoint( str, e ) {
var len, z;
// Negative exponent?
if ( e < 0 ) {
// Prepend zeros.
for ( z = '0.'; ++e; z += '0' );
str = z + str;
// Positive exponent
} else {
len = str.length;
// Append zeros.
if ( ++e > len ) {
for ( z = '0', e -= len; --e; z += '0' );
str += z;
} else if ( e < len ) {
str = str.slice( 0, e ) + '.' + str.slice(e);
}
}
return str;
}
function truncate(n) {
n = parseFloat(n);
return n < 0 ? mathceil(n) : mathfloor(n);
}
// EXPORT
BigNumber = constructorFactory();
BigNumber.default = BigNumber.BigNumber = BigNumber;
// AMD.
if ( typeof define == 'function' && define.amd ) {
define( function () { return BigNumber; } );
// Node.js and other environments that support module.exports.
} else if ( typeof module != 'undefined' && module.exports ) {
module.exports = BigNumber;
// Browser.
} else {
if ( !globalObj ) globalObj = typeof self != 'undefined' ? self : Function('return this')();
globalObj.BigNumber = BigNumber;
}
})(this);
{"version":3,"file":"bignumber.min.js","sources":["bignumber.js"],"names":["globalObj","constructorFactory","configObj","BigNumber","n","b","c","e","i","num","len","str","x","this","ERRORS","raise","isValidInt","id","round","DECIMAL_PLACES","ROUNDING_MODE","RegExp","ALPHABET","slice","test","parseNumeric","s","replace","length","tooManyDigits","charCodeAt","convertBase","isNumeric","indexOf","search","substring","MAX_SAFE_INTEGER","mathfloor","MAX_EXP","MIN_EXP","LOG_BASE","push","baseOut","baseIn","sign","d","k","r","xc","y","dp","rm","toLowerCase","POW_PRECISION","pow","toBaseOut","toFixedPoint","coeffToString","pop","div","unshift","charAt","format","caller","c0","ne","roundingMode","toString","TO_EXP_NEG","toExponential","maxOrMin","args","method","m","isArray","call","intValidatorWithErrors","min","max","name","truncate","normalise","j","msg","val","error","Error","sd","ni","rd","pows10","POWS_TEN","out","mathceil","BASE","P","prototype","ONE","TO_EXP_POS","CRYPTO","MODULO_MODE","FORMAT","decimalSeparator","groupSeparator","groupSize","secondaryGroupSize","fractionGroupSeparator","fractionGroupSize","another","ROUND_UP","ROUND_DOWN","ROUND_CEIL","ROUND_FLOOR","ROUND_HALF_UP","ROUND_HALF_DOWN","ROUND_HALF_EVEN","ROUND_HALF_CEIL","ROUND_HALF_FLOOR","EUCLID","config","set","v","p","a","arguments","o","has","hasOwnProperty","MAX","intValidatorNoErrors","notBool","crypto","getRandomValues","randomBytes","isBigNumber","lt","gt","random","pow2_53","random53bitInt","Math","rand","Uint32Array","copy","shift","multiply","base","temp","xlo","xhi","carry","klo","SQRT_BASE","khi","compare","aL","bL","cmp","subtract","more","prod","prodL","q","qc","rem","remL","rem0","xi","xL","yc0","yL","yz","yc","NaN","bitFloor","basePrefix","dotAfter","dotBefore","isInfinityOrNaN","whitespaceOrPlus","isNaN","p1","p2","absoluteValue","abs","ceil","comparedTo","decimalPlaces","dividedBy","dividedToIntegerBy","divToInt","equals","eq","floor","greaterThan","greaterThanOrEqualTo","gte","isFinite","isInteger","isInt","isNegative","isNeg","isZero","lessThan","lessThanOrEqualTo","lte","minus","sub","t","xLTy","plus","xe","ye","reverse","modulo","mod","times","negated","neg","add","precision","z","squareRoot","sqrt","rep","half","mul","xcL","ycL","ylo","yhi","zc","sqrtBase","toDigits","toFixed","toFormat","arr","split","g1","g2","intPart","fractionPart","intDigits","substr","toFraction","md","d0","d2","exp","n0","n1","d1","toNumber","toPower","parseFloat","toPrecision","truncated","trunc","valueOf","toJSON","l","obj","Object","constructor","arrL","define","amd","module","exports","self","Function"],"mappings":";CAEC,SAAWA,GACR,YAqCA,SAASC,GAAmBC,GAiHxB,QAASC,GAAWC,EAAGC,GACnB,GAAIC,GAAGC,EAAGC,EAAGC,EAAKC,EAAKC,EACnBC,EAAIC,IAGR,MAAQD,YAAaT,IAIjB,MADIW,IAAQC,EAAO,GAAI,+BAAgCX,GAChD,GAAID,GAAWC,EAAGC,EAK7B,IAAU,MAALA,GAAcW,EAAYX,EAAG,EAAG,GAAIY,EAAI,QA4BtC,CAMH,GALAZ,EAAQ,EAAJA,EACJM,EAAMP,EAAI,GAIA,IAALC,EAED,MADAO,GAAI,GAAIT,GAAWC,YAAaD,GAAYC,EAAIO,GACzCO,EAAON,EAAGO,EAAiBP,EAAEL,EAAI,EAAGa,EAK/C,KAAOX,EAAkB,gBAALL,KAAuB,EAAJA,GAAS,IAC7C,GAAMiB,QAAQ,OAAUf,EAAI,IAAMgB,EAASC,MAAO,EAAGlB,GAAM,MAC1D,SAAWC,EAAI,MAAU,GAAJD,EAAS,IAAM,IAAOmB,KAAKb,GAChD,MAAOc,GAAcb,EAAGD,EAAKF,EAAKJ,EAGlCI,IACAG,EAAEc,EAAY,EAAR,EAAItB,GAAUO,EAAMA,EAAIY,MAAM,GAAI,IAAO,EAE1CT,GAAUH,EAAIgB,QAAS,YAAa,IAAKC,OAAS,IAGnDb,EAAOE,EAAIY,EAAezB,GAI9BK,GAAM,GAENG,EAAEc,EAA0B,KAAtBf,EAAImB,WAAW,IAAcnB,EAAMA,EAAIY,MAAM,GAAI,IAAO,EAGlEZ,EAAMoB,EAAapB,EAAK,GAAIN,EAAGO,EAAEc,OA9DmB,CAGpD,GAAKtB,YAAaD,GAKd,MAJAS,GAAEc,EAAItB,EAAEsB,EACRd,EAAEL,EAAIH,EAAEG,EACRK,EAAEN,GAAMF,EAAIA,EAAEE,GAAMF,EAAEmB,QAAUnB,OAChCa,EAAK,EAIT,KAAOR,EAAkB,gBAALL,KAAuB,EAAJA,GAAS,EAAI,CAIhD,GAHAQ,EAAEc,EAAY,EAAR,EAAItB,GAAUA,GAAKA,EAAG,IAAO,EAG9BA,MAAQA,EAAI,CACb,IAAMG,EAAI,EAAGC,EAAIJ,EAAGI,GAAK,GAAIA,GAAK,GAAID,KAItC,MAHAK,GAAEL,EAAIA,EACNK,EAAEN,GAAKF,QACPa,EAAK,GAITN,EAAMP,EAAI,OACP,CACH,IAAM4B,EAAUR,KAAMb,EAAMP,EAAI,IAAO,MAAOqB,GAAcb,EAAGD,EAAKF,EACpEG,GAAEc,EAA0B,KAAtBf,EAAImB,WAAW,IAAcnB,EAAMA,EAAIY,MAAM,GAAI,IAAO,GAwDtE,KAhBOhB,EAAII,EAAIsB,QAAQ,MAAS,KAAKtB,EAAMA,EAAIgB,QAAS,IAAK,MAGtDnB,EAAIG,EAAIuB,OAAQ,OAAW,GAGrB,EAAJ3B,IAAQA,EAAIC,GACjBD,IAAMI,EAAIY,MAAOf,EAAI,GACrBG,EAAMA,EAAIwB,UAAW,EAAG3B,IACZ,EAAJD,IAGRA,EAAII,EAAIiB,QAINpB,EAAI,EAAyB,KAAtBG,EAAImB,WAAWtB,GAAWA,KAGvC,IAAME,EAAMC,EAAIiB,OAAkC,KAA1BjB,EAAImB,aAAapB,KAGzC,GAFAC,EAAMA,EAAIY,MAAOf,EAAGE,EAAM,GActB,GAXAA,EAAMC,EAAIiB,OAILnB,GAAOK,GAAUJ,EAAM,KAAQN,EAAIgC,GAAoBhC,IAAMiC,EAAUjC,KACxEW,EAAOE,EAAIY,EAAejB,EAAEc,EAAItB,GAGpCG,EAAIA,EAAIC,EAAI,EAGPD,EAAI+B,EAGL1B,EAAEN,EAAIM,EAAEL,EAAI,SAGT,IAASgC,EAAJhC,EAGRK,EAAEN,GAAMM,EAAEL,EAAI,OACX,CAWH,GAVAK,EAAEL,EAAIA,EACNK,EAAEN,KAMFE,GAAMD,EAAI,GAAMiC,EACP,EAAJjC,IAAQC,GAAKgC,GAET9B,EAAJF,EAAU,CAGX,IAFIA,GAAGI,EAAEN,EAAEmC,MAAO9B,EAAIY,MAAO,EAAGf,IAE1BE,GAAO8B,EAAc9B,EAAJF,GACnBI,EAAEN,EAAEmC,MAAO9B,EAAIY,MAAOf,EAAGA,GAAKgC,GAGlC7B,GAAMA,EAAIY,MAAMf,GAChBA,EAAIgC,EAAW7B,EAAIiB,WAEnBpB,IAAKE,CAGT,MAAQF,IAAKG,GAAO,KACpBC,EAAEN,EAAEmC,MAAO9B,OAKfC,GAAEN,GAAMM,EAAEL,EAAI,EAGlBU,GAAK,EAmWT,QAASc,GAAapB,EAAK+B,EAASC,EAAQC,GACxC,GAAIC,GAAGtC,EAAGuC,EAAGC,EAAGnC,EAAGoC,EAAIC,EACnBzC,EAAIG,EAAIsB,QAAS,KACjBiB,EAAK/B,EACLgC,EAAK/B,CA0BT,KAxBc,GAATuB,IAAchC,EAAMA,EAAIyC,eAGxB5C,GAAK,IACNsC,EAAIO,EAGJA,EAAgB,EAChB1C,EAAMA,EAAIgB,QAAS,IAAK,IACxBsB,EAAI,GAAI9C,GAAUwC,GAClB/B,EAAIqC,EAAEK,IAAK3C,EAAIiB,OAASpB,GACxB6C,EAAgBP,EAIhBG,EAAE3C,EAAIiD,EAAWC,EAAcC,EAAe7C,EAAEN,GAAKM,EAAEL,GAAK,GAAImC,GAChEO,EAAE1C,EAAI0C,EAAE3C,EAAEsB,QAIdoB,EAAKO,EAAW5C,EAAKgC,EAAQD,GAC7BnC,EAAIuC,EAAIE,EAAGpB,OAGQ,GAAXoB,IAAKF,GAASE,EAAGU,OACzB,IAAMV,EAAG,GAAK,MAAO,GA2BrB,IAzBS,EAAJxC,IACCD,GAEFK,EAAEN,EAAI0C,EACNpC,EAAEL,EAAIA,EAGNK,EAAEc,EAAIkB,EACNhC,EAAI+C,EAAK/C,EAAGqC,EAAGC,EAAIC,EAAIT,GACvBM,EAAKpC,EAAEN,EACPyC,EAAInC,EAAEmC,EACNxC,EAAIK,EAAEL,GAGVsC,EAAItC,EAAI2C,EAAK,EAGb1C,EAAIwC,EAAGH,GACPC,EAAIJ,EAAU,EACdK,EAAIA,GAAS,EAAJF,GAAsB,MAAbG,EAAGH,EAAI,GAEzBE,EAAS,EAALI,GAAgB,MAAL3C,GAAauC,KAAe,GAANI,GAAWA,IAAQvC,EAAEc,EAAI,EAAI,EAAI,IACzDlB,EAAIsC,GAAKtC,GAAKsC,IAAY,GAANK,GAAWJ,GAAW,GAANI,GAAuB,EAAZH,EAAGH,EAAI,IACtDM,IAAQvC,EAAEc,EAAI,EAAI,EAAI,IAE1B,EAAJmB,IAAUG,EAAG,GAGdrC,EAAMoC,EAAIS,EAAc,KAAMN,GAAO,QAClC,CAGH,GAFAF,EAAGpB,OAASiB,EAERE,EAGA,MAAQL,IAAWM,IAAKH,GAAKH,GACzBM,EAAGH,GAAK,EAEFA,MACAtC,EACFyC,EAAGY,QAAQ,GAMvB,KAAMd,EAAIE,EAAGpB,QAASoB,IAAKF,KAG3B,IAAMtC,EAAI,EAAGG,EAAM,GAASmC,GAALtC,EAAQG,GAAOW,EAASuC,OAAQb,EAAGxC,OAC1DG,EAAM6C,EAAc7C,EAAKJ,GAI7B,MAAOI,GA4QX,QAASmD,GAAQ1D,EAAGI,EAAG2C,EAAIY,GACvB,GAAIC,GAAIzD,EAAG0D,EAAIvD,EAAKC,CAKpB,IAHAwC,EAAW,MAANA,GAAcnC,EAAYmC,EAAI,EAAG,EAAGY,EAAQG,GACxC,EAALf,EAAS/B,GAEPhB,EAAEE,EAAI,MAAOF,GAAE+D,UAIrB,IAHAH,EAAK5D,EAAEE,EAAE,GACT2D,EAAK7D,EAAEG,EAEG,MAALC,EACDG,EAAM8C,EAAerD,EAAEE,GACvBK,EAAgB,IAAVoD,GAA0B,IAAVA,GAAsBK,GAANH,EAClCI,EAAe1D,EAAKsD,GACpBT,EAAc7C,EAAKsD,OAevB,IAbA7D,EAAIc,EAAO,GAAIf,GAAUC,GAAII,EAAG2C,GAGhC5C,EAAIH,EAAEG,EAENI,EAAM8C,EAAerD,EAAEE,GACvBI,EAAMC,EAAIiB,OAOK,IAAVmC,GAA0B,IAAVA,IAAuBxD,GAALC,GAAe4D,GAAL7D,GAAoB,CAGjE,KAAcC,EAANE,EAASC,GAAO,IAAKD,KAC7BC,EAAM0D,EAAe1D,EAAKJ,OAQ1B,IAJAC,GAAKyD,EACLtD,EAAM6C,EAAc7C,EAAKJ,GAGpBA,EAAI,EAAIG,GACT,KAAOF,EAAI,EAAI,IAAMG,GAAO,IAAKH,IAAKG,GAAO,UAG7C,IADAH,GAAKD,EAAIG,EACJF,EAAI,EAEL,IADKD,EAAI,GAAKG,IAAMC,GAAO,KACnBH,IAAKG,GAAO,KAMpC,MAAOP,GAAEsB,EAAI,GAAKsC,EAAK,IAAMrD,EAAMA,EAKvC,QAAS2D,GAAUC,EAAMC,GACrB,GAAIC,GAAGrE,EACHI,EAAI,CAKR,KAHKkE,EAASH,EAAK,MAAOA,EAAOA,EAAK,IACtCE,EAAI,GAAItE,GAAWoE,EAAK,MAEd/D,EAAI+D,EAAK3C,QAAU,CAIzB,GAHAxB,EAAI,GAAID,GAAWoE,EAAK/D,KAGlBJ,EAAEsB,EAAI,CACR+C,EAAIrE,CACJ,OACQoE,EAAOG,KAAMF,EAAGrE,KACxBqE,EAAIrE,GAIZ,MAAOqE,GAQX,QAASG,GAAwBxE,EAAGyE,EAAKC,EAAKf,EAAQgB,GAMlD,OALSF,EAAJzE,GAAWA,EAAI0E,GAAO1E,GAAK4E,EAAS5E,KACrCW,EAAOgD,GAAUgB,GAAQ,mBACjBF,EAAJzE,GAAWA,EAAI0E,EAAM,gBAAkB,mBAAqB1E,IAG7D,EAQX,QAAS6E,GAAW7E,EAAGE,EAAGC,GAKtB,IAJA,GAAIC,GAAI,EACJ0E,EAAI5E,EAAEsB,QAGDtB,IAAI4E,GAAI5E,EAAEoD,OAGnB,IAAMwB,EAAI5E,EAAE,GAAI4E,GAAK,GAAIA,GAAK,GAAI1E,KAkBlC,OAfOD,EAAIC,EAAID,EAAIiC,EAAW,GAAMF,EAGhClC,EAAEE,EAAIF,EAAEG,EAAI,KAGAgC,EAAJhC,EAGRH,EAAEE,GAAMF,EAAEG,EAAI,IAEdH,EAAEG,EAAIA,EACNH,EAAEE,EAAIA,GAGHF,EAmDX,QAASW,GAAOgD,EAAQoB,EAAKC,GACzB,GAAIC,GAAQ,GAAIC,QACZ,gBACA,MACA,SACA,MACA,WACA,KACA,KACA,MACA,KACA,MACA,QACA,MACA,OACA,YACA,SACA,QACA,QACA,QACA,WACA,gBACA,UACA,WACA,aACA,MACA,cACA,WACA,aACFvB,GAAU,MAAQoB,EAAM,KAAOC,EAIjC,MAFAC,GAAMN,KAAO,kBACb9D,EAAK,EACCoE,EAQV,QAASnE,GAAON,EAAG2E,EAAIpC,EAAIJ,GACvB,GAAIF,GAAGrC,EAAG0E,EAAGpC,EAAG1C,EAAGoF,EAAIC,EACnBzC,EAAKpC,EAAEN,EACPoF,EAASC,CAGb,IAAI3C,EAAI,CAQJ4C,EAAK,CAGD,IAAM/C,EAAI,EAAGC,EAAIE,EAAG,GAAIF,GAAK,GAAIA,GAAK,GAAID,KAI1C,GAHArC,EAAI+E,EAAK1C,EAGA,EAAJrC,EACDA,GAAKgC,EACL0C,EAAIK,EACJnF,EAAI4C,EAAIwC,EAAK,GAGbC,EAAKrF,EAAIsF,EAAQ7C,EAAIqC,EAAI,GAAM,GAAK,MAIpC,IAFAM,EAAKK,GAAYrF,EAAI,GAAMgC,GAEtBgD,GAAMxC,EAAGpB,OAAS,CAEnB,IAAImB,EASA,KAAM6C,EANN,MAAQ5C,EAAGpB,QAAU4D,EAAIxC,EAAGP,KAAK,IACjCrC,EAAIqF,EAAK,EACT5C,EAAI,EACJrC,GAAKgC,EACL0C,EAAI1E,EAAIgC,EAAW,MAIpB,CAIH,IAHApC,EAAI0C,EAAIE,EAAGwC,GAGL3C,EAAI,EAAGC,GAAK,GAAIA,GAAK,GAAID,KAG/BrC,GAAKgC,EAIL0C,EAAI1E,EAAIgC,EAAWK,EAGnB4C,EAAS,EAAJP,EAAQ,EAAI9E,EAAIsF,EAAQ7C,EAAIqC,EAAI,GAAM,GAAK,EAmBxD,GAfAnC,EAAIA,GAAU,EAALwC,GAKO,MAAdvC,EAAGwC,EAAK,KAAoB,EAAJN,EAAQ9E,EAAIA,EAAIsF,EAAQ7C,EAAIqC,EAAI,IAE1DnC,EAAS,EAALI,GACEsC,GAAM1C,KAAe,GAANI,GAAWA,IAAQvC,EAAEc,EAAI,EAAI,EAAI,IAClD+D,EAAK,GAAW,GAANA,IAAmB,GAANtC,GAAWJ,GAAW,GAANI,IAGnC3C,EAAI,EAAI0E,EAAI,EAAI9E,EAAIsF,EAAQ7C,EAAIqC,GAAM,EAAIlC,EAAGwC,EAAK,IAAO,GAAO,GAClErC,IAAQvC,EAAEc,EAAI,EAAI,EAAI,IAElB,EAAL6D,IAAWvC,EAAG,GAiBf,MAhBAA,GAAGpB,OAAS,EAERmB,GAGAwC,GAAM3E,EAAEL,EAAI,EAGZyC,EAAG,GAAK0C,GAAUlD,EAAW+C,EAAK/C,GAAaA,GAC/C5B,EAAEL,GAAKgF,GAAM,GAIbvC,EAAG,GAAKpC,EAAEL,EAAI,EAGXK,CAkBX,IAdU,GAALJ,GACDwC,EAAGpB,OAAS4D,EACZ1C,EAAI,EACJ0C,MAEAxC,EAAGpB,OAAS4D,EAAK,EACjB1C,EAAI4C,EAAQlD,EAAWhC,GAIvBwC,EAAGwC,GAAMN,EAAI,EAAI7C,EAAWjC,EAAIsF,EAAQ7C,EAAIqC,GAAMQ,EAAOR,IAAOpC,EAAI,GAIpEC,EAEA,OAAY,CAGR,GAAW,GAANyC,EAAU,CAGX,IAAMhF,EAAI,EAAG0E,EAAIlC,EAAG,GAAIkC,GAAK,GAAIA,GAAK,GAAI1E,KAE1C,IADA0E,EAAIlC,EAAG,IAAMF,EACPA,EAAI,EAAGoC,GAAK,GAAIA,GAAK,GAAIpC,KAG1BtC,GAAKsC,IACNlC,EAAEL,IACGyC,EAAG,IAAM8C,IAAO9C,EAAG,GAAK,GAGjC,OAGA,GADAA,EAAGwC,IAAO1C,EACLE,EAAGwC,IAAOM,EAAO,KACtB9C,GAAGwC,KAAQ,EACX1C,EAAI,EAMhB,IAAMtC,EAAIwC,EAAGpB,OAAoB,IAAZoB,IAAKxC,GAAUwC,EAAGU,QAItC9C,EAAEL,EAAI+B,EACP1B,EAAEN,EAAIM,EAAEL,EAAI,KAGJK,EAAEL,EAAIgC,IACd3B,EAAEN,GAAMM,EAAEL,EAAI,IAItB,MAAOK,GAt0CX,GAAI+C,GAAKlC,EAGLR,EAAK,EACL8E,EAAI5F,EAAU6F,UACdC,EAAM,GAAI9F,GAAU,GAYpBgB,EAAiB,GAejBC,EAAgB,EAMhBgD,EAAa,GAIb8B,EAAa,GAMb3D,EAAU,KAKVD,EAAU,IAGVxB,GAAS,EAGTE,EAAa4D,EAGbuB,GAAS,EAoBTC,EAAc,EAId/C,EAAgB,EAGhBgD,GACIC,iBAAkB,IAClBC,eAAgB,IAChBC,UAAW,EACXC,mBAAoB,EACpBC,uBAAwB,IACxBC,kBAAmB,EAy3E3B,OApsEAxG,GAAUyG,QAAU3G,EAEpBE,EAAU0G,SAAW,EACrB1G,EAAU2G,WAAa,EACvB3G,EAAU4G,WAAa,EACvB5G,EAAU6G,YAAc,EACxB7G,EAAU8G,cAAgB,EAC1B9G,EAAU+G,gBAAkB,EAC5B/G,EAAUgH,gBAAkB,EAC5BhH,EAAUiH,gBAAkB,EAC5BjH,EAAUkH,iBAAmB,EAC7BlH,EAAUmH,OAAS,EAoCnBnH,EAAUoH,OAASpH,EAAUqH,IAAM,WAC/B,GAAIC,GAAGC,EACHlH,EAAI,EACJuC,KACA4E,EAAIC,UACJC,EAAIF,EAAE,GACNG,EAAMD,GAAiB,gBAALA,GACd,WAAc,MAAKA,GAAEE,eAAeL,GAA4B,OAAdD,EAAII,EAAEH,IAA1C,QACd,WAAc,MAAKC,GAAE/F,OAASpB,EAA6B,OAAhBiH,EAAIE,EAAEnH,MAAnC,OAuHtB,OAlHKsH,GAAKJ,EAAI,mBAAsB1G,EAAYyG,EAAG,EAAGO,EAAK,EAAGN,KAC1DvG,EAAqB,EAAJsG,GAErB1E,EAAE2E,GAAKvG,EAKF2G,EAAKJ,EAAI,kBAAqB1G,EAAYyG,EAAG,EAAG,EAAG,EAAGC,KACvDtG,EAAoB,EAAJqG,GAEpB1E,EAAE2E,GAAKtG,EAMF0G,EAAKJ,EAAI,oBAELhD,EAAQ+C,GACJzG,EAAYyG,EAAE,IAAKO,EAAK,EAAG,EAAGN,IAAO1G,EAAYyG,EAAE,GAAI,EAAGO,EAAK,EAAGN,KACnEtD,EAAoB,EAAPqD,EAAE,GACfvB,EAAoB,EAAPuB,EAAE,IAEXzG,EAAYyG,GAAIO,EAAKA,EAAK,EAAGN,KACrCtD,IAAgB8B,EAAkC,GAAf,EAAJuB,GAASA,EAAIA,MAGpD1E,EAAE2E,IAAOtD,EAAY8B,GAOhB4B,EAAKJ,EAAI,WAELhD,EAAQ+C,GACJzG,EAAYyG,EAAE,IAAKO,EAAK,GAAI,EAAGN,IAAO1G,EAAYyG,EAAE,GAAI,EAAGO,EAAK,EAAGN,KACpEnF,EAAiB,EAAPkF,EAAE,GACZnF,EAAiB,EAAPmF,EAAE,IAERzG,EAAYyG,GAAIO,EAAKA,EAAK,EAAGN,KAC5B,EAAJD,EAAQlF,IAAaD,EAA+B,GAAf,EAAJmF,GAASA,EAAIA,IAC1C3G,GAAQC,EAAO,EAAG2G,EAAI,kBAAmBD,KAG1D1E,EAAE2E,IAAOnF,EAASD,GAIbwF,EAAKJ,EAAI,YAELD,MAAQA,GAAW,IAANA,GAAiB,IAANA,GACzBxG,EAAK,EACLD,GAAeF,IAAW2G,GAAM7C,EAAyBqD,GAClDnH,GACPC,EAAO,EAAG2G,EAAIQ,EAAST,IAG/B1E,EAAE2E,GAAK5G,EAKFgH,EAAKJ,EAAI,YAELD,KAAM,GAAQA,KAAM,GAAe,IAANA,GAAiB,IAANA,EACrCA,GACAA,EAAqB,mBAAVU,SACLV,GAAKU,SAAWA,OAAOC,iBAAmBD,OAAOE,aACnDlC,GAAS,EACFrF,EACPC,EAAO,EAAG,qBAAsB0G,EAAI,OAASU,QAE7ChC,GAAS,GAGbA,GAAS,EAENrF,GACPC,EAAO,EAAG2G,EAAIQ,EAAST,IAG/B1E,EAAE2E,GAAKvB,EAKF2B,EAAKJ,EAAI,gBAAmB1G,EAAYyG,EAAG,EAAG,EAAG,EAAGC,KACrDtB,EAAkB,EAAJqB,GAElB1E,EAAE2E,GAAKtB,EAKF0B,EAAKJ,EAAI,kBAAqB1G,EAAYyG,EAAG,EAAGO,EAAK,EAAGN,KACzDrE,EAAoB,EAAJoE,GAEpB1E,EAAE2E,GAAKrE,EAIFyE,EAAKJ,EAAI,YAEO,gBAALD,GACRpB,EAASoB,EACF3G,GACPC,EAAO,EAAG2G,EAAI,iBAAkBD,IAGxC1E,EAAE2E,GAAKrB,EAEAtD,GASX5C,EAAUmI,YAAcA,EAQxBnI,EAAU2E,IAAM,WAAc,MAAOR,GAAUsD,UAAW7B,EAAEwC,KAQ5DpI,EAAU0E,IAAM,WAAc,MAAOP,GAAUsD,UAAW7B,EAAEyC,KAc5DrI,EAAUsI,OAAS,WACf,GAAIC,GAAU,iBAMVC,EAAkBC,KAAKH,SAAWC,EAAW,QAC7C,WAAc,MAAOrG,GAAWuG,KAAKH,SAAWC,IAChD,WAAc,MAA2C,UAAlB,WAAhBE,KAAKH,SAAwB,IACjC,QAAhBG,KAAKH,SAAsB,GAElC,OAAO,UAAUvF,GACb,GAAIyE,GAAGtH,EAAGE,EAAGuC,EAAG2E,EACZjH,EAAI,EACJF,KACAuI,EAAO,GAAI1I,GAAU8F,EAKzB,IAHA/C,EAAW,MAANA,GAAelC,EAAYkC,EAAI,EAAG8E,EAAK,IAA6B,EAAL9E,EAAjB/B,EACnD2B,EAAI+C,EAAU3C,EAAKV,GAEf2D,EAGA,GAAIgC,OAAOC,gBAAiB,CAIxB,IAFAT,EAAIQ,OAAOC,gBAAiB,GAAIU,aAAahG,GAAK,IAEtCA,EAAJtC,GAQJiH,EAAW,OAAPE,EAAEnH,IAAgBmH,EAAEnH,EAAI,KAAO,IAM9BiH,GAAK,MACNpH,EAAI8H,OAAOC,gBAAiB,GAAIU,aAAY,IAC5CnB,EAAEnH,GAAKH,EAAE,GACTsH,EAAEnH,EAAI,GAAKH,EAAE,KAKbC,EAAEmC,KAAMgF,EAAI,MACZjH,GAAK,EAGbA,GAAIsC,EAAI,MAGL,IAAIqF,OAAOE,YAAa,CAK3B,IAFAV,EAAIQ,OAAOE,YAAavF,GAAK,GAEjBA,EAAJtC,GAMJiH,EAAsB,iBAAP,GAAPE,EAAEnH,IAA6C,cAAXmH,EAAEnH,EAAI,GAC/B,WAAXmH,EAAEnH,EAAI,GAAkC,SAAXmH,EAAEnH,EAAI,IACnCmH,EAAEnH,EAAI,IAAM,KAASmH,EAAEnH,EAAI,IAAM,GAAMmH,EAAEnH,EAAI,GAEhDiH,GAAK,KACNU,OAAOE,YAAY,GAAGU,KAAMpB,EAAGnH,IAI/BF,EAAEmC,KAAMgF,EAAI,MACZjH,GAAK,EAGbA,GAAIsC,EAAI,MAERqD,IAAS,EACLrF,GAAQC,EAAO,GAAI,qBAAsBoH,OAKrD,KAAKhC,EAED,KAAYrD,EAAJtC,GACJiH,EAAIkB,IACK,KAAJlB,IAAWnH,EAAEE,KAAOiH,EAAI,KAcrC,KAVA3E,EAAIxC,IAAIE,GACR0C,GAAMV,EAGDM,GAAKI,IACNuE,EAAI9B,EAASnD,EAAWU,GACxB5C,EAAEE,GAAK6B,EAAWS,EAAI2E,GAAMA,GAIf,IAATnH,EAAEE,GAAUF,EAAEoD,MAAOlD,KAG7B,GAAS,EAAJA,EACDF,GAAMC,EAAI,OACP,CAGH,IAAMA,EAAI,GAAc,IAATD,EAAE,GAAUA,EAAE0I,QAASzI,GAAKiC,GAG3C,IAAMhC,EAAI,EAAGiH,EAAInH,EAAE,GAAImH,GAAK,GAAIA,GAAK,GAAIjH,KAGhCgC,EAAJhC,IAAeD,GAAKiC,EAAWhC,GAKxC,MAFAqI,GAAKtI,EAAIA,EACTsI,EAAKvI,EAAIA,EACFuI,MAqGflF,EAAM,WAGF,QAASsF,GAAUrI,EAAGkC,EAAGoG,GACrB,GAAIzE,GAAG0E,EAAMC,EAAKC,EACdC,EAAQ,EACR9I,EAAII,EAAEgB,OACN2H,EAAMzG,EAAI0G,EACVC,EAAM3G,EAAI0G,EAAY,CAE1B,KAAM5I,EAAIA,EAAEW,QAASf,KACjB4I,EAAMxI,EAAEJ,GAAKgJ,EACbH,EAAMzI,EAAEJ,GAAKgJ,EAAY,EACzB/E,EAAIgF,EAAML,EAAMC,EAAME,EACtBJ,EAAOI,EAAMH,EAAU3E,EAAI+E,EAAcA,EAAcF,EACvDA,GAAUH,EAAOD,EAAO,IAAQzE,EAAI+E,EAAY,GAAMC,EAAMJ,EAC5DzI,EAAEJ,GAAK2I,EAAOD,CAKlB,OAFII,IAAO1I,EAAEgD,QAAQ0F,GAEd1I,EAGX,QAAS8I,GAAS/B,EAAGtH,EAAGsJ,EAAIC,GACxB,GAAIpJ,GAAGqJ,CAEP,IAAKF,GAAMC,EACPC,EAAMF,EAAKC,EAAK,EAAI,OAGpB,KAAMpJ,EAAIqJ,EAAM,EAAOF,EAAJnJ,EAAQA,IAEvB,GAAKmH,EAAEnH,IAAMH,EAAEG,GAAK,CAChBqJ,EAAMlC,EAAEnH,GAAKH,EAAEG,GAAK,EAAI,EACxB,OAIZ,MAAOqJ,GAGX,QAASC,GAAUnC,EAAGtH,EAAGsJ,EAAIT,GAIzB,IAHA,GAAI1I,GAAI,EAGAmJ,KACJhC,EAAEgC,IAAOnJ,EACTA,EAAImH,EAAEgC,GAAMtJ,EAAEsJ,GAAM,EAAI,EACxBhC,EAAEgC,GAAMnJ,EAAI0I,EAAOvB,EAAEgC,GAAMtJ,EAAEsJ,EAIjC,OAAShC,EAAE,IAAMA,EAAE/F,OAAS,EAAG+F,EAAEqB,UAIrC,MAAO,UAAWpI,EAAGqC,EAAGC,EAAIC,EAAI+F,GAC5B,GAAIW,GAAKtJ,EAAGC,EAAGuJ,EAAM3J,EAAG4J,EAAMC,EAAOC,EAAGC,EAAIC,EAAKC,EAAMC,EAAMC,EAAIC,EAAIC,EACjEC,EAAIC,EACJjJ,EAAId,EAAEc,GAAKuB,EAAEvB,EAAI,EAAI,GACrBsB,EAAKpC,EAAEN,EACPsK,EAAK3H,EAAE3C,CAGX,MAAM0C,GAAOA,EAAG,IAAO4H,GAAOA,EAAG,IAE7B,MAAO,IAAIzK,GAGRS,EAAEc,GAAMuB,EAAEvB,IAAOsB,GAAK4H,GAAM5H,EAAG,IAAM4H,EAAG,GAAMA,GAG7C5H,GAAe,GAATA,EAAG,KAAY4H,EAAS,EAAJlJ,EAAQA,EAAI,EAHcmJ,IAoB5D,KAbAX,EAAI,GAAI/J,GAAUuB,GAClByI,EAAKD,EAAE5J,KACPC,EAAIK,EAAEL,EAAI0C,EAAE1C,EACZmB,EAAIwB,EAAK3C,EAAI,EAEP2I,IACFA,EAAOpD,EACPvF,EAAIuK,EAAUlK,EAAEL,EAAIiC,GAAasI,EAAU7H,EAAE1C,EAAIiC,GACjDd,EAAIA,EAAIc,EAAW,GAKjBhC,EAAI,EAAGoK,EAAGpK,KAAQwC,EAAGxC,IAAM,GAAKA,KAGtC,GAFKoK,EAAGpK,IAAOwC,EAAGxC,IAAM,IAAMD,IAErB,EAAJmB,EACDyI,EAAG1H,KAAK,GACRsH,GAAO,MACJ,CAwBH,IAvBAS,EAAKxH,EAAGpB,OACR8I,EAAKE,EAAGhJ,OACRpB,EAAI,EACJkB,GAAK,EAILtB,EAAIiC,EAAW6G,GAAS0B,EAAG,GAAK,IAI3BxK,EAAI,IACLwK,EAAK3B,EAAU2B,EAAIxK,EAAG8I,GACtBlG,EAAKiG,EAAUjG,EAAI5C,EAAG8I,GACtBwB,EAAKE,EAAGhJ,OACR4I,EAAKxH,EAAGpB,QAGZ2I,EAAKG,EACLN,EAAMpH,EAAGzB,MAAO,EAAGmJ,GACnBL,EAAOD,EAAIxI,OAGI8I,EAAPL,EAAWD,EAAIC,KAAU,GACjCM,EAAKC,EAAGrJ,QACRoJ,EAAG/G,QAAQ,GACX6G,EAAMG,EAAG,GACJA,EAAG,IAAM1B,EAAO,GAAIuB,GAIzB,GAAG,CAOC,GANArK,EAAI,EAGJyJ,EAAMH,EAASkB,EAAIR,EAAKM,EAAIL,GAGjB,EAANR,EAAU,CAkBX,GAdAS,EAAOF,EAAI,GACNM,GAAML,IAAOC,EAAOA,EAAOpB,GAASkB,EAAI,IAAM,IAGnDhK,EAAIiC,EAAWiI,EAAOG,GAUjBrK,EAAI,EAeL,IAZIA,GAAK8I,IAAM9I,EAAI8I,EAAO,GAG1Bc,EAAOf,EAAU2B,EAAIxK,EAAG8I,GACxBe,EAAQD,EAAKpI,OACbyI,EAAOD,EAAIxI,OAOkC,GAArC8H,EAASM,EAAMI,EAAKH,EAAOI,IAC/BjK,IAGA0J,EAAUE,EAAWC,EAALS,EAAaC,EAAKC,EAAIX,EAAOf,GAC7Ce,EAAQD,EAAKpI,OACbiI,EAAM,MAQA,IAALzJ,IAGDyJ,EAAMzJ,EAAI,GAId4J,EAAOY,EAAGrJ,QACV0I,EAAQD,EAAKpI,MAUjB,IAPayI,EAARJ,GAAeD,EAAKpG,QAAQ,GAGjCkG,EAAUM,EAAKJ,EAAMK,EAAMnB,GAC3BmB,EAAOD,EAAIxI,OAGC,IAAPiI,EAMD,KAAQH,EAASkB,EAAIR,EAAKM,EAAIL,GAAS,GACnCjK,IAGA0J,EAAUM,EAAUC,EAALK,EAAYC,EAAKC,EAAIP,EAAMnB,GAC1CmB,EAAOD,EAAIxI,WAGH,KAARiI,IACRzJ,IACAgK,GAAO,GAIXD,GAAG3J,KAAOJ,EAGLgK,EAAI,GACLA,EAAIC,KAAUrH,EAAGuH,IAAO,GAExBH,GAAQpH,EAAGuH,IACXF,EAAO,UAEHE,IAAOC,GAAgB,MAAVJ,EAAI,KAAgB1I,IAE7CqI,GAAiB,MAAVK,EAAI,GAGLD,EAAG,IAAKA,EAAGnB,QAGrB,GAAKE,GAAQpD,EAAO,CAGhB,IAAMtF,EAAI,EAAGkB,EAAIyI,EAAG,GAAIzI,GAAK,GAAIA,GAAK,GAAIlB,KAC1CU,EAAOgJ,EAAGhH,GAAOgH,EAAE3J,EAAIC,EAAID,EAAIiC,EAAW,GAAM,EAAGW,EAAI4G,OAIvDG,GAAE3J,EAAIA,EACN2J,EAAEnH,GAAKgH,CAGX,OAAOG,OAgJfzI,EAAe,WACX,GAAIsJ,GAAa,8BACbC,EAAW,cACXC,EAAY,cACZC,EAAkB,qBAClBC,EAAmB,4BAEvB,OAAO,UAAWvK,EAAGD,EAAKF,EAAKJ,GAC3B,GAAI6I,GACAxH,EAAIjB,EAAME,EAAMA,EAAIgB,QAASwJ,EAAkB,GAGnD,IAAKD,EAAgB1J,KAAKE,GACtBd,EAAEc,EAAI0J,MAAM1J,GAAK,KAAW,EAAJA,EAAQ,GAAK,MAClC,CACH,IAAMjB,IAGFiB,EAAIA,EAAEC,QAASoJ,EAAY,SAAWtG,EAAG4G,EAAIC,GAEzC,MADApC,GAAoC,MAA3BoC,EAAKA,EAAGlI,eAAyB,GAAW,KAANkI,EAAY,EAAI,EACvDjL,GAAKA,GAAK6I,EAAYzE,EAAL4G,IAGzBhL,IACA6I,EAAO7I,EAGPqB,EAAIA,EAAEC,QAASqJ,EAAU,MAAOrJ,QAASsJ,EAAW,SAGnDtK,GAAOe,GAAI,MAAO,IAAIvB,GAAWuB,EAAGwH,EAKzCpI,IAAQC,EAAOE,EAAI,SAAYZ,EAAI,SAAWA,EAAI,IAAO,UAAWM,GACxEC,EAAEc,EAAI,KAGVd,EAAEN,EAAIM,EAAEL,EAAI,KACZU,EAAK,MAmNb8E,EAAEwF,cAAgBxF,EAAEyF,IAAM,WACtB,GAAI5K,GAAI,GAAIT,GAAUU,KAEtB,OADKD,GAAEc,EAAI,IAAId,EAAEc,EAAI,GACdd,GAQXmF,EAAE0F,KAAO,WACL,MAAOvK,GAAO,GAAIf,GAAUU,MAAOA,KAAKN,EAAI,EAAG,IAWnDwF,EAAE2F,WAAa3F,EAAE8D,IAAM,SAAW5G,EAAG5C,GAEjC,MADAY,GAAK,EACEyI,EAAS7I,KAAM,GAAIV,GAAW8C,EAAG5C,KAQ5C0F,EAAE4F,cAAgB5F,EAAE7C,GAAK,WACrB,GAAI9C,GAAGqH,EACHnH,EAAIO,KAAKP,CAEb,KAAMA,EAAI,MAAO,KAIjB,IAHAF,IAAQqH,EAAInH,EAAEsB,OAAS,GAAMkJ,EAAUjK,KAAKN,EAAIiC,IAAeA,EAG1DiF,EAAInH,EAAEmH,GAAK,KAAQA,EAAI,IAAM,EAAGA,GAAK,GAAIrH,KAG9C,MAFS,GAAJA,IAAQA,EAAI,GAEVA,GAwBX2F,EAAE6F,UAAY7F,EAAEpC,IAAM,SAAWV,EAAG5C,GAEhC,MADAY,GAAK,EACE0C,EAAK9C,KAAM,GAAIV,GAAW8C,EAAG5C,GAAKc,EAAgBC,IAQ7D2E,EAAE8F,mBAAqB9F,EAAE+F,SAAW,SAAW7I,EAAG5C,GAE9C,MADAY,GAAK,EACE0C,EAAK9C,KAAM,GAAIV,GAAW8C,EAAG5C,GAAK,EAAG,IAQhD0F,EAAEgG,OAAShG,EAAEiG,GAAK,SAAW/I,EAAG5C,GAE5B,MADAY,GAAK,EAC6C,IAA3CyI,EAAS7I,KAAM,GAAIV,GAAW8C,EAAG5C,KAQ5C0F,EAAEkG,MAAQ,WACN,MAAO/K,GAAO,GAAIf,GAAUU,MAAOA,KAAKN,EAAI,EAAG,IAQnDwF,EAAEmG,YAAcnG,EAAEyC,GAAK,SAAWvF,EAAG5C,GAEjC,MADAY,GAAK,EACEyI,EAAS7I,KAAM,GAAIV,GAAW8C,EAAG5C,IAAQ,GAQpD0F,EAAEoG,qBAAuBpG,EAAEqG,IAAM,SAAWnJ,EAAG5C,GAE3C,MADAY,GAAK,EACqD,KAAjDZ,EAAIqJ,EAAS7I,KAAM,GAAIV,GAAW8C,EAAG5C,MAAuB,IAANA,GAQnE0F,EAAEsG,SAAW,WACT,QAASxL,KAAKP,GAOlByF,EAAEuG,UAAYvG,EAAEwG,MAAQ,WACpB,QAAS1L,KAAKP,GAAKwK,EAAUjK,KAAKN,EAAIiC,GAAa3B,KAAKP,EAAEsB,OAAS,GAOvEmE,EAAEqF,MAAQ,WACN,OAAQvK,KAAKa,GAOjBqE,EAAEyG,WAAazG,EAAE0G,MAAQ,WACrB,MAAO5L,MAAKa,EAAI,GAOpBqE,EAAE2G,OAAS,WACP,QAAS7L,KAAKP,GAAkB,GAAbO,KAAKP,EAAE,IAQ9ByF,EAAE4G,SAAW5G,EAAEwC,GAAK,SAAWtF,EAAG5C,GAE9B,MADAY,GAAK,EACEyI,EAAS7I,KAAM,GAAIV,GAAW8C,EAAG5C,IAAQ,GAQpD0F,EAAE6G,kBAAoB7G,EAAE8G,IAAM,SAAW5J,EAAG5C,GAExC,MADAY,GAAK,EACqD,MAAjDZ,EAAIqJ,EAAS7I,KAAM,GAAIV,GAAW8C,EAAG5C,MAAwB,IAANA,GAwBpE0F,EAAE+G,MAAQ/G,EAAEgH,IAAM,SAAW9J,EAAG5C,GAC5B,GAAIG,GAAG0E,EAAG8H,EAAGC,EACTrM,EAAIC,KACJ8G,EAAI/G,EAAEc,CAOV,IALAT,EAAK,GACLgC,EAAI,GAAI9C,GAAW8C,EAAG5C,GACtBA,EAAI4C,EAAEvB,GAGAiG,IAAMtH,EAAI,MAAO,IAAIF,GAAU0K,IAGrC,IAAKlD,GAAKtH,EAEN,MADA4C,GAAEvB,GAAKrB,EACAO,EAAEsM,KAAKjK,EAGlB,IAAIkK,GAAKvM,EAAEL,EAAIiC,EACX4K,EAAKnK,EAAE1C,EAAIiC,EACXQ,EAAKpC,EAAEN,EACPsK,EAAK3H,EAAE3C,CAEX,KAAM6M,IAAOC,EAAK,CAGd,IAAMpK,IAAO4H,EAAK,MAAO5H,IAAOC,EAAEvB,GAAKrB,EAAG4C,GAAM,GAAI9C,GAAWyK,EAAKhK,EAAIiK,IAGxE,KAAM7H,EAAG,KAAO4H,EAAG,GAGf,MAAOA,GAAG,IAAO3H,EAAEvB,GAAKrB,EAAG4C,GAAM,GAAI9C,GAAW6C,EAAG,GAAKpC,EAGrC,GAAjBQ,GAAsB,EAAI,GASpC,GALA+L,EAAKrC,EAASqC,GACdC,EAAKtC,EAASsC,GACdpK,EAAKA,EAAGzB,QAGHoG,EAAIwF,EAAKC,EAAK,CAaf,KAXKH,EAAW,EAAJtF,IACRA,GAAKA,EACLqF,EAAIhK,IAEJoK,EAAKD,EACLH,EAAIpC,GAGRoC,EAAEK,UAGIhN,EAAIsH,EAAGtH,IAAK2M,EAAEvK,KAAK,IACzBuK,EAAEK,cAMF,KAFAnI,GAAM+H,GAAStF,EAAI3E,EAAGpB,SAAavB,EAAIuK,EAAGhJ,SAAa+F,EAAItH,EAErDsH,EAAItH,EAAI,EAAO6E,EAAJ7E,EAAOA,IAEpB,GAAK2C,EAAG3C,IAAMuK,EAAGvK,GAAK,CAClB4M,EAAOjK,EAAG3C,GAAKuK,EAAGvK,EAClB,OAYZ,GANI4M,IAAMD,EAAIhK,EAAIA,EAAK4H,EAAIA,EAAKoC,EAAG/J,EAAEvB,GAAKuB,EAAEvB,GAE5CrB,GAAM6E,EAAI0F,EAAGhJ,SAAapB,EAAIwC,EAAGpB,QAI5BvB,EAAI,EAAI,KAAQA,IAAK2C,EAAGxC,KAAO,GAIpC,IAHAH,EAAIyF,EAAO,EAGHZ,EAAIyC,GAAK,CAEb,GAAK3E,IAAKkC,GAAK0F,EAAG1F,GAAK,CACnB,IAAM1E,EAAI0E,EAAG1E,IAAMwC,IAAKxC,GAAIwC,EAAGxC,GAAKH,KAClC2C,EAAGxC,GACLwC,EAAGkC,IAAMY,EAGb9C,EAAGkC,IAAM0F,EAAG1F,GAIhB,KAAiB,GAATlC,EAAG,GAASA,EAAGgG,UAAWoE,GAGlC,MAAMpK,GAAG,GAWFiC,EAAWhC,EAAGD,EAAIoK,IAPrBnK,EAAEvB,EAAqB,GAAjBN,EAAqB,GAAK,EAChC6B,EAAE3C,GAAM2C,EAAE1C,EAAI,GACP0C,IA8Bf8C,EAAEuH,OAASvH,EAAEwH,IAAM,SAAWtK,EAAG5C,GAC7B,GAAI6J,GAAGxI,EACHd,EAAIC,IAMR,OAJAI,GAAK,GACLgC,EAAI,GAAI9C,GAAW8C,EAAG5C,IAGhBO,EAAEN,IAAM2C,EAAEvB,GAAKuB,EAAE3C,IAAM2C,EAAE3C,EAAE,GACtB,GAAIH,GAAU0K,MAGZ5H,EAAE3C,GAAKM,EAAEN,IAAMM,EAAEN,EAAE,GACrB,GAAIH,GAAUS,IAGL,GAAfwF,GAID1E,EAAIuB,EAAEvB,EACNuB,EAAEvB,EAAI,EACNwI,EAAIvG,EAAK/C,EAAGqC,EAAG,EAAG,GAClBA,EAAEvB,EAAIA,EACNwI,EAAExI,GAAKA,GAEPwI,EAAIvG,EAAK/C,EAAGqC,EAAG,EAAGmD,GAGfxF,EAAEkM,MAAO5C,EAAEsD,MAAMvK,MAQ5B8C,EAAE0H,QAAU1H,EAAE2H,IAAM,WAChB,GAAI9M,GAAI,GAAIT,GAAUU,KAEtB,OADAD,GAAEc,GAAKd,EAAEc,GAAK,KACPd,GAwBXmF,EAAEmH,KAAOnH,EAAE4H,IAAM,SAAW1K,EAAG5C,GAC3B,GAAI2M,GACApM,EAAIC,KACJ8G,EAAI/G,EAAEc,CAOV,IALAT,EAAK,GACLgC,EAAI,GAAI9C,GAAW8C,EAAG5C,GACtBA,EAAI4C,EAAEvB,GAGAiG,IAAMtH,EAAI,MAAO,IAAIF,GAAU0K,IAGpC,IAAKlD,GAAKtH,EAEP,MADA4C,GAAEvB,GAAKrB,EACAO,EAAEkM,MAAM7J,EAGnB,IAAIkK,GAAKvM,EAAEL,EAAIiC,EACX4K,EAAKnK,EAAE1C,EAAIiC,EACXQ,EAAKpC,EAAEN,EACPsK,EAAK3H,EAAE3C,CAEX,KAAM6M,IAAOC,EAAK,CAGd,IAAMpK,IAAO4H,EAAK,MAAO,IAAIzK,GAAWwH,EAAI,EAI5C,KAAM3E,EAAG,KAAO4H,EAAG,GAAK,MAAOA,GAAG,GAAK3H,EAAI,GAAI9C,GAAW6C,EAAG,GAAKpC,EAAQ,EAAJ+G,GAQ1E,GALAwF,EAAKrC,EAASqC,GACdC,EAAKtC,EAASsC,GACdpK,EAAKA,EAAGzB,QAGHoG,EAAIwF,EAAKC,EAAK,CAUf,IATKzF,EAAI,GACLyF,EAAKD,EACLH,EAAIpC,IAEJjD,GAAKA,EACLqF,EAAIhK,GAGRgK,EAAEK,UACM1F,IAAKqF,EAAEvK,KAAK,IACpBuK,EAAEK,UAUN,IAPA1F,EAAI3E,EAAGpB,OACPvB,EAAIuK,EAAGhJ,OAGM,EAAR+F,EAAItH,IAAQ2M,EAAIpC,EAAIA,EAAK5H,EAAIA,EAAKgK,EAAG3M,EAAIsH,GAGxCA,EAAI,EAAGtH,GACTsH,GAAM3E,IAAK3C,GAAK2C,EAAG3C,GAAKuK,EAAGvK,GAAKsH,GAAM7B,EAAO,EAC7C9C,EAAG3C,GAAKyF,IAAS9C,EAAG3C,GAAK,EAAI2C,EAAG3C,GAAKyF,CAUzC,OAPI6B,KACA3E,EAAGY,QAAQ+D,KACTyF,GAKCnI,EAAWhC,EAAGD,EAAIoK,IAS7BrH,EAAE6H,UAAY7H,EAAER,GAAK,SAAUsI,GAC3B,GAAIzN,GAAGqH,EACH7G,EAAIC,KACJP,EAAIM,EAAEN,CAQV,IALU,MAALuN,GAAaA,MAAQA,GAAW,IAANA,GAAiB,IAANA,IAClC/M,GAAQC,EAAO,GAAI,WAAamH,EAAS2F,GACxCA,KAAOA,IAAIA,EAAI,QAGlBvN,EAAI,MAAO,KAIjB,IAHAmH,EAAInH,EAAEsB,OAAS,EACfxB,EAAIqH,EAAIjF,EAAW,EAEdiF,EAAInH,EAAEmH,GAAK,CAGZ,KAAQA,EAAI,IAAM,EAAGA,GAAK,GAAIrH,KAG9B,IAAMqH,EAAInH,EAAE,GAAImH,GAAK,GAAIA,GAAK,GAAIrH,MAKtC,MAFKyN,IAAKjN,EAAEL,EAAI,EAAIH,IAAIA,EAAIQ,EAAEL,EAAI,GAE3BH,GAiBX2F,EAAE7E,MAAQ,SAAWgC,EAAIC,GACrB,GAAI/C,GAAI,GAAID,GAAUU,KAOtB,QALW,MAANqC,GAAclC,EAAYkC,EAAI,EAAG8E,EAAK,MACvC9G,EAAOd,IAAK8C,EAAKrC,KAAKN,EAAI,EAAS,MAAN4C,GAC1BnC,EAAYmC,EAAI,EAAG,EAAG,GAAIe,GAAsC,EAALf,EAAhB/B,GAG3ChB,GAgBX2F,EAAEiD,MAAQ,SAAUlG,GAChB,GAAI1C,GAAIS,IACR,OAAOG,GAAY8B,GAAIV,EAAkBA,EAAkB,GAAI,YAG3DhC,EAAEoN,MAAO,KAAOxI,EAASlC,IACzB,GAAI3C,GAAWC,EAAEE,GAAKF,EAAEE,EAAE,MAAa8B,EAALU,GAAyBA,EAAIV,GAC7DhC,EAAEsB,GAAU,EAAJoB,EAAQ,EAAI,EAAI,GACxB1C,IAeV2F,EAAE+H,WAAa/H,EAAEgI,KAAO,WACpB,GAAItJ,GAAGrE,EAAG2C,EAAGiL,EAAKhB,EACdpM,EAAIC,KACJP,EAAIM,EAAEN,EACNoB,EAAId,EAAEc,EACNnB,EAAIK,EAAEL,EACN2C,EAAK/B,EAAiB,EACtB8M,EAAO,GAAI9N,GAAU,MAGzB,IAAW,IAANuB,IAAYpB,IAAMA,EAAE,GACrB,MAAO,IAAIH,IAAYuB,GAAS,EAAJA,KAAYpB,GAAKA,EAAE,IAAOuK,IAAMvK,EAAIM,EAAI,EAAI,EA8B5E,IA1BAc,EAAIkH,KAAKmF,MAAOnN,GAIN,GAALc,GAAUA,GAAK,EAAI,GACpBtB,EAAIqD,EAAcnD,IACXF,EAAEwB,OAASrB,GAAM,GAAK,IAAIH,GAAK,KACtCsB,EAAIkH,KAAKmF,KAAK3N,GACdG,EAAIuK,GAAYvK,EAAI,GAAM,IAAY,EAAJA,GAASA,EAAI,GAE1CmB,GAAK,EAAI,EACVtB,EAAI,KAAOG,GAEXH,EAAIsB,EAAE2C,gBACNjE,EAAIA,EAAEmB,MAAO,EAAGnB,EAAE6B,QAAQ,KAAO,GAAM1B,GAG3CwC,EAAI,GAAI5C,GAAUC,IAElB2C,EAAI,GAAI5C,GAAWuB,EAAI,IAOtBqB,EAAEzC,EAAE,GAML,IALAC,EAAIwC,EAAExC,EACNmB,EAAInB,EAAI2C,EACC,EAAJxB,IAAQA,EAAI,KAOb,GAHAsL,EAAIjK,EACJA,EAAIkL,EAAKT,MAAOR,EAAEE,KAAMvJ,EAAK/C,EAAGoM,EAAG9J,EAAI,KAElCO,EAAeuJ,EAAE1M,GAAMiB,MAAO,EAAGG,MAAUtB,EAC3CqD,EAAeV,EAAEzC,IAAMiB,MAAO,EAAGG,GAAM,CAWxC,GANKqB,EAAExC,EAAIA,KAAMmB,EACjBtB,EAAIA,EAAEmB,MAAOG,EAAI,EAAGA,EAAI,GAKd,QAALtB,IAAgB4N,GAAY,QAAL5N,GAgBrB,IAIIA,KAAOA,EAAEmB,MAAM,IAAqB,KAAfnB,EAAEyD,OAAO,MAGjC3C,EAAO6B,EAAGA,EAAExC,EAAIY,EAAiB,EAAG,GACpCsD,GAAK1B,EAAEyK,MAAMzK,GAAGiJ,GAAGpL,GAGvB,OAvBA,IAAMoN,IACF9M,EAAO8L,EAAGA,EAAEzM,EAAIY,EAAiB,EAAG,GAE/B6L,EAAEQ,MAAMR,GAAGhB,GAAGpL,IAAK,CACpBmC,EAAIiK,CACJ,OAIR9J,GAAM,EACNxB,GAAK,EACLsM,EAAM,EAkBtB,MAAO9M,GAAO6B,EAAGA,EAAExC,EAAIY,EAAiB,EAAGC,EAAeqD,IAwB9DsB,EAAEyH,MAAQzH,EAAEmI,IAAM,SAAWjL,EAAG5C,GAC5B,GAAIC,GAAGC,EAAGC,EAAG0E,EAAGpC,EAAG2B,EAAG0J,EAAK/E,EAAKC,EAAK+E,EAAKC,EAAKC,EAAKC,EAChDrF,EAAMsF,EACN5N,EAAIC,KACJmC,EAAKpC,EAAEN,EACPsK,GAAO3J,EAAK,GAAIgC,EAAI,GAAI9C,GAAW8C,EAAG5C,IAAMC,CAGhD,MAAM0C,GAAO4H,GAAO5H,EAAG,IAAO4H,EAAG,IAmB7B,OAhBMhK,EAAEc,IAAMuB,EAAEvB,GAAKsB,IAAOA,EAAG,KAAO4H,GAAMA,IAAOA,EAAG,KAAO5H,EACzDC,EAAE3C,EAAI2C,EAAE1C,EAAI0C,EAAEvB,EAAI,MAElBuB,EAAEvB,GAAKd,EAAEc,EAGHsB,GAAO4H,GAKT3H,EAAE3C,GAAK,GACP2C,EAAE1C,EAAI,GALN0C,EAAE3C,EAAI2C,EAAE1C,EAAI,MASb0C,CAYX,KATA1C,EAAIuK,EAAUlK,EAAEL,EAAIiC,GAAasI,EAAU7H,EAAE1C,EAAIiC,GACjDS,EAAEvB,GAAKd,EAAEc,EACTyM,EAAMnL,EAAGpB,OACTwM,EAAMxD,EAAGhJ,OAGEwM,EAAND,IAAYI,EAAKvL,EAAIA,EAAK4H,EAAIA,EAAK2D,EAAI/N,EAAI2N,EAAKA,EAAMC,EAAKA,EAAM5N,GAGhEA,EAAI2N,EAAMC,EAAKG,KAAS/N,IAAK+N,EAAG9L,KAAK,IAK3C,IAHAyG,EAAOpD,EACP0I,EAAWhF,EAELhJ,EAAI4N,IAAO5N,GAAK,GAAK,CAKvB,IAJAF,EAAI,EACJ+N,EAAMzD,EAAGpK,GAAKgO,EACdF,EAAM1D,EAAGpK,GAAKgO,EAAW,EAEnB1L,EAAIqL,EAAKjJ,EAAI1E,EAAIsC,EAAGoC,EAAI1E,GAC1B4I,EAAMpG,IAAKF,GAAK0L,EAChBnF,EAAMrG,EAAGF,GAAK0L,EAAW,EACzB/J,EAAI6J,EAAMlF,EAAMC,EAAMgF,EACtBjF,EAAMiF,EAAMjF,EAAU3E,EAAI+J,EAAaA,EAAaD,EAAGrJ,GAAK5E,EAC5DA,GAAM8I,EAAMF,EAAO,IAAQzE,EAAI+J,EAAW,GAAMF,EAAMjF,EACtDkF,EAAGrJ,KAAOkE,EAAMF,CAGpBqF,GAAGrJ,GAAK5E,EASZ,MANIA,KACEC,EAEFgO,EAAGvF,QAGA/D,EAAWhC,EAAGsL,EAAIhO,IAgB7BwF,EAAE0I,SAAW,SAAWlJ,EAAIpC,GACxB,GAAI/C,GAAI,GAAID,GAAUU,KAGtB,OAFA0E,GAAW,MAANA,GAAevE,EAAYuE,EAAI,EAAGyC,EAAK,GAAI,aAA4B,EAALzC,EAAP,KAChEpC,EAAW,MAANA,GAAenC,EAAYmC,EAAI,EAAG,EAAG,GAAIe,GAAsC,EAALf,EAAhB/B,EACxDmE,EAAKrE,EAAOd,EAAGmF,EAAIpC,GAAO/C,GAgBrC2F,EAAE1B,cAAgB,SAAWnB,EAAIC,GAC7B,MAAOW,GAAQjD,KACP,MAANqC,GAAclC,EAAYkC,EAAI,EAAG8E,EAAK,MAAS9E,EAAK,EAAI,KAAMC,EAAI,KAmBxE4C,EAAE2I,QAAU,SAAWxL,EAAIC,GACvB,MAAOW,GAAQjD,KAAY,MAANqC,GAAclC,EAAYkC,EAAI,EAAG8E,EAAK,MACrD9E,EAAKrC,KAAKN,EAAI,EAAI,KAAM4C,EAAI,KA0BtC4C,EAAE4I,SAAW,SAAWzL,EAAIC,GACxB,GAAIxC,GAAMmD,EAAQjD,KAAY,MAANqC,GAAclC,EAAYkC,EAAI,EAAG8E,EAAK,MACxD9E,EAAKrC,KAAKN,EAAI,EAAI,KAAM4C,EAAI,GAElC,IAAKtC,KAAKP,EAAI,CACV,GAAIE,GACAoO,EAAMjO,EAAIkO,MAAM,KAChBC,GAAMzI,EAAOG,UACbuI,GAAM1I,EAAOI,mBACbF,EAAiBF,EAAOE,eACxByI,EAAUJ,EAAI,GACdK,EAAeL,EAAI,GACnBnC,EAAQ5L,KAAKa,EAAI,EACjBwN,EAAYzC,EAAQuC,EAAQzN,MAAM,GAAKyN,EACvCtO,EAAMwO,EAAUtN,MAIpB,IAFImN,IAAIvO,EAAIsO,EAAIA,EAAKC,EAAIA,EAAKvO,EAAGE,GAAOF,GAEnCsO,EAAK,GAAKpO,EAAM,EAAI,CAIrB,IAHAF,EAAIE,EAAMoO,GAAMA,EAChBE,EAAUE,EAAUC,OAAQ,EAAG3O,GAEnBE,EAAJF,EAASA,GAAKsO,EAClBE,GAAWzI,EAAiB2I,EAAUC,OAAQ3O,EAAGsO,EAGhDC,GAAK,IAAIC,GAAWzI,EAAiB2I,EAAU3N,MAAMf,IACtDiM,IAAOuC,EAAU,IAAMA,GAG/BrO,EAAMsO,EACFD,EAAU3I,EAAOC,mBAAuByI,GAAM1I,EAAOM,mBACnDsI,EAAatN,QAAS,GAAIN,QAAQ,OAAS0N,EAAK,OAAQ,KACxD,KAAO1I,EAAOK,wBACduI,GACFD,EAGR,MAAOrO,IAgBXoF,EAAEqJ,WAAa,SAAUC,GACrB,GAAIT,GAAKU,EAAIC,EAAIhP,EAAGiP,EAAKpP,EAAGqP,EAAIvF,EAAGxI,EAC/BoB,EAAIhC,EACJF,EAAIC,KACJmC,EAAKpC,EAAEN,EACPuC,EAAI,GAAI1C,GAAU8F,GAClByJ,EAAKJ,EAAK,GAAInP,GAAU8F,GACxB0J,EAAKF,EAAK,GAAItP,GAAU8F,EAoB5B,IAlBW,MAANoJ,IACDvO,GAAS,EACTV,EAAI,GAAID,GAAUkP,GAClBvO,EAASgC,KAEDA,EAAI1C,EAAEmM,UAAanM,EAAEmI,GAAGtC,MAExBnF,GACAC,EAAO,GACL,oBAAuB+B,EAAI,eAAiB,kBAAoBuM,GAKtEA,GAAMvM,GAAK1C,EAAEE,GAAKY,EAAOd,EAAGA,EAAEG,EAAI,EAAG,GAAI6L,IAAInG,GAAO7F,EAAI,QAI1D4C,EAAK,MAAOpC,GAAEuD,UAgBpB,KAfAzC,EAAI+B,EAAcT,GAIlBzC,EAAIsC,EAAEtC,EAAImB,EAAEE,OAAShB,EAAEL,EAAI,EAC3BsC,EAAEvC,EAAE,GAAKqF,GAAY6J,EAAMjP,EAAIiC,GAAa,EAAIA,EAAWgN,EAAMA,GACjEH,GAAMA,GAAMjP,EAAEyJ,IAAIhH,GAAK,EAAMtC,EAAI,EAAIsC,EAAI6M,EAAOtP,EAEhDoP,EAAMlN,EACNA,EAAU,EAAI,EACdlC,EAAI,GAAID,GAAUuB,GAGlB+N,EAAGnP,EAAE,GAAK,EAGN4J,EAAIvG,EAAKvD,EAAGyC,EAAG,EAAG,GAClB0M,EAAKD,EAAGpC,KAAMhD,EAAEsD,MAAMmC,IACH,GAAdJ,EAAG1F,IAAIwF,IACZC,EAAKK,EACLA,EAAKJ,EACLG,EAAKD,EAAGvC,KAAMhD,EAAEsD,MAAO+B,EAAKG,IAC5BD,EAAKF,EACL1M,EAAIzC,EAAE0M,MAAO5C,EAAEsD,MAAO+B,EAAK1M,IAC3BzC,EAAImP,CAgBR,OAbAA,GAAK5L,EAAK0L,EAAGvC,MAAMwC,GAAKK,EAAI,EAAG,GAC/BF,EAAKA,EAAGvC,KAAMqC,EAAG/B,MAAMkC,IACvBJ,EAAKA,EAAGpC,KAAMqC,EAAG/B,MAAMmC,IACvBF,EAAG/N,EAAIgO,EAAGhO,EAAId,EAAEc,EAChBnB,GAAK,EAGLqO,EAAMjL,EAAK+L,EAAIC,EAAIpP,EAAGa,GAAgB0L,MAAMlM,GAAG4K,MAAM3B,IAC/ClG,EAAK8L,EAAIH,EAAI/O,EAAGa,GAAgB0L,MAAMlM,GAAG4K,OAAU,GAC7CkE,EAAGvL,WAAYwL,EAAGxL,aAClBsL,EAAGtL,WAAYmL,EAAGnL,YAE9B7B,EAAUkN,EACHZ,GAOX7I,EAAE6J,SAAW,WACT,OAAQ/O,MAsBZkF,EAAE8J,QAAU9J,EAAEzC,IAAM,SAAWlD,EAAGqE,GAC9B,GAAI3B,GAAGG,EAAG4K,EACNrN,EAAI6B,EAAe,EAAJjC,GAASA,GAAKA,GAC7BQ,EAAIC,IAQR,IANU,MAAL4D,IACDxD,EAAK,GACLwD,EAAI,GAAItE,GAAUsE,KAIhBzD,EAAYZ,GAAIgC,EAAkBA,EAAkB,GAAI,eACzDiK,SAASjM,IAAMI,EAAI4B,IAAsBhC,GAAK,IAC/C0P,WAAW1P,IAAMA,KAAQA,EAAIyK,OAAgB,GAALzK,EAExC,MADA0C,GAAI8F,KAAKtF,KAAM1C,EAAGR,GACX,GAAID,GAAWsE,EAAI3B,EAAI2B,EAAI3B,EAuBtC,KApBI2B,EACKrE,EAAI,GAAKQ,EAAE4H,GAAGvC,IAAQrF,EAAE2L,SAAW9H,EAAE+D,GAAGvC,IAAQxB,EAAE8H,QACnD3L,EAAIA,EAAE2M,IAAI9I,IAEVoJ,EAAIpJ,EAGJA,EAAI,MAEDpB,IAMPP,EAAI+C,EAAUxC,EAAgBb,EAAW,IAG7CS,EAAI,GAAI9C,GAAU8F,KAEN,CACR,GAAKzF,EAAI,EAAI,CAET,GADAyC,EAAIA,EAAEuK,MAAM5M,IACNqC,EAAE3C,EAAI,KACRwC,GACKG,EAAE3C,EAAEsB,OAASkB,IAAIG,EAAE3C,EAAEsB,OAASkB,GAC5B2B,IACPxB,EAAIA,EAAEsK,IAAI9I,IAKlB,GADAjE,EAAI6B,EAAW7B,EAAI,IACbA,EAAI,KACVI,GAAIA,EAAE4M,MAAM5M,GACRkC,EACKlC,EAAEN,GAAKM,EAAEN,EAAEsB,OAASkB,IAAIlC,EAAEN,EAAEsB,OAASkB,GACnC2B,IACP7D,EAAIA,EAAE2M,IAAI9I,IAIlB,MAAIA,GAAUxB,GACL,EAAJ7C,IAAQ6C,EAAIgD,EAAItC,IAAIV,IAElB4K,EAAI5K,EAAEsK,IAAIM,GAAK/K,EAAI5B,EAAO+B,EAAGI,EAAejC,GAAkB6B,IAkBzE8C,EAAEgK,YAAc,SAAWxK,EAAIpC,GAC3B,MAAOW,GAAQjD,KAAY,MAAN0E,GAAcvE,EAAYuE,EAAI,EAAGyC,EAAK,GAAI,aACtD,EAALzC,EAAS,KAAMpC,EAAI,KAgB3B4C,EAAE5B,SAAW,SAAU9D,GACnB,GAAIM,GACAP,EAAIS,KACJa,EAAItB,EAAEsB,EACNnB,EAAIH,EAAEG,CAyBV,OAtBW,QAANA,EAEGmB,GACAf,EAAM,WACG,EAAJe,IAAQf,EAAM,IAAMA,IAEzBA,EAAM,OAGVA,EAAM8C,EAAerD,EAAEE,GAOnBK,EALM,MAALN,GAAcW,EAAYX,EAAG,EAAG,GAAI,GAAI,QAKnC0B,EAAayB,EAAc7C,EAAKJ,GAAS,EAAJF,EAAO,GAAIqB,GAJ3C0C,GAAL7D,GAAmBA,GAAK2F,EAC1B7B,EAAe1D,EAAKJ,GACpBiD,EAAc7C,EAAKJ,GAKlB,EAAJmB,GAAStB,EAAEE,EAAE,KAAKK,EAAM,IAAMA,IAGhCA,GAQXoF,EAAEiK,UAAYjK,EAAEkK,MAAQ,WACpB,MAAO/O,GAAO,GAAIf,GAAUU,MAAOA,KAAKN,EAAI,EAAG,IAQnDwF,EAAEmK,QAAUnK,EAAEoK,OAAS,WACnB,GAAIxP,GACAP,EAAIS,KACJN,EAAIH,EAAEG,CAEV,OAAW,QAANA,EAAoBH,EAAE+D,YAE3BxD,EAAM8C,EAAerD,EAAEE,GAEvBK,EAAWyD,GAAL7D,GAAmBA,GAAK2F,EACxB7B,EAAe1D,EAAKJ,GACpBiD,EAAc7C,EAAKJ,GAElBH,EAAEsB,EAAI,EAAI,IAAMf,EAAMA,IAIf,MAAbT,GAAoBC,EAAUoH,OAAOrH,GAEnCC,EAOX,QAAS2K,GAAS1K,GACd,GAAII,GAAQ,EAAJJ,CACR,OAAOA,GAAI,GAAKA,IAAMI,EAAIA,EAAIA,EAAI,EAKtC,QAASiD,GAAckE,GAMnB,IALA,GAAIjG,GAAGmM,EACHrN,EAAI,EACJ0E,EAAIyC,EAAE/F,OACNmB,EAAI4E,EAAE,GAAK,GAEHzC,EAAJ1E,GAAS,CAGb,IAFAkB,EAAIiG,EAAEnH,KAAO,GACbqN,EAAIrL,EAAWd,EAAEE,OACTiM,IAAKnM,EAAI,IAAMA,GACvBqB,GAAKrB,EAIT,IAAMwD,EAAInC,EAAEnB,OAA8B,KAAtBmB,EAAEjB,aAAaoD,KACnC,MAAOnC,GAAExB,MAAO,EAAG2D,EAAI,GAAK,GAKhC,QAASwE,GAAS9I,EAAGqC,GACjB,GAAI0E,GAAGtH,EACH2C,EAAKpC,EAAEN,EACPsK,EAAK3H,EAAE3C,EACPE,EAAII,EAAEc,EACNwD,EAAIjC,EAAEvB,EACNoB,EAAIlC,EAAEL,EACN6P,EAAInN,EAAE1C,CAGV,KAAMC,IAAM0E,EAAI,MAAO,KAMvB,IAJAyC,EAAI3E,IAAOA,EAAG,GACd3C,EAAIuK,IAAOA,EAAG,GAGTjD,GAAKtH,EAAI,MAAOsH,GAAItH,EAAI,GAAK6E,EAAI1E,CAGtC,IAAKA,GAAK0E,EAAI,MAAO1E,EAMrB,IAJAmH,EAAQ,EAAJnH,EACJH,EAAIyC,GAAKsN,GAGHpN,IAAO4H,EAAK,MAAOvK,GAAI,GAAK2C,EAAK2E,EAAI,EAAI,EAG/C,KAAMtH,EAAI,MAAOyC,GAAIsN,EAAIzI,EAAI,EAAI,EAKjC,KAHAzC,GAAMpC,EAAIE,EAAGpB,SAAawO,EAAIxF,EAAGhJ,QAAWkB,EAAIsN,EAG1C5P,EAAI,EAAO0E,EAAJ1E,EAAOA,IAAM,GAAKwC,EAAGxC,IAAMoK,EAAGpK,GAAK,MAAOwC,GAAGxC,GAAKoK,EAAGpK,GAAKmH,EAAI,EAAI,EAG/E,OAAO7E,IAAKsN,EAAI,EAAItN,EAAIsN,EAAIzI,EAAI,EAAI,GASxC,QAASM,GAAsB7H,EAAGyE,EAAKC,GACnC,OAAS1E,EAAI4E,EAAS5E,KAAQyE,GAAYC,GAAL1E,EAIzC,QAASsE,GAAQ2L,GACb,MAA8C,kBAAvCC,OAAOtK,UAAU7B,SAASQ,KAAK0L,GAI1C,QAAS/H,GAAYb,GACnB,SAAWA,IAAKA,EAAE8I,aAAe9I,EAAE8I,YAAYjI,cAAgBA,GASjE,QAAS/E,GAAW5C,EAAKgC,EAAQD,GAO7B,IANA,GAAIwC,GAEAsL,EADA5B,GAAO,GAEPpO,EAAI,EACJE,EAAMC,EAAIiB,OAEFlB,EAAJF,GAAW,CACf,IAAMgQ,EAAO5B,EAAIhN,OAAQ4O,IAAQ5B,EAAI4B,IAAS7N,GAG9C,IAFAiM,EAAK1J,EAAI,IAAO5D,EAASW,QAAStB,EAAIkD,OAAQrD,MAEtC0E,EAAI0J,EAAIhN,OAAQsD,IAEf0J,EAAI1J,GAAKxC,EAAU,IACD,MAAdkM,EAAI1J,EAAI,KAAa0J,EAAI1J,EAAI,GAAK,GACvC0J,EAAI1J,EAAI,IAAM0J,EAAI1J,GAAKxC,EAAU,EACjCkM,EAAI1J,IAAMxC,GAKtB,MAAOkM,GAAIvB,UAIf,QAAShJ,GAAe1D,EAAKJ,GACzB,OAASI,EAAIiB,OAAS,EAAIjB,EAAIkD,OAAO,GAAK,IAAMlD,EAAIY,MAAM,GAAKZ,IACvD,EAAJJ,EAAQ,IAAM,MAASA,EAI/B,QAASiD,GAAc7C,EAAKJ,GACxB,GAAIG,GAAKmN,CAGT,IAAS,EAAJtN,EAAQ,CAGT,IAAMsN,EAAI,OAAQtN,EAAGsN,GAAK,KAC1BlN,EAAMkN,EAAIlN,MAOV,IAHAD,EAAMC,EAAIiB,SAGHrB,EAAIG,EAAM,CACb,IAAMmN,EAAI,IAAKtN,GAAKG,IAAOH,EAAGsN,GAAK,KACnClN,GAAOkN,MACKnN,GAAJH,IACRI,EAAMA,EAAIY,MAAO,EAAGhB,GAAM,IAAMI,EAAIY,MAAMhB,GAIlD,OAAOI,GAIX,QAASqE,GAAS5E,GAEd,MADAA,GAAI0P,WAAW1P,GACJ,EAAJA,EAAQyF,EAASzF,GAAKiC,EAAUjC,GAlpF3C,GAAID,GACA6B,EAAY,uCACZ6D,EAAW+C,KAAK6C,KAChBpJ,EAAYuG,KAAKqD,MACjB/D,EAAU,iCACVhE,EAAe,gBACfrC,EAAgB,kDAChBP,EAAW,mEACXwE,EAAO,KACPtD,EAAW,GACXJ,EAAmB,iBAEnBuD,GAAY,EAAG,GAAI,IAAK,IAAK,IAAK,IAAK,IAAK,IAAK,IAAK,IAAK,KAAM,KAAM,KAAM,MAC7E6D,EAAY,IAOZxB,EAAM,GAqoFV7H,GAAYF,IACZE,EAAAA,WAAoBA,EAAUA,UAAYA,EAIpB,kBAAVsQ,SAAwBA,OAAOC,IACvCD,OAAQ,WAAc,MAAOtQ,KAGJ,mBAAVwQ,SAAyBA,OAAOC,QAC/CD,OAAOC,QAAUzQ,GAIXH,IAAYA,EAA2B,mBAAR6Q,MAAsBA,KAAOC,SAAS,kBAC3E9Q,EAAUG,UAAYA,IAE3BU"}
/* bignumber.js v3.1.2 https://github.com/MikeMcl/bignumber.js/LICENCE */
!function(e){"use strict";function n(e){function h(e,n){var t,r,i,o,u,s,f=this;if(!(f instanceof h))return V&&I(26,"constructor call without new",e),new h(e,n);if(null!=n&&j(n,2,64,C,"base")){if(n=0|n,s=e+"",10==n)return f=new h(e instanceof h?e:s),L(f,P+f.e+1,q);if((o="number"==typeof e)&&0*e!=0||!new RegExp("^-?"+(t="["+N.slice(0,n)+"]+")+"(?:\\."+t+")?$",37>n?"i":"").test(s))return B(f,s,o,n);o?(f.s=0>1/e?(s=s.slice(1),-1):1,V&&s.replace(/^0\.0*|\./,"").length>15&&I(C,v,e),o=!1):f.s=45===s.charCodeAt(0)?(s=s.slice(1),-1):1,s=E(s,10,n,f.s)}else{if(e instanceof h)return f.s=e.s,f.e=e.e,f.c=(e=e.c)?e.slice():e,void(C=0);if((o="number"==typeof e)&&0*e==0){if(f.s=0>1/e?(e=-e,-1):1,e===~~e){for(r=0,i=e;i>=10;i/=10,r++);return f.e=r,f.c=[e],void(C=0)}s=e+""}else{if(!g.test(s=e+""))return B(f,s,o);f.s=45===s.charCodeAt(0)?(s=s.slice(1),-1):1}}for((r=s.indexOf("."))>-1&&(s=s.replace(".","")),(i=s.search(/e/i))>0?(0>r&&(r=i),r+=+s.slice(i+1),s=s.substring(0,i)):0>r&&(r=s.length),i=0;48===s.charCodeAt(i);i++);for(u=s.length;48===s.charCodeAt(--u););if(s=s.slice(i,u+1))if(u=s.length,o&&V&&u>15&&(e>O||e!==d(e))&&I(C,v,f.s*e),r=r-i-1,r>z)f.c=f.e=null;else if(G>r)f.c=[f.e=0];else{if(f.e=r,f.c=[],i=(r+1)%y,0>r&&(i+=y),u>i){for(i&&f.c.push(+s.slice(0,i)),u-=y;u>i;)f.c.push(+s.slice(i,i+=y));s=s.slice(i),i=y-s.length}else i-=u;for(;i--;s+="0");f.c.push(+s)}else f.c=[f.e=0];C=0}function E(e,n,t,i){var o,u,s,l,a,g,p,d=e.indexOf("."),m=P,w=q;for(37>t&&(e=e.toLowerCase()),d>=0&&(s=J,J=0,e=e.replace(".",""),p=new h(t),a=p.pow(e.length-d),J=s,p.c=f(c(r(a.c),a.e),10,n),p.e=p.c.length),g=f(e,t,n),u=s=g.length;0==g[--s];g.pop());if(!g[0])return"0";if(0>d?--u:(a.c=g,a.e=u,a.s=i,a=U(a,p,m,w,n),g=a.c,l=a.r,u=a.e),o=u+m+1,d=g[o],s=n/2,l=l||0>o||null!=g[o+1],l=4>w?(null!=d||l)&&(0==w||w==(a.s<0?3:2)):d>s||d==s&&(4==w||l||6==w&&1&g[o-1]||w==(a.s<0?8:7)),1>o||!g[0])e=l?c("1",-m):"0";else{if(g.length=o,l)for(--n;++g[--o]>n;)g[o]=0,o||(++u,g.unshift(1));for(s=g.length;!g[--s];);for(d=0,e="";s>=d;e+=N.charAt(g[d++]));e=c(e,u)}return e}function D(e,n,t,i){var o,u,s,f,a;if(t=null!=t&&j(t,0,8,i,w)?0|t:q,!e.c)return e.toString();if(o=e.c[0],s=e.e,null==n)a=r(e.c),a=19==i||24==i&&k>=s?l(a,s):c(a,s);else if(e=L(new h(e),n,t),u=e.e,a=r(e.c),f=a.length,19==i||24==i&&(u>=n||k>=u)){for(;n>f;a+="0",f++);a=l(a,u)}else if(n-=s,a=c(a,u),u+1>f){if(--n>0)for(a+=".";n--;a+="0");}else if(n+=u-f,n>0)for(u+1==f&&(a+=".");n--;a+="0");return e.s<0&&o?"-"+a:a}function F(e,n){var t,r,i=0;for(u(e[0])&&(e=e[0]),t=new h(e[0]);++i<e.length;){if(r=new h(e[i]),!r.s){t=r;break}n.call(t,r)&&(t=r)}return t}function _(e,n,t,r,i){return(n>e||e>t||e!=a(e))&&I(r,(i||"decimal places")+(n>e||e>t?" out of range":" not an integer"),e),!0}function x(e,n,t){for(var r=1,i=n.length;!n[--i];n.pop());for(i=n[0];i>=10;i/=10,r++);return(t=r+t*y-1)>z?e.c=e.e=null:G>t?e.c=[e.e=0]:(e.e=t,e.c=n),e}function I(e,n,t){var r=new Error(["new BigNumber","cmp","config","div","divToInt","eq","gt","gte","lt","lte","minus","mod","plus","precision","random","round","shift","times","toDigits","toExponential","toFixed","toFormat","toFraction","pow","toPrecision","toString","BigNumber"][e]+"() "+n+": "+t);throw r.name="BigNumber Error",C=0,r}function L(e,n,t,r){var i,o,u,s,f,l,c,a=e.c,h=R;if(a){e:{for(i=1,s=a[0];s>=10;s/=10,i++);if(o=n-i,0>o)o+=y,u=n,f=a[l=0],c=f/h[i-u-1]%10|0;else if(l=p((o+1)/y),l>=a.length){if(!r)break e;for(;a.length<=l;a.push(0));f=c=0,i=1,o%=y,u=o-y+1}else{for(f=s=a[l],i=1;s>=10;s/=10,i++);o%=y,u=o-y+i,c=0>u?0:f/h[i-u-1]%10|0}if(r=r||0>n||null!=a[l+1]||(0>u?f:f%h[i-u-1]),r=4>t?(c||r)&&(0==t||t==(e.s<0?3:2)):c>5||5==c&&(4==t||r||6==t&&(o>0?u>0?f/h[i-u]:0:a[l-1])%10&1||t==(e.s<0?8:7)),1>n||!a[0])return a.length=0,r?(n-=e.e+1,a[0]=h[(y-n%y)%y],e.e=-n||0):a[0]=e.e=0,e;if(0==o?(a.length=l,s=1,l--):(a.length=l+1,s=h[y-o],a[l]=u>0?d(f/h[i-u]%h[u])*s:0),r)for(;;){if(0==l){for(o=1,u=a[0];u>=10;u/=10,o++);for(u=a[0]+=s,s=1;u>=10;u/=10,s++);o!=s&&(e.e++,a[0]==b&&(a[0]=1));break}if(a[l]+=s,a[l]!=b)break;a[l--]=0,s=1}for(o=a.length;0===a[--o];a.pop());}e.e>z?e.c=e.e=null:e.e<G&&(e.c=[e.e=0])}return e}var U,B,C=0,M=h.prototype,T=new h(1),P=20,q=4,k=-7,$=21,G=-1e7,z=1e7,V=!0,j=_,H=!1,W=1,J=0,X={decimalSeparator:".",groupSeparator:",",groupSize:3,secondaryGroupSize:0,fractionGroupSeparator:" ",fractionGroupSize:0};return h.another=n,h.ROUND_UP=0,h.ROUND_DOWN=1,h.ROUND_CEIL=2,h.ROUND_FLOOR=3,h.ROUND_HALF_UP=4,h.ROUND_HALF_DOWN=5,h.ROUND_HALF_EVEN=6,h.ROUND_HALF_CEIL=7,h.ROUND_HALF_FLOOR=8,h.EUCLID=9,h.config=h.set=function(){var e,n,t=0,r={},i=arguments,s=i[0],f=s&&"object"==typeof s?function(){return s.hasOwnProperty(n)?null!=(e=s[n]):void 0}:function(){return i.length>t?null!=(e=i[t++]):void 0};return f(n="DECIMAL_PLACES")&&j(e,0,A,2,n)&&(P=0|e),r[n]=P,f(n="ROUNDING_MODE")&&j(e,0,8,2,n)&&(q=0|e),r[n]=q,f(n="EXPONENTIAL_AT")&&(u(e)?j(e[0],-A,0,2,n)&&j(e[1],0,A,2,n)&&(k=0|e[0],$=0|e[1]):j(e,-A,A,2,n)&&(k=-($=0|(0>e?-e:e)))),r[n]=[k,$],f(n="RANGE")&&(u(e)?j(e[0],-A,-1,2,n)&&j(e[1],1,A,2,n)&&(G=0|e[0],z=0|e[1]):j(e,-A,A,2,n)&&(0|e?G=-(z=0|(0>e?-e:e)):V&&I(2,n+" cannot be zero",e))),r[n]=[G,z],f(n="ERRORS")&&(e===!!e||1===e||0===e?(C=0,j=(V=!!e)?_:o):V&&I(2,n+m,e)),r[n]=V,f(n="CRYPTO")&&(e===!0||e===!1||1===e||0===e?e?(e="undefined"==typeof crypto,!e&&crypto&&(crypto.getRandomValues||crypto.randomBytes)?H=!0:V?I(2,"crypto unavailable",e?void 0:crypto):H=!1):H=!1:V&&I(2,n+m,e)),r[n]=H,f(n="MODULO_MODE")&&j(e,0,9,2,n)&&(W=0|e),r[n]=W,f(n="POW_PRECISION")&&j(e,0,A,2,n)&&(J=0|e),r[n]=J,f(n="FORMAT")&&("object"==typeof e?X=e:V&&I(2,n+" not an object",e)),r[n]=X,r},h.isBigNumber=s,h.max=function(){return F(arguments,M.lt)},h.min=function(){return F(arguments,M.gt)},h.random=function(){var e=9007199254740992,n=Math.random()*e&2097151?function(){return d(Math.random()*e)}:function(){return 8388608*(1073741824*Math.random()|0)+(8388608*Math.random()|0)};return function(e){var t,r,i,o,u,s=0,f=[],l=new h(T);if(e=null!=e&&j(e,0,A,14)?0|e:P,o=p(e/y),H)if(crypto.getRandomValues){for(t=crypto.getRandomValues(new Uint32Array(o*=2));o>s;)u=131072*t[s]+(t[s+1]>>>11),u>=9e15?(r=crypto.getRandomValues(new Uint32Array(2)),t[s]=r[0],t[s+1]=r[1]):(f.push(u%1e14),s+=2);s=o/2}else if(crypto.randomBytes){for(t=crypto.randomBytes(o*=7);o>s;)u=281474976710656*(31&t[s])+1099511627776*t[s+1]+4294967296*t[s+2]+16777216*t[s+3]+(t[s+4]<<16)+(t[s+5]<<8)+t[s+6],u>=9e15?crypto.randomBytes(7).copy(t,s):(f.push(u%1e14),s+=7);s=o/7}else H=!1,V&&I(14,"crypto unavailable",crypto);if(!H)for(;o>s;)u=n(),9e15>u&&(f[s++]=u%1e14);for(o=f[--s],e%=y,o&&e&&(u=R[y-e],f[s]=d(o/u)*u);0===f[s];f.pop(),s--);if(0>s)f=[i=0];else{for(i=-1;0===f[0];f.shift(),i-=y);for(s=1,u=f[0];u>=10;u/=10,s++);y>s&&(i-=y-s)}return l.e=i,l.c=f,l}}(),U=function(){function e(e,n,t){var r,i,o,u,s=0,f=e.length,l=n%S,c=n/S|0;for(e=e.slice();f--;)o=e[f]%S,u=e[f]/S|0,r=c*o+u*l,i=l*o+r%S*S+s,s=(i/t|0)+(r/S|0)+c*u,e[f]=i%t;return s&&e.unshift(s),e}function n(e,n,t,r){var i,o;if(t!=r)o=t>r?1:-1;else for(i=o=0;t>i;i++)if(e[i]!=n[i]){o=e[i]>n[i]?1:-1;break}return o}function r(e,n,t,r){for(var i=0;t--;)e[t]-=i,i=e[t]<n[t]?1:0,e[t]=i*r+e[t]-n[t];for(;!e[0]&&e.length>1;e.shift());}return function(i,o,u,s,f){var l,c,a,g,p,m,w,v,N,O,R,S,A,E,D,F,_,x=i.s==o.s?1:-1,I=i.c,U=o.c;if(!(I&&I[0]&&U&&U[0]))return new h(i.s&&o.s&&(I?!U||I[0]!=U[0]:U)?I&&0==I[0]||!U?0*x:x/0:NaN);for(v=new h(x),N=v.c=[],c=i.e-o.e,x=u+c+1,f||(f=b,c=t(i.e/y)-t(o.e/y),x=x/y|0),a=0;U[a]==(I[a]||0);a++);if(U[a]>(I[a]||0)&&c--,0>x)N.push(1),g=!0;else{for(E=I.length,F=U.length,a=0,x+=2,p=d(f/(U[0]+1)),p>1&&(U=e(U,p,f),I=e(I,p,f),F=U.length,E=I.length),A=F,O=I.slice(0,F),R=O.length;F>R;O[R++]=0);_=U.slice(),_.unshift(0),D=U[0],U[1]>=f/2&&D++;do{if(p=0,l=n(U,O,F,R),0>l){if(S=O[0],F!=R&&(S=S*f+(O[1]||0)),p=d(S/D),p>1)for(p>=f&&(p=f-1),m=e(U,p,f),w=m.length,R=O.length;1==n(m,O,w,R);)p--,r(m,w>F?_:U,w,f),w=m.length,l=1;else 0==p&&(l=p=1),m=U.slice(),w=m.length;if(R>w&&m.unshift(0),r(O,m,R,f),R=O.length,-1==l)for(;n(U,O,F,R)<1;)p++,r(O,R>F?_:U,R,f),R=O.length}else 0===l&&(p++,O=[0]);N[a++]=p,O[0]?O[R++]=I[A]||0:(O=[I[A]],R=1)}while((A++<E||null!=O[0])&&x--);g=null!=O[0],N[0]||N.shift()}if(f==b){for(a=1,x=N[0];x>=10;x/=10,a++);L(v,u+(v.e=a+c*y-1)+1,s,g)}else v.e=c,v.r=+g;return v}}(),B=function(){var e=/^(-?)0([xbo])(?=\w[\w.]*$)/i,n=/^([^.]+)\.$/,t=/^\.([^.]+)$/,r=/^-?(Infinity|NaN)$/,i=/^\s*\+(?=[\w.])|^\s+|\s+$/g;return function(o,u,s,f){var l,c=s?u:u.replace(i,"");if(r.test(c))o.s=isNaN(c)?null:0>c?-1:1;else{if(!s&&(c=c.replace(e,function(e,n,t){return l="x"==(t=t.toLowerCase())?16:"b"==t?2:8,f&&f!=l?e:n}),f&&(l=f,c=c.replace(n,"$1").replace(t,"0.$1")),u!=c))return new h(c,l);V&&I(C,"not a"+(f?" base "+f:"")+" number",u),o.s=null}o.c=o.e=null,C=0}}(),M.absoluteValue=M.abs=function(){var e=new h(this);return e.s<0&&(e.s=1),e},M.ceil=function(){return L(new h(this),this.e+1,2)},M.comparedTo=M.cmp=function(e,n){return C=1,i(this,new h(e,n))},M.decimalPlaces=M.dp=function(){var e,n,r=this.c;if(!r)return null;if(e=((n=r.length-1)-t(this.e/y))*y,n=r[n])for(;n%10==0;n/=10,e--);return 0>e&&(e=0),e},M.dividedBy=M.div=function(e,n){return C=3,U(this,new h(e,n),P,q)},M.dividedToIntegerBy=M.divToInt=function(e,n){return C=4,U(this,new h(e,n),0,1)},M.equals=M.eq=function(e,n){return C=5,0===i(this,new h(e,n))},M.floor=function(){return L(new h(this),this.e+1,3)},M.greaterThan=M.gt=function(e,n){return C=6,i(this,new h(e,n))>0},M.greaterThanOrEqualTo=M.gte=function(e,n){return C=7,1===(n=i(this,new h(e,n)))||0===n},M.isFinite=function(){return!!this.c},M.isInteger=M.isInt=function(){return!!this.c&&t(this.e/y)>this.c.length-2},M.isNaN=function(){return!this.s},M.isNegative=M.isNeg=function(){return this.s<0},M.isZero=function(){return!!this.c&&0==this.c[0]},M.lessThan=M.lt=function(e,n){return C=8,i(this,new h(e,n))<0},M.lessThanOrEqualTo=M.lte=function(e,n){return C=9,-1===(n=i(this,new h(e,n)))||0===n},M.minus=M.sub=function(e,n){var r,i,o,u,s=this,f=s.s;if(C=10,e=new h(e,n),n=e.s,!f||!n)return new h(NaN);if(f!=n)return e.s=-n,s.plus(e);var l=s.e/y,c=e.e/y,a=s.c,g=e.c;if(!l||!c){if(!a||!g)return a?(e.s=-n,e):new h(g?s:NaN);if(!a[0]||!g[0])return g[0]?(e.s=-n,e):new h(a[0]?s:3==q?-0:0)}if(l=t(l),c=t(c),a=a.slice(),f=l-c){for((u=0>f)?(f=-f,o=a):(c=l,o=g),o.reverse(),n=f;n--;o.push(0));o.reverse()}else for(i=(u=(f=a.length)<(n=g.length))?f:n,f=n=0;i>n;n++)if(a[n]!=g[n]){u=a[n]<g[n];break}if(u&&(o=a,a=g,g=o,e.s=-e.s),n=(i=g.length)-(r=a.length),n>0)for(;n--;a[r++]=0);for(n=b-1;i>f;){if(a[--i]<g[i]){for(r=i;r&&!a[--r];a[r]=n);--a[r],a[i]+=b}a[i]-=g[i]}for(;0==a[0];a.shift(),--c);return a[0]?x(e,a,c):(e.s=3==q?-1:1,e.c=[e.e=0],e)},M.modulo=M.mod=function(e,n){var t,r,i=this;return C=11,e=new h(e,n),!i.c||!e.s||e.c&&!e.c[0]?new h(NaN):!e.c||i.c&&!i.c[0]?new h(i):(9==W?(r=e.s,e.s=1,t=U(i,e,0,3),e.s=r,t.s*=r):t=U(i,e,0,W),i.minus(t.times(e)))},M.negated=M.neg=function(){var e=new h(this);return e.s=-e.s||null,e},M.plus=M.add=function(e,n){var r,i=this,o=i.s;if(C=12,e=new h(e,n),n=e.s,!o||!n)return new h(NaN);if(o!=n)return e.s=-n,i.minus(e);var u=i.e/y,s=e.e/y,f=i.c,l=e.c;if(!u||!s){if(!f||!l)return new h(o/0);if(!f[0]||!l[0])return l[0]?e:new h(f[0]?i:0*o)}if(u=t(u),s=t(s),f=f.slice(),o=u-s){for(o>0?(s=u,r=l):(o=-o,r=f),r.reverse();o--;r.push(0));r.reverse()}for(o=f.length,n=l.length,0>o-n&&(r=l,l=f,f=r,n=o),o=0;n;)o=(f[--n]=f[n]+l[n]+o)/b|0,f[n]=b===f[n]?0:f[n]%b;return o&&(f.unshift(o),++s),x(e,f,s)},M.precision=M.sd=function(e){var n,t,r=this,i=r.c;if(null!=e&&e!==!!e&&1!==e&&0!==e&&(V&&I(13,"argument"+m,e),e!=!!e&&(e=null)),!i)return null;if(t=i.length-1,n=t*y+1,t=i[t]){for(;t%10==0;t/=10,n--);for(t=i[0];t>=10;t/=10,n++);}return e&&r.e+1>n&&(n=r.e+1),n},M.round=function(e,n){var t=new h(this);return(null==e||j(e,0,A,15))&&L(t,~~e+this.e+1,null!=n&&j(n,0,8,15,w)?0|n:q),t},M.shift=function(e){var n=this;return j(e,-O,O,16,"argument")?n.times("1e"+a(e)):new h(n.c&&n.c[0]&&(-O>e||e>O)?n.s*(0>e?0:1/0):n)},M.squareRoot=M.sqrt=function(){var e,n,i,o,u,s=this,f=s.c,l=s.s,c=s.e,a=P+4,g=new h("0.5");if(1!==l||!f||!f[0])return new h(!l||0>l&&(!f||f[0])?NaN:f?s:1/0);if(l=Math.sqrt(+s),0==l||l==1/0?(n=r(f),(n.length+c)%2==0&&(n+="0"),l=Math.sqrt(n),c=t((c+1)/2)-(0>c||c%2),l==1/0?n="1e"+c:(n=l.toExponential(),n=n.slice(0,n.indexOf("e")+1)+c),i=new h(n)):i=new h(l+""),i.c[0])for(c=i.e,l=c+a,3>l&&(l=0);;)if(u=i,i=g.times(u.plus(U(s,u,a,1))),r(u.c).slice(0,l)===(n=r(i.c)).slice(0,l)){if(i.e<c&&--l,n=n.slice(l-3,l+1),"9999"!=n&&(o||"4999"!=n)){(!+n||!+n.slice(1)&&"5"==n.charAt(0))&&(L(i,i.e+P+2,1),e=!i.times(i).eq(s));break}if(!o&&(L(u,u.e+P+2,0),u.times(u).eq(s))){i=u;break}a+=4,l+=4,o=1}return L(i,i.e+P+1,q,e)},M.times=M.mul=function(e,n){var r,i,o,u,s,f,l,c,a,g,p,d,m,w,v,N=this,O=N.c,R=(C=17,e=new h(e,n)).c;if(!(O&&R&&O[0]&&R[0]))return!N.s||!e.s||O&&!O[0]&&!R||R&&!R[0]&&!O?e.c=e.e=e.s=null:(e.s*=N.s,O&&R?(e.c=[0],e.e=0):e.c=e.e=null),e;for(i=t(N.e/y)+t(e.e/y),e.s*=N.s,l=O.length,g=R.length,g>l&&(m=O,O=R,R=m,o=l,l=g,g=o),o=l+g,m=[];o--;m.push(0));for(w=b,v=S,o=g;--o>=0;){for(r=0,p=R[o]%v,d=R[o]/v|0,s=l,u=o+s;u>o;)c=O[--s]%v,a=O[s]/v|0,f=d*c+a*p,c=p*c+f%v*v+m[u]+r,r=(c/w|0)+(f/v|0)+d*a,m[u--]=c%w;m[u]=r}return r?++i:m.shift(),x(e,m,i)},M.toDigits=function(e,n){var t=new h(this);return e=null!=e&&j(e,1,A,18,"precision")?0|e:null,n=null!=n&&j(n,0,8,18,w)?0|n:q,e?L(t,e,n):t},M.toExponential=function(e,n){return D(this,null!=e&&j(e,0,A,19)?~~e+1:null,n,19)},M.toFixed=function(e,n){return D(this,null!=e&&j(e,0,A,20)?~~e+this.e+1:null,n,20)},M.toFormat=function(e,n){var t=D(this,null!=e&&j(e,0,A,21)?~~e+this.e+1:null,n,21);if(this.c){var r,i=t.split("."),o=+X.groupSize,u=+X.secondaryGroupSize,s=X.groupSeparator,f=i[0],l=i[1],c=this.s<0,a=c?f.slice(1):f,h=a.length;if(u&&(r=o,o=u,u=r,h-=r),o>0&&h>0){for(r=h%o||o,f=a.substr(0,r);h>r;r+=o)f+=s+a.substr(r,o);u>0&&(f+=s+a.slice(r)),c&&(f="-"+f)}t=l?f+X.decimalSeparator+((u=+X.fractionGroupSize)?l.replace(new RegExp("\\d{"+u+"}\\B","g"),"$&"+X.fractionGroupSeparator):l):f}return t},M.toFraction=function(e){var n,t,i,o,u,s,f,l,c,a=V,g=this,p=g.c,d=new h(T),m=t=new h(T),w=f=new h(T);if(null!=e&&(V=!1,s=new h(e),V=a,(!(a=s.isInt())||s.lt(T))&&(V&&I(22,"max denominator "+(a?"out of range":"not an integer"),e),e=!a&&s.c&&L(s,s.e+1,1).gte(T)?s:null)),!p)return g.toString();for(c=r(p),o=d.e=c.length-g.e-1,d.c[0]=R[(u=o%y)<0?y+u:u],e=!e||s.cmp(d)>0?o>0?d:m:s,u=z,z=1/0,s=new h(c),f.c[0]=0;l=U(s,d,0,1),i=t.plus(l.times(w)),1!=i.cmp(e);)t=w,w=i,m=f.plus(l.times(i=m)),f=i,d=s.minus(l.times(i=d)),s=i;return i=U(e.minus(t),w,0,1),f=f.plus(i.times(m)),t=t.plus(i.times(w)),f.s=m.s=g.s,o*=2,n=U(m,w,o,q).minus(g).abs().cmp(U(f,t,o,q).minus(g).abs())<1?[m.toString(),w.toString()]:[f.toString(),t.toString()],z=u,n},M.toNumber=function(){return+this},M.toPower=M.pow=function(e,n){var t,r,i,o=d(0>e?-e:+e),u=this;if(null!=n&&(C=23,n=new h(n)),!j(e,-O,O,23,"exponent")&&(!isFinite(e)||o>O&&(e/=0)||parseFloat(e)!=e&&!(e=NaN))||0==e)return t=Math.pow(+u,e),new h(n?t%n:t);for(n?e>1&&u.gt(T)&&u.isInt()&&n.gt(T)&&n.isInt()?u=u.mod(n):(i=n,n=null):J&&(t=p(J/y+2)),r=new h(T);;){if(o%2){if(r=r.times(u),!r.c)break;t?r.c.length>t&&(r.c.length=t):n&&(r=r.mod(n))}if(o=d(o/2),!o)break;u=u.times(u),t?u.c&&u.c.length>t&&(u.c.length=t):n&&(u=u.mod(n))}return n?r:(0>e&&(r=T.div(r)),i?r.mod(i):t?L(r,J,q):r)},M.toPrecision=function(e,n){return D(this,null!=e&&j(e,1,A,24,"precision")?0|e:null,n,24)},M.toString=function(e){var n,t=this,i=t.s,o=t.e;return null===o?i?(n="Infinity",0>i&&(n="-"+n)):n="NaN":(n=r(t.c),n=null!=e&&j(e,2,64,25,"base")?E(c(n,o),0|e,10,i):k>=o||o>=$?l(n,o):c(n,o),0>i&&t.c[0]&&(n="-"+n)),n},M.truncated=M.trunc=function(){return L(new h(this),this.e+1,1)},M.valueOf=M.toJSON=function(){var e,n=this,t=n.e;return null===t?n.toString():(e=r(n.c),e=k>=t||t>=$?l(e,t):c(e,t),n.s<0?"-"+e:e)},null!=e&&h.config(e),h}function t(e){var n=0|e;return e>0||e===n?n:n-1}function r(e){for(var n,t,r=1,i=e.length,o=e[0]+"";i>r;){for(n=e[r++]+"",t=y-n.length;t--;n="0"+n);o+=n}for(i=o.length;48===o.charCodeAt(--i););return o.slice(0,i+1||1)}function i(e,n){var t,r,i=e.c,o=n.c,u=e.s,s=n.s,f=e.e,l=n.e;if(!u||!s)return null;if(t=i&&!i[0],r=o&&!o[0],t||r)return t?r?0:-s:u;if(u!=s)return u;if(t=0>u,r=f==l,!i||!o)return r?0:!i^t?1:-1;if(!r)return f>l^t?1:-1;for(s=(f=i.length)<(l=o.length)?f:l,u=0;s>u;u++)if(i[u]!=o[u])return i[u]>o[u]^t?1:-1;return f==l?0:f>l^t?1:-1}function o(e,n,t){return(e=a(e))>=n&&t>=e}function u(e){return"[object Array]"==Object.prototype.toString.call(e)}function s(e){return!(!e||!e.constructor||e.constructor.isBigNumber!==s)}function f(e,n,t){for(var r,i,o=[0],u=0,s=e.length;s>u;){for(i=o.length;i--;o[i]*=n);for(o[r=0]+=N.indexOf(e.charAt(u++));r<o.length;r++)o[r]>t-1&&(null==o[r+1]&&(o[r+1]=0),o[r+1]+=o[r]/t|0,o[r]%=t)}return o.reverse()}function l(e,n){return(e.length>1?e.charAt(0)+"."+e.slice(1):e)+(0>n?"e":"e+")+n}function c(e,n){var t,r;if(0>n){for(r="0.";++n;r+="0");e=r+e}else if(t=e.length,++n>t){for(r="0",n-=t;--n;r+="0");e+=r}else t>n&&(e=e.slice(0,n)+"."+e.slice(n));return e}function a(e){return e=parseFloat(e),0>e?p(e):d(e)}var h,g=/^-?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,p=Math.ceil,d=Math.floor,m=" not a boolean or binary digit",w="rounding mode",v="number type has more than 15 significant digits",N="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_",b=1e14,y=14,O=9007199254740991,R=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],S=1e7,A=1e9;h=n(),h["default"]=h.BigNumber=h,"function"==typeof define&&define.amd?define(function(){return h}):"undefined"!=typeof module&&module.exports?module.exports=h:(e||(e="undefined"!=typeof self?self:Function("return this")()),e.BigNumber=h)}(this);
//# sourceMappingURL=bignumber.js.map
{
"name": "bignumber.js",
"main": "bignumber.js",
"version": "3.1.2",
"homepage": "https://github.com/MikeMcl/bignumber.js",
"authors": [
"Michael Mclaughlin <M8ch88l@gmail.com>"
],
"description": "A library for arbitrary-precision decimal and non-decimal arithmetic",
"moduleType": [
"amd",
"globals",
"node"
],
"keywords": [
"arbitrary",
"precision",
"arithmetic",
"big",
"number",
"decimal",
"float",
"biginteger",
"bigdecimal",
"bignumber",
"bigint",
"bignum"
],
"license": "MIT",
"ignore": [
".*",
"*.json",
"test"
]
}
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="Author" content="M Mclaughlin">
<title>bignumber.js API</title>
<style>
html{font-size:100%}
body{background:#fff;font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;font-size:13px;
line-height:1.65em;min-height:100%;margin:0}
body,i{color:#000}
.nav{background:#fff;position:fixed;top:0;bottom:0;left:0;width:200px;overflow-y:auto;
padding:15px 0 30px 15px}
div.container{width:600px;margin:50px 0 50px 240px}
p{margin:0 0 1em;width:600px}
pre,ul{margin:1em 0}
h1,h2,h3,h4,h5{margin:0;padding:1.5em 0 0}
h1,h2{padding:.75em 0}
!h1{font:400 3em Consolas,monaco,monospace;color:#000;margin-bottom:1em}
h1{font:400 3em Verdana,sans-serif;color:#000;margin-bottom:1em}
h2{font-size:2.25em;color:#ff2a00}
h3{font-size:1.75em;color:#4dc71f}
h4{font-size:1.75em;color:#ff2a00;padding-bottom:.75em}
h5{font-size:1.2em;margin-bottom:.4em}
h6{font-size:1.1em;margin-bottom:0.8em;padding:0.5em 0}
dd{padding-top:.35em}
dt{padding-top:.5em}
b{font-weight:700}
dt b{font-size:1.3em}
a,a:visited{color:#ff2a00;text-decoration:none}
a:active,a:hover{outline:0;text-decoration:underline}
.nav a,.nav b,.nav a:visited{display:block;color:#ff2a00;font-weight:700; margin-top:15px}
.nav b{color:#4dc71f;margin-top:20px;cursor:default;width:auto}
ul{list-style-type:none;padding:0 0 0 20px}
.nav ul{line-height:14px;padding-left:0;margin:5px 0 0}
.nav ul a,.nav ul a:visited,span{display:inline;color:#000;font-family:Verdana,Geneva,sans-serif;
font-size:11px;font-weight:400;margin:0}
.inset,ul.inset{margin-left:20px}
.inset{font-size:.9em}
.nav li{width:auto;margin:0 0 3px}
.alias{font-style:italic;margin-left:20px}
table{border-collapse:collapse;border-spacing:0;border:2px solid #a7dbd8;margin:1.75em 0;padding:0}
td,th{text-align:left;margin:0;padding:2px 5px;border:1px dotted #a7dbd8}
th{border-top:2px solid #a7dbd8;border-bottom:2px solid #a7dbd8;color:#ff2a00}
code,pre{font-family:Consolas, monaco, monospace;font-weight:400}
pre{background:#f5f5f5;white-space:pre-wrap;word-wrap:break-word;border-left:5px solid #abef98;
padding:1px 0 1px 15px;margin:1.2em 0}
code,.nav-title{color:#ff2a00}
.end{margin-bottom:25px}
.centre{text-align:center}
.error-table{font-size:13px;width:100%}
#faq{margin:3em 0 0}
li span{float:right;margin-right:10px;color:#c0c0c0}
#js{font:inherit;color:#4dc71f}
</style>
</head>
<body>
<div class="nav">
<a class='nav-title' href="#">API</a>
<b> CONSTRUCTOR </b>
<ul>
<li><a href="#bignumber">BigNumber</a></li>
</ul>
<a href="#methods">Methods</a>
<ul>
<li><a href="#another">another</a></li>
<li><a href="#config" >config</a></li>
<li>
<ul class="inset">
<li><a href="#decimal-places">DECIMAL_PLACES</a></li>
<li><a href="#rounding-mode" >ROUNDING_MODE</a></li>
<li><a href="#exponential-at">EXPONENTIAL_AT</a></li>
<li><a href="#range" >RANGE</a></li>
<li><a href="#errors" >ERRORS</a></li>
<li><a href="#crypto" >CRYPTO</a></li>
<li><a href="#modulo-mode" >MODULO_MODE</a></li>
<li><a href="#pow-precision" >POW_PRECISION</a></li>
<li><a href="#format" >FORMAT</a></li>
</ul>
</li>
<li><a href="#is-bignumber">isBigNumber</a></li>
<li><a href="#max">max</a></li>
<li><a href="#min">min</a></li>
<li><a href="#random">random</a></li>
</ul>
<a href="#constructor-properties">Properties</a>
<ul>
<li><a href="#round-up" >ROUND_UP</a></li>
<li><a href="#round-down" >ROUND_DOWN</a></li>
<li><a href="#round-ceil" >ROUND_CEIL</a></li>
<li><a href="#round-floor" >ROUND_FLOOR</a></li>
<li><a href="#round-half-up" >ROUND_HALF_UP</a></li>
<li><a href="#round-half-down" >ROUND_HALF_DOWN</a></li>
<li><a href="#round-half-even" >ROUND_HALF_EVEN</a></li>
<li><a href="#round-half-ceil" >ROUND_HALF_CEIL</a></li>
<li><a href="#round-half-floor">ROUND_HALF_FLOOR</a></li>
</ul>
<b> INSTANCE </b>
<a href="#prototype-methods">Methods</a>
<ul>
<li><a href="#abs" >absoluteValue </a><span>abs</span> </li>
<li><a href="#ceil" >ceil </a> </li>
<li><a href="#cmp" >comparedTo </a><span>cmp</span> </li>
<li><a href="#dp" >decimalPlaces </a><span>dp</span> </li>
<li><a href="#div" >dividedBy </a><span>div</span> </li>
<li><a href="#divInt" >dividedToIntegerBy </a><span>divToInt</span></li>
<li><a href="#eq" >equals </a><span>eq</span> </li>
<li><a href="#floor" >floor </a> </li>
<li><a href="#gt" >greaterThan </a><span>gt</span> </li>
<li><a href="#gte" >greaterThanOrEqualTo</a><span>gte</span> </li>
<li><a href="#isF" >isFinite </a> </li>
<li><a href="#isInt" >isInteger </a><span>isInt</span> </li>
<li><a href="#isNaN" >isNaN </a> </li>
<li><a href="#isNeg" >isNegative </a><span>isNeg</span> </li>
<li><a href="#isZ" >isZero </a> </li>
<li><a href="#lt" >lessThan </a><span>lt</span> </li>
<li><a href="#lte" >lessThanOrEqualTo </a><span>lte</span> </li>
<li><a href="#minus" >minus </a><span>sub</span> </li>
<li><a href="#mod" >modulo </a><span>mod</span> </li>
<li><a href="#neg" >negated </a><span>neg</span> </li>
<li><a href="#plus" >plus </a><span>add</span> </li>
<li><a href="#sd" >precision </a><span>sd</span> </li>
<li><a href="#round" >round </a> </li>
<li><a href="#shift" >shift </a> </li>
<li><a href="#sqrt" >squareRoot </a><span>sqrt</span> </li>
<li><a href="#times" >times </a><span>mul</span> </li>
<li><a href="#toD" >toDigits </a> </li>
<li><a href="#toE" >toExponential </a> </li>
<li><a href="#toFix" >toFixed </a> </li>
<li><a href="#toFor" >toFormat </a> </li>
<li><a href="#toFr" >toFraction </a> </li>
<li><a href="#toJSON" >toJSON </a> </li>
<li><a href="#toN" >toNumber </a> </li>
<li><a href="#pow" >toPower </a><span>pow</span> </li>
<li><a href="#toP" >toPrecision </a> </li>
<li><a href="#toS" >toString </a> </li>
<li><a href="#trunc" >truncated </a><span>trunc</span> </li>
<li><a href="#valueOf">valueOf </a> </li>
</ul>
<a href="#instance-properties">Properties</a>
<ul>
<li><a href="#coefficient">c: coefficient</a></li>
<li><a href="#exponent" >e: exponent</a></li>
<li><a href="#sign" >s: sign</a></li>
</ul>
<a href="#zero-nan-infinity">Zero, NaN &amp; Infinity</a>
<a href="#Errors">Errors</a>
<a class='end' href="#faq">FAQ</a>
</div>
<div class="container">
<h1>bignumber<span id='js'>.js</span></h1>
<p>A JavaScript library for arbitrary-precision arithmetic.</p>
<p><a href="https://github.com/MikeMcl/bignumber.js">Hosted on GitHub</a>. </p>
<h2>API</h2>
<p>
See the <a href='https://github.com/MikeMcl/bignumber.js'>README</a> on GitHub for a
quick-start introduction.
</p>
<p>
In all examples below, <code>var</code> and semicolons are not shown, and if a commented-out
value is in quotes it means <code>toString</code> has been called on the preceding expression.
</p>
<h3>CONSTRUCTOR</h3>
<h5 id="bignumber">
BigNumber<code class='inset'>BigNumber(value [, base]) <i>&rArr; BigNumber</i></code>
</h5>
<dl>
<dt><code>value</code></dt>
<dd>
<i>number|string|BigNumber</i>: see <a href='#range'>RANGE</a> for
range.
</dd>
<dd>
A numeric value.
</dd>
<dd>
Legitimate values include &plusmn;<code>0</code>, &plusmn;<code>Infinity</code> and
<code>NaN</code>.
</dd>
<dd>
Values of type <em>number</em> with more than <code>15</code> significant digits are
considered invalid (if <a href='#errors'><code>ERRORS</code></a> is true) as calling
<code><a href='#toS'>toString</a></code> or <code><a href='#valueOf'>valueOf</a></code> on
such numbers may not result in the intended value.
<pre>console.log( 823456789123456.3 ); // 823456789123456.2</pre>
</dd>
<dd>
There is no limit to the number of digits of a value of type <em>string</em> (other than
that of JavaScript's maximum array size).
</dd>
<dd>
Decimal string values may be in exponential, as well as normal (fixed-point) notation.
Non-decimal values must be in normal notation.
</dd>
<dd>
String values in hexadecimal literal form, e.g. <code>'0xff'</code>, are valid, as are
string values with the octal and binary prefixs <code>'0o'</code> and <code>'0b'</code>.
String values in octal literal form without the prefix will be interpreted as
decimals, e.g. <code>'011'</code> is interpreted as 11, not 9.
</dd>
<dd>Values in any base may have fraction digits.</dd>
<dd>
For bases from <code>10</code> to <code>36</code>, lower and/or upper case letters can be
used to represent values from <code>10</code> to <code>35</code>.
</dd>
<dd>
For bases above 36, <code>a-z</code> represents values from <code>10</code> to
<code>35</code>, <code>A-Z</code> from <code>36</code> to <code>61</code>, and
<code>$</code> and <code>_</code> represent <code>62</code> and <code>63</code> respectively
<i>(this can be changed by editing the <code>ALPHABET</code> variable near the top of the
source file)</i>.
</dd>
</dl>
<dl>
<dt><code>base</code></dt>
<dd>
<i>number</i>: integer, <code>2</code> to <code>64</code> inclusive
</dd>
<dd>The base of <code>value</code>.</dd>
<dd>
If <code>base</code> is omitted, or is <code>null</code> or <code>undefined</code>, base
<code>10</code> is assumed.
</dd>
</dl>
<br />
<p>Returns a new instance of a BigNumber object.</p>
<p>
If a base is specified, the value is rounded according to
the current <a href='#decimal-places'><code>DECIMAL_PLACES</code></a> and
<a href='#rounding-mode'><code>ROUNDING_MODE</code></a> configuration.
</p>
<p>
See <a href='#Errors'>Errors</a> for the treatment of an invalid <code>value</code> or
<code>base</code>.
</p>
<pre>
x = new BigNumber(9) // '9'
y = new BigNumber(x) // '9'
// 'new' is optional if ERRORS is false
BigNumber(435.345) // '435.345'
new BigNumber('5032485723458348569331745.33434346346912144534543')
new BigNumber('4.321e+4') // '43210'
new BigNumber('-735.0918e-430') // '-7.350918e-428'
new BigNumber(Infinity) // 'Infinity'
new BigNumber(NaN) // 'NaN'
new BigNumber('.5') // '0.5'
new BigNumber('+2') // '2'
new BigNumber(-10110100.1, 2) // '-180.5'
new BigNumber(-0b10110100.1) // '-180.5'
new BigNumber('123412421.234324', 5) // '607236.557696'
new BigNumber('ff.8', 16) // '255.5'
new BigNumber('0xff.8') // '255.5'</pre>
<p>
The following throws <code>'not a base 2 number'</code> if
<a href='#errors'><code>ERRORS</code></a> is true, otherwise it returns a BigNumber with value
<code>NaN</code>.
</p>
<pre>new BigNumber(9, 2)</pre>
<p>
The following throws <code>'number type has more than 15 significant digits'</code> if
<a href='#errors'><code>ERRORS</code></a> is true, otherwise it returns a BigNumber with value
<code>96517860459076820</code>.
</p>
<pre>new BigNumber(96517860459076817.4395)</pre>
<p>
The following throws <code>'not a number'</code> if <a href='#errors'><code>ERRORS</code></a>
is true, otherwise it returns a BigNumber with value <code>NaN</code>.
</p>
<pre>new BigNumber('blurgh')</pre>
<p>
A value is only rounded by the constructor if a base is specified.
</p>
<pre>BigNumber.config({ DECIMAL_PLACES: 5 })
new BigNumber(1.23456789) // '1.23456789'
new BigNumber(1.23456789, 10) // '1.23457'</pre>
<h4 id="methods">Methods</h4>
<p>The static methods of a BigNumber constructor.</p>
<h5 id="another">
another<code class='inset'>.another([obj]) <i>&rArr; BigNumber constructor</i></code>
</h5>
<p><code>obj</code>: <i>object</i></p>
<p>
Returns a new independent BigNumber constructor with configuration as described by
<code>obj</code> (see <a href='#config'><code>config</code></a>), or with the default
configuration if <code>obj</code> is <code>null</code> or <code>undefined</code>.
</p>
<pre>BigNumber.config({ DECIMAL_PLACES: 5 })
BN = BigNumber.another({ DECIMAL_PLACES: 9 })
x = new BigNumber(1)
y = new BN(1)
x.div(3) // 0.33333
y.div(3) // 0.333333333
// BN = BigNumber.another({ DECIMAL_PLACES: 9 }) is equivalent to:
BN = BigNumber.another()
BN.config({ DECIMAL_PLACES: 9 })</pre>
<h5 id="config">config<code class='inset'>set([obj]) <i>&rArr; object</i></code></h5>
<p>
<code>obj</code>: <i>object</i>: an object that contains some or all of the following
properties.
</p>
<p>Configures the settings for this particular BigNumber constructor.</p>
<p><i>Note: the configuration can also be supplied as an argument list, see below.</i></p>
<dl class='inset'>
<dt id="decimal-places"><code><b>DECIMAL_PLACES</b></code></dt>
<dd>
<i>number</i>: integer, <code>0</code> to <code>1e+9</code> inclusive<br />
Default value: <code>20</code>
</dd>
<dd>
The <u>maximum</u> number of decimal places of the results of operations involving
division, i.e. division, square root and base conversion operations, and power
operations with negative exponents.<br />
</dd>
<dd>
<pre>BigNumber.config({ DECIMAL_PLACES: 5 })
BigNumber.set({ DECIMAL_PLACES: 5 }) // equivalent
BigNumber.config(5) // equivalent</pre>
</dd>
<dt id="rounding-mode"><code><b>ROUNDING_MODE</b></code></dt>
<dd>
<i>number</i>: integer, <code>0</code> to <code>8</code> inclusive<br />
Default value: <code>4</code> <a href="#round-half-up">(<code>ROUND_HALF_UP</code>)</a>
</dd>
<dd>
The rounding mode used in the above operations and the default rounding mode of
<a href='#round'><code>round</code></a>,
<a href='#toE'><code>toExponential</code></a>,
<a href='#toFix'><code>toFixed</code></a>,
<a href='#toFor'><code>toFormat</code></a> and
<a href='#toP'><code>toPrecision</code></a>.
</dd>
<dd>The modes are available as enumerated properties of the BigNumber constructor.</dd>
<dd>
<pre>BigNumber.config({ ROUNDING_MODE: 0 })
BigNumber.config(null, BigNumber.ROUND_UP) // equivalent</pre>
</dd>
<dt id="exponential-at"><code><b>EXPONENTIAL_AT</b></code></dt>
<dd>
<i>number</i>: integer, magnitude <code>0</code> to <code>1e+9</code> inclusive, or
<br />
<i>number</i>[]: [ integer <code>-1e+9</code> to <code>0</code> inclusive, integer
<code>0</code> to <code>1e+9</code> inclusive ]<br />
Default value: <code>[-7, 20]</code>
</dd>
<dd>
The exponent value(s) at which <code>toString</code> returns exponential notation.
</dd>
<dd>
If a single number is assigned, the value is the exponent magnitude.<br />
If an array of two numbers is assigned then the first number is the negative exponent
value at and beneath which exponential notation is used, and the second number is the
positive exponent value at and above which the same.
</dd>
<dd>
For example, to emulate JavaScript numbers in terms of the exponent values at which they
begin to use exponential notation, use <code>[-7, 20]</code>.
</dd>
<dd>
<pre>BigNumber.config({ EXPONENTIAL_AT: 2 })
new BigNumber(12.3) // '12.3' e is only 1
new BigNumber(123) // '1.23e+2'
new BigNumber(0.123) // '0.123' e is only -1
new BigNumber(0.0123) // '1.23e-2'
BigNumber.config({ EXPONENTIAL_AT: [-7, 20] })
new BigNumber(123456789) // '123456789' e is only 8
new BigNumber(0.000000123) // '1.23e-7'
// Almost never return exponential notation:
BigNumber.config({ EXPONENTIAL_AT: 1e+9 })
// Always return exponential notation:
BigNumber.config({ EXPONENTIAL_AT: 0 })</pre>
</dd>
<dd>
Regardless of the value of <code>EXPONENTIAL_AT</code>, the <code>toFixed</code> method
will always return a value in normal notation and the <code>toExponential</code> method
will always return a value in exponential form.
</dd>
<dd>
Calling <code>toString</code> with a base argument, e.g. <code>toString(10)</code>, will
also always return normal notation.
</dd>
<dt id="range"><code><b>RANGE</b></code></dt>
<dd>
<i>number</i>: integer, magnitude <code>1</code> to <code>1e+9</code> inclusive, or
<br />
<i>number</i>[]: [ integer <code>-1e+9</code> to <code>-1</code> inclusive, integer
<code>1</code> to <code>1e+9</code> inclusive ]<br />
Default value: <code>[-1e+9, 1e+9]</code>
</dd>
<dd>
The exponent value(s) beyond which overflow to <code>Infinity</code> and underflow to
zero occurs.
</dd>
<dd>
If a single number is assigned, it is the maximum exponent magnitude: values wth a
positive exponent of greater magnitude become <code>Infinity</code> and those with a
negative exponent of greater magnitude become zero.
<dd>
If an array of two numbers is assigned then the first number is the negative exponent
limit and the second number is the positive exponent limit.
</dd>
<dd>
For example, to emulate JavaScript numbers in terms of the exponent values at which they
become zero and <code>Infinity</code>, use <code>[-324, 308]</code>.
</dd>
<dd>
<pre>BigNumber.config({ RANGE: 500 })
BigNumber.config().RANGE // [ -500, 500 ]
new BigNumber('9.999e499') // '9.999e+499'
new BigNumber('1e500') // 'Infinity'
new BigNumber('1e-499') // '1e-499'
new BigNumber('1e-500') // '0'
BigNumber.config({ RANGE: [-3, 4] })
new BigNumber(99999) // '99999' e is only 4
new BigNumber(100000) // 'Infinity' e is 5
new BigNumber(0.001) // '0.01' e is only -3
new BigNumber(0.0001) // '0' e is -4</pre>
</dd>
<dd>
The largest possible magnitude of a finite BigNumber is
<code>9.999...e+1000000000</code>.<br />
The smallest possible magnitude of a non-zero BigNumber is <code>1e-1000000000</code>.
</dd>
<dt id="errors"><code><b>ERRORS</b></code></dt>
<dd>
<i>boolean|number</i>: <code>true</code>, <code>false</code>, <code>0</code> or
<code>1</code>.<br />
Default value: <code>true</code>
</dd>
<dd>
The value that determines whether BigNumber Errors are thrown.<br />
If <code>ERRORS</code> is false, no errors will be thrown.
</dd>
<dd>See <a href='#Errors'>Errors</a>.</dd>
<dd><pre>BigNumber.config({ ERRORS: false })</pre></dd>
<dt id="crypto"><code><b>CRYPTO</b></code></dt>
<dd>
<i>boolean|number</i>: <code>true</code>, <code>false</code>, <code>0</code> or
<code>1</code>.<br />
Default value: <code>false</code>
</dd>
<dd>
The value that determines whether cryptographically-secure pseudo-random number
generation is used.
</dd>
<dd>
If <code>CRYPTO</code> is set to <code>true</code> then the
<a href='#random'><code>random</code></a> method will generate random digits using
<code>crypto.getRandomValues</code> in browsers that support it, or
<code>crypto.randomBytes</code> if using a version of Node.js that supports it.
</dd>
<dd>
If neither function is supported by the host environment then attempting to set
<code>CRYPTO</code> to <code>true</code> will fail, and if <code>ERRORS</code>
is <code>true</code> an exception will be thrown.
</dd>
<dd>
If <code>CRYPTO</code> is <code>false</code> then the source of randomness used will be
<code>Math.random</code> (which is assumed to generate at least <code>30</code> bits of
randomness).
</dd>
<dd>See <a href='#random'><code>random</code></a>.</dd>
<dd>
<pre>BigNumber.config({ CRYPTO: true })
BigNumber.config().CRYPTO // true
BigNumber.random() // 0.54340758610486147524</pre>
</dd>
<dt id="modulo-mode"><code><b>MODULO_MODE</b></code></dt>
<dd>
<i>number</i>: integer, <code>0</code> to <code>9</code> inclusive<br />
Default value: <code>1</code> (<a href="#round-down"><code>ROUND_DOWN</code></a>)
</dd>
<dd>The modulo mode used when calculating the modulus: <code>a mod n</code>.</dd>
<dd>
The quotient, <code>q = a / n</code>, is calculated according to the
<a href='#rounding-mode'><code>ROUNDING_MODE</code></a> that corresponds to the chosen
<code>MODULO_MODE</code>.
</dd>
<dd>The remainder, <code>r</code>, is calculated as: <code>r = a - n * q</code>.</dd>
<dd>
The modes that are most commonly used for the modulus/remainder operation are shown in
the following table. Although the other rounding modes can be used, they may not give
useful results.
</dd>
<dd>
<table>
<tr><th>Property</th><th>Value</th><th>Description</th></tr>
<tr>
<td><b>ROUND_UP</b></td><td class='centre'>0</td>
<td>
The remainder is positive if the dividend is negative, otherwise it is negative.
</td>
</tr>
<tr>
<td><b>ROUND_DOWN</b></td><td class='centre'>1</td>
<td>
The remainder has the same sign as the dividend.<br />
This uses 'truncating division' and matches the behaviour of JavaScript's
remainder operator <code>%</code>.
</td>
</tr>
<tr>
<td><b>ROUND_FLOOR</b></td><td class='centre'>3</td>
<td>
The remainder has the same sign as the divisor.<br />
This matches Python's <code>%</code> operator.
</td>
</tr>
<tr>
<td><b>ROUND_HALF_EVEN</b></td><td class='centre'>6</td>
<td>The <i>IEEE 754</i> remainder function.</td>
</tr>
<tr>
<td><b>EUCLID</b></td><td class='centre'>9</td>
<td>
The remainder is always positive. Euclidian division: <br />
<code>q = sign(n) * floor(a / abs(n))</code>
</td>
</tr>
</table>
</dd>
<dd>
The rounding/modulo modes are available as enumerated properties of the BigNumber
constructor.
</dd>
<dd>See <a href='#mod'><code>modulo</code></a>.</dd>
<dd>
<pre>BigNumber.config({ MODULO_MODE: BigNumber.EUCLID })
BigNumber.config({ MODULO_MODE: 9 }) // equivalent</pre>
</dd>
<dt id="pow-precision"><code><b>POW_PRECISION</b></code></dt>
<dd>
<i>number</i>: integer, <code>0</code> to <code>1e+9</code> inclusive.<br />
Default value: <code>0</code>
</dd>
<dd>
The <i>maximum</i> number of significant digits of the result of the power operation
(unless a modulus is specified).
</dd>
<dd>If set to <code>0</code>, the number of signifcant digits will not be limited.</dd>
<dd>See <a href='#pow'><code>toPower</code></a>.</dd>
<dd><pre>BigNumber.config({ POW_PRECISION: 100 })</pre></dd>
<dt id="format"><code><b>FORMAT</b></code></dt>
<dd><i>object</i></dd>
<dd>
The <code>FORMAT</code> object configures the format of the string returned by the
<a href='#toFor'><code>toFormat</code></a> method.
</dd>
<dd>
The example below shows the properties of the <code>FORMAT</code> object that are
recognised, and their default values.
</dd>
<dd>
Unlike the other configuration properties, the values of the properties of the
<code>FORMAT</code> object will not be checked for validity. The existing
<code>FORMAT</code> object will simply be replaced by the object that is passed in.
Note that all the properties shown below do not have to be included.
</dd>
<dd>See <a href='#toFor'><code>toFormat</code></a> for examples of usage.</dd>
<dd>
<pre>
BigNumber.config({
FORMAT: {
// the decimal separator
decimalSeparator: '.',
// the grouping separator of the integer part
groupSeparator: ',',
// the primary grouping size of the integer part
groupSize: 3,
// the secondary grouping size of the integer part
secondaryGroupSize: 0,
// the grouping separator of the fraction part
fractionGroupSeparator: ' ',
// the grouping size of the fraction part
fractionGroupSize: 0
}
});</pre>
</dd>
</dl>
<br />
<p>Returns an object with the above properties and their current values.</p>
<p>
If the value to be assigned to any of the above properties is <code>null</code> or
<code>undefined</code> it is ignored.
</p>
<p>See <a href='#Errors'>Errors</a> for the treatment of invalid values.</p>
<pre>
BigNumber.config({
DECIMAL_PLACES: 40,
ROUNDING_MODE: BigNumber.ROUND_HALF_CEIL,
EXPONENTIAL_AT: [-10, 20],
RANGE: [-500, 500],
ERRORS: true,
CRYPTO: true,
MODULO_MODE: BigNumber.ROUND_FLOOR,
POW_PRECISION: 80,
FORMAT: {
groupSize: 3,
groupSeparator: ' ',
decimalSeparator: ','
}
});
// Alternatively but equivalently (excluding FORMAT):
BigNumber.config( 40, 7, [-10, 20], 500, 1, 1, 3, 80 )
obj = BigNumber.config();
obj.ERRORS // true
obj.RANGE // [-500, 500]</pre>
<h5 id="is-bignumber">
isBigNumber<code class='inset'>.isBigNumber(n) <i>&rArr; boolean</i></code>
</h5>
<p><code>n</code>: <i>any</i></p>
<p>
Returns <code>true</code> if <code>n</code> is a BigNumber instance, otherwise returns
<code>false</code>.
</p>
<pre>
x = 42
y = new BigNumber(x)
BigNumber.isBigNumber(x) // false
BigNumber.isBigNumber(y) // true
BN = BigNumber.another();
z = new BN(x)
BigNumber.isBigNumber(z) // true</pre>
<h5 id="max">
max<code class='inset'>.max([arg1 [, arg2, ...]]) <i>&rArr; BigNumber</i></code>
</h5>
<p>
<code>arg1</code>, <code>arg2</code>, ...: <i>number|string|BigNumber</i><br />
<i>See <code><a href="#bignumber">BigNumber</a></code> for further parameter details.</i>
</p>
<p>
Returns a BigNumber whose value is the maximum of <code>arg1</code>,
<code>arg2</code>,... .
</p>
<p>The argument to this method can also be an array of values.</p>
<p>The return value is always exact and unrounded.</p>
<pre>x = new BigNumber('3257869345.0378653')
BigNumber.max(4e9, x, '123456789.9') // '4000000000'
arr = [12, '13', new BigNumber(14)]
BigNumber.max(arr) // '14'</pre>
<h5 id="min">
min<code class='inset'>.min([arg1 [, arg2, ...]]) <i>&rArr; BigNumber</i></code>
</h5>
<p>
<code>arg1</code>, <code>arg2</code>, ...: <i>number|string|BigNumber</i><br />
<i>See <code><a href="#bignumber">BigNumber</a></code> for further parameter details.</i>
</p>
<p>
Returns a BigNumber whose value is the minimum of <code>arg1</code>,
<code>arg2</code>,... .
</p>
<p>The argument to this method can also be an array of values.</p>
<p>The return value is always exact and unrounded.</p>
<pre>x = new BigNumber('3257869345.0378653')
BigNumber.min(4e9, x, '123456789.9') // '123456789.9'
arr = [2, new BigNumber(-14), '-15.9999', -12]
BigNumber.min(arr) // '-15.9999'</pre>
<h5 id="random">
random<code class='inset'>.random([dp]) <i>&rArr; BigNumber</i></code>
</h5>
<p><code>dp</code>: <i>number</i>: integer, <code>0</code> to <code>1e+9</code> inclusive</p>
<p>
Returns a new BigNumber with a pseudo-random value equal to or greater than <code>0</code> and
less than <code>1</code>.
</p>
<p>
The return value will have <code>dp</code> decimal places (or less if trailing zeros are
produced).<br />
If <code>dp</code> is omitted then the number of decimal places will default to the current
<a href='#decimal-places'><code>DECIMAL_PLACES</code></a> setting.
</p>
<p>
Depending on the value of this BigNumber constructor's
<a href='#crypto'><code>CRYPTO</code></a> setting and the support for the
<code>crypto</code> object in the host environment, the random digits of the return value are
generated by either <code>Math.random</code> (fastest), <code>crypto.getRandomValues</code>
(Web Cryptography API in recent browsers) or <code>crypto.randomBytes</code> (Node.js).
</p>
<p>
If <a href='#crypto'><code>CRYPTO</code></a> is <code>true</code>, i.e. one of the
<code>crypto</code> methods is to be used, the value of a returned BigNumber should be
cryptographically-secure and statistically indistinguishable from a random value.
</p>
<pre>BigNumber.config({ DECIMAL_PLACES: 10 })
BigNumber.random() // '0.4117936847'
BigNumber.random(20) // '0.78193327636914089009'</pre>
<h4 id="constructor-properties">Properties</h4>
<p>
The library's enumerated rounding modes are stored as properties of the constructor.<br />
(They are not referenced internally by the library itself.)
</p>
<p>
Rounding modes <code>0</code> to <code>6</code> (inclusive) are the same as those of Java's
BigDecimal class.
</p>
<table>
<tr>
<th>Property</th>
<th>Value</th>
<th>Description</th>
</tr>
<tr>
<td id="round-up"><b>ROUND_UP</b></td>
<td class='centre'>0</td>
<td>Rounds away from zero</td>
</tr>
<tr>
<td id="round-down"><b>ROUND_DOWN</b></td>
<td class='centre'>1</td>
<td>Rounds towards zero</td>
</tr>
<tr>
<td id="round-ceil"><b>ROUND_CEIL</b></td>
<td class='centre'>2</td>
<td>Rounds towards <code>Infinity</code></td>
</tr>
<tr>
<td id="round-floor"><b>ROUND_FLOOR</b></td>
<td class='centre'>3</td>
<td>Rounds towards <code>-Infinity</code></td>
</tr>
<tr>
<td id="round-half-up"><b>ROUND_HALF_UP</b></td>
<td class='centre'>4</td>
<td>
Rounds towards nearest neighbour.<br />
If equidistant, rounds away from zero
</td>
</tr>
<tr>
<td id="round-half-down"><b>ROUND_HALF_DOWN</b></td>
<td class='centre'>5</td>
<td>
Rounds towards nearest neighbour.<br />
If equidistant, rounds towards zero
</td>
</tr>
<tr>
<td id="round-half-even"><b>ROUND_HALF_EVEN</b></td>
<td class='centre'>6</td>
<td>
Rounds towards nearest neighbour.<br />
If equidistant, rounds towards even neighbour
</td>
</tr>
<tr>
<td id="round-half-ceil"><b>ROUND_HALF_CEIL</b></td>
<td class='centre'>7</td>
<td>
Rounds towards nearest neighbour.<br />
If equidistant, rounds towards <code>Infinity</code>
</td>
</tr>
<tr>
<td id="round-half-floor"><b>ROUND_HALF_FLOOR</b></td>
<td class='centre'>8</td>
<td>
Rounds towards nearest neighbour.<br />
If equidistant, rounds towards <code>-Infinity</code>
</td>
</tr>
</table>
<pre>
BigNumber.config({ ROUNDING_MODE: BigNumber.ROUND_CEIL })
BigNumber.config({ ROUNDING_MODE: 2 }) // equivalent</pre>
<h3>INSTANCE</h3>
<h4 id="prototype-methods">Methods</h4>
<p>The methods inherited by a BigNumber instance from its constructor's prototype object.</p>
<p>A BigNumber is immutable in the sense that it is not changed by its methods. </p>
<p>
The treatment of &plusmn;<code>0</code>, &plusmn;<code>Infinity</code> and <code>NaN</code> is
consistent with how JavaScript treats these values.
</p>
<p>
Many method names have a shorter alias.<br />
(Internally, the library always uses the shorter method names.)
</p>
<h5 id="abs">absoluteValue<code class='inset'>.abs() <i>&rArr; BigNumber</i></code></h5>
<p>
Returns a BigNumber whose value is the absolute value, i.e. the magnitude, of the value of
this BigNumber.
</p>
<p>The return value is always exact and unrounded.</p>
<pre>
x = new BigNumber(-0.8)
y = x.absoluteValue() // '0.8'
z = y.abs() // '0.8'</pre>
<h5 id="ceil">ceil<code class='inset'>.ceil() <i>&rArr; BigNumber</i></code></h5>
<p>
Returns a BigNumber whose value is the value of this BigNumber rounded to
a whole number in the direction of positive <code>Infinity</code>.
</p>
<pre>
x = new BigNumber(1.3)
x.ceil() // '2'
y = new BigNumber(-1.8)
y.ceil() // '-1'</pre>
<h5 id="cmp">comparedTo<code class='inset'>.cmp(n [, base]) <i>&rArr; number</i></code></h5>
<p>
<code>n</code>: <i>number|string|BigNumber</i><br />
<code>base</code>: <i>number</i><br />
<i>See <a href="#bignumber">BigNumber</a> for further parameter details.</i>
</p>
<table>
<tr><th>Returns</th><th>&nbsp;</th></tr>
<tr>
<td class='centre'><code>1</code></td>
<td>If the value of this BigNumber is greater than the value of <code>n</code></td>
</tr>
<tr>
<td class='centre'><code>-1</code></td>
<td>If the value of this BigNumber is less than the value of <code>n</code></td>
</tr>
<tr>
<td class='centre'><code>0</code></td>
<td>If this BigNumber and <code>n</code> have the same value</td>
</tr>
<tr>
<td class='centre'><code>null</code></td>
<td>If the value of either this BigNumber or <code>n</code> is <code>NaN</code></td>
</tr>
</table>
<pre>
x = new BigNumber(Infinity)
y = new BigNumber(5)
x.comparedTo(y) // 1
x.comparedTo(x.minus(1)) // 0
y.cmp(NaN) // null
y.cmp('110', 2) // -1</pre>
<h5 id="dp">decimalPlaces<code class='inset'>.dp() <i>&rArr; number</i></code></h5>
<p>
Return the number of decimal places of the value of this BigNumber, or <code>null</code> if
the value of this BigNumber is &plusmn;<code>Infinity</code> or <code>NaN</code>.
</p>
<pre>
x = new BigNumber(123.45)
x.decimalPlaces() // 2
y = new BigNumber('9.9e-101')
y.dp() // 102</pre>
<h5 id="div">dividedBy<code class='inset'>.div(n [, base]) <i>&rArr; BigNumber</i></code>
</h5>
<p>
<code>n</code>: <i>number|string|BigNumber</i><br />
<code>base</code>: <i>number</i><br />
<i>See <a href="#bignumber">BigNumber</a> for further parameter details.</i>
</p>
<p>
Returns a BigNumber whose value is the value of this BigNumber divided by
<code>n</code>, rounded according to the current
<a href='#decimal-places'><code>DECIMAL_PLACES</code></a> and
<a href='#rounding-mode'><code>ROUNDING_MODE</code></a> configuration.
</p>
<pre>
x = new BigNumber(355)
y = new BigNumber(113)
x.dividedBy(y) // '3.14159292035398230088'
x.div(5) // '71'
x.div(47, 16) // '5'</pre>
<h5 id="divInt">
dividedToIntegerBy<code class='inset'>.divToInt(n [, base]) &rArr;
<i>BigNumber</i></code>
</h5>
<p>
<code>n</code>: <i>number|string|BigNumber</i><br />
<code>base</code>: <i>number</i><br />
<i>See <a href="#bignumber">BigNumber</a> for further parameter details.</i>
</p>
<p>
Return a BigNumber whose value is the integer part of dividing the value of this BigNumber by
<code>n</code>.
</p>
<pre>
x = new BigNumber(5)
y = new BigNumber(3)
x.dividedToIntegerBy(y) // '1'
x.divToInt(0.7) // '7'
x.divToInt('0.f', 16) // '5'</pre>
<h5 id="eq">equals<code class='inset'>.eq(n [, base]) <i>&rArr; boolean</i></code></h5>
<p>
<code>n</code>: <i>number|string|BigNumber</i><br />
<code>base</code>: <i>number</i><br />
<i>See <a href="#bignumber">BigNumber</a> for further parameter details.</i>
</p>
<p>
Returns <code>true</code> if the value of this BigNumber equals the value of <code>n</code>,
otherwise returns <code>false</code>.<br />
As with JavaScript, <code>NaN</code> does not equal <code>NaN</code>.
</p>
<p>Note: This method uses the <a href='#cmp'><code>comparedTo</code></a> method internally.</p>
<pre>
0 === 1e-324 // true
x = new BigNumber(0)
x.equals('1e-324') // false
BigNumber(-0).eq(x) // true ( -0 === 0 )
BigNumber(255).eq('ff', 16) // true
y = new BigNumber(NaN)
y.equals(NaN) // false</pre>
<h5 id="floor">floor<code class='inset'>.floor() <i>&rArr; BigNumber</i></code></h5>
<p>
Returns a BigNumber whose value is the value of this BigNumber rounded to a whole number in
the direction of negative <code>Infinity</code>.
</p>
<pre>
x = new BigNumber(1.8)
x.floor() // '1'
y = new BigNumber(-1.3)
y.floor() // '-2'</pre>
<h5 id="gt">greaterThan<code class='inset'>.gt(n [, base]) <i>&rArr; boolean</i></code></h5>
<p>
<code>n</code>: <i>number|string|BigNumber</i><br />
<code>base</code>: <i>number</i><br />
<i>See <a href="#bignumber">BigNumber</a> for further parameter details.</i>
</p>
<p>
Returns <code>true</code> if the value of this BigNumber is greater than the value of
<code>n</code>, otherwise returns <code>false</code>.
</p>
<p>Note: This method uses the <a href='#cmp'><code>comparedTo</code></a> method internally.</p>
<pre>
0.1 &gt; (0.3 - 0.2) // true
x = new BigNumber(0.1)
x.greaterThan(BigNumber(0.3).minus(0.2)) // false
BigNumber(0).gt(x) // false
BigNumber(11, 3).gt(11.1, 2) // true</pre>
<h5 id="gte">
greaterThanOrEqualTo<code class='inset'>.gte(n [, base]) <i>&rArr; boolean</i></code>
</h5>
<p>
<code>n</code>: <i>number|string|BigNumber</i><br />
<code>base</code>: <i>number</i><br />
<i>See <a href="#bignumber">BigNumber</a> for further parameter details.</i>
</p>
<p>
Returns <code>true</code> if the value of this BigNumber is greater than or equal to the value
of <code>n</code>, otherwise returns <code>false</code>.
</p>
<p>Note: This method uses the <a href='#cmp'><code>comparedTo</code></a> method internally.</p>
<pre>
(0.3 - 0.2) &gt;= 0.1 // false
x = new BigNumber(0.3).minus(0.2)
x.greaterThanOrEqualTo(0.1) // true
BigNumber(1).gte(x) // true
BigNumber(10, 18).gte('i', 36) // true</pre>
<h5 id="isF">isFinite<code class='inset'>.isFinite() <i>&rArr; boolean</i></code></h5>
<p>
Returns <code>true</code> if the value of this BigNumber is a finite number, otherwise
returns <code>false</code>.
</p>
<p>
The only possible non-finite values of a BigNumber are <code>NaN</code>, <code>Infinity</code>
and <code>-Infinity</code>.
</p>
<pre>
x = new BigNumber(1)
x.isFinite() // true
y = new BigNumber(Infinity)
y.isFinite() // false</pre>
<p>
Note: The native method <code>isFinite()</code> can be used if
<code>n &lt;= Number.MAX_VALUE</code>.
</p>
<h5 id="isInt">isInteger<code class='inset'>.isInt() <i>&rArr; boolean</i></code></h5>
<p>
Returns <code>true</code> if the value of this BigNumber is a whole number, otherwise returns
<code>false</code>.
</p>
<pre>
x = new BigNumber(1)
x.isInteger() // true
y = new BigNumber(123.456)
y.isInt() // false</pre>
<h5 id="isNaN">isNaN<code class='inset'>.isNaN() <i>&rArr; boolean</i></code></h5>
<p>
Returns <code>true</code> if the value of this BigNumber is <code>NaN</code>, otherwise
returns <code>false</code>.
</p>
<pre>
x = new BigNumber(NaN)
x.isNaN() // true
y = new BigNumber('Infinity')
y.isNaN() // false</pre>
<p>Note: The native method <code>isNaN()</code> can also be used.</p>
<h5 id="isNeg">isNegative<code class='inset'>.isNeg() <i>&rArr; boolean</i></code></h5>
<p>
Returns <code>true</code> if the value of this BigNumber is negative, otherwise returns
<code>false</code>.
</p>
<pre>
x = new BigNumber(-0)
x.isNegative() // true
y = new BigNumber(2)
y.isNeg() // false</pre>
<p>Note: <code>n &lt; 0</code> can be used if <code>n &lt;= -Number.MIN_VALUE</code>.</p>
<h5 id="isZ">isZero<code class='inset'>.isZero() <i>&rArr; boolean</i></code></h5>
<p>
Returns <code>true</code> if the value of this BigNumber is zero or minus zero, otherwise
returns <code>false</code>.
</p>
<pre>
x = new BigNumber(-0)
x.isZero() && x.isNeg() // true
y = new BigNumber(Infinity)
y.isZero() // false</pre>
<p>Note: <code>n == 0</code> can be used if <code>n &gt;= Number.MIN_VALUE</code>.</p>
<h5 id="lt">lessThan<code class='inset'>.lt(n [, base]) <i>&rArr; boolean</i></code></h5>
<p>
<code>n</code>: <i>number|string|BigNumber</i><br />
<code>base</code>: <i>number</i><br />
<i>See <a href="#bignumber">BigNumber</a> for further parameter details.</i>
</p>
<p>
Returns <code>true</code> if the value of this BigNumber is less than the value of
<code>n</code>, otherwise returns <code>false</code>.
</p>
<p>Note: This method uses the <a href='#cmp'><code>comparedTo</code></a> method internally.</p>
<pre>
(0.3 - 0.2) &lt; 0.1 // true
x = new BigNumber(0.3).minus(0.2)
x.lessThan(0.1) // false
BigNumber(0).lt(x) // true
BigNumber(11.1, 2).lt(11, 3) // true</pre>
<h5 id="lte">
lessThanOrEqualTo<code class='inset'>.lte(n [, base]) <i>&rArr; boolean</i></code>
</h5>
<p>
<code>n</code>: <i>number|string|BigNumber</i><br />
<code>base</code>: <i>number</i><br />
<i>See <a href="#bignumber">BigNumber</a> for further parameter details.</i>
</p>
<p>
Returns <code>true</code> if the value of this BigNumber is less than or equal to the value of
<code>n</code>, otherwise returns <code>false</code>.
</p>
<p>Note: This method uses the <a href='#cmp'><code>comparedTo</code></a> method internally.</p>
<pre>
0.1 &lt;= (0.3 - 0.2) // false
x = new BigNumber(0.1)
x.lessThanOrEqualTo(BigNumber(0.3).minus(0.2)) // true
BigNumber(-1).lte(x) // true
BigNumber(10, 18).lte('i', 36) // true</pre>
<h5 id="minus">
minus<code class='inset'>.minus(n [, base]) <i>&rArr; BigNumber</i></code>
</h5>
<p>
<code>n</code>: <i>number|string|BigNumber</i><br />
<code>base</code>: <i>number</i><br />
<i>See <a href="#bignumber">BigNumber</a> for further parameter details.</i>
</p>
<p>Returns a BigNumber whose value is the value of this BigNumber minus <code>n</code>.</p>
<p>The return value is always exact and unrounded.</p>
<pre>
0.3 - 0.1 // 0.19999999999999998
x = new BigNumber(0.3)
x.minus(0.1) // '0.2'
x.minus(0.6, 20) // '0'</pre>
<h5 id="mod">modulo<code class='inset'>.mod(n [, base]) <i>&rArr; BigNumber</i></code></h5>
<p>
<code>n</code>: <i>number|string|BigNumber</i><br />
<code>base</code>: <i>number</i><br />
<i>See <a href="#bignumber">BigNumber</a> for further parameter details.</i>
</p>
<p>
Returns a BigNumber whose value is the value of this BigNumber modulo <code>n</code>, i.e.
the integer remainder of dividing this BigNumber by <code>n</code>.
</p>
<p>
The value returned, and in particular its sign, is dependent on the value of the
<a href='#modulo-mode'><code>MODULO_MODE</code></a> setting of this BigNumber constructor.
If it is <code>1</code> (default value), the result will have the same sign as this BigNumber,
and it will match that of Javascript's <code>%</code> operator (within the limits of double
precision) and BigDecimal's <code>remainder</code> method.
</p>
<p>The return value is always exact and unrounded.</p>
<p>
See <a href='#modulo-mode'><code>MODULO_MODE</code></a> for a description of the other
modulo modes.
</p>
<pre>
1 % 0.9 // 0.09999999999999998
x = new BigNumber(1)
x.modulo(0.9) // '0.1'
y = new BigNumber(33)
y.mod('a', 33) // '3'</pre>
<h5 id="neg">negated<code class='inset'>.neg() <i>&rArr; BigNumber</i></code></h5>
<p>
Returns a BigNumber whose value is the value of this BigNumber negated, i.e. multiplied by
<code>-1</code>.
</p>
<pre>
x = new BigNumber(1.8)
x.negated() // '-1.8'
y = new BigNumber(-1.3)
y.neg() // '1.3'</pre>
<h5 id="plus">plus<code class='inset'>.plus(n [, base]) <i>&rArr; BigNumber</i></code></h5>
<p>
<code>n</code>: <i>number|string|BigNumber</i><br />
<code>base</code>: <i>number</i><br />
<i>See <a href="#bignumber">BigNumber</a> for further parameter details.</i>
</p>
<p>Returns a BigNumber whose value is the value of this BigNumber plus <code>n</code>.</p>
<p>The return value is always exact and unrounded.</p>
<pre>
0.1 + 0.2 // 0.30000000000000004
x = new BigNumber(0.1)
y = x.plus(0.2) // '0.3'
BigNumber(0.7).plus(x).plus(y) // '1'
x.plus('0.1', 8) // '0.225'</pre>
<h5 id="sd">precision<code class='inset'>.sd([z]) <i>&rArr; number</i></code></h5>
<p>
<code>z</code>: <i>boolean|number</i>: <code>true</code>, <code>false</code>, <code>0</code>
or <code>1</code>
</p>
<p>Returns the number of significant digits of the value of this BigNumber.</p>
<p>
If <code>z</code> is <code>true</code> or <code>1</code> then any trailing zeros of the
integer part of a number are counted as significant digits, otherwise they are not.
</p>
<pre>
x = new BigNumber(1.234)
x.precision() // 4
y = new BigNumber(987000)
y.sd() // 3
y.sd(true) // 6</pre>
<h5 id="round">round<code class='inset'>.round([dp [, rm]]) <i>&rArr; BigNumber</i></code></h5>
<p>
<code>dp</code>: <i>number</i>: integer, <code>0</code> to <code>1e+9</code> inclusive<br />
<code>rm</code>: <i>number</i>: integer, <code>0</code> to <code>8</code> inclusive
</p>
<p>
Returns a BigNumber whose value is the value of this BigNumber rounded by rounding mode
<code>rm</code> to a maximum of <code>dp</code> decimal places.
</p>
<p>
if <code>dp</code> is omitted, or is <code>null</code> or <code>undefined</code>, the
return value is <code>n</code> rounded to a whole number.<br />
if <code>rm</code> is omitted, or is <code>null</code> or <code>undefined</code>,
<a href='#rounding-mode'><code>ROUNDING_MODE</code></a> is used.
</p>
<p>
See <a href='#Errors'>Errors</a> for the treatment of other non-integer or out of range
<code>dp</code> or <code>rm</code> values.
</p>
<pre>
x = 1234.56
Math.round(x) // 1235
y = new BigNumber(x)
y.round() // '1235'
y.round(1) // '1234.6'
y.round(2) // '1234.56'
y.round(10) // '1234.56'
y.round(0, 1) // '1234'
y.round(0, 6) // '1235'
y.round(1, 1) // '1234.5'
y.round(1, BigNumber.ROUND_HALF_EVEN) // '1234.6'
y // '1234.56'</pre>
<h5 id="shift">shift<code class='inset'>.shift(n) <i>&rArr; BigNumber</i></code></h5>
<p>
<code>n</code>: <i>number</i>: integer,
<code>-9007199254740991</code> to <code>9007199254740991</code> inclusive
</p>
<p>
Returns a BigNumber whose value is the value of this BigNumber shifted <code>n</code> places.
<p>
The shift is of the decimal point, i.e. of powers of ten, and is to the left if <code>n</code>
is negative or to the right if <code>n</code> is positive.
</p>
<p>The return value is always exact and unrounded.</p>
<pre>
x = new BigNumber(1.23)
x.shift(3) // '1230'
x.shift(-3) // '0.00123'</pre>
<h5 id="sqrt">squareRoot<code class='inset'>.sqrt() <i>&rArr; BigNumber</i></code></h5>
<p>
Returns a BigNumber whose value is the square root of the value of this BigNumber,
rounded according to the current
<a href='#decimal-places'><code>DECIMAL_PLACES</code></a> and
<a href='#rounding-mode'><code>ROUNDING_MODE</code></a> configuration.
</p>
<p>
The return value will be correctly rounded, i.e. rounded as if the result was first calculated
to an infinite number of correct digits before rounding.
</p>
<pre>
x = new BigNumber(16)
x.squareRoot() // '4'
y = new BigNumber(3)
y.sqrt() // '1.73205080756887729353'</pre>
<h5 id="times">times<code class='inset'>.times(n [, base]) <i>&rArr; BigNumber</i></code></h5>
<p>
<code>n</code>: <i>number|string|BigNumber</i><br />
<code>base</code>: <i>number</i><br />
<i>See <a href="#bignumber">BigNumber</a> for further parameter details.</i>
</p>
<p>Returns a BigNumber whose value is the value of this BigNumber times <code>n</code>.</p>
<p>The return value is always exact and unrounded.</p>
<pre>
0.6 * 3 // 1.7999999999999998
x = new BigNumber(0.6)
y = x.times(3) // '1.8'
BigNumber('7e+500').times(y) // '1.26e+501'
x.times('-a', 16) // '-6'</pre>
<h5 id="toD">
toDigits<code class='inset'>.toDigits([sd [, rm]]) <i>&rArr; BigNumber</i></code>
</h5>
<p>
<code>sd</code>: <i>number</i>: integer, <code>1</code> to <code>1e+9</code> inclusive.<br />
<code>rm</code>: <i>number</i>: integer, <code>0</code> to <code>8</code> inclusive.
</p>
<p>
Returns a BigNumber whose value is the value of this BigNumber rounded to <code>sd</code>
significant digits using rounding mode <code>rm</code>.
</p>
<p>
If <code>sd</code> is omitted or is <code>null</code> or <code>undefined</code>, the return
value will not be rounded.<br />
If <code>rm</code> is omitted or is <code>null</code> or <code>undefined</code>,
<a href='#rounding-mode'><code>ROUNDING_MODE</code></a> will be used.
</p>
<p>
See <a href='#Errors'>Errors</a> for the treatment of other non-integer or out of range
<code>sd</code> or <code>rm</code> values.
</p>
<pre>
BigNumber.config({ precision: 5, rounding: 4 })
x = new BigNumber(9876.54321)
x.toDigits() // '9876.5'
x.toDigits(6) // '9876.54'
x.toDigits(6, BigNumber.ROUND_UP) // '9876.55'
x.toDigits(2) // '9900'
x.toDigits(2, 1) // '9800'
x // '9876.54321'</pre>
<h5 id="toE">
toExponential<code class='inset'>.toExponential([dp [, rm]]) <i>&rArr; string</i></code>
</h5>
<p>
<code>dp</code>: <i>number</i>: integer, <code>0</code> to <code>1e+9</code> inclusive<br />
<code>rm</code>: <i>number</i>: integer, <code>0</code> to <code>8</code> inclusive
</p>
<p>
Returns a string representing the value of this BigNumber in exponential notation rounded
using rounding mode <code>rm</code> to <code>dp</code> decimal places, i.e with one digit
before the decimal point and <code>dp</code> digits after it.
</p>
<p>
If the value of this BigNumber in exponential notation has fewer than <code>dp</code> fraction
digits, the return value will be appended with zeros accordingly.
</p>
<p>
If <code>dp</code> is omitted, or is <code>null</code> or <code>undefined</code>, the number
of digits after the decimal point defaults to the minimum number of digits necessary to
represent the value exactly.<br />
If <code>rm</code> is omitted or is <code>null</code> or <code>undefined</code>,
<a href='#rounding-mode'><code>ROUNDING_MODE</code></a> is used.
</p>
<p>
See <a href='#Errors'>Errors</a> for the treatment of other non-integer or out of range
<code>dp</code> or <code>rm</code> values.
</p>
<pre>
x = 45.6
y = new BigNumber(x)
x.toExponential() // '4.56e+1'
y.toExponential() // '4.56e+1'
x.toExponential(0) // '5e+1'
y.toExponential(0) // '5e+1'
x.toExponential(1) // '4.6e+1'
y.toExponential(1) // '4.6e+1'
y.toExponential(1, 1) // '4.5e+1' (ROUND_DOWN)
x.toExponential(3) // '4.560e+1'
y.toExponential(3) // '4.560e+1'</pre>
<h5 id="toFix">
toFixed<code class='inset'>.toFixed([dp [, rm]]) <i>&rArr; string</i></code>
</h5>
<p>
<code>dp</code>: <i>number</i>: integer, <code>0</code> to <code>1e+9</code> inclusive<br />
<code>rm</code>: <i>number</i>: integer, <code>0</code> to <code>8</code> inclusive
</p>
<p>
Returns a string representing the value of this BigNumber in normal (fixed-point) notation
rounded to <code>dp</code> decimal places using rounding mode <code>rm</code>.
</p>
<p>
If the value of this BigNumber in normal notation has fewer than <code>dp</code> fraction
digits, the return value will be appended with zeros accordingly.
</p>
<p>
Unlike <code>Number.prototype.toFixed</code>, which returns exponential notation if a number
is greater or equal to <code>10<sup>21</sup></code>, this method will always return normal
notation.
</p>
<p>
If <code>dp</code> is omitted or is <code>null</code> or <code>undefined</code>, the return
value will be unrounded and in normal notation. This is also unlike
<code>Number.prototype.toFixed</code>, which returns the value to zero decimal places.<br />
It is useful when fixed-point notation is required and the current
<a href="#exponential-at"><code>EXPONENTIAL_AT</code></a> setting causes
<code><a href='#toS'>toString</a></code> to return exponential notation.<br />
If <code>rm</code> is omitted or is <code>null</code> or <code>undefined</code>,
<a href='#rounding-mode'><code>ROUNDING_MODE</code></a> is used.
</p>
<p>
See <a href='#Errors'>Errors</a> for the treatment of other non-integer or out of range
<code>dp</code> or <code>rm</code> values.
</p>
<pre>
x = 3.456
y = new BigNumber(x)
x.toFixed() // '3'
y.toFixed() // '3.456'
y.toFixed(0) // '3'
x.toFixed(2) // '3.46'
y.toFixed(2) // '3.46'
y.toFixed(2, 1) // '3.45' (ROUND_DOWN)
x.toFixed(5) // '3.45600'
y.toFixed(5) // '3.45600'</pre>
<h5 id="toFor">
toFormat<code class='inset'>.toFormat([dp [, rm]]) <i>&rArr; string</i></code>
</h5>
<p>
<code>dp</code>: <i>number</i>: integer, <code>0</code> to <code>1e+9</code> inclusive<br />
<code>rm</code>: <i>number</i>: integer, <code>0</code> to <code>8</code> inclusive
</p>
<p>
<p>
Returns a string representing the value of this BigNumber in normal (fixed-point) notation
rounded to <code>dp</code> decimal places using rounding mode <code>rm</code>, and formatted
according to the properties of the <a href='#format'><code>FORMAT</code></a> object.
</p>
<p>
See the examples below for the properties of the
<a href='#format'><code>FORMAT</code></a> object, their types and their usage.
</p>
<p>
If <code>dp</code> is omitted or is <code>null</code> or <code>undefined</code>, then the
return value is not rounded to a fixed number of decimal places.<br />
If <code>rm</code> is omitted or is <code>null</code> or <code>undefined</code>,
<a href='#rounding-mode'><code>ROUNDING_MODE</code></a> is used.
</p>
<p>
See <a href='#Errors'>Errors</a> for the treatment of other non-integer or out of range
<code>dp</code> or <code>rm</code> values.
</p>
<pre>
format = {
decimalSeparator: '.',
groupSeparator: ',',
groupSize: 3,
secondaryGroupSize: 0,
fractionGroupSeparator: ' ',
fractionGroupSize: 0
}
BigNumber.config({ FORMAT: format })
x = new BigNumber('123456789.123456789')
x.toFormat() // '123,456,789.123456789'
x.toFormat(1) // '123,456,789.1'
// If a reference to the object assigned to FORMAT has been retained,
// the format properties can be changed directly
format.groupSeparator = ' '
format.fractionGroupSize = 5
x.toFormat() // '123 456 789.12345 6789'
BigNumber.config({
FORMAT: {
decimalSeparator = ',',
groupSeparator = '.',
groupSize = 3,
secondaryGroupSize = 2
}
})
x.toFormat(6) // '12.34.56.789,123'</pre>
<h5 id="toFr">
toFraction<code class='inset'>.toFraction([max]) <i>&rArr; [string, string]</i></code>
</h5>
<p>
<code>max</code>: <i>number|string|BigNumber</i>: integer &gt;= <code>1</code> and &lt;
<code>Infinity</code>
</p>
<p>
Returns a string array representing the value of this BigNumber as a simple fraction with an
integer numerator and an integer denominator. The denominator will be a positive non-zero
value less than or equal to <code>max</code>.
</p>
<p>
If a maximum denominator, <code>max</code>, is not specified, or is <code>null</code> or
<code>undefined</code>, the denominator will be the lowest value necessary to represent the
number exactly.
</p>
<p>
See <a href='#Errors'>Errors</a> for the treatment of other non-integer or out of range
<code>max</code> values.
</p>
<pre>
x = new BigNumber(1.75)
x.toFraction() // '7, 4'
pi = new BigNumber('3.14159265358')
pi.toFraction() // '157079632679,50000000000'
pi.toFraction(100000) // '312689, 99532'
pi.toFraction(10000) // '355, 113'
pi.toFraction(100) // '311, 99'
pi.toFraction(10) // '22, 7'
pi.toFraction(1) // '3, 1'</pre>
<h5 id="toJSON">toJSON<code class='inset'>.toJSON() <i>&rArr; string</i></code></h5>
<p>As <code>valueOf</code>.</p>
<pre>
x = new BigNumber('177.7e+457')
y = new BigNumber(235.4325)
z = new BigNumber('0.0098074')
// Serialize an array of three BigNumbers
str = JSON.stringify( [x, y, z] )
// "["1.777e+459","235.4325","0.0098074"]"
// Return an array of three BigNumbers
JSON.parse(str, function (key, val) {
return key === '' ? val : new BigNumber(val)
})</pre>
<h5 id="toN">toNumber<code class='inset'>.toNumber() <i>&rArr; number</i></code></h5>
<p>Returns the value of this BigNumber as a JavaScript number primitive.</p>
<p>
Type coercion with, for example, the unary plus operator will also work, except that a
BigNumber with the value minus zero will be converted to positive zero.
</p>
<pre>
x = new BigNumber(456.789)
x.toNumber() // 456.789
+x // 456.789
y = new BigNumber('45987349857634085409857349856430985')
y.toNumber() // 4.598734985763409e+34
z = new BigNumber(-0)
1 / +z // Infinity
1 / z.toNumber() // -Infinity</pre>
<h5 id="pow">toPower<code class='inset'>.pow(n [, m]) <i>&rArr; BigNumber</i></code></h5>
<p>
<code>n</code>: <i>number</i>: integer,
<code>-9007199254740991</code> to <code>9007199254740991</code> inclusive<br />
<code>m</code>: <i>number|string|BigNumber</i>
</p>
<p>
Returns a BigNumber whose value is the value of this BigNumber raised to the power
<code>n</code>, and optionally modulo a modulus <code>m</code>.
</p>
<p>
If <code>n</code> is negative the result is rounded according to the current
<a href='#decimal-places'><code>DECIMAL_PLACES</code></a> and
<a href='#rounding-mode'><code>ROUNDING_MODE</code></a> configuration.
</p>
<p>
If <code>n</code> is not an integer or is out of range:
</p>
<p class='inset'>
If <code>ERRORS</code> is <code>true</code> a BigNumber Error is thrown,<br />
else if <code>n</code> is greater than <code>9007199254740991</code>, it is interpreted as
<code>Infinity</code>;<br />
else if <code>n</code> is less than <code>-9007199254740991</code>, it is interpreted as
<code>-Infinity</code>;<br />
else if <code>n</code> is otherwise a number, it is truncated to an integer;<br />
else it is interpreted as <code>NaN</code>.
</p>
<p>
As the number of digits of the result of the power operation can grow so large so quickly,
e.g. 123.456<sup>10000</sup> has over <code>50000</code> digits, the number of significant
digits calculated is limited to the value of the
<a href='#pow-precision'><code>POW_PRECISION</code></a> setting (unless a modulus
<code>m</code> is specified).
</p>
<p>
By default <a href='#pow-precision'><code>POW_PRECISION</code></a> is set to <code>0</code>.
This means that an unlimited number of significant digits will be calculated, and that the
method's performance will decrease dramatically for larger exponents.
</p>
<p>
Negative exponents will be calculated to the number of decimal places specified by
<a href='#decimal-places'><code>DECIMAL_PLACES</code></a> (but not to more than
<a href='#pow-precision'><code>POW_PRECISION</code></a> significant digits).
</p>
<p>
If <code>m</code> is specified and the value of <code>m</code>, <code>n</code> and this
BigNumber are positive integers, then a fast modular exponentiation algorithm is used,
otherwise if any of the values is not a positive integer the operation will simply be
performed as <code>x.toPower(n).modulo(m)</code> with a
<a href='#pow-precision'><code>POW_PRECISION</code></a> of <code>0</code>.
</p>
<pre>
Math.pow(0.7, 2) // 0.48999999999999994
x = new BigNumber(0.7)
x.toPower(2) // '0.49'
BigNumber(3).pow(-2) // '0.11111111111111111111'</pre>
<h5 id="toP">
toPrecision<code class='inset'>.toPrecision([sd [, rm]]) <i>&rArr; string</i></code>
</h5>
<p>
<code>sd</code>: <i>number</i>: integer, <code>1</code> to <code>1e+9</code> inclusive<br />
<code>rm</code>: <i>number</i>: integer, <code>0</code> to <code>8</code> inclusive
</p>
<p>
Returns a string representing the value of this BigNumber rounded to <code>sd</code>
significant digits using rounding mode <code>rm</code>.
</p>
<p>
If <code>sd</code> is less than the number of digits necessary to represent the integer part
of the value in normal (fixed-point) notation, then exponential notation is used.
</p>
<p>
If <code>sd</code> is omitted, or is <code>null</code> or <code>undefined</code>, then the
return value is the same as <code>n.toString()</code>.<br />
If <code>rm</code> is omitted or is <code>null</code> or <code>undefined</code>,
<a href='#rounding-mode'><code>ROUNDING_MODE</code></a> is used.
</p>
<p>
See <a href='#Errors'>Errors</a> for the treatment of other non-integer or out of range
<code>sd</code> or <code>rm</code> values.
</p>
<pre>
x = 45.6
y = new BigNumber(x)
x.toPrecision() // '45.6'
y.toPrecision() // '45.6'
x.toPrecision(1) // '5e+1'
y.toPrecision(1) // '5e+1'
y.toPrecision(2, 0) // '4.6e+1' (ROUND_UP)
y.toPrecision(2, 1) // '4.5e+1' (ROUND_DOWN)
x.toPrecision(5) // '45.600'
y.toPrecision(5) // '45.600'</pre>
<h5 id="toS">toString<code class='inset'>.toString([base]) <i>&rArr; string</i></code></h5>
<p><code>base</code>: <i>number</i>: integer, <code>2</code> to <code>64</code> inclusive</p>
<p>
Returns a string representing the value of this BigNumber in the specified base, or base
<code>10</code> if <code>base</code> is omitted or is <code>null</code> or
<code>undefined</code>.
</p>
<p>
For bases above <code>10</code>, values from <code>10</code> to <code>35</code> are
represented by <code>a-z</code> (as with <code>Number.prototype.toString</code>),
<code>36</code> to <code>61</code> by <code>A-Z</code>, and <code>62</code> and
<code>63</code> by <code>$</code> and <code>_</code> respectively.
</p>
<p>
If a base is specified the value is rounded according to the current
<a href='#decimal-places'><code>DECIMAL_PLACES</code></a>
and <a href='#rounding-mode'><code>ROUNDING_MODE</code></a> configuration.
</p>
<p>
If a base is not specified, and this BigNumber has a positive
exponent that is equal to or greater than the positive component of the
current <a href="#exponential-at"><code>EXPONENTIAL_AT</code></a> setting,
or a negative exponent equal to or less than the negative component of the
setting, then exponential notation is returned.
</p>
<p>If <code>base</code> is <code>null</code> or <code>undefined</code> it is ignored.</p>
<p>
See <a href='#Errors'>Errors</a> for the treatment of other non-integer or out of range
<code>base</code> values.
</p>
<pre>
x = new BigNumber(750000)
x.toString() // '750000'
BigNumber.config({ EXPONENTIAL_AT: 5 })
x.toString() // '7.5e+5'
y = new BigNumber(362.875)
y.toString(2) // '101101010.111'
y.toString(9) // '442.77777777777777777778'
y.toString(32) // 'ba.s'
BigNumber.config({ DECIMAL_PLACES: 4 });
z = new BigNumber('1.23456789')
z.toString() // '1.23456789'
z.toString(10) // '1.2346'</pre>
<h5 id="trunc">truncated<code class='inset'>.trunc() <i>&rArr; BigNumber</i></code></h5>
<p>
Returns a BigNumber whose value is the value of this BigNumber truncated to a whole number.
</p>
<pre>
x = new BigNumber(123.456)
x.truncated() // '123'
y = new BigNumber(-12.3)
y.trunc() // '-12'</pre>
<h5 id="valueOf">valueOf<code class='inset'>.valueOf() <i>&rArr; string</i></code></h5>
<p>
As <code>toString</code>, but does not accept a base argument and includes the minus sign
for negative zero.
</p>
<pre>
x = new BigNumber('-0')
x.toString() // '0'
x.valueOf() // '-0'
y = new BigNumber('1.777e+457')
y.valueOf() // '1.777e+457'</pre>
<h4 id="instance-properties">Properties</h4>
<p>A BigNumber is an object with three properties:</p>
<table>
<tr>
<th>Property</th>
<th>Description</th>
<th>Type</th>
<th>Value</th>
</tr>
<tr>
<td class='centre' id='coefficient'><b>c</b></td>
<td>coefficient<sup>*</sup></td>
<td><i>number</i><code>[]</code></td>
<td> Array of base <code>1e14</code> numbers</td>
</tr>
<tr>
<td class='centre' id='exponent'><b>e</b></td>
<td>exponent</td>
<td><i>number</i></td>
<td>Integer, <code>-1000000000</code> to <code>1000000000</code> inclusive</td>
</tr>
<tr>
<td class='centre' id='sign'><b>s</b></td>
<td>sign</td>
<td><i>number</i></td>
<td><code>-1</code> or <code>1</code></td>
</tr>
</table>
<p><sup>*</sup>significand</p>
<p>The value of any of the three properties may also be <code>null</code>. </p>
<p>
From v2.0.0 of this library, the value of the coefficient of a BigNumber is stored in a
normalised base <code>100000000000000</code> floating point format, as opposed to the base
<code>10</code> format used in v1.x.x
</p>
<p>
This change means the properties of a BigNumber are now best considered to be read-only.
Previously it was acceptable to change the exponent of a BigNumber by writing to its exponent
property directly, but this is no longer recommended as the number of digits in the first
element of the coefficient array is dependent on the exponent, so the coefficient would also
need to be altered.
</p>
<p>
Note that, as with JavaScript numbers, the original exponent and fractional trailing zeros are
not necessarily preserved.
</p>
<pre>x = new BigNumber(0.123) // '0.123'
x.toExponential() // '1.23e-1'
x.c // '1,2,3'
x.e // -1
x.s // 1
y = new Number(-123.4567000e+2) // '-12345.67'
y.toExponential() // '-1.234567e+4'
z = new BigNumber('-123.4567000e+2') // '-12345.67'
z.toExponential() // '-1.234567e+4'
z.c // '1,2,3,4,5,6,7'
z.e // 4
z.s // -1</pre>
<h4 id="zero-nan-infinity">Zero, NaN and Infinity</h4>
<p>
The table below shows how &plusmn;<code>0</code>, <code>NaN</code> and
&plusmn;<code>Infinity</code> are stored.
</p>
<table>
<tr>
<th> </th>
<th class='centre'>c</th>
<th class='centre'>e</th>
<th class='centre'>s</th>
</tr>
<tr>
<td>&plusmn;0</td>
<td><code>[0]</code></td>
<td><code>0</code></td>
<td><code>&plusmn;1</code></td>
</tr>
<tr>
<td>NaN</td>
<td><code>null</code></td>
<td><code>null</code></td>
<td><code>null</code></td>
</tr>
<tr>
<td>&plusmn;Infinity</td>
<td><code>null</code></td>
<td><code>null</code></td>
<td><code>&plusmn;1</code></td>
</tr>
</table>
<pre>
x = new Number(-0) // 0
1 / x == -Infinity // true
y = new BigNumber(-0) // '0'
y.c // '0' ( [0].toString() )
y.e // 0
y.s // -1</pre>
<h4 id='Errors'>Errors</h4>
<p>
The errors that are thrown are generic <code>Error</code> objects with <code>name</code>
<i>BigNumber Error</i>.
</p>
<p>
The table below shows the errors that may be thrown if <code>ERRORS</code> is
<code>true</code>, and the action taken if <code>ERRORS</code> is <code>false</code>.
</p>
<table class='error-table'>
<tr>
<th>Method(s)</th>
<th>ERRORS: true<br />Throw BigNumber Error</th>
<th>ERRORS: false<br />Action on invalid argument</th>
</tr>
<tr>
<td rowspan=5>
<code>
BigNumber<br />
comparedTo<br />
dividedBy<br />
dividedToIntegerBy<br />
equals<br />
greaterThan<br />
greaterThanOrEqualTo<br />
lessThan<br />
lessThanOrEqualTo<br />
minus<br />
modulo<br />
plus<br />
times
</code></td>
<td>number type has more than<br />15 significant digits</td>
<td>Accept.</td>
</tr>
<tr>
<td>not a base... number</td>
<td>Substitute <code>NaN</code>.</td>
</tr>
<tr>
<td>base not an integer</td>
<td>Truncate to integer.<br />Ignore if not a number.</td>
</tr>
<tr>
<td>base out of range</td>
<td>Ignore.</td>
</tr>
<tr>
<td>not a number<sup>*</sup></td>
<td>Substitute <code>NaN</code>.</td>
</tr>
<tr>
<td><code>another</code></td>
<td>not an object</td>
<td>Ignore.</td>
</tr>
<tr>
<td rowspan=17><code>config</code></td>
<td><code>DECIMAL_PLACES</code> not an integer</td>
<td>Truncate to integer.<br />Ignore if not a number.</td>
</tr>
<tr>
<td><code>DECIMAL_PLACES</code> out of range</td>
<td>Ignore.</td>
</tr>
<tr>
<td><code>ROUNDING_MODE</code> not an integer</td>
<td>Truncate to integer.<br />Ignore if not a number.</td>
</tr>
<tr>
<td><code>ROUNDING_MODE</code> out of range</td>
<td>Ignore.</td>
</tr>
<tr>
<td><code>EXPONENTIAL_AT</code> not an integer<br />or not [integer, integer]</td>
<td>Truncate to integer(s).<br />Ignore if not number(s).</td>
</tr>
<tr>
<td><code>EXPONENTIAL_AT</code> out of range<br />or not [negative, positive]</td>
<td>Ignore.</td>
</tr>
<tr>
<td><code>RANGE</code> not an integer<br />or not [integer, integer]</td>
<td> Truncate to integer(s).<br />Ignore if not number(s).</td>
</tr>
<tr>
<td><code>RANGE</code> cannot be zero</td>
<td>Ignore.</td>
</tr>
<tr>
<td><code>RANGE</code> out of range<br />or not [negative, positive]</td>
<td>Ignore.</td>
</tr>
<tr>
<td><code>ERRORS</code> not a boolean<br />or binary digit</td>
<td>Ignore.</td>
</tr>
<tr>
<td><code>CRYPTO</code> not a boolean<br />or binary digit</td>
<td>Ignore.</td>
</tr>
<tr>
<td><code>CRYPTO</code> crypto unavailable</td>
<td>Ignore.</td>
</tr>
<tr>
<td><code>MODULO_MODE</code> not an integer</td>
<td>Truncate to integer.<br />Ignore if not a number.</td>
</tr>
<tr>
<td><code>MODULO_MODE</code> out of range</td>
<td>Ignore.</td>
</tr>
<tr>
<td><code>POW_PRECISION</code> not an integer</td>
<td>Truncate to integer.<br />Ignore if not a number.</td>
</tr>
<tr>
<td><code>POW_PRECISION</code> out of range</td>
<td>Ignore.</td>
</tr>
<tr>
<td><code>FORMAT</code> not an object</td>
<td>Ignore.</td>
</tr>
<tr>
<td><code>precision</code></td>
<td>argument not a boolean<br />or binary digit</td>
<td>Ignore.</td>
</tr>
<tr>
<td rowspan=4><code>round</code></td>
<td>decimal places not an integer</td>
<td>Truncate to integer.<br />Ignore if not a number.</td>
</tr>
<tr>
<td>decimal places out of range</td>
<td>Ignore.</td>
</tr>
<tr>
<td>rounding mode not an integer</td>
<td>Truncate to integer.<br />Ignore if not a number.</td>
</tr>
<tr>
<td>rounding mode out of range</td>
<td>Ignore.</td>
</tr>
<tr>
<td rowspan=2><code>shift</code></td>
<td>argument not an integer</td>
<td>Truncate to integer.<br />Ignore if not a number.</td>
</tr>
<tr>
<td>argument out of range</td>
<td>Substitute &plusmn;<code>Infinity</code>.
</tr>
<tr>
<td rowspan=4>
<code>toExponential</code><br />
<code>toFixed</code><br />
<code>toFormat</code>
</td>
<td>decimal places not an integer</td>
<td>Truncate to integer.<br />Ignore if not a number.</td>
</tr>
<tr>
<td>decimal places out of range</td>
<td>Ignore.</td>
</tr>
<tr>
<td>rounding mode not an integer</td>
<td>Truncate to integer.<br />Ignore if not a number.</td>
</tr>
<tr>
<td>rounding mode out of range</td>
<td>Ignore.</td>
</tr>
<tr>
<td rowspan=2><code>toFraction</code></td>
<td>max denominator not an integer</td>
<td>Truncate to integer.<br />Ignore if not a number.</td>
</tr>
<tr>
<td>max denominator out of range</td>
<td>Ignore.</td>
</tr>
<tr>
<td rowspan=4>
<code>toDigits</code><br />
<code>toPrecision</code>
</td>
<td>precision not an integer</td>
<td>Truncate to integer.<br />Ignore if not a number.</td>
</tr>
<tr>
<td>precision out of range</td>
<td>Ignore.</td>
</tr>
<tr>
<td>rounding mode not an integer</td>
<td>Truncate to integer.<br />Ignore if not a number.</td>
</tr>
<tr>
<td>rounding mode out of range</td>
<td>Ignore.</td>
</tr>
<tr>
<td rowspan=2><code>toPower</code></td>
<td>exponent not an integer</td>
<td>Truncate to integer.<br />Substitute <code>NaN</code> if not a number.</td>
</tr>
<tr>
<td>exponent out of range</td>
<td>Substitute &plusmn;<code>Infinity</code>.
</td>
</tr>
<tr>
<td rowspan=2><code>toString</code></td>
<td>base not an integer</td>
<td>Truncate to integer.<br />Ignore if not a number.</td>
</tr>
<tr>
<td>base out of range</td>
<td>Ignore.</td>
</tr>
</table>
<p><sup>*</sup>No error is thrown if the value is <code>NaN</code> or 'NaN'.</p>
<p>
The message of a <i>BigNumber Error</i> will also contain the name of the method from which
the error originated.
</p>
<p>To determine if an exception is a <i>BigNumber Error</i>:</p>
<pre>
try {
// ...
} catch (e) {
if ( e instanceof Error && e.name == 'BigNumber Error' ) {
// ...
}
}</pre>
<h4 id='faq'>FAQ</h4>
<h6>Why are trailing fractional zeros removed from BigNumbers?</h6>
<p>
Some arbitrary-precision libraries retain trailing fractional zeros as they can indicate the
precision of a value. This can be useful but the results of arithmetic operations can be
misleading.
</p>
<pre>
x = new BigDecimal("1.0")
y = new BigDecimal("1.1000")
z = x.add(y) // 2.1000
x = new BigDecimal("1.20")
y = new BigDecimal("3.45000")
z = x.multiply(y) // 4.1400000</pre>
<p>
To specify the precision of a value is to specify that the value lies
within a certain range.
</p>
<p>
In the first example, <code>x</code> has a value of <code>1.0</code>. The trailing zero shows
the precision of the value, implying that it is in the range <code>0.95</code> to
<code>1.05</code>. Similarly, the precision indicated by the trailing zeros of <code>y</code>
indicates that the value is in the range <code>1.09995</code> to <code>1.10005</code>.
</p>
<p>
If we add the two lowest values in the ranges we have, <code>0.95 + 1.09995 = 2.04995</code>,
and if we add the two highest values we have, <code>1.05 + 1.10005 = 2.15005</code>, so the
range of the result of the addition implied by the precision of its operands is
<code>2.04995</code> to <code>2.15005</code>.
</p>
<p>
The result given by BigDecimal of <code>2.1000</code> however, indicates that the value is in
the range <code>2.09995</code> to <code>2.10005</code> and therefore the precision implied by
its trailing zeros may be misleading.
</p>
<p>
In the second example, the true range is <code>4.122744</code> to <code>4.157256</code> yet
the BigDecimal answer of <code>4.1400000</code> indicates a range of <code>4.13999995</code>
to <code>4.14000005</code>. Again, the precision implied by the trailing zeros may be
misleading.
</p>
<p>
This library, like binary floating point and most calculators, does not retain trailing
fractional zeros. Instead, the <code>toExponential</code>, <code>toFixed</code> and
<code>toPrecision</code> methods enable trailing zeros to be added if and when required.<br />
</p>
</div>
</body>
</html>
The MIT Licence.
Copyright (c) 2012 Michael Mclaughlin
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.
{
"_args": [
[
{
"raw": "bignumber.js@3.1.2",
"scope": null,
"escapedName": "bignumber.js",
"name": "bignumber.js",
"rawSpec": "3.1.2",
"spec": "3.1.2",
"type": "version"
},
"C:\\xampp\\htdocs\\cafe\\node_modules\\mysql"
]
],
"_from": "bignumber.js@3.1.2",
"_id": "bignumber.js@3.1.2",
"_inCache": true,
"_location": "/bignumber.js",
"_nodeVersion": "7.2.0",
"_npmOperationalInternal": {
"host": "packages-12-west.internal.npmjs.com",
"tmp": "tmp/bignumber.js-3.1.2.tgz_1483896554937_0.13670875830575824"
},
"_npmUser": {
"name": "mikemcl",
"email": "M8ch88l@gmail.com"
},
"_npmVersion": "3.8.1",
"_phantomChildren": {},
"_requested": {
"raw": "bignumber.js@3.1.2",
"scope": null,
"escapedName": "bignumber.js",
"name": "bignumber.js",
"rawSpec": "3.1.2",
"spec": "3.1.2",
"type": "version"
},
"_requiredBy": [
"/mysql"
],
"_resolved": "https://registry.npmjs.org/bignumber.js/-/bignumber.js-3.1.2.tgz",
"_shasum": "f3bdb99ad5268a15fc1f0bed2fb018e2693fe236",
"_shrinkwrap": null,
"_spec": "bignumber.js@3.1.2",
"_where": "C:\\xampp\\htdocs\\cafe\\node_modules\\mysql",
"author": {
"name": "Michael Mclaughlin",
"email": "M8ch88l@gmail.com"
},
"bugs": {
"url": "https://github.com/MikeMcl/bignumber.js/issues"
},
"dependencies": {},
"description": "A library for arbitrary-precision decimal and non-decimal arithmetic",
"devDependencies": {},
"directories": {},
"dist": {
"shasum": "f3bdb99ad5268a15fc1f0bed2fb018e2693fe236",
"tarball": "https://registry.npmjs.org/bignumber.js/-/bignumber.js-3.1.2.tgz"
},
"engines": {
"node": "*"
},
"gitHead": "2ccc3a7d2831fbd849fe1efbd9895c814bb344ff",
"homepage": "https://github.com/MikeMcl/bignumber.js#readme",
"keywords": [
"arbitrary",
"precision",
"arithmetic",
"big",
"number",
"decimal",
"float",
"biginteger",
"bigdecimal",
"bignumber",
"bigint",
"bignum"
],
"license": "MIT",
"main": "bignumber.js",
"maintainers": [
{
"name": "mikemcl",
"email": "M8ch88l@gmail.com"
}
],
"name": "bignumber.js",
"optionalDependencies": {},
"readme": "ERROR: No README data found!",
"repository": {
"type": "git",
"url": "git+https://github.com/MikeMcl/bignumber.js.git"
},
"scripts": {
"build": "uglifyjs bignumber.js --source-map bignumber.js.map -c -m -o bignumber.min.js --preamble \"/* bignumber.js v3.1.2 https://github.com/MikeMcl/bignumber.js/LICENCE */\"",
"test": "node ./test/every-test.js"
},
"version": "3.1.2"
}

bignumber.js

A JavaScript library for arbitrary-precision decimal and non-decimal arithmetic.

Build Status


Features

  • Faster, smaller, and perhaps easier to use than JavaScript versions of Java's BigDecimal
  • 8 KB minified and gzipped
  • Simple API but full-featured
  • Works with numbers with or without fraction digits in bases from 2 to 64 inclusive
  • Replicates the toExponential, toFixed, toPrecision and toString methods of JavaScript's Number type
  • Includes a toFraction and a correctly-rounded squareRoot method
  • Supports cryptographically-secure pseudo-random number generation
  • No dependencies
  • Wide platform compatibility: uses JavaScript 1.5 (ECMAScript 3) features only
  • Comprehensive documentation and test set

API

If a smaller and simpler library is required see big.js. It's less than half the size but only works with decimal numbers and only has half the methods. It also does not allow NaN or Infinity, or have the configuration options of this library.

See also decimal.js, which among other things adds support for non-integer powers, and performs all operations to a specified number of significant digits.

Load

The library is the single JavaScript file bignumber.js (or minified, bignumber.min.js).

<script src='relative/path/to/bignumber.js'></script>

For Node.js, the library is available from the npm registry

$ npm install bignumber.js
var BigNumber = require('bignumber.js');

To load with AMD loader libraries such as requireJS:

require(['path/to/bignumber'], function(BigNumber) {
    // Use BigNumber here in local scope. No global BigNumber.
});

Use

In all examples below, var, semicolons and toString calls are not shown. If a commented-out value is in quotes it means toString has been called on the preceding expression.

The library exports a single function: BigNumber, the constructor of BigNumber instances.

It accepts a value of type number (up to 15 significant digits only), string or BigNumber object,

x = new BigNumber(123.4567)
y = BigNumber('123456.7e-3')
z = new BigNumber(x)
x.equals(y) && y.equals(z) && x.equals(z)      // true

and a base from 2 to 64 inclusive can be specified.

x = new BigNumber(1011, 2)          // "11"
y = new BigNumber('zz.9', 36)       // "1295.25"
z = x.plus(y)                       // "1306.25"

A BigNumber is immutable in the sense that it is not changed by its methods.

0.3 - 0.1                           // 0.19999999999999998
x = new BigNumber(0.3)
x.minus(0.1)                        // "0.2"
x                                   // "0.3"

The methods that return a BigNumber can be chained.

x.dividedBy(y).plus(z).times(9).floor()
x.times('1.23456780123456789e+9').plus(9876.5432321).dividedBy('4444562598.111772').ceil()

Many method names have a shorter alias.

x.squareRoot().dividedBy(y).toPower(3).equals(x.sqrt().div(y).pow(3))         // true
x.cmp(y.mod(z).neg()) == 1 && x.comparedTo(y.modulo(z).negated()) == 1        // true

Like JavaScript's number type, there are toExponential, toFixed and toPrecision methods

x = new BigNumber(255.5)
x.toExponential(5)                  // "2.55500e+2"
x.toFixed(5)                        // "255.50000"
x.toPrecision(5)                    // "255.50"
x.toNumber()                        // 255.5

and a base can be specified for toString.

x.toString(16)                     // "ff.8"

There is also a toFormat method which may be useful for internationalisation

y = new BigNumber('1234567.898765')
y.toFormat(2)                       // "1,234,567.90"

The maximum number of decimal places of the result of an operation involving division (i.e. a division, square root, base conversion or negative power operation) is set using the config method of the BigNumber constructor.

The other arithmetic operations always give the exact result.

BigNumber.config({ DECIMAL_PLACES: 10, ROUNDING_MODE: 4 })

x = new BigNumber(2);
y = new BigNumber(3);
z = x.div(y)                        // "0.6666666667"
z.sqrt()                            // "0.8164965809"
z.pow(-3)                           // "3.3749999995"
z.toString(2)                       // "0.1010101011"
z.times(z)                          // "0.44444444448888888889"
z.times(z).round(10)                // "0.4444444445"

There is a toFraction method with an optional maximum denominator argument

y = new BigNumber(355)
pi = y.dividedBy(113)               // "3.1415929204"
pi.toFraction()                     // [ "7853982301", "2500000000" ]
pi.toFraction(1000)                 // [ "355", "113" ]

and isNaN and isFinite methods, as NaN and Infinity are valid BigNumber values.

x = new BigNumber(NaN)                                           // "NaN"
y = new BigNumber(Infinity)                                      // "Infinity"
x.isNaN() && !y.isNaN() && !x.isFinite() && !y.isFinite()        // true

The value of a BigNumber is stored in a decimal floating point format in terms of a coefficient, exponent and sign.

x = new BigNumber(-123.456);
x.c                                 // [ 123, 45600000000000 ]  coefficient (i.e. significand)
x.e                                 // 2                        exponent
x.s                                 // -1                       sign

Multiple BigNumber constructors can be created, each with their own independent configuration which applies to all BigNumber's created from it.

// Set DECIMAL_PLACES for the original BigNumber constructor
BigNumber.config({ DECIMAL_PLACES: 10 })

// Create another BigNumber constructor, optionally passing in a configuration object
BN = BigNumber.another({ DECIMAL_PLACES: 5 })

x = new BigNumber(1)
y = new BN(1)

x.div(3)                            // '0.3333333333'
y.div(3)                            // '0.33333'

For futher information see the API reference in the doc directory.

Test

The test directory contains the test scripts for each method.

The tests can be run with Node or a browser. For Node use

$ npm test

or

$ node test/every-test

To test a single method, e.g.

$ node test/toFraction

For the browser, see every-test.html and single-test.html in the test/browser directory.

bignumber-vs-number.html enables some of the methods of bignumber.js to be compared with those of JavaScript's number type.

Versions

Version 1.x.x of this library is still supported on the 'original' branch. The advantages of later versions are that they are considerably faster for numbers with many digits and that there are some added methods (see Change Log below). The disadvantages are more lines of code and increased code complexity, and the loss of simplicity in no longer having the coefficient of a BigNumber stored in base 10.

Performance

See the README in the perf directory.

Build

For Node, if uglify-js is installed

npm install uglify-js -g

then

npm run build

will create bignumber.min.js.

A source map will also be created in the root directory.

Feedback

Open an issue, or email

Michael

M8ch88l@gmail.com

Licence

MIT.

See LICENCE.

Change Log

3.1.2

  • 08/01/2017
  • Minor documentation edit.

3.1.1

  • 08/01/2017
  • Uncomment isBigNumber tests.
  • Ignore dot files.

3.1.0

  • 08/01/2017
  • Add isBigNumber method.

3.0.2

  • 08/01/2017
  • Bugfix: Possible incorrect value of ERRORS after a BigNumber.another call (due to parseNumeric declaration in outer scope).

3.0.1

  • 23/11/2016
  • Apply fix for old ipads with % issue, see #57 and #102.
  • Correct error message.

3.0.0

  • 09/11/2016
  • Remove require('crypto') - leave it to the user.
  • Add BigNumber.set as BigNumber.config alias.
  • Default POW_PRECISION to 0.

2.4.0

  • 14/07/2016
  • #97 Add exports to support ES6 imports.

2.3.0

  • 07/03/2016
  • #86 Add modulus parameter to toPower.

2.2.0

  • 03/03/2016
  • #91 Permit larger JS integers.

2.1.4

  • 15/12/2015
  • Correct UMD.

2.1.3

  • 13/12/2015
  • Refactor re global object and crypto availability when bundling.

2.1.2

  • 10/12/2015
  • Bugfix: window.crypto not assigned to crypto.

2.1.1

  • 09/12/2015
  • Prevent code bundler from adding crypto shim.

2.1.0

  • 26/10/2015
  • For valueOf and toJSON, include the minus sign with negative zero.

2.0.8

  • 2/10/2015
  • Internal round function bugfix.

2.0.6

  • 31/03/2015
  • Add bower.json. Tweak division after in-depth review.

2.0.5

  • 25/03/2015
  • Amend README. Remove bitcoin address.

2.0.4

  • 25/03/2015
  • Critical bugfix #58: division.

2.0.3

  • 18/02/2015
  • Amend README. Add source map.

2.0.2

  • 18/02/2015
  • Correct links.

2.0.1

  • 18/02/2015
  • Add max, min, precision, random, shift, toDigits and truncated methods.
  • Add the short-forms: add, mul, sd, sub and trunc.
  • Add an another method to enable multiple independent constructors to be created.
  • Add support for the base 2, 8 and 16 prefixes 0b, 0o and 0x.
  • Enable a rounding mode to be specified as a second parameter to toExponential, toFixed, toFormat and toPrecision.
  • Add a CRYPTO configuration property so cryptographically-secure pseudo-random number generation can be specified.
  • Add a MODULO_MODE configuration property to enable the rounding mode used by the modulo operation to be specified.
  • Add a POW_PRECISION configuration property to enable the number of significant digits calculated by the power operation to be limited.
  • Improve code quality.
  • Improve documentation.

2.0.0

  • 29/12/2014
  • Add dividedToIntegerBy, isInteger and toFormat methods.
  • Remove the following short-forms: isF, isZ, toE, toF, toFr, toN, toP, toS.
  • Store a BigNumber's coefficient in base 1e14, rather than base 10.
  • Add fast path for integers to BigNumber constructor.
  • Incorporate the library into the online documentation.

1.5.0

  • 13/11/2014
  • Add toJSON and decimalPlaces methods.

1.4.1

  • 08/06/2014
  • Amend README.

1.4.0

  • 08/05/2014
  • Add toNumber.

1.3.0

  • 08/11/2013
  • Ensure correct rounding of sqrt in all, rather than almost all, cases.
  • Maximum radix to 64.

1.2.1

  • 17/10/2013
  • Sign of zero when x < 0 and x + (-x) = 0.

1.2.0

  • 19/9/2013
  • Throw Error objects for stack.

1.1.1

  • 22/8/2013
  • Show original value in constructor error message.

1.1.0

  • 1/8/2013
  • Allow numbers with trailing radix point.

1.0.1

  • Bugfix: error messages with incorrect method name

1.0.0

  • 8/11/2012
  • Initial release
ui: mocha-bdd
browsers:
- name: chrome
version: 8..latest
- name: firefox
version: 7..latest
- name: safari
version: 6..latest
- name: opera
version: 12.1..latest
- name: ie
version: 10..latest
- name: android
version: latest
/**
* Create a blob builder even when vendor prefixes exist
*/
var BlobBuilder = global.BlobBuilder
|| global.WebKitBlobBuilder
|| global.MSBlobBuilder
|| global.MozBlobBuilder;
/**
* Check if Blob constructor is supported
*/
var blobSupported = (function() {
try {
var a = new Blob(['hi']);
return a.size === 2;
} catch(e) {
return false;
}
})();
/**
* Check if Blob constructor supports ArrayBufferViews
* Fails in Safari 6, so we need to map to ArrayBuffers there.
*/
var blobSupportsArrayBufferView = blobSupported && (function() {
try {
var b = new Blob([new Uint8Array([1,2])]);
return b.size === 2;
} catch(e) {
return false;
}
})();
/**
* Check if BlobBuilder is supported
*/
var blobBuilderSupported = BlobBuilder
&& BlobBuilder.prototype.append
&& BlobBuilder.prototype.getBlob;
/**
* Helper function that maps ArrayBufferViews to ArrayBuffers
* Used by BlobBuilder constructor and old browsers that didn't
* support it in the Blob constructor.
*/
function mapArrayBufferViews(ary) {
for (var i = 0; i < ary.length; i++) {
var chunk = ary[i];
if (chunk.buffer instanceof ArrayBuffer) {
var buf = chunk.buffer;
// if this is a subarray, make a copy so we only
// include the subarray region from the underlying buffer
if (chunk.byteLength !== buf.byteLength) {
var copy = new Uint8Array(chunk.byteLength);
copy.set(new Uint8Array(buf, chunk.byteOffset, chunk.byteLength));
buf = copy.buffer;
}
ary[i] = buf;
}
}
}
function BlobBuilderConstructor(ary, options) {
options = options || {};
var bb = new BlobBuilder();
mapArrayBufferViews(ary);
for (var i = 0; i < ary.length; i++) {
bb.append(ary[i]);
}
return (options.type) ? bb.getBlob(options.type) : bb.getBlob();
};
function BlobConstructor(ary, options) {
mapArrayBufferViews(ary);
return new Blob(ary, options || {});
};
module.exports = (function() {
if (blobSupported) {
return blobSupportsArrayBufferView ? global.Blob : BlobConstructor;
} else if (blobBuilderSupported) {
return BlobBuilderConstructor;
} else {
return undefined;
}
})();
REPORTER = dot
build: blob.js
blob.js:
@./node_modules/.bin/browserify --standalone blob index.js > blob.js
test:
@./node_modules/.bin/zuul -- test/index.js
clean:
rm blob.js
.PHONY: test blob.js
{
"_args": [
[
{
"raw": "blob@0.0.4",
"scope": null,
"escapedName": "blob",
"name": "blob",
"rawSpec": "0.0.4",
"spec": "0.0.4",
"type": "version"
},
"C:\\xampp\\htdocs\\cafe\\node_modules\\engine.io-parser"
]
],
"_from": "blob@0.0.4",
"_id": "blob@0.0.4",
"_inCache": true,
"_location": "/blob",
"_npmUser": {
"name": "rase-",
"email": "tonykovanen@hotmail.com"
},
"_npmVersion": "1.4.6",
"_phantomChildren": {},
"_requested": {
"raw": "blob@0.0.4",
"scope": null,
"escapedName": "blob",
"name": "blob",
"rawSpec": "0.0.4",
"spec": "0.0.4",
"type": "version"
},
"_requiredBy": [
"/engine.io-parser"
],
"_resolved": "https://registry.npmjs.org/blob/-/blob-0.0.4.tgz",
"_shasum": "bcf13052ca54463f30f9fc7e95b9a47630a94921",
"_shrinkwrap": null,
"_spec": "blob@0.0.4",
"_where": "C:\\xampp\\htdocs\\cafe\\node_modules\\engine.io-parser",
"bugs": {
"url": "https://github.com/rase-/blob/issues"
},
"dependencies": {},
"description": "Abstracts out Blob and uses BlobBulder in cases where it is supported with any vendor prefix.",
"devDependencies": {
"browserify": "3.30.1",
"expect.js": "0.2.0",
"mocha": "1.17.1",
"zuul": "1.5.4"
},
"directories": {},
"dist": {
"shasum": "bcf13052ca54463f30f9fc7e95b9a47630a94921",
"tarball": "https://registry.npmjs.org/blob/-/blob-0.0.4.tgz"
},
"homepage": "https://github.com/rase-/blob",
"maintainers": [
{
"name": "rase-",
"email": "tonykovanen@hotmail.com"
}
],
"name": "blob",
"optionalDependencies": {},
"readme": "ERROR: No README data found!",
"repository": {
"type": "git",
"url": "git+ssh://git@github.com/rase-/blob.git"
},
"scripts": {
"test": "make test"
},
"version": "0.0.4"
}

Blob

A module that exports a constructor that uses window.Blob when available, and a BlobBuilder with any vendor prefix in other cases. If neither is available, it exports undefined.

Usage:

var Blob = require('blob');
var b = new Blob(['hi', 'constructing', 'a', 'blob']);

Licence

MIT

var Blob = require('../');
var expect = require('expect.js');
describe('blob', function() {
if (!Blob) {
it('should not have a blob or a blob builder in the global namespace, or blob should not be a constructor function if the module exports false', function() {
try {
var ab = (new Uint8Array(5)).buffer;
global.Blob([ab]);
expect().fail('Blob shouldn\'t be constructable');
} catch (e) {}
var BlobBuilder = global.BlobBuilder
|| global.WebKitBlobBuilder
|| global.MSBlobBuilder
|| global.MozBlobBuilder;
expect(BlobBuilder).to.be(undefined);
});
} else {
it('should encode a proper sized blob when given a string argument', function() {
var b = new Blob(['hi']);
expect(b.size).to.be(2);
});
it('should encode a blob with proper size when given two strings as arguments', function() {
var b = new Blob(['hi', 'hello']);
expect(b.size).to.be(7);
});
it('should encode arraybuffers with right content', function(done) {
var ary = new Uint8Array(5);
for (var i = 0; i < 5; i++) ary[i] = i;
var b = new Blob([ary.buffer]);
var fr = new FileReader();
fr.onload = function() {
var newAry = new Uint8Array(this.result);
for (var i = 0; i < 5; i++) expect(newAry[i]).to.be(i);
done();
};
fr.readAsArrayBuffer(b);
});
it('should encode typed arrays with right content', function(done) {
var ary = new Uint8Array(5);
for (var i = 0; i < 5; i++) ary[i] = i;
var b = new Blob([ary]);
var fr = new FileReader();
fr.onload = function() {
var newAry = new Uint8Array(this.result);
for (var i = 0; i < 5; i++) expect(newAry[i]).to.be(i);
done();
};
fr.readAsArrayBuffer(b);
});
it('should encode sliced typed arrays with right content', function(done) {
var ary = new Uint8Array(5);
for (var i = 0; i < 5; i++) ary[i] = i;
var b = new Blob([ary.subarray(2)]);
var fr = new FileReader();
fr.onload = function() {
var newAry = new Uint8Array(this.result);
for (var i = 0; i < 3; i++) expect(newAry[i]).to.be(i + 2);
done();
};
fr.readAsArrayBuffer(b);
});
it('should encode with blobs', function(done) {
var ary = new Uint8Array(5);
for (var i = 0; i < 5; i++) ary[i] = i;
var b = new Blob([new Blob([ary.buffer])]);
var fr = new FileReader();
fr.onload = function() {
var newAry = new Uint8Array(this.result);
for (var i = 0; i < 5; i++) expect(newAry[i]).to.be(i);
done();
};
fr.readAsArrayBuffer(b);
});
it('should enode mixed contents to right size', function() {
var ary = new Uint8Array(5);
for (var i = 0; i < 5; i++) ary[i] = i;
var b = new Blob([ary.buffer, 'hello']);
expect(b.size).to.be(10);
});
it('should accept mime type', function() {
var b = new Blob(['hi', 'hello'], { type: 'text/html' });
expect(b.type).to.be('text/html');
});
}
});

1.16.0 / 2017-01-17

  • deps: debug@2.6.0
    • Allow colors in workers
    • Deprecated DEBUG_FD environment variable
    • Fix error when running under React Native
    • Use same color for same namespace
    • deps: ms@0.7.2
  • deps: http-errors@~1.5.1
    • deps: inherits@2.0.3
    • deps: setprototypeof@1.0.2
    • deps: statuses@'>= 1.3.1 < 2'
  • deps: iconv-lite@0.4.15
    • Added encoding MS-31J
    • Added encoding MS-932
    • Added encoding MS-936
    • Added encoding MS-949
    • Added encoding MS-950
    • Fix GBK/GB18030 handling of Euro character
  • deps: qs@6.3.0
    • Fix array parsing from skipping empty values
    • Fix compacting nested arrays
  • deps: raw-body@~2.2.0
    • deps: iconv-lite@0.4.15
  • deps: type-is@~1.6.14
    • deps: mime-types@~2.1.13

1.15.2 / 2016-06-19

  • deps: bytes@2.4.0
  • deps: content-type@~1.0.2
    • perf: enable strict mode
  • deps: http-errors@~1.5.0
    • Use setprototypeof module to replace __proto__ setting
    • deps: statuses@'>= 1.3.0 < 2'
    • perf: enable strict mode
  • deps: qs@6.2.0
  • deps: raw-body@~2.1.7
    • deps: bytes@2.4.0
    • perf: remove double-cleanup on happy path
  • deps: type-is@~1.6.13
    • deps: mime-types@~2.1.11

1.15.1 / 2016-05-05

  • deps: bytes@2.3.0
    • Drop partial bytes on all parsed units
    • Fix parsing byte string that looks like hex
  • deps: raw-body@~2.1.6
    • deps: bytes@2.3.0
  • deps: type-is@~1.6.12
    • deps: mime-types@~2.1.10

1.15.0 / 2016-02-10

  • deps: http-errors@~1.4.0
    • Add HttpError export, for err instanceof createError.HttpError
    • deps: inherits@2.0.1
    • deps: statuses@'>= 1.2.1 < 2'
  • deps: qs@6.1.0
  • deps: type-is@~1.6.11
    • deps: mime-types@~2.1.9

1.14.2 / 2015-12-16

  • deps: bytes@2.2.0
  • deps: iconv-lite@0.4.13
  • deps: qs@5.2.0
  • deps: raw-body@~2.1.5
    • deps: bytes@2.2.0
    • deps: iconv-lite@0.4.13
  • deps: type-is@~1.6.10
    • deps: mime-types@~2.1.8

1.14.1 / 2015-09-27

  • Fix issue where invalid charset results in 400 when verify used
  • deps: iconv-lite@0.4.12
    • Fix CESU-8 decoding in Node.js 4.x
  • deps: raw-body@~2.1.4
    • Fix masking critical errors from iconv-lite
    • deps: iconv-lite@0.4.12
  • deps: type-is@~1.6.9
    • deps: mime-types@~2.1.7

1.14.0 / 2015-09-16

  • Fix JSON strict parse error to match syntax errors
  • Provide static require analysis in urlencoded parser
  • deps: depd@~1.1.0
    • Support web browser loading
  • deps: qs@5.1.0
  • deps: raw-body@~2.1.3
    • Fix sync callback when attaching data listener causes sync read
  • deps: type-is@~1.6.8
    • Fix type error when given invalid type to match against
    • deps: mime-types@~2.1.6

1.13.3 / 2015-07-31

  • deps: type-is@~1.6.6
    • deps: mime-types@~2.1.4

1.13.2 / 2015-07-05

  • deps: iconv-lite@0.4.11
  • deps: qs@4.0.0
    • Fix dropping parameters like hasOwnProperty
    • Fix user-visible incompatibilities from 3.1.0
    • Fix various parsing edge cases
  • deps: raw-body@~2.1.2
    • Fix error stack traces to skip makeError
    • deps: iconv-lite@0.4.11
  • deps: type-is@~1.6.4
    • deps: mime-types@~2.1.2
    • perf: enable strict mode
    • perf: remove argument reassignment

1.13.1 / 2015-06-16

  • deps: qs@2.4.2
    • Downgraded from 3.1.0 because of user-visible incompatibilities

1.13.0 / 2015-06-14

  • Add statusCode property on Errors, in addition to status
  • Change type default to application/json for JSON parser
  • Change type default to application/x-www-form-urlencoded for urlencoded parser
  • Provide static require analysis
  • Use the http-errors module to generate errors
  • deps: bytes@2.1.0
    • Slight optimizations
  • deps: iconv-lite@0.4.10
    • The encoding UTF-16 without BOM now defaults to UTF-16LE when detection fails
    • Leading BOM is now removed when decoding
  • deps: on-finished@~2.3.0
    • Add defined behavior for HTTP CONNECT requests
    • Add defined behavior for HTTP Upgrade requests
    • deps: ee-first@1.1.1
  • deps: qs@3.1.0
    • Fix dropping parameters like hasOwnProperty
    • Fix various parsing edge cases
    • Parsed object now has null prototype
  • deps: raw-body@~2.1.1
    • Use unpipe module for unpiping requests
    • deps: iconv-lite@0.4.10
  • deps: type-is@~1.6.3
    • deps: mime-types@~2.1.1
    • perf: reduce try block size
    • perf: remove bitwise operations
  • perf: enable strict mode
  • perf: remove argument reassignment
  • perf: remove delete call

1.12.4 / 2015-05-10

  • deps: debug@~2.2.0
  • deps: qs@2.4.2
    • Fix allowing parameters like constructor
  • deps: on-finished@~2.2.1
  • deps: raw-body@~2.0.1
    • Fix a false-positive when unpiping in Node.js 0.8
    • deps: bytes@2.0.1
  • deps: type-is@~1.6.2
    • deps: mime-types@~2.0.11

1.12.3 / 2015-04-15

  • Slight efficiency improvement when not debugging
  • deps: depd@~1.0.1
  • deps: iconv-lite@0.4.8
    • Add encoding alias UNICODE-1-1-UTF-7
  • deps: raw-body@1.3.4
    • Fix hanging callback if request aborts during read
    • deps: iconv-lite@0.4.8

1.12.2 / 2015-03-16

  • deps: qs@2.4.1
    • Fix error when parameter hasOwnProperty is present

1.12.1 / 2015-03-15

  • deps: debug@~2.1.3
    • Fix high intensity foreground color for bold
    • deps: ms@0.7.0
  • deps: type-is@~1.6.1
    • deps: mime-types@~2.0.10

1.12.0 / 2015-02-13

  • add debug messages
  • accept a function for the type option
  • use content-type to parse Content-Type headers
  • deps: iconv-lite@0.4.7
    • Gracefully support enumerables on Object.prototype
  • deps: raw-body@1.3.3
    • deps: iconv-lite@0.4.7
  • deps: type-is@~1.6.0
    • fix argument reassignment
    • fix false-positives in hasBody Transfer-Encoding check
    • support wildcard for both type and subtype (*/*)
    • deps: mime-types@~2.0.9

1.11.0 / 2015-01-30

  • make internal extended: true depth limit infinity
  • deps: type-is@~1.5.6
    • deps: mime-types@~2.0.8

1.10.2 / 2015-01-20

  • deps: iconv-lite@0.4.6
    • Fix rare aliases of single-byte encodings
  • deps: raw-body@1.3.2
    • deps: iconv-lite@0.4.6

1.10.1 / 2015-01-01

  • deps: on-finished@~2.2.0
  • deps: type-is@~1.5.5
    • deps: mime-types@~2.0.7

1.10.0 / 2014-12-02

  • make internal extended: true array limit dynamic

1.9.3 / 2014-11-21

  • deps: iconv-lite@0.4.5
    • Fix Windows-31J and X-SJIS encoding support
  • deps: qs@2.3.3
    • Fix arrayLimit behavior
  • deps: raw-body@1.3.1
    • deps: iconv-lite@0.4.5
  • deps: type-is@~1.5.3
    • deps: mime-types@~2.0.3

1.9.2 / 2014-10-27

  • deps: qs@2.3.2
    • Fix parsing of mixed objects and values

1.9.1 / 2014-10-22

  • deps: on-finished@~2.1.1
    • Fix handling of pipelined requests
  • deps: qs@2.3.0
    • Fix parsing of mixed implicit and explicit arrays
  • deps: type-is@~1.5.2
    • deps: mime-types@~2.0.2

1.9.0 / 2014-09-24

  • include the charset in "unsupported charset" error message
  • include the encoding in "unsupported content encoding" error message
  • deps: depd@~1.0.0

1.8.4 / 2014-09-23

  • fix content encoding to be case-insensitive

1.8.3 / 2014-09-19

  • deps: qs@2.2.4
    • Fix issue with object keys starting with numbers truncated

1.8.2 / 2014-09-15

  • deps: depd@0.4.5

1.8.1 / 2014-09-07

  • deps: media-typer@0.3.0
  • deps: type-is@~1.5.1

1.8.0 / 2014-09-05

  • make empty-body-handling consistent between chunked requests
    • empty json produces {}
    • empty raw produces new Buffer(0)
    • empty text produces ''
    • empty urlencoded produces {}
  • deps: qs@2.2.3
    • Fix issue where first empty value in array is discarded
  • deps: type-is@~1.5.0
    • fix hasbody to be true for content-length: 0

1.7.0 / 2014-09-01

  • add parameterLimit option to urlencoded parser
  • change urlencoded extended array limit to 100
  • respond with 413 when over parameterLimit in urlencoded

1.6.7 / 2014-08-29

  • deps: qs@2.2.2
    • Remove unnecessary cloning

1.6.6 / 2014-08-27

  • deps: qs@2.2.0
    • Array parsing fix
    • Performance improvements

1.6.5 / 2014-08-16

  • deps: on-finished@2.1.0

1.6.4 / 2014-08-14

  • deps: qs@1.2.2

1.6.3 / 2014-08-10

  • deps: qs@1.2.1

1.6.2 / 2014-08-07

  • deps: qs@1.2.0
    • Fix parsing array of objects

1.6.1 / 2014-08-06

  • deps: qs@1.1.0
    • Accept urlencoded square brackets
    • Accept empty values in implicit array notation

1.6.0 / 2014-08-05

  • deps: qs@1.0.2
    • Complete rewrite
    • Limits array length to 20
    • Limits object depth to 5
    • Limits parameters to 1,000

1.5.2 / 2014-07-27

  • deps: depd@0.4.4
    • Work-around v8 generating empty stack traces

1.5.1 / 2014-07-26

  • deps: depd@0.4.3
    • Fix exception when global Error.stackTraceLimit is too low

1.5.0 / 2014-07-20

  • deps: depd@0.4.2
    • Add TRACE_DEPRECATION environment variable
    • Remove non-standard grey color from color output
    • Support --no-deprecation argument
    • Support --trace-deprecation argument
  • deps: iconv-lite@0.4.4
    • Added encoding UTF-7
  • deps: raw-body@1.3.0
    • deps: iconv-lite@0.4.4
    • Added encoding UTF-7
    • Fix Cannot switch to old mode now error on Node.js 0.10+
  • deps: type-is@~1.3.2

1.4.3 / 2014-06-19

  • deps: type-is@1.3.1
    • fix global variable leak

1.4.2 / 2014-06-19

  • deps: type-is@1.3.0
    • improve type parsing

1.4.1 / 2014-06-19

  • fix urlencoded extended deprecation message

1.4.0 / 2014-06-19

  • add text parser
  • add raw parser
  • check accepted charset in content-type (accepts utf-8)
  • check accepted encoding in content-encoding (accepts identity)
  • deprecate bodyParser() middleware; use .json() and .urlencoded() as needed
  • deprecate urlencoded() without provided extended option
  • lazy-load urlencoded parsers
  • parsers split into files for reduced mem usage
  • support gzip and deflate bodies
    • set inflate: false to turn off
  • deps: raw-body@1.2.2
    • Support all encodings from iconv-lite

1.3.1 / 2014-06-11

  • deps: type-is@1.2.1
    • Switch dependency from mime to mime-types@1.0.0

1.3.0 / 2014-05-31

  • add extended option to urlencoded parser

1.2.2 / 2014-05-27

  • deps: raw-body@1.1.6
    • assert stream encoding on node.js 0.8
    • assert stream encoding on node.js < 0.10.6
    • deps: bytes@1

1.2.1 / 2014-05-26

  • invoke next(err) after request fully read
    • prevents hung responses and socket hang ups

1.2.0 / 2014-05-11

  • add verify option
  • deps: type-is@1.2.0
    • support suffix matching

1.1.2 / 2014-05-11

  • improve json parser speed

1.1.1 / 2014-05-11

  • fix repeated limit parsing with every request

1.1.0 / 2014-05-10

  • add type option
  • deps: pin for safety and consistency

1.0.2 / 2014-04-14

  • use type-is module

1.0.1 / 2014-03-20

  • lower default limits to 100kb
/*!
* body-parser
* Copyright(c) 2014-2015 Douglas Christopher Wilson
* MIT Licensed
*/
'use strict'
/**
* Module dependencies.
* @private
*/
var deprecate = require('depd')('body-parser')
/**
* Cache of loaded parsers.
* @private
*/
var parsers = Object.create(null)
/**
* @typedef Parsers
* @type {function}
* @property {function} json
* @property {function} raw
* @property {function} text
* @property {function} urlencoded
*/
/**
* Module exports.
* @type {Parsers}
*/
exports = module.exports = deprecate.function(bodyParser,
'bodyParser: use individual json/urlencoded middlewares')
/**
* JSON parser.
* @public
*/
Object.defineProperty(exports, 'json', {
configurable: true,
enumerable: true,
get: createParserGetter('json')
})
/**
* Raw parser.
* @public
*/
Object.defineProperty(exports, 'raw', {
configurable: true,
enumerable: true,
get: createParserGetter('raw')
})
/**
* Text parser.
* @public
*/
Object.defineProperty(exports, 'text', {
configurable: true,
enumerable: true,
get: createParserGetter('text')
})
/**
* URL-encoded parser.
* @public
*/
Object.defineProperty(exports, 'urlencoded', {
configurable: true,
enumerable: true,
get: createParserGetter('urlencoded')
})
/**
* Create a middleware to parse json and urlencoded bodies.
*
* @param {object} [options]
* @return {function}
* @deprecated
* @public
*/
function bodyParser (options) {
var opts = {}
// exclude type option
if (options) {
for (var prop in options) {
if (prop !== 'type') {
opts[prop] = options[prop]
}
}
}
var _urlencoded = exports.urlencoded(opts)
var _json = exports.json(opts)
return function bodyParser (req, res, next) {
_json(req, res, function (err) {
if (err) return next(err)
_urlencoded(req, res, next)
})
}
}
/**
* Create a getter for loading a parser.
* @private
*/
function createParserGetter (name) {
return function get () {
return loadParser(name)
}
}
/**
* Load a parser module.
* @private
*/
function loadParser (parserName) {
var parser = parsers[parserName]
if (parser !== undefined) {
return parser
}
// this uses a switch for static require analysis
switch (parserName) {
case 'json':
parser = require('./lib/types/json')
break
case 'raw':
parser = require('./lib/types/raw')
break
case 'text':
parser = require('./lib/types/text')
break
case 'urlencoded':
parser = require('./lib/types/urlencoded')
break
}
// store to prevent invoking require()
return (parsers[parserName] = parser)
}
/*!
* body-parser
* Copyright(c) 2014-2015 Douglas Christopher Wilson
* MIT Licensed
*/
'use strict'
/**
* Module dependencies.
* @private
*/
var createError = require('http-errors')
var getBody = require('raw-body')
var iconv = require('iconv-lite')
var onFinished = require('on-finished')
var zlib = require('zlib')
/**
* Module exports.
*/
module.exports = read
/**
* Read a request into a buffer and parse.
*
* @param {object} req
* @param {object} res
* @param {function} next
* @param {function} parse
* @param {function} debug
* @param {object} [options]
* @api private
*/
function read (req, res, next, parse, debug, options) {
var length
var opts = options || {}
var stream
// flag as parsed
req._body = true
// read options
var encoding = opts.encoding !== null
? opts.encoding || 'utf-8'
: null
var verify = opts.verify
try {
// get the content stream
stream = contentstream(req, debug, opts.inflate)
length = stream.length
stream.length = undefined
} catch (err) {
return next(err)
}
// set raw-body options
opts.length = length
opts.encoding = verify
? null
: encoding
// assert charset is supported
if (opts.encoding === null && encoding !== null && !iconv.encodingExists(encoding)) {
return next(createError(415, 'unsupported charset "' + encoding.toUpperCase() + '"', {
charset: encoding.toLowerCase()
}))
}
// read body
debug('read body')
getBody(stream, opts, function (err, body) {
if (err) {
// default to 400
setErrorStatus(err, 400)
// echo back charset
if (err.type === 'encoding.unsupported') {
err = createError(415, 'unsupported charset "' + encoding.toUpperCase() + '"', {
charset: encoding.toLowerCase()
})
}
// read off entire request
stream.resume()
onFinished(req, function onfinished () {
next(err)
})
return
}
// verify
if (verify) {
try {
debug('verify body')
verify(req, res, body, encoding)
} catch (err) {
// default to 403
setErrorStatus(err, 403)
next(err)
return
}
}
// parse
var str
try {
debug('parse body')
str = typeof body !== 'string' && encoding !== null
? iconv.decode(body, encoding)
: body
req.body = parse(str)
} catch (err) {
err.body = str === undefined
? body
: str
// default to 400
setErrorStatus(err, 400)
next(err)
return
}
next()
})
}
/**
* Get the content stream of the request.
*
* @param {object} req
* @param {function} debug
* @param {boolean} [inflate=true]
* @return {object}
* @api private
*/
function contentstream (req, debug, inflate) {
var encoding = (req.headers['content-encoding'] || 'identity').toLowerCase()
var length = req.headers['content-length']
var stream
debug('content-encoding "%s"', encoding)
if (inflate === false && encoding !== 'identity') {
throw createError(415, 'content encoding unsupported')
}
switch (encoding) {
case 'deflate':
stream = zlib.createInflate()
debug('inflate body')
req.pipe(stream)
break
case 'gzip':
stream = zlib.createGunzip()
debug('gunzip body')
req.pipe(stream)
break
case 'identity':
stream = req
stream.length = length
break
default:
throw createError(415, 'unsupported content encoding "' + encoding + '"', {
encoding: encoding
})
}
return stream
}
/**
* Set a status on an error object, if ones does not exist
* @private
*/
function setErrorStatus (error, status) {
if (!error.status && !error.statusCode) {
error.status = status
error.statusCode = status
}
}
/*!
* body-parser
* Copyright(c) 2014 Jonathan Ong
* Copyright(c) 2014-2015 Douglas Christopher Wilson
* MIT Licensed
*/
'use strict'
/**
* Module dependencies.
* @private
*/
var bytes = require('bytes')
var contentType = require('content-type')
var createError = require('http-errors')
var debug = require('debug')('body-parser:json')
var read = require('../read')
var typeis = require('type-is')
/**
* Module exports.
*/
module.exports = json
/**
* RegExp to match the first non-space in a string.
*
* Allowed whitespace is defined in RFC 7159:
*
* ws = *(
* %x20 / ; Space
* %x09 / ; Horizontal tab
* %x0A / ; Line feed or New line
* %x0D ) ; Carriage return
*/
var FIRST_CHAR_REGEXP = /^[\x20\x09\x0a\x0d]*(.)/ // eslint-disable-line no-control-regex
/**
* Create a middleware to parse JSON bodies.
*
* @param {object} [options]
* @return {function}
* @public
*/
function json (options) {
var opts = options || {}
var limit = typeof opts.limit !== 'number'
? bytes.parse(opts.limit || '100kb')
: opts.limit
var inflate = opts.inflate !== false
var reviver = opts.reviver
var strict = opts.strict !== false
var type = opts.type || 'application/json'
var verify = opts.verify || false
if (verify !== false && typeof verify !== 'function') {
throw new TypeError('option verify must be function')
}
// create the appropriate type checking function
var shouldParse = typeof type !== 'function'
? typeChecker(type)
: type
function parse (body) {
if (body.length === 0) {
// special-case empty json body, as it's a common client-side mistake
// TODO: maybe make this configurable or part of "strict" option
return {}
}
if (strict) {
var first = firstchar(body)
if (first !== '{' && first !== '[') {
debug('strict violation')
throw new SyntaxError('Unexpected token ' + first)
}
}
debug('parse json')
return JSON.parse(body, reviver)
}
return function jsonParser (req, res, next) {
if (req._body) {
debug('body already parsed')
next()
return
}
req.body = req.body || {}
// skip requests without bodies
if (!typeis.hasBody(req)) {
debug('skip empty body')
next()
return
}
debug('content-type %j', req.headers['content-type'])
// determine if request should be parsed
if (!shouldParse(req)) {
debug('skip parsing')
next()
return
}
// assert charset per RFC 7159 sec 8.1
var charset = getCharset(req) || 'utf-8'
if (charset.substr(0, 4) !== 'utf-') {
debug('invalid charset')
next(createError(415, 'unsupported charset "' + charset.toUpperCase() + '"', {
charset: charset
}))
return
}
// read
read(req, res, next, parse, debug, {
encoding: charset,
inflate: inflate,
limit: limit,
verify: verify
})
}
}
/**
* Get the first non-whitespace character in a string.
*
* @param {string} str
* @return {function}
* @api public
*/
function firstchar (str) {
var match = FIRST_CHAR_REGEXP.exec(str)
return match ? match[1] : ''
}
/**
* Get the charset of a request.
*
* @param {object} req
* @api private
*/
function getCharset (req) {
try {
return contentType.parse(req).parameters.charset.toLowerCase()
} catch (e) {
return undefined
}
}
/**
* Get the simple type checker.
*
* @param {string} type
* @return {function}
*/
function typeChecker (type) {
return function checkType (req) {
return Boolean(typeis(req, type))
}
}
/*!
* body-parser
* Copyright(c) 2014-2015 Douglas Christopher Wilson
* MIT Licensed
*/
'use strict'
/**
* Module dependencies.
*/
var bytes = require('bytes')
var debug = require('debug')('body-parser:raw')
var read = require('../read')
var typeis = require('type-is')
/**
* Module exports.
*/
module.exports = raw
/**
* Create a middleware to parse raw bodies.
*
* @param {object} [options]
* @return {function}
* @api public
*/
function raw (options) {
var opts = options || {}
var inflate = opts.inflate !== false
var limit = typeof opts.limit !== 'number'
? bytes.parse(opts.limit || '100kb')
: opts.limit
var type = opts.type || 'application/octet-stream'
var verify = opts.verify || false
if (verify !== false && typeof verify !== 'function') {
throw new TypeError('option verify must be function')
}
// create the appropriate type checking function
var shouldParse = typeof type !== 'function'
? typeChecker(type)
: type
function parse (buf) {
return buf
}
return function rawParser (req, res, next) {
if (req._body) {
debug('body already parsed')
next()
return
}
req.body = req.body || {}
// skip requests without bodies
if (!typeis.hasBody(req)) {
debug('skip empty body')
next()
return
}
debug('content-type %j', req.headers['content-type'])
// determine if request should be parsed
if (!shouldParse(req)) {
debug('skip parsing')
next()
return
}
// read
read(req, res, next, parse, debug, {
encoding: null,
inflate: inflate,
limit: limit,
verify: verify
})
}
}
/**
* Get the simple type checker.
*
* @param {string} type
* @return {function}
*/
function typeChecker (type) {
return function checkType (req) {
return Boolean(typeis(req, type))
}
}
/*!
* body-parser
* Copyright(c) 2014-2015 Douglas Christopher Wilson
* MIT Licensed
*/
'use strict'
/**
* Module dependencies.
*/
var bytes = require('bytes')
var contentType = require('content-type')
var debug = require('debug')('body-parser:text')
var read = require('../read')
var typeis = require('type-is')
/**
* Module exports.
*/
module.exports = text
/**
* Create a middleware to parse text bodies.
*
* @param {object} [options]
* @return {function}
* @api public
*/
function text (options) {
var opts = options || {}
var defaultCharset = opts.defaultCharset || 'utf-8'
var inflate = opts.inflate !== false
var limit = typeof opts.limit !== 'number'
? bytes.parse(opts.limit || '100kb')
: opts.limit
var type = opts.type || 'text/plain'
var verify = opts.verify || false
if (verify !== false && typeof verify !== 'function') {
throw new TypeError('option verify must be function')
}
// create the appropriate type checking function
var shouldParse = typeof type !== 'function'
? typeChecker(type)
: type
function parse (buf) {
return buf
}
return function textParser (req, res, next) {
if (req._body) {
debug('body already parsed')
next()
return
}
req.body = req.body || {}
// skip requests without bodies
if (!typeis.hasBody(req)) {
debug('skip empty body')
next()
return
}
debug('content-type %j', req.headers['content-type'])
// determine if request should be parsed
if (!shouldParse(req)) {
debug('skip parsing')
next()
return
}
// get charset
var charset = getCharset(req) || defaultCharset
// read
read(req, res, next, parse, debug, {
encoding: charset,
inflate: inflate,
limit: limit,
verify: verify
})
}
}
/**
* Get the charset of a request.
*
* @param {object} req
* @api private
*/
function getCharset (req) {
try {
return contentType.parse(req).parameters.charset.toLowerCase()
} catch (e) {
return undefined
}
}
/**
* Get the simple type checker.
*
* @param {string} type
* @return {function}
*/
function typeChecker (type) {
return function checkType (req) {
return Boolean(typeis(req, type))
}
}
/*!
* body-parser
* Copyright(c) 2014 Jonathan Ong
* Copyright(c) 2014-2015 Douglas Christopher Wilson
* MIT Licensed
*/
'use strict'
/**
* Module dependencies.
* @private
*/
var bytes = require('bytes')
var contentType = require('content-type')
var createError = require('http-errors')
var debug = require('debug')('body-parser:urlencoded')
var deprecate = require('depd')('body-parser')
var read = require('../read')
var typeis = require('type-is')
/**
* Module exports.
*/
module.exports = urlencoded
/**
* Cache of parser modules.
*/
var parsers = Object.create(null)
/**
* Create a middleware to parse urlencoded bodies.
*
* @param {object} [options]
* @return {function}
* @public
*/
function urlencoded (options) {
var opts = options || {}
// notice because option default will flip in next major
if (opts.extended === undefined) {
deprecate('undefined extended: provide extended option')
}
var extended = opts.extended !== false
var inflate = opts.inflate !== false
var limit = typeof opts.limit !== 'number'
? bytes.parse(opts.limit || '100kb')
: opts.limit
var type = opts.type || 'application/x-www-form-urlencoded'
var verify = opts.verify || false
if (verify !== false && typeof verify !== 'function') {
throw new TypeError('option verify must be function')
}
// create the appropriate query parser
var queryparse = extended
? extendedparser(opts)
: simpleparser(opts)
// create the appropriate type checking function
var shouldParse = typeof type !== 'function'
? typeChecker(type)
: type
function parse (body) {
return body.length
? queryparse(body)
: {}
}
return function urlencodedParser (req, res, next) {
if (req._body) {
debug('body already parsed')
next()
return
}
req.body = req.body || {}
// skip requests without bodies
if (!typeis.hasBody(req)) {
debug('skip empty body')
next()
return
}
debug('content-type %j', req.headers['content-type'])
// determine if request should be parsed
if (!shouldParse(req)) {
debug('skip parsing')
next()
return
}
// assert charset
var charset = getCharset(req) || 'utf-8'
if (charset !== 'utf-8') {
debug('invalid charset')
next(createError(415, 'unsupported charset "' + charset.toUpperCase() + '"', {
charset: charset
}))
return
}
// read
read(req, res, next, parse, debug, {
debug: debug,
encoding: charset,
inflate: inflate,
limit: limit,
verify: verify
})
}
}
/**
* Get the extended query parser.
*
* @param {object} options
*/
function extendedparser (options) {
var parameterLimit = options.parameterLimit !== undefined
? options.parameterLimit
: 1000
var parse = parser('qs')
if (isNaN(parameterLimit) || parameterLimit < 1) {
throw new TypeError('option parameterLimit must be a positive number')
}
if (isFinite(parameterLimit)) {
parameterLimit = parameterLimit | 0
}
return function queryparse (body) {
var paramCount = parameterCount(body, parameterLimit)
if (paramCount === undefined) {
debug('too many parameters')
throw createError(413, 'too many parameters')
}
var arrayLimit = Math.max(100, paramCount)
debug('parse extended urlencoding')
return parse(body, {
allowPrototypes: true,
arrayLimit: arrayLimit,
depth: Infinity,
parameterLimit: parameterLimit
})
}
}
/**
* Get the charset of a request.
*
* @param {object} req
* @api private
*/
function getCharset (req) {
try {
return contentType.parse(req).parameters.charset.toLowerCase()
} catch (e) {
return undefined
}
}
/**
* Count the number of parameters, stopping once limit reached
*
* @param {string} body
* @param {number} limit
* @api private
*/
function parameterCount (body, limit) {
var count = 0
var index = 0
while ((index = body.indexOf('&', index)) !== -1) {
count++
index++
if (count === limit) {
return undefined
}
}
return count
}
/**
* Get parser for module name dynamically.
*
* @param {string} name
* @return {function}
* @api private
*/
function parser (name) {
var mod = parsers[name]
if (mod !== undefined) {
return mod.parse
}
// this uses a switch for static require analysis
switch (name) {
case 'qs':
mod = require('qs')
break
case 'querystring':
mod = require('querystring')
break
}
// store to prevent invoking require()
parsers[name] = mod
return mod.parse
}
/**
* Get the simple query parser.
*
* @param {object} options
*/
function simpleparser (options) {
var parameterLimit = options.parameterLimit !== undefined
? options.parameterLimit
: 1000
var parse = parser('querystring')
if (isNaN(parameterLimit) || parameterLimit < 1) {
throw new TypeError('option parameterLimit must be a positive number')
}
if (isFinite(parameterLimit)) {
parameterLimit = parameterLimit | 0
}
return function queryparse (body) {
var paramCount = parameterCount(body, parameterLimit)
if (paramCount === undefined) {
debug('too many parameters')
throw createError(413, 'too many parameters')
}
debug('parse urlencoding')
return parse(body, undefined, undefined, {maxKeys: parameterLimit})
}
}
/**
* Get the simple type checker.
*
* @param {string} type
* @return {function}
*/
function typeChecker (type) {
return function checkType (req) {
return Boolean(typeis(req, type))
}
}
(The MIT License)
Copyright (c) 2014 Jonathan Ong <me@jongleberry.com>
Copyright (c) 2014-2015 Douglas Christopher Wilson <doug@somethingdoug.com>
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.
{
"env": {
"browser": true,
"node": true
},
"rules": {
"no-console": 0,
"no-empty": [1, { "allowEmptyCatch": true }]
},
"extends": "eslint:recommended"
}
support
test
examples
example
*.sock
dist
yarn.lock
coverage
language: node_js
node_js:
- "6"
- "5"
- "4"
install:
- make node_modules
script:
- make lint
- make test
- make coveralls
{
"name": "visionmedia-debug",
"main": "./src/browser.js",
"homepage": "https://github.com/visionmedia/debug",
"authors": [
"TJ Holowaychuk <tj@vision-media.ca>",
"Nathan Rajlich <nathan@tootallnate.net> (http://n8.io)",
"Andrew Rhyne <rhyneandrew@gmail.com>"
],
"description": "visionmedia-debug",
"moduleType": [
"amd",
"es6",
"globals",
"node"
],
"keywords": [
"visionmedia",
"debug"
],
"license": "MIT",
"ignore": [
"**/.*",
"node_modules",
"bower_components",
"test",
"tests"
]
}

2.6.0 / 2016-12-28

  • Fix: added better null pointer checks for browser useColors (@thebigredgeek)
  • Improvement: removed explicit window.debug export (#404, @tootallnate)
  • Improvement: deprecated DEBUG_FD environment variable (#405, @tootallnate)

2.5.2 / 2016-12-25

  • Fix: reference error on window within webworkers (#393, @KlausTrainer)
  • Docs: fixed README typo (#391, @lurch)
  • Docs: added notice about v3 api discussion (@thebigredgeek)

2.5.1 / 2016-12-20

  • Fix: babel-core compatibility

2.5.0 / 2016-12-20

  • Fix: wrong reference in bower file (@thebigredgeek)
  • Fix: webworker compatibility (@thebigredgeek)
  • Fix: output formatting issue (#388, @kribblo)
  • Fix: babel-loader compatibility (#383, @escwald)
  • Misc: removed built asset from repo and publications (@thebigredgeek)
  • Misc: moved source files to /src (#378, @yamikuronue)
  • Test: added karma integration and replaced babel with browserify for browser tests (#378, @yamikuronue)
  • Test: coveralls integration (#378, @yamikuronue)
  • Docs: simplified language in the opening paragraph (#373, @yamikuronue)

2.4.5 / 2016-12-17

  • Fix: navigator undefined in Rhino (#376, @jochenberger)
  • Fix: custom log function (#379, @hsiliev)
  • Improvement: bit of cleanup + linting fixes (@thebigredgeek)
  • Improvement: rm non-maintainted dist/ dir (#375, @freewil)
  • Docs: simplified language in the opening paragraph. (#373, @yamikuronue)

2.4.4 / 2016-12-14

  • Fix: work around debug being loaded in preload scripts for electron (#368, @paulcbetts)

2.4.3 / 2016-12-14

  • Fix: navigation.userAgent error for react native (#364, @escwald)

2.4.2 / 2016-12-14

  • Fix: browser colors (#367, @tootallnate)
  • Misc: travis ci integration (@thebigredgeek)
  • Misc: added linting and testing boilerplate with sanity check (@thebigredgeek)

2.4.1 / 2016-12-13

  • Fix: typo that broke the package (#356)

2.4.0 / 2016-12-13

  • Fix: bower.json references unbuilt src entry point (#342, @justmatt)
  • Fix: revert "handle regex special characters" (@tootallnate)
  • Feature: configurable util.inspect()`options for NodeJS (#327, @tootallnate)
  • Feature: %O`(big O) pretty-prints objects (#322, @tootallnate)
  • Improvement: allow colors in workers (#335, @botverse)
  • Improvement: use same color for same namespace. (#338, @lchenay)

2.3.3 / 2016-11-09

  • Fix: Catch JSON.stringify() errors (#195, Jovan Alleyne)
  • Fix: Returning localStorage saved values (#331, Levi Thomason)
  • Improvement: Don't create an empty object when no process (Nathan Rajlich)

2.3.2 / 2016-11-09

  • Fix: be super-safe in index.js as well (@TooTallNate)
  • Fix: should check whether process exists (Tom Newby)

2.3.1 / 2016-11-09

  • Fix: Added electron compatibility (#324, @paulcbetts)
  • Improvement: Added performance optimizations (@tootallnate)
  • Readme: Corrected PowerShell environment variable example (#252, @gimre)
  • Misc: Removed yarn lock file from source control (#321, @fengmk2)

2.3.0 / 2016-11-07

  • Fix: Consistent placement of ms diff at end of output (#215, @gorangajic)
  • Fix: Escaping of regex special characters in namespace strings (#250, @zacronos)
  • Fix: Fixed bug causing crash on react-native (#282, @vkarpov15)
  • Feature: Enabled ES6+ compatible import via default export (#212 @bucaran)
  • Feature: Added %O formatter to reflect Chrome's console.log capability (#279, @oncletom)
  • Package: Update "ms" to 0.7.2 (#315, @DevSide)
  • Package: removed superfluous version property from bower.json (#207 @kkirsche)
  • Readme: fix USE_COLORS to DEBUG_COLORS
  • Readme: Doc fixes for format string sugar (#269, @mlucool)
  • Readme: Updated docs for DEBUG_FD and DEBUG_COLORS environment variables (#232, @mattlyons0)
  • Readme: doc fixes for PowerShell (#271 #243, @exoticknight @unreadable)
  • Readme: better docs for browser support (#224, @matthewmueller)
  • Tooling: Added yarn integration for development (#317, @thebigredgeek)
  • Misc: Renamed History.md to CHANGELOG.md (@thebigredgeek)
  • Misc: Added license file (#226 #274, @CantemoInternal @sdaitzman)
  • Misc: Updated contributors (@thebigredgeek)

2.2.0 / 2015-05-09

  • package: update "ms" to v0.7.1 (#202, @dougwilson)
  • README: add logging to file example (#193, @DanielOchoa)
  • README: fixed a typo (#191, @amir-s)
  • browser: expose storage (#190, @stephenmathieson)
  • Makefile: add a distclean target (#189, @stephenmathieson)

2.1.3 / 2015-03-13

  • Updated stdout/stderr example (#186)
  • Updated example/stdout.js to match debug current behaviour
  • Renamed example/stderr.js to stdout.js
  • Update Readme.md (#184)
  • replace high intensity foreground color for bold (#182, #183)

2.1.2 / 2015-03-01

  • dist: recompile
  • update "ms" to v0.7.0
  • package: update "browserify" to v9.0.3
  • component: fix "ms.js" repo location
  • changed bower package name
  • updated documentation about using debug in a browser
  • fix: security error on safari (#167, #168, @yields)

2.1.1 / 2014-12-29

  • browser: use typeof to check for console existence
  • browser: check for console.log truthiness (fix IE 8/9)
  • browser: add support for Chrome apps
  • Readme: added Windows usage remarks
  • Add bower.json to properly support bower install

2.1.0 / 2014-10-15

  • node: implement DEBUG_FD env variable support
  • package: update "browserify" to v6.1.0
  • package: add "license" field to package.json (#135, @panuhorsmalahti)

2.0.0 / 2014-09-01

  • package: update "browserify" to v5.11.0
  • node: use stderr rather than stdout for logging (#29, @stephenmathieson)

1.0.4 / 2014-07-15

  • dist: recompile
  • example: remove console.info() log usage
  • example: add "Content-Type" UTF-8 header to browser example
  • browser: place %c marker after the space character
  • browser: reset the "content" color via color: inherit
  • browser: add colors support for Firefox >= v31
  • debug: prefer an instance log() function over the global one (#119)
  • Readme: update documentation about styled console logs for FF v31 (#116, @wryk)

1.0.3 / 2014-07-09

  • Add support for multiple wildcards in namespaces (#122, @seegno)
  • browser: fix lint

1.0.2 / 2014-06-10

  • browser: update color palette (#113, @gscottolson)
  • common: make console logging function configurable (#108, @timoxley)
  • node: fix %o colors on old node <= 0.8.x
  • Makefile: find node path using shell/which (#109, @timoxley)

1.0.1 / 2014-06-06

  • browser: use removeItem() to clear localStorage
  • browser, node: don't set DEBUG if namespaces is undefined (#107, @leedm777)
  • package: add "contributors" section
  • node: fix comment typo
  • README: list authors

1.0.0 / 2014-06-04

  • make ms diff be global, not be scope
  • debug: ignore empty strings in enable()
  • node: make DEBUG_COLORS able to disable coloring
  • *: export the colors array
  • npmignore: don't publish the dist dir
  • Makefile: refactor to use browserify
  • package: add "browserify" as a dev dependency
  • Readme: add Web Inspector Colors section
  • node: reset terminal color for the debug content
  • node: map "%o" to util.inspect()
  • browser: map "%j" to JSON.stringify()
  • debug: add custom "formatters"
  • debug: use "ms" module for humanizing the diff
  • Readme: add "bash" syntax highlighting
  • browser: add Firebug color support
  • browser: add colors for WebKit browsers
  • node: apply log to console
  • rewrite: abstract common logic for Node & browsers
  • add .jshintrc file

0.8.1 / 2014-04-14

  • package: re-add the "component" section

0.8.0 / 2014-03-30

  • add enable() method for nodejs. Closes #27
  • change from stderr to stdout
  • remove unnecessary index.js file

0.7.4 / 2013-11-13

  • remove "browserify" key from package.json (fixes something in browserify)

0.7.3 / 2013-10-30

  • fix: catch localStorage security error when cookies are blocked (Chrome)
  • add debug(err) support. Closes #46
  • add .browser prop to package.json. Closes #42

0.7.2 / 2013-02-06

  • fix package.json
  • fix: Mobile Safari (private mode) is broken with debug
  • fix: Use unicode to send escape character to shell instead of octal to work with strict mode javascript

0.7.1 / 2013-02-05

  • add repository URL to package.json
  • add DEBUG_COLORED to force colored output
  • add browserify support
  • fix component. Closes #24

0.7.0 / 2012-05-04

  • Added .component to package.json
  • Added debug.component.js build

0.6.0 / 2012-03-16

  • Added support for "-" prefix in DEBUG [Vinay Pulim]
  • Added .enabled flag to the node version [TooTallNate]

0.5.0 / 2012-02-02

  • Added: humanize diffs. Closes #8
  • Added debug.disable() to the CS variant
  • Removed padding. Closes #10
  • Fixed: persist client-side variant again. Closes #9

0.4.0 / 2012-02-01

  • Added browser variant support for older browsers [TooTallNate]
  • Added debug.enable('project:*') to browser variant [TooTallNate]
  • Added padding to diff (moved it to the right)

0.3.0 / 2012-01-26

  • Added millisecond diff when isatty, otherwise UTC string

0.2.0 / 2012-01-22

  • Added wildcard support

0.1.0 / 2011-12-02

  • Added: remove colors unless stderr isatty [TooTallNate]

0.0.1 / 2010-01-03

  • Initial release
{
"name": "debug",
"repo": "visionmedia/debug",
"description": "small debugging utility",
"version": "2.6.0",
"keywords": [
"debug",
"log",
"debugger"
],
"main": "src/browser.js",
"scripts": [
"src/browser.js",
"src/debug.js"
],
"dependencies": {
"rauchg/ms.js": "0.7.1"
}
}
// Karma configuration
// Generated on Fri Dec 16 2016 13:09:51 GMT+0000 (UTC)
module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['mocha', 'chai', 'sinon'],
// list of files / patterns to load in the browser
files: [
'dist/debug.js',
'test/*spec.js'
],
// list of files to exclude
exclude: [
'src/node.js'
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['progress'],
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['PhantomJS'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false,
// Concurrency level
// how many browser should be started simultaneous
concurrency: Infinity
})
}
(The MIT License)
Copyright (c) 2014 TJ Holowaychuk <tj@vision-media.ca>
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.
# get Makefile directory name: http://stackoverflow.com/a/5982798/376773
THIS_MAKEFILE_PATH:=$(word $(words $(MAKEFILE_LIST)),$(MAKEFILE_LIST))
THIS_DIR:=$(shell cd $(dir $(THIS_MAKEFILE_PATH));pwd)
# BIN directory
BIN := $(THIS_DIR)/node_modules/.bin
# Path
PATH := node_modules/.bin:$(PATH)
SHELL := /bin/bash
# applications
NODE ?= $(shell which node)
YARN ?= $(shell which yarn)
PKG ?= $(if $(YARN),$(YARN),$(NODE) $(shell which npm))
BROWSERIFY ?= $(NODE) $(BIN)/browserify
.FORCE:
all: dist/debug.js
install: node_modules
node_modules: package.json
@NODE_ENV= $(PKG) install
@touch node_modules
lint: .FORCE
eslint browser.js debug.js index.js node.js
test-node: .FORCE
istanbul cover node_modules/mocha/bin/_mocha -- test/**.js
test-browser: .FORCE
mkdir -p dist
@$(BROWSERIFY) \
--standalone debug \
. > dist/debug.js
karma start --single-run
rimraf dist
test: .FORCE
concurrently \
"make test-node" \
"make test-browser"
coveralls:
cat ./coverage/lcov.info | ./node_modules/coveralls/bin/coveralls.js
.PHONY: all install clean distclean
{
"_args": [
[
{
"raw": "debug@2.6.0",
"scope": null,
"escapedName": "debug",
"name": "debug",
"rawSpec": "2.6.0",
"spec": "2.6.0",
"type": "version"
},
"C:\\xampp\\htdocs\\cafe\\node_modules\\body-parser"
]
],
"_from": "debug@2.6.0",
"_id": "debug@2.6.0",
"_inCache": true,
"_location": "/body-parser/debug",
"_nodeVersion": "6.9.2",
"_npmOperationalInternal": {
"host": "packages-12-west.internal.npmjs.com",
"tmp": "tmp/debug-2.6.0.tgz_1482990633625_0.042889281176030636"
},
"_npmUser": {
"name": "thebigredgeek",
"email": "rhyneandrew@gmail.com"
},
"_npmVersion": "3.10.9",
"_phantomChildren": {},
"_requested": {
"raw": "debug@2.6.0",
"scope": null,
"escapedName": "debug",
"name": "debug",
"rawSpec": "2.6.0",
"spec": "2.6.0",
"type": "version"
},
"_requiredBy": [
"/body-parser"
],
"_resolved": "https://registry.npmjs.org/debug/-/debug-2.6.0.tgz",
"_shasum": "bc596bcabe7617f11d9fa15361eded5608b8499b",
"_shrinkwrap": null,
"_spec": "debug@2.6.0",
"_where": "C:\\xampp\\htdocs\\cafe\\node_modules\\body-parser",
"author": {
"name": "TJ Holowaychuk",
"email": "tj@vision-media.ca"
},
"browser": "./src/browser.js",
"bugs": {
"url": "https://github.com/visionmedia/debug/issues"
},
"component": {
"scripts": {
"debug/index.js": "browser.js",
"debug/debug.js": "debug.js"
}
},
"contributors": [
{
"name": "Nathan Rajlich",
"email": "nathan@tootallnate.net",
"url": "http://n8.io"
},
{
"name": "Andrew Rhyne",
"email": "rhyneandrew@gmail.com"
}
],
"dependencies": {
"ms": "0.7.2"
},
"description": "small debugging utility",
"devDependencies": {
"browserify": "9.0.3",
"chai": "^3.5.0",
"concurrently": "^3.1.0",
"coveralls": "^2.11.15",
"eslint": "^3.12.1",
"istanbul": "^0.4.5",
"karma": "^1.3.0",
"karma-chai": "^0.1.0",
"karma-mocha": "^1.3.0",
"karma-phantomjs-launcher": "^1.0.2",
"karma-sinon": "^1.0.5",
"mocha": "^3.2.0",
"mocha-lcov-reporter": "^1.2.0",
"rimraf": "^2.5.4",
"sinon": "^1.17.6",
"sinon-chai": "^2.8.0"
},
"directories": {},
"dist": {
"shasum": "bc596bcabe7617f11d9fa15361eded5608b8499b",
"tarball": "https://registry.npmjs.org/debug/-/debug-2.6.0.tgz"
},
"gitHead": "ac5ccae70358a2bccc71d288e5f9c656a7678748",
"homepage": "https://github.com/visionmedia/debug#readme",
"keywords": [
"debug",
"log",
"debugger"
],
"license": "MIT",
"main": "./src/index.js",
"maintainers": [
{
"name": "thebigredgeek",
"email": "rhyneandrew@gmail.com"
}
],
"name": "debug",
"optionalDependencies": {},
"readme": "ERROR: No README data found!",
"repository": {
"type": "git",
"url": "git://github.com/visionmedia/debug.git"
},
"scripts": {},
"version": "2.6.0"
}

debug

Build Status Coverage Status

A tiny node.js debugging utility modelled after node core's debugging technique.

Discussion around the V3 API is under way here

Installation

$ npm install debug

Usage

debug exposes a function; simply pass this function the name of your module, and it will return a decorated version of console.error for you to pass debug statements to. This will allow you to toggle the debug output for different parts of your module as well as the module as a whole.

Example app.js:

var debug = require('debug')('http')
  , http = require('http')
  , name = 'My App';

// fake app

debug('booting %s', name);

http.createServer(function(req, res){
  debug(req.method + ' ' + req.url);
  res.end('hello\n');
}).listen(3000, function(){
  debug('listening');
});

// fake worker of some kind

require('./worker');

Example worker.js:

var debug = require('debug')('worker');

setInterval(function(){
  debug('doing some work');
}, 1000);

The DEBUG environment variable is then used to enable these based on space or comma-delimited names. Here are some examples:

debug http and worker

debug worker

Windows note

On Windows the environment variable is set using the set command.

set DEBUG=*,-not_this

Note that PowerShell uses different syntax to set environment variables.

$env:DEBUG = "*,-not_this"

Then, run the program to be debugged as usual.

Millisecond diff

When actively developing an application it can be useful to see when the time spent between one debug() call and the next. Suppose for example you invoke debug() before requesting a resource, and after as well, the "+NNNms" will show you how much time was spent between calls.

When stdout is not a TTY, Date#toUTCString() is used, making it more useful for logging the debug information as shown below:

Conventions

If you're using this in one or more of your libraries, you should use the name of your library so that developers may toggle debugging as desired without guessing names. If you have more than one debuggers you should prefix them with your library name and use ":" to separate features. For example "bodyParser" from Connect would then be "connect:bodyParser".

Wildcards

The * character may be used as a wildcard. Suppose for example your library has debuggers named "connect:bodyParser", "connect:compress", "connect:session", instead of listing all three with DEBUG=connect:bodyParser,connect:compress,connect:session, you may simply do DEBUG=connect:*, or to run everything using this module simply use DEBUG=*.

You can also exclude specific debuggers by prefixing them with a "-" character. For example, DEBUG=*,-connect:* would include all debuggers except those starting with "connect:".

Environment Variables

When running through Node.js, you can set a few environment variables that will change the behavior of the debug logging:

Name Purpose
DEBUG Enables/disabled specific debugging namespaces.
DEBUG_COLORS Whether or not to use colors in the debug output.
DEBUG_DEPTH Object inspection depth.
DEBUG_SHOW_HIDDEN Shows hidden properties on inspected objects.

Note: The environment variables beginning with DEBUG_ end up being converted into an Options object that gets used with %o/%O formatters. See the Node.js documentation for util.inspect() for the complete list.

Formatters

Debug uses printf-style formatting. Below are the officially supported formatters:

Formatter Representation
%O Pretty-print an Object on multiple lines.
%o Pretty-print an Object all on a single line.
%s String.
%d Number (both integer and float).
%j JSON. Replaced with the string '[Circular]' if the argument contains circular references.
%% Single percent sign ('%'). This does not consume an argument.

Custom formatters

You can add custom formatters by extending the debug.formatters object. For example, if you wanted to add support for rendering a Buffer as hex with %h, you could do something like:

const createDebug = require('debug')
createDebug.formatters.h = (v) => {
  return v.toString('hex')
}

// …elsewhere
const debug = createDebug('foo')
debug('this is hex: %h', new Buffer('hello world'))
//   foo this is hex: 68656c6c6f20776f726c6421 +0ms

Browser support

You can build a browser-ready script using browserify, or just use the browserify-as-a-service build, if you don't want to build it yourself.

Debug's enable state is currently persisted by localStorage. Consider the situation shown below where you have worker:a and worker:b, and wish to debug both. You can enable this using localStorage.debug:

localStorage.debug = 'worker:*'

And then refresh the page.

a = debug('worker:a');
b = debug('worker:b');

setInterval(function(){
  a('doing some work');
}, 1000);

setInterval(function(){
  b('doing some work');
}, 1200);

Web Inspector Colors

Colors are also enabled on "Web Inspectors" that understand the %c formatting option. These are WebKit web inspectors, Firefox (since version 31) and the Firebug plugin for Firefox (any version).

Colored output looks something like:

Output streams

By default debug will log to stderr, however this can be configured per-namespace by overriding the log method:

Example stdout.js:

var debug = require('debug');
var error = debug('app:error');

// by default stderr is used
error('goes to stderr!');

var log = debug('app:log');
// set this namespace to log via console.log
log.log = console.log.bind(console); // don't forget to bind to console!
log('goes to stdout');
error('still goes to stderr!');

// set all output to go via console.info
// overrides all per-namespace log settings
debug.log = console.info.bind(console);
error('now goes to stdout via console.info');
log('still goes to stdout, but via console.info now');

Authors

  • TJ Holowaychuk
  • Nathan Rajlich
  • Andrew Rhyne

License

(The MIT License)

Copyright (c) 2014-2016 TJ Holowaychuk <tj@vision-media.ca>

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.

/**
* This is the web browser implementation of `debug()`.
*
* Expose `debug()` as the module.
*/
exports = module.exports = require('./debug');
exports.log = log;
exports.formatArgs = formatArgs;
exports.save = save;
exports.load = load;
exports.useColors = useColors;
exports.storage = 'undefined' != typeof chrome
&& 'undefined' != typeof chrome.storage
? chrome.storage.local
: localstorage();
/**
* Colors.
*/
exports.colors = [
'lightseagreen',
'forestgreen',
'goldenrod',
'dodgerblue',
'darkorchid',
'crimson'
];
/**
* Currently only WebKit-based Web Inspectors, Firefox >= v31,
* and the Firebug extension (any Firefox version) are known
* to support "%c" CSS customizations.
*
* TODO: add a `localStorage` variable to explicitly enable/disable colors
*/
function useColors() {
// NB: In an Electron preload script, document will be defined but not fully
// initialized. Since we know we're in Chrome, we'll just detect this case
// explicitly
if (typeof window !== 'undefined' && window && typeof window.process !== 'undefined' && window.process.type === 'renderer') {
return true;
}
// is webkit? http://stackoverflow.com/a/16459606/376773
// document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
return (typeof document !== 'undefined' && document && 'WebkitAppearance' in document.documentElement.style) ||
// is firebug? http://stackoverflow.com/a/398120/376773
(typeof window !== 'undefined' && window && window.console && (console.firebug || (console.exception && console.table))) ||
// is firefox >= v31?
// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
(typeof navigator !== 'undefined' && navigator && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||
// double check webkit in userAgent just in case we are in a worker
(typeof navigator !== 'undefined' && navigator && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/));
}
/**
* Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
*/
exports.formatters.j = function(v) {
try {
return JSON.stringify(v);
} catch (err) {
return '[UnexpectedJSONParseError]: ' + err.message;
}
};
/**
* Colorize log arguments if enabled.
*
* @api public
*/
function formatArgs(args) {
var useColors = this.useColors;
args[0] = (useColors ? '%c' : '')
+ this.namespace
+ (useColors ? ' %c' : ' ')
+ args[0]
+ (useColors ? '%c ' : ' ')
+ '+' + exports.humanize(this.diff);
if (!useColors) return;
var c = 'color: ' + this.color;
args.splice(1, 0, c, 'color: inherit')
// the final "%c" is somewhat tricky, because there could be other
// arguments passed either before or after the %c, so we need to
// figure out the correct index to insert the CSS into
var index = 0;
var lastC = 0;
args[0].replace(/%[a-zA-Z%]/g, function(match) {
if ('%%' === match) return;
index++;
if ('%c' === match) {
// we only are interested in the *last* %c
// (the user may have provided their own)
lastC = index;
}
});
args.splice(lastC, 0, c);
}
/**
* Invokes `console.log()` when available.
* No-op when `console.log` is not a "function".
*
* @api public
*/
function log() {
// this hackery is required for IE8/9, where
// the `console.log` function doesn't have 'apply'
return 'object' === typeof console
&& console.log
&& Function.prototype.apply.call(console.log, console, arguments);
}
/**
* Save `namespaces`.
*
* @param {String} namespaces
* @api private
*/
function save(namespaces) {
try {
if (null == namespaces) {
exports.storage.removeItem('debug');
} else {
exports.storage.debug = namespaces;
}
} catch(e) {}
}
/**
* Load `namespaces`.
*
* @return {String} returns the previously persisted debug modes
* @api private
*/
function load() {
try {
return exports.storage.debug;
} catch(e) {}
// If debug isn't set in LS, and we're in Electron, try to load $DEBUG
if (typeof process !== 'undefined' && 'env' in process) {
return process.env.DEBUG;
}
}
/**
* Enable namespaces listed in `localStorage.debug` initially.
*/
exports.enable(load());
/**
* Localstorage attempts to return the localstorage.
*
* This is necessary because safari throws
* when a user disables cookies/localstorage
* and you attempt to access it.
*
* @return {LocalStorage}
* @api private
*/
function localstorage() {
try {
return window.localStorage;
} catch (e) {}
}
/**
* This is the common logic for both the Node.js and web browser
* implementations of `debug()`.
*
* Expose `debug()` as the module.
*/
exports = module.exports = createDebug.debug = createDebug.default = createDebug;
exports.coerce = coerce;
exports.disable = disable;
exports.enable = enable;
exports.enabled = enabled;
exports.humanize = require('ms');
/**
* The currently active debug mode names, and names to skip.
*/
exports.names = [];
exports.skips = [];
/**
* Map of special "%n" handling functions, for the debug "format" argument.
*
* Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
*/
exports.formatters = {};
/**
* Previous log timestamp.
*/
var prevTime;
/**
* Select a color.
* @param {String} namespace
* @return {Number}
* @api private
*/
function selectColor(namespace) {
var hash = 0, i;
for (i in namespace) {
hash = ((hash << 5) - hash) + namespace.charCodeAt(i);
hash |= 0; // Convert to 32bit integer
}
return exports.colors[Math.abs(hash) % exports.colors.length];
}
/**
* Create a debugger with the given `namespace`.
*
* @param {String} namespace
* @return {Function}
* @api public
*/
function createDebug(namespace) {
function debug() {
// disabled?
if (!debug.enabled) return;
var self = debug;
// set `diff` timestamp
var curr = +new Date();
var ms = curr - (prevTime || curr);
self.diff = ms;
self.prev = prevTime;
self.curr = curr;
prevTime = curr;
// turn the `arguments` into a proper Array
var args = new Array(arguments.length);
for (var i = 0; i < args.length; i++) {
args[i] = arguments[i];
}
args[0] = exports.coerce(args[0]);
if ('string' !== typeof args[0]) {
// anything else let's inspect with %O
args.unshift('%O');
}
// apply any `formatters` transformations
var index = 0;
args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) {
// if we encounter an escaped % then don't increase the array index
if (match === '%%') return match;
index++;
var formatter = exports.formatters[format];
if ('function' === typeof formatter) {
var val = args[index];
match = formatter.call(self, val);
// now we need to remove `args[index]` since it's inlined in the `format`
args.splice(index, 1);
index--;
}
return match;
});
// apply env-specific formatting (colors, etc.)
exports.formatArgs.call(self, args);
var logFn = debug.log || exports.log || console.log.bind(console);
logFn.apply(self, args);
}
debug.namespace = namespace;
debug.enabled = exports.enabled(namespace);
debug.useColors = exports.useColors();
debug.color = selectColor(namespace);
// env-specific initialization logic for debug instances
if ('function' === typeof exports.init) {
exports.init(debug);
}
return debug;
}
/**
* Enables a debug mode by namespaces. This can include modes
* separated by a colon and wildcards.
*
* @param {String} namespaces
* @api public
*/
function enable(namespaces) {
exports.save(namespaces);
var split = (namespaces || '').split(/[\s,]+/);
var len = split.length;
for (var i = 0; i < len; i++) {
if (!split[i]) continue; // ignore empty strings
namespaces = split[i].replace(/\*/g, '.*?');
if (namespaces[0] === '-') {
exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
} else {
exports.names.push(new RegExp('^' + namespaces + '$'));
}
}
}
/**
* Disable debug output.
*
* @api public
*/
function disable() {
exports.enable('');
}
/**
* Returns true if the given mode name is enabled, false otherwise.
*
* @param {String} name
* @return {Boolean}
* @api public
*/
function enabled(name) {
var i, len;
for (i = 0, len = exports.skips.length; i < len; i++) {
if (exports.skips[i].test(name)) {
return false;
}
}
for (i = 0, len = exports.names.length; i < len; i++) {
if (exports.names[i].test(name)) {
return true;
}
}
return false;
}
/**
* Coerce `val`.
*
* @param {Mixed} val
* @return {Mixed}
* @api private
*/
function coerce(val) {
if (val instanceof Error) return val.stack || val.message;
return val;
}
/**
* Detect Electron renderer process, which is node, but we should
* treat as a browser.
*/
if (typeof process !== 'undefined' && process.type === 'renderer') {
module.exports = require('./browser.js');
} else {
module.exports = require('./node.js');
}
/**
* Module dependencies.
*/
var tty = require('tty');
var util = require('util');
/**
* This is the Node.js implementation of `debug()`.
*
* Expose `debug()` as the module.
*/
exports = module.exports = require('./debug');
exports.init = init;
exports.log = log;
exports.formatArgs = formatArgs;
exports.save = save;
exports.load = load;
exports.useColors = useColors;
/**
* Colors.
*/
exports.colors = [6, 2, 3, 4, 5, 1];
/**
* Build up the default `inspectOpts` object from the environment variables.
*
* $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js
*/
exports.inspectOpts = Object.keys(process.env).filter(function (key) {
return /^debug_/i.test(key);
}).reduce(function (obj, key) {
// camel-case
var prop = key
.substring(6)
.toLowerCase()
.replace(/_([a-z])/, function (_, k) { return k.toUpperCase() });
// coerce string value into JS value
var val = process.env[key];
if (/^(yes|on|true|enabled)$/i.test(val)) val = true;
else if (/^(no|off|false|disabled)$/i.test(val)) val = false;
else if (val === 'null') val = null;
else val = Number(val);
obj[prop] = val;
return obj;
}, {});
/**
* The file descriptor to write the `debug()` calls to.
* Set the `DEBUG_FD` env variable to override with another value. i.e.:
*
* $ DEBUG_FD=3 node script.js 3>debug.log
*/
if ('DEBUG_FD' in process.env) {
util.deprecate(function(){}, '`DEBUG_FD` is deprecated. Override `debug.log` if you want to use a different log function (https://git.io/vMUyr)')()
}
var fd = parseInt(process.env.DEBUG_FD, 10) || 2;
var stream = 1 === fd ? process.stdout :
2 === fd ? process.stderr :
createWritableStdioStream(fd);
/**
* Is stdout a TTY? Colored output is enabled when `true`.
*/
function useColors() {
return 'colors' in exports.inspectOpts
? Boolean(exports.inspectOpts.colors)
: tty.isatty(fd);
}
/**
* Map %o to `util.inspect()`, all on a single line.
*/
exports.formatters.o = function(v) {
this.inspectOpts.colors = this.useColors;
return util.inspect(v, this.inspectOpts)
.replace(/\s*\n\s*/g, ' ');
};
/**
* Map %o to `util.inspect()`, allowing multiple lines if needed.
*/
exports.formatters.O = function(v) {
this.inspectOpts.colors = this.useColors;
return util.inspect(v, this.inspectOpts);
};
/**
* Adds ANSI color escape codes if enabled.
*
* @api public
*/
function formatArgs(args) {
var name = this.namespace;
var useColors = this.useColors;
if (useColors) {
var c = this.color;
var prefix = ' \u001b[3' + c + ';1m' + name + ' ' + '\u001b[0m';
args[0] = prefix + args[0].split('\n').join('\n' + prefix);
args.push('\u001b[3' + c + 'm+' + exports.humanize(this.diff) + '\u001b[0m');
} else {
args[0] = new Date().toUTCString()
+ ' ' + name + ' ' + args[0];
}
}
/**
* Invokes `util.format()` with the specified arguments and writes to `stream`.
*/
function log() {
return stream.write(util.format.apply(util, arguments) + '\n');
}
/**
* Save `namespaces`.
*
* @param {String} namespaces
* @api private
*/
function save(namespaces) {
if (null == namespaces) {
// If you set a process.env field to null or undefined, it gets cast to the
// string 'null' or 'undefined'. Just delete instead.
delete process.env.DEBUG;
} else {
process.env.DEBUG = namespaces;
}
}
/**
* Load `namespaces`.
*
* @return {String} returns the previously persisted debug modes
* @api private
*/
function load() {
return process.env.DEBUG;
}
/**
* Copied from `node/src/node.js`.
*
* XXX: It's lame that node doesn't expose this API out-of-the-box. It also
* relies on the undocumented `tty_wrap.guessHandleType()` which is also lame.
*/
function createWritableStdioStream (fd) {
var stream;
var tty_wrap = process.binding('tty_wrap');
// Note stream._type is used for test-module-load-list.js
switch (tty_wrap.guessHandleType(fd)) {
case 'TTY':
stream = new tty.WriteStream(fd);
stream._type = 'tty';
// Hack to have stream not keep the event loop alive.
// See https://github.com/joyent/node/issues/1726
if (stream._handle && stream._handle.unref) {
stream._handle.unref();
}
break;
case 'FILE':
var fs = require('fs');
stream = new fs.SyncWriteStream(fd, { autoClose: false });
stream._type = 'fs';
break;
case 'PIPE':
case 'TCP':
var net = require('net');
stream = new net.Socket({
fd: fd,
readable: false,
writable: true
});
// FIXME Should probably have an option in net.Socket to create a
// stream from an existing fd which is writable only. But for now
// we'll just add this hack and set the `readable` member to false.
// Test: ./node test/fixtures/echo.js < /etc/passwd
stream.readable = false;
stream.read = null;
stream._type = 'pipe';
// FIXME Hack to have stream not keep the event loop alive.
// See https://github.com/joyent/node/issues/1726
if (stream._handle && stream._handle.unref) {
stream._handle.unref();
}
break;
default:
// Probably an error on in uv_guess_handle()
throw new Error('Implement me. Unknown stream file type!');
}
// For supporting legacy API we put the FD here.
stream.fd = fd;
stream._isStdio = true;
return stream;
}
/**
* Init logic for `debug` instances.
*
* Create a new `inspectOpts` object in case `useColors` is set
* differently for a particular `debug` instance.
*/
function init (debug) {
debug.inspectOpts = util._extend({}, exports.inspectOpts);
}
/**
* Enable namespaces listed in `process.env.DEBUG` initially.
*/
exports.enable(load());
/**
* Helpers.
*/
var s = 1000
var m = s * 60
var h = m * 60
var d = h * 24
var y = d * 365.25
/**
* Parse or format the given `val`.
*
* Options:
*
* - `long` verbose formatting [false]
*
* @param {String|Number} val
* @param {Object} options
* @throws {Error} throw an error if val is not a non-empty string or a number
* @return {String|Number}
* @api public
*/
module.exports = function (val, options) {
options = options || {}
var type = typeof val
if (type === 'string' && val.length > 0) {
return parse(val)
} else if (type === 'number' && isNaN(val) === false) {
return options.long ?
fmtLong(val) :
fmtShort(val)
}
throw new Error('val is not a non-empty string or a valid number. val=' + JSON.stringify(val))
}
/**
* Parse the given `str` and return milliseconds.
*
* @param {String} str
* @return {Number}
* @api private
*/
function parse(str) {
str = String(str)
if (str.length > 10000) {
return
}
var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(str)
if (!match) {
return
}
var n = parseFloat(match[1])
var type = (match[2] || 'ms').toLowerCase()
switch (type) {
case 'years':
case 'year':
case 'yrs':
case 'yr':
case 'y':
return n * y
case 'days':
case 'day':
case 'd':
return n * d
case 'hours':
case 'hour':
case 'hrs':
case 'hr':
case 'h':
return n * h
case 'minutes':
case 'minute':
case 'mins':
case 'min':
case 'm':
return n * m
case 'seconds':
case 'second':
case 'secs':
case 'sec':
case 's':
return n * s
case 'milliseconds':
case 'millisecond':
case 'msecs':
case 'msec':
case 'ms':
return n
default:
return undefined
}
}
/**
* Short format for `ms`.
*
* @param {Number} ms
* @return {String}
* @api private
*/
function fmtShort(ms) {
if (ms >= d) {
return Math.round(ms / d) + 'd'
}
if (ms >= h) {
return Math.round(ms / h) + 'h'
}
if (ms >= m) {
return Math.round(ms / m) + 'm'
}
if (ms >= s) {
return Math.round(ms / s) + 's'
}
return ms + 'ms'
}
/**
* Long format for `ms`.
*
* @param {Number} ms
* @return {String}
* @api private
*/
function fmtLong(ms) {
return plural(ms, d, 'day') ||
plural(ms, h, 'hour') ||
plural(ms, m, 'minute') ||
plural(ms, s, 'second') ||
ms + ' ms'
}
/**
* Pluralization helper.
*/
function plural(ms, n, name) {
if (ms < n) {
return
}
if (ms < n * 1.5) {
return Math.floor(ms / n) + ' ' + name
}
return Math.ceil(ms / n) + ' ' + name + 's'
}

The MIT License (MIT)

Copyright (c) 2016 Zeit, Inc.

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.

{
"_args": [
[
{
"raw": "ms@0.7.2",
"scope": null,
"escapedName": "ms",
"name": "ms",
"rawSpec": "0.7.2",
"spec": "0.7.2",
"type": "version"
},
"C:\\xampp\\htdocs\\cafe\\node_modules\\body-parser\\node_modules\\debug"
]
],
"_from": "ms@0.7.2",
"_id": "ms@0.7.2",
"_inCache": true,
"_location": "/body-parser/ms",
"_nodeVersion": "6.8.0",
"_npmOperationalInternal": {
"host": "packages-18-east.internal.npmjs.com",
"tmp": "tmp/ms-0.7.2.tgz_1477383407940_0.4743474116548896"
},
"_npmUser": {
"name": "leo",
"email": "leo@zeit.co"
},
"_npmVersion": "3.10.8",
"_phantomChildren": {},
"_requested": {
"raw": "ms@0.7.2",
"scope": null,
"escapedName": "ms",
"name": "ms",
"rawSpec": "0.7.2",
"spec": "0.7.2",
"type": "version"
},
"_requiredBy": [
"/body-parser/debug"
],
"_resolved": "https://registry.npmjs.org/ms/-/ms-0.7.2.tgz",
"_shasum": "ae25cf2512b3885a1d95d7f037868d8431124765",
"_shrinkwrap": null,
"_spec": "ms@0.7.2",
"_where": "C:\\xampp\\htdocs\\cafe\\node_modules\\body-parser\\node_modules\\debug",
"bugs": {
"url": "https://github.com/zeit/ms/issues"
},
"component": {
"scripts": {
"ms/index.js": "index.js"
}
},
"dependencies": {},
"description": "Tiny milisecond conversion utility",
"devDependencies": {
"expect.js": "^0.3.1",
"mocha": "^3.0.2",
"serve": "^1.4.0",
"xo": "^0.17.0"
},
"directories": {},
"dist": {
"shasum": "ae25cf2512b3885a1d95d7f037868d8431124765",
"tarball": "https://registry.npmjs.org/ms/-/ms-0.7.2.tgz"
},
"files": [
"index.js"
],
"gitHead": "ac92a7e0790ba2622a74d9d60690ca0d2c070a45",
"homepage": "https://github.com/zeit/ms#readme",
"license": "MIT",
"main": "./index",
"maintainers": [
{
"name": "leo",
"email": "leo@zeit.co"
},
{
"name": "rauchg",
"email": "rauchg@gmail.com"
}
],
"name": "ms",
"optionalDependencies": {},
"readme": "ERROR: No README data found!",
"repository": {
"type": "git",
"url": "git+https://github.com/zeit/ms.git"
},
"scripts": {
"test": "xo && mocha test/index.js",
"test-browser": "serve ./test"
},
"version": "0.7.2",
"xo": {
"space": true,
"semicolon": false,
"envs": [
"mocha"
],
"rules": {
"complexity": 0
}
}
}

ms

Build Status XO code style Slack Channel

Use this package to easily convert various time formats to milliseconds.

Examples

ms('2 days')  // 172800000
ms('1d')      // 86400000
ms('10h')     // 36000000
ms('2.5 hrs') // 9000000
ms('2h')      // 7200000
ms('1m')      // 60000
ms('5s')      // 5000
ms('1y')      // 31557600000
ms('100')     // 100

Convert from milliseconds

ms(60000)             // "1m"
ms(2 * 60000)         // "2m"
ms(ms('10 hours'))    // "10h"

Time format written-out

ms(60000, { long: true })             // "1 minute"
ms(2 * 60000, { long: true })         // "2 minutes"
ms(ms('10 hours'), { long: true })    // "10 hours"

Features

  • Works both in node and in the browser.
  • If a number is supplied to ms, a string with a unit is returned.
  • If a string that contains the number is supplied, it returns it as a number (e.g.: it returns 100 for '100').
  • If you pass a string with a number and a valid unit, the number of equivalent ms is returned.

Caught a bug?

  1. Fork this repository to your own GitHub account and then clone it to your local device
  2. Link the package to the global module directory: npm link
  3. Within the module you want to test your local development instance of ms, just link it to the dependencies: npm link ms. Instead of the default one from npm, node will now use your clone of ms!

As always, you can run the tests using: npm test

{
"root": true,
"extends": "@ljharb",
"rules": {
"complexity": [2, 22],
"consistent-return": [1],
"id-length": [2, { "min": 1, "max": 25, "properties": "never" }],
"indent": [2, 4],
"max-params": [2, 9],
"max-statements": [2, 36],
"no-extra-parens": [1],
"no-continue": [1],
"no-magic-numbers": 0,
"no-restricted-syntax": [2, "BreakStatement", "DebuggerStatement", "ForInStatement", "LabeledStatement", "WithStatement"],
"operator-linebreak": 1
}
}

6.2.1

  • [Fix] ensure key[]=x&key[]&key[]=y results in 3, not 2, values
  • [Refactor] Be explicit and use Object.prototype.hasOwnProperty.call
  • [Tests] remove parallelshell since it does not reliably report failures
  • [Tests] up to node v6.3, v5.12
  • [Dev Deps] update tape, eslint, @ljharb/eslint-config, qs-iconv
  • [New] pass Buffers to the encoder/decoder directly (#161)
  • [New] add "encoder" and "decoder" options, for custom param encoding/decoding (#160)
  • [Fix] fix compacting of nested sparse arrays (#150)
  • [New] allowDots option for stringify (#151)
  • [Fix] "sort" option should work at a depth of 3 or more (#151)
  • [Fix] Restore dist directory; will be removed in v7 (#148)
  • Revert ES6 requirement and restore support for node down to v0.8.
  • #127 Fix engines definition in package.json
  • #124 Use ES6 and drop support for node < v4

5.2.1

  • [Fix] ensure key[]=x&key[]&key[]=y results in 3, not 2, values
  • #64 Add option to sort object keys in the query string
  • #117 make URI encoding stringified results optional
  • #106 Add flag skipNulls to optionally skip null values in stringify
  • #114 default allowDots to false
  • #100 include dist to npm
  • #98 make returning plain objects and allowing prototype overwriting properties optional
  • #89 Add option to disable "Transform dot notation to bracket notation"
  • #80 qs.parse silently drops properties
  • #77 Perf boost
  • #60 Add explicit option to disable array parsing
  • #74 Bad parse when turning array into object
  • #81 Add a filter option
  • #68 Fixed issue with recursion and passing strings into objects.
  • #66 Add mixed array and object dot notation support Closes: #47
  • #76 RFC 3986
  • #85 No equal sign
  • #84 update license attribute
  • #73 Property 'hasOwnProperty' of object # is not a function
    • #70 Add arrayFormat option
    • #59 make sure array indexes are >= 0, closes #57
    • #58 make qs usable for browser loader
    • #55 allow merging a string into an object
    • #52 Return "undefined" and "false" instead of throwing "TypeError".
    • #50 add option to omit array indices, closes #46
    • #39 Is there an alternative to Buffer.isBuffer?
    • #49 refactor utils.merge, fixes #45
    • #41 avoid browserifying Buffer, for #39
    • #38 how to handle object keys beginning with a number
    • #37 parser discards first empty value in array
    • #36 Update to lab 4.x
    • #33 Error when plain object in a value
    • #34 use Object.prototype.hasOwnProperty.call instead of obj.hasOwnProperty
    • #24 Changelog? Semver?
    • #32 account for circular references properly, closes #31
    • #31 qs.parse stackoverflow on circular objects
    • #26 Don't use Buffer global if it's not present
    • #30 Bug when merging non-object values into arrays
    • #29 Don't call Utils.clone at the top of Utils.merge
    • #23 Ability to not limit parameters?
    • #22 Enable using a RegExp as delimiter
    • #18 Why is there arrayLimit?
    • #20 Configurable parametersLimit
    • #21 make all limits optional, for #18, for #20
    • #19 Don't overwrite null values
    • #16 ignore non-string delimiters
    • #15 Close code block
    • #12 Add optional delim argument
    • #13 fix #11: flattened keys in array are now correctly parsed
    • #7 Empty values of a POST array disappear after being submitted
    • #9 Should not omit equals signs (=) when value is null
    • #6 Minor grammar fix in README
    • #5 array holes incorrectly copied into object on large index
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.Qs = f()}})(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);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 Stringify = require('./stringify');
var Parse = require('./parse');
module.exports = {
stringify: Stringify,
parse: Parse
};
},{"./parse":2,"./stringify":3}],2:[function(require,module,exports){
'use strict';
var Utils = require('./utils');
var has = Object.prototype.hasOwnProperty;
var defaults = {
delimiter: '&',
depth: 5,
arrayLimit: 20,
parameterLimit: 1000,
strictNullHandling: false,
plainObjects: false,
allowPrototypes: false,
allowDots: false,
decoder: Utils.decode
};
var parseValues = function parseValues(str, options) {
var obj = {};
var parts = str.split(options.delimiter, options.parameterLimit === Infinity ? undefined : options.parameterLimit);
for (var i = 0; i < parts.length; ++i) {
var part = parts[i];
var pos = part.indexOf(']=') === -1 ? part.indexOf('=') : part.indexOf(']=') + 1;
var key, val;
if (pos === -1) {
key = options.decoder(part);
val = options.strictNullHandling ? null : '';
} else {
key = options.decoder(part.slice(0, pos));
val = options.decoder(part.slice(pos + 1));
}
if (has.call(obj, key)) {
obj[key] = [].concat(obj[key]).concat(val);
} else {
obj[key] = val;
}
}
return obj;
};
var parseObject = function parseObject(chain, val, options) {
if (!chain.length) {
return val;
}
var root = chain.shift();
var obj;
if (root === '[]') {
obj = [];
obj = obj.concat(parseObject(chain, val, options));
} else {
obj = options.plainObjects ? Object.create(null) : {};
var cleanRoot = root[0] === '[' && root[root.length - 1] === ']' ? root.slice(1, root.length - 1) : root;
var index = parseInt(cleanRoot, 10);
if (
!isNaN(index) &&
root !== cleanRoot &&
String(index) === cleanRoot &&
index >= 0 &&
(options.parseArrays && index <= options.arrayLimit)
) {
obj = [];
obj[index] = parseObject(chain, val, options);
} else {
obj[cleanRoot] = parseObject(chain, val, options);
}
}
return obj;
};
var parseKeys = function parseKeys(givenKey, val, options) {
if (!givenKey) {
return;
}
// Transform dot notation to bracket notation
var key = options.allowDots ? givenKey.replace(/\.([^\.\[]+)/g, '[$1]') : givenKey;
// The regex chunks
var parent = /^([^\[\]]*)/;
var child = /(\[[^\[\]]*\])/g;
// Get the parent
var segment = parent.exec(key);
// Stash the parent if it exists
var keys = [];
if (segment[1]) {
// If we aren't using plain objects, optionally prefix keys
// that would overwrite object prototype properties
if (!options.plainObjects && has.call(Object.prototype, segment[1])) {
if (!options.allowPrototypes) {
return;
}
}
keys.push(segment[1]);
}
// Loop through children appending to the array until we hit depth
var i = 0;
while ((segment = child.exec(key)) !== null && i < options.depth) {
i += 1;
if (!options.plainObjects && has.call(Object.prototype, segment[1].replace(/\[|\]/g, ''))) {
if (!options.allowPrototypes) {
continue;
}
}
keys.push(segment[1]);
}
// If there's a remainder, just add whatever is left
if (segment) {
keys.push('[' + key.slice(segment.index) + ']');
}
return parseObject(keys, val, options);
};
module.exports = function (str, opts) {
var options = opts || {};
if (options.decoder !== null && options.decoder !== undefined && typeof options.decoder !== 'function') {
throw new TypeError('Decoder has to be a function.');
}
options.delimiter = typeof options.delimiter === 'string' || Utils.isRegExp(options.delimiter) ? options.delimiter : defaults.delimiter;
options.depth = typeof options.depth === 'number' ? options.depth : defaults.depth;
options.arrayLimit = typeof options.arrayLimit === 'number' ? options.arrayLimit : defaults.arrayLimit;
options.parseArrays = options.parseArrays !== false;
options.decoder = typeof options.decoder === 'function' ? options.decoder : defaults.decoder;
options.allowDots = typeof options.allowDots === 'boolean' ? options.allowDots : defaults.allowDots;
options.plainObjects = typeof options.plainObjects === 'boolean' ? options.plainObjects : defaults.plainObjects;
options.allowPrototypes = typeof options.allowPrototypes === 'boolean' ? options.allowPrototypes : defaults.allowPrototypes;
options.parameterLimit = typeof options.parameterLimit === 'number' ? options.parameterLimit : defaults.parameterLimit;
options.strictNullHandling = typeof options.strictNullHandling === 'boolean' ? options.strictNullHandling : defaults.strictNullHandling;
if (str === '' || str === null || typeof str === 'undefined') {
return options.plainObjects ? Object.create(null) : {};
}
var tempObj = typeof str === 'string' ? parseValues(str, options) : str;
var obj = options.plainObjects ? Object.create(null) : {};
// Iterate over the keys and setup the new object
var keys = Object.keys(tempObj);
for (var i = 0; i < keys.length; ++i) {
var key = keys[i];
var newObj = parseKeys(key, tempObj[key], options);
obj = Utils.merge(obj, newObj, options);
}
return Utils.compact(obj);
};
},{"./utils":4}],3:[function(require,module,exports){
'use strict';
var Utils = require('./utils');
var arrayPrefixGenerators = {
brackets: function brackets(prefix) {
return prefix + '[]';
},
indices: function indices(prefix, key) {
return prefix + '[' + key + ']';
},
repeat: function repeat(prefix) {
return prefix;
}
};
var defaults = {
delimiter: '&',
strictNullHandling: false,
skipNulls: false,
encode: true,
encoder: Utils.encode
};
var stringify = function stringify(object, prefix, generateArrayPrefix, strictNullHandling, skipNulls, encoder, filter, sort, allowDots) {
var obj = object;
if (typeof filter === 'function') {
obj = filter(prefix, obj);
} else if (obj instanceof Date) {
obj = obj.toISOString();
} else if (obj === null) {
if (strictNullHandling) {
return encoder ? encoder(prefix) : prefix;
}
obj = '';
}
if (typeof obj === 'string' || typeof obj === 'number' || typeof obj === 'boolean' || Utils.isBuffer(obj)) {
if (encoder) {
return [encoder(prefix) + '=' + encoder(obj)];
}
return [prefix + '=' + String(obj)];
}
var values = [];
if (typeof obj === 'undefined') {
return values;
}
var objKeys;
if (Array.isArray(filter)) {
objKeys = filter;
} else {
var keys = Object.keys(obj);
objKeys = sort ? keys.sort(sort) : keys;
}
for (var i = 0; i < objKeys.length; ++i) {
var key = objKeys[i];
if (skipNulls && obj[key] === null) {
continue;
}
if (Array.isArray(obj)) {
values = values.concat(stringify(obj[key], generateArrayPrefix(prefix, key), generateArrayPrefix, strictNullHandling, skipNulls, encoder, filter, sort, allowDots));
} else {
values = values.concat(stringify(obj[key], prefix + (allowDots ? '.' + key : '[' + key + ']'), generateArrayPrefix, strictNullHandling, skipNulls, encoder, filter, sort, allowDots));
}
}
return values;
};
module.exports = function (object, opts) {
var obj = object;
var options = opts || {};
var delimiter = typeof options.delimiter === 'undefined' ? defaults.delimiter : options.delimiter;
var strictNullHandling = typeof options.strictNullHandling === 'boolean' ? options.strictNullHandling : defaults.strictNullHandling;
var skipNulls = typeof options.skipNulls === 'boolean' ? options.skipNulls : defaults.skipNulls;
var encode = typeof options.encode === 'boolean' ? options.encode : defaults.encode;
var encoder = encode ? (typeof options.encoder === 'function' ? options.encoder : defaults.encoder) : null;
var sort = typeof options.sort === 'function' ? options.sort : null;
var allowDots = typeof options.allowDots === 'undefined' ? false : options.allowDots;
var objKeys;
var filter;
if (options.encoder !== null && options.encoder !== undefined && typeof options.encoder !== 'function') {
throw new TypeError('Encoder has to be a function.');
}
if (typeof options.filter === 'function') {
filter = options.filter;
obj = filter('', obj);
} else if (Array.isArray(options.filter)) {
objKeys = filter = options.filter;
}
var keys = [];
if (typeof obj !== 'object' || obj === null) {
return '';
}
var arrayFormat;
if (options.arrayFormat in arrayPrefixGenerators) {
arrayFormat = options.arrayFormat;
} else if ('indices' in options) {
arrayFormat = options.indices ? 'indices' : 'repeat';
} else {
arrayFormat = 'indices';
}
var generateArrayPrefix = arrayPrefixGenerators[arrayFormat];
if (!objKeys) {
objKeys = Object.keys(obj);
}
if (sort) {
objKeys.sort(sort);
}
for (var i = 0; i < objKeys.length; ++i) {
var key = objKeys[i];
if (skipNulls && obj[key] === null) {
continue;
}
keys = keys.concat(stringify(obj[key], key, generateArrayPrefix, strictNullHandling, skipNulls, encoder, filter, sort, allowDots));
}
return keys.join(delimiter);
};
},{"./utils":4}],4:[function(require,module,exports){
'use strict';
var hexTable = (function () {
var array = new Array(256);
for (var i = 0; i < 256; ++i) {
array[i] = '%' + ((i < 16 ? '0' : '') + i.toString(16)).toUpperCase();
}
return array;
}());
exports.arrayToObject = function (source, options) {
var obj = options.plainObjects ? Object.create(null) : {};
for (var i = 0; i < source.length; ++i) {
if (typeof source[i] !== 'undefined') {
obj[i] = source[i];
}
}
return obj;
};
exports.merge = function (target, source, options) {
if (!source) {
return target;
}
if (typeof source !== 'object') {
if (Array.isArray(target)) {
target.push(source);
} else if (typeof target === 'object') {
target[source] = true;
} else {
return [target, source];
}
return target;
}
if (typeof target !== 'object') {
return [target].concat(source);
}
var mergeTarget = target;
if (Array.isArray(target) && !Array.isArray(source)) {
mergeTarget = exports.arrayToObject(target, options);
}
return Object.keys(source).reduce(function (acc, key) {
var value = source[key];
if (Object.prototype.hasOwnProperty.call(acc, key)) {
acc[key] = exports.merge(acc[key], value, options);
} else {
acc[key] = value;
}
return acc;
}, mergeTarget);
};
exports.decode = function (str) {
try {
return decodeURIComponent(str.replace(/\+/g, ' '));
} catch (e) {
return str;
}
};
exports.encode = function (str) {
// This code was originally written by Brian White (mscdex) for the io.js core querystring library.
// It has been adapted here for stricter adherence to RFC 3986
if (str.length === 0) {
return str;
}
var string = typeof str === 'string' ? str : String(str);
var out = '';
for (var i = 0; i < string.length; ++i) {
var c = string.charCodeAt(i);
if (
c === 0x2D || // -
c === 0x2E || // .
c === 0x5F || // _
c === 0x7E || // ~
(c >= 0x30 && c <= 0x39) || // 0-9
(c >= 0x41 && c <= 0x5A) || // a-z
(c >= 0x61 && c <= 0x7A) // A-Z
) {
out += string.charAt(i);
continue;
}
if (c < 0x80) {
out = out + hexTable[c];
continue;
}
if (c < 0x800) {
out = out + (hexTable[0xC0 | (c >> 6)] + hexTable[0x80 | (c & 0x3F)]);
continue;
}
if (c < 0xD800 || c >= 0xE000) {
out = out + (hexTable[0xE0 | (c >> 12)] + hexTable[0x80 | ((c >> 6) & 0x3F)] + hexTable[0x80 | (c & 0x3F)]);
continue;
}
i += 1;
c = 0x10000 + (((c & 0x3FF) << 10) | (string.charCodeAt(i) & 0x3FF));
out += hexTable[0xF0 | (c >> 18)] + hexTable[0x80 | ((c >> 12) & 0x3F)] + hexTable[0x80 | ((c >> 6) & 0x3F)] + hexTable[0x80 | (c & 0x3F)];
}
return out;
};
exports.compact = function (obj, references) {
if (typeof obj !== 'object' || obj === null) {
return obj;
}
var refs = references || [];
var lookup = refs.indexOf(obj);
if (lookup !== -1) {
return refs[lookup];
}
refs.push(obj);
if (Array.isArray(obj)) {
var compacted = [];
for (var i = 0; i < obj.length; ++i) {
if (obj[i] && typeof obj[i] === 'object') {
compacted.push(exports.compact(obj[i], refs));
} else if (typeof obj[i] !== 'undefined') {
compacted.push(obj[i]);
}
}
return compacted;
}
var keys = Object.keys(obj);
for (var j = 0; j < keys.length; ++j) {
var key = keys[j];
obj[key] = exports.compact(obj[key], refs);
}
return obj;
};
exports.isRegExp = function (obj) {
return Object.prototype.toString.call(obj) === '[object RegExp]';
};
exports.isBuffer = function (obj) {
if (obj === null || typeof obj === 'undefined') {
return false;
}
return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj));
};
},{}]},{},[1])(1)
});
'use strict';
var Stringify = require('./stringify');
var Parse = require('./parse');
module.exports = {
stringify: Stringify,
parse: Parse
};
'use strict';
var Utils = require('./utils');
var has = Object.prototype.hasOwnProperty;
var defaults = {
delimiter: '&',
depth: 5,
arrayLimit: 20,
parameterLimit: 1000,
strictNullHandling: false,
plainObjects: false,
allowPrototypes: false,
allowDots: false,
decoder: Utils.decode
};
var parseValues = function parseValues(str, options) {
var obj = {};
var parts = str.split(options.delimiter, options.parameterLimit === Infinity ? undefined : options.parameterLimit);
for (var i = 0; i < parts.length; ++i) {
var part = parts[i];
var pos = part.indexOf(']=') === -1 ? part.indexOf('=') : part.indexOf(']=') + 1;
var key, val;
if (pos === -1) {
key = options.decoder(part);
val = options.strictNullHandling ? null : '';
} else {
key = options.decoder(part.slice(0, pos));
val = options.decoder(part.slice(pos + 1));
}
if (has.call(obj, key)) {
obj[key] = [].concat(obj[key]).concat(val);
} else {
obj[key] = val;
}
}
return obj;
};
var parseObject = function parseObject(chain, val, options) {
if (!chain.length) {
return val;
}
var root = chain.shift();
var obj;
if (root === '[]') {
obj = [];
obj = obj.concat(parseObject(chain, val, options));
} else {
obj = options.plainObjects ? Object.create(null) : {};
var cleanRoot = root[0] === '[' && root[root.length - 1] === ']' ? root.slice(1, root.length - 1) : root;
var index = parseInt(cleanRoot, 10);
if (
!isNaN(index) &&
root !== cleanRoot &&
String(index) === cleanRoot &&
index >= 0 &&
(options.parseArrays && index <= options.arrayLimit)
) {
obj = [];
obj[index] = parseObject(chain, val, options);
} else {
obj[cleanRoot] = parseObject(chain, val, options);
}
}
return obj;
};
var parseKeys = function parseKeys(givenKey, val, options) {
if (!givenKey) {
return;
}
// Transform dot notation to bracket notation
var key = options.allowDots ? givenKey.replace(/\.([^\.\[]+)/g, '[$1]') : givenKey;
// The regex chunks
var parent = /^([^\[\]]*)/;
var child = /(\[[^\[\]]*\])/g;
// Get the parent
var segment = parent.exec(key);
// Stash the parent if it exists
var keys = [];
if (segment[1]) {
// If we aren't using plain objects, optionally prefix keys
// that would overwrite object prototype properties
if (!options.plainObjects && has.call(Object.prototype, segment[1])) {
if (!options.allowPrototypes) {
return;
}
}
keys.push(segment[1]);
}
// Loop through children appending to the array until we hit depth
var i = 0;
while ((segment = child.exec(key)) !== null && i < options.depth) {
i += 1;
if (!options.plainObjects && has.call(Object.prototype, segment[1].replace(/\[|\]/g, ''))) {
if (!options.allowPrototypes) {
continue;
}
}
keys.push(segment[1]);
}
// If there's a remainder, just add whatever is left
if (segment) {
keys.push('[' + key.slice(segment.index) + ']');
}
return parseObject(keys, val, options);
};
module.exports = function (str, opts) {
var options = opts || {};
if (options.decoder !== null && options.decoder !== undefined && typeof options.decoder !== 'function') {
throw new TypeError('Decoder has to be a function.');
}
options.delimiter = typeof options.delimiter === 'string' || Utils.isRegExp(options.delimiter) ? options.delimiter : defaults.delimiter;
options.depth = typeof options.depth === 'number' ? options.depth : defaults.depth;
options.arrayLimit = typeof options.arrayLimit === 'number' ? options.arrayLimit : defaults.arrayLimit;
options.parseArrays = options.parseArrays !== false;
options.decoder = typeof options.decoder === 'function' ? options.decoder : defaults.decoder;
options.allowDots = typeof options.allowDots === 'boolean' ? options.allowDots : defaults.allowDots;
options.plainObjects = typeof options.plainObjects === 'boolean' ? options.plainObjects : defaults.plainObjects;
options.allowPrototypes = typeof options.allowPrototypes === 'boolean' ? options.allowPrototypes : defaults.allowPrototypes;
options.parameterLimit = typeof options.parameterLimit === 'number' ? options.parameterLimit : defaults.parameterLimit;
options.strictNullHandling = typeof options.strictNullHandling === 'boolean' ? options.strictNullHandling : defaults.strictNullHandling;
if (str === '' || str === null || typeof str === 'undefined') {
return options.plainObjects ? Object.create(null) : {};
}
var tempObj = typeof str === 'string' ? parseValues(str, options) : str;
var obj = options.plainObjects ? Object.create(null) : {};
// Iterate over the keys and setup the new object
var keys = Object.keys(tempObj);
for (var i = 0; i < keys.length; ++i) {
var key = keys[i];
var newObj = parseKeys(key, tempObj[key], options);
obj = Utils.merge(obj, newObj, options);
}
return Utils.compact(obj);
};
'use strict';
var Utils = require('./utils');
var arrayPrefixGenerators = {
brackets: function brackets(prefix) {
return prefix + '[]';
},
indices: function indices(prefix, key) {
return prefix + '[' + key + ']';
},
repeat: function repeat(prefix) {
return prefix;
}
};
var defaults = {
delimiter: '&',
strictNullHandling: false,
skipNulls: false,
encode: true,
encoder: Utils.encode
};
var stringify = function stringify(object, prefix, generateArrayPrefix, strictNullHandling, skipNulls, encoder, filter, sort, allowDots) {
var obj = object;
if (typeof filter === 'function') {
obj = filter(prefix, obj);
} else if (obj instanceof Date) {
obj = obj.toISOString();
} else if (obj === null) {
if (strictNullHandling) {
return encoder ? encoder(prefix) : prefix;
}
obj = '';
}
if (typeof obj === 'string' || typeof obj === 'number' || typeof obj === 'boolean' || Utils.isBuffer(obj)) {
if (encoder) {
return [encoder(prefix) + '=' + encoder(obj)];
}
return [prefix + '=' + String(obj)];
}
var values = [];
if (typeof obj === 'undefined') {
return values;
}
var objKeys;
if (Array.isArray(filter)) {
objKeys = filter;
} else {
var keys = Object.keys(obj);
objKeys = sort ? keys.sort(sort) : keys;
}
for (var i = 0; i < objKeys.length; ++i) {
var key = objKeys[i];
if (skipNulls && obj[key] === null) {
continue;
}
if (Array.isArray(obj)) {
values = values.concat(stringify(obj[key], generateArrayPrefix(prefix, key), generateArrayPrefix, strictNullHandling, skipNulls, encoder, filter, sort, allowDots));
} else {
values = values.concat(stringify(obj[key], prefix + (allowDots ? '.' + key : '[' + key + ']'), generateArrayPrefix, strictNullHandling, skipNulls, encoder, filter, sort, allowDots));
}
}
return values;
};
module.exports = function (object, opts) {
var obj = object;
var options = opts || {};
var delimiter = typeof options.delimiter === 'undefined' ? defaults.delimiter : options.delimiter;
var strictNullHandling = typeof options.strictNullHandling === 'boolean' ? options.strictNullHandling : defaults.strictNullHandling;
var skipNulls = typeof options.skipNulls === 'boolean' ? options.skipNulls : defaults.skipNulls;
var encode = typeof options.encode === 'boolean' ? options.encode : defaults.encode;
var encoder = encode ? (typeof options.encoder === 'function' ? options.encoder : defaults.encoder) : null;
var sort = typeof options.sort === 'function' ? options.sort : null;
var allowDots = typeof options.allowDots === 'undefined' ? false : options.allowDots;
var objKeys;
var filter;
if (options.encoder !== null && options.encoder !== undefined && typeof options.encoder !== 'function') {
throw new TypeError('Encoder has to be a function.');
}
if (typeof options.filter === 'function') {
filter = options.filter;
obj = filter('', obj);
} else if (Array.isArray(options.filter)) {
objKeys = filter = options.filter;
}
var keys = [];
if (typeof obj !== 'object' || obj === null) {
return '';
}
var arrayFormat;
if (options.arrayFormat in arrayPrefixGenerators) {
arrayFormat = options.arrayFormat;
} else if ('indices' in options) {
arrayFormat = options.indices ? 'indices' : 'repeat';
} else {
arrayFormat = 'indices';
}
var generateArrayPrefix = arrayPrefixGenerators[arrayFormat];
if (!objKeys) {
objKeys = Object.keys(obj);
}
if (sort) {
objKeys.sort(sort);
}
for (var i = 0; i < objKeys.length; ++i) {
var key = objKeys[i];
if (skipNulls && obj[key] === null) {
continue;
}
keys = keys.concat(stringify(obj[key], key, generateArrayPrefix, strictNullHandling, skipNulls, encoder, filter, sort, allowDots));
}
return keys.join(delimiter);
};
'use strict';
var hexTable = (function () {
var array = new Array(256);
for (var i = 0; i < 256; ++i) {
array[i] = '%' + ((i < 16 ? '0' : '') + i.toString(16)).toUpperCase();
}
return array;
}());
exports.arrayToObject = function (source, options) {
var obj = options.plainObjects ? Object.create(null) : {};
for (var i = 0; i < source.length; ++i) {
if (typeof source[i] !== 'undefined') {
obj[i] = source[i];
}
}
return obj;
};
exports.merge = function (target, source, options) {
if (!source) {
return target;
}
if (typeof source !== 'object') {
if (Array.isArray(target)) {
target.push(source);
} else if (typeof target === 'object') {
target[source] = true;
} else {
return [target, source];
}
return target;
}
if (typeof target !== 'object') {
return [target].concat(source);
}
var mergeTarget = target;
if (Array.isArray(target) && !Array.isArray(source)) {
mergeTarget = exports.arrayToObject(target, options);
}
return Object.keys(source).reduce(function (acc, key) {
var value = source[key];
if (Object.prototype.hasOwnProperty.call(acc, key)) {
acc[key] = exports.merge(acc[key], value, options);
} else {
acc[key] = value;
}
return acc;
}, mergeTarget);
};
exports.decode = function (str) {
try {
return decodeURIComponent(str.replace(/\+/g, ' '));
} catch (e) {
return str;
}
};
exports.encode = function (str) {
// This code was originally written by Brian White (mscdex) for the io.js core querystring library.
// It has been adapted here for stricter adherence to RFC 3986
if (str.length === 0) {
return str;
}
var string = typeof str === 'string' ? str : String(str);
var out = '';
for (var i = 0; i < string.length; ++i) {
var c = string.charCodeAt(i);
if (
c === 0x2D || // -
c === 0x2E || // .
c === 0x5F || // _
c === 0x7E || // ~
(c >= 0x30 && c <= 0x39) || // 0-9
(c >= 0x41 && c <= 0x5A) || // a-z
(c >= 0x61 && c <= 0x7A) // A-Z
) {
out += string.charAt(i);
continue;
}
if (c < 0x80) {
out = out + hexTable[c];
continue;
}
if (c < 0x800) {
out = out + (hexTable[0xC0 | (c >> 6)] + hexTable[0x80 | (c & 0x3F)]);
continue;
}
if (c < 0xD800 || c >= 0xE000) {
out = out + (hexTable[0xE0 | (c >> 12)] + hexTable[0x80 | ((c >> 6) & 0x3F)] + hexTable[0x80 | (c & 0x3F)]);
continue;
}
i += 1;
c = 0x10000 + (((c & 0x3FF) << 10) | (string.charCodeAt(i) & 0x3FF));
out += hexTable[0xF0 | (c >> 18)] + hexTable[0x80 | ((c >> 12) & 0x3F)] + hexTable[0x80 | ((c >> 6) & 0x3F)] + hexTable[0x80 | (c & 0x3F)];
}
return out;
};
exports.compact = function (obj, references) {
if (typeof obj !== 'object' || obj === null) {
return obj;
}
var refs = references || [];
var lookup = refs.indexOf(obj);
if (lookup !== -1) {
return refs[lookup];
}
refs.push(obj);
if (Array.isArray(obj)) {
var compacted = [];
for (var i = 0; i < obj.length; ++i) {
if (obj[i] && typeof obj[i] === 'object') {
compacted.push(exports.compact(obj[i], refs));
} else if (typeof obj[i] !== 'undefined') {
compacted.push(obj[i]);
}
}
return compacted;
}
var keys = Object.keys(obj);
for (var j = 0; j < keys.length; ++j) {
var key = keys[j];
obj[key] = exports.compact(obj[key], refs);
}
return obj;
};
exports.isRegExp = function (obj) {
return Object.prototype.toString.call(obj) === '[object RegExp]';
};
exports.isBuffer = function (obj) {
if (obj === null || typeof obj === 'undefined') {
return false;
}
return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj));
};
Copyright (c) 2014 Nathan LaFreniere and other contributors.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* The names of any contributors may not be used to endorse or promote
products derived from this software without specific prior written
permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* * *
The complete list of contributors can be found at: https://github.com/hapijs/qs/graphs/contributors
{
"_args": [
[
{
"raw": "qs@6.2.1",
"scope": null,
"escapedName": "qs",
"name": "qs",
"rawSpec": "6.2.1",
"spec": "6.2.1",
"type": "version"
},
"C:\\xampp\\htdocs\\cafe\\node_modules\\body-parser"
]
],
"_from": "qs@6.2.1",
"_id": "qs@6.2.1",
"_inCache": true,
"_location": "/body-parser/qs",
"_nodeVersion": "6.3.0",
"_npmOperationalInternal": {
"host": "packages-12-west.internal.npmjs.com",
"tmp": "tmp/qs-6.2.1.tgz_1469044929716_0.06957711698487401"
},
"_npmUser": {
"name": "ljharb",
"email": "ljharb@gmail.com"
},
"_npmVersion": "3.10.3",
"_phantomChildren": {},
"_requested": {
"raw": "qs@6.2.1",
"scope": null,
"escapedName": "qs",
"name": "qs",
"rawSpec": "6.2.1",
"spec": "6.2.1",
"type": "version"
},
"_requiredBy": [
"/body-parser"
],
"_resolved": "https://registry.npmjs.org/qs/-/qs-6.2.1.tgz",
"_shasum": "ce03c5ff0935bc1d9d69a9f14cbd18e568d67625",
"_shrinkwrap": null,
"_spec": "qs@6.2.1",
"_where": "C:\\xampp\\htdocs\\cafe\\node_modules\\body-parser",
"bugs": {
"url": "https://github.com/ljharb/qs/issues"
},
"contributors": [
{
"name": "Jordan Harband",
"email": "ljharb@gmail.com",
"url": "http://ljharb.codes"
}
],
"dependencies": {},
"description": "A querystring parser that supports nesting and arrays, with a depth limit",
"devDependencies": {
"@ljharb/eslint-config": "^6.0.0",
"browserify": "^13.0.1",
"covert": "^1.1.0",
"eslint": "^3.1.0",
"evalmd": "^0.0.17",
"iconv-lite": "^0.4.13",
"mkdirp": "^0.5.1",
"parallelshell": "^2.0.0",
"qs-iconv": "^1.0.3",
"tape": "^4.6.0"
},
"directories": {},
"dist": {
"shasum": "ce03c5ff0935bc1d9d69a9f14cbd18e568d67625",
"tarball": "https://registry.npmjs.org/qs/-/qs-6.2.1.tgz"
},
"engines": {
"node": ">=0.6"
},
"gitHead": "335f839142e6c2c69f5302c4940d92acb0e77561",
"homepage": "https://github.com/ljharb/qs",
"keywords": [
"querystring",
"qs"
],
"license": "BSD-3-Clause",
"main": "lib/index.js",
"maintainers": [
{
"name": "hueniverse",
"email": "eran@hammer.io"
},
{
"name": "ljharb",
"email": "ljharb@gmail.com"
},
{
"name": "nlf",
"email": "quitlahok@gmail.com"
}
],
"name": "qs",
"optionalDependencies": {},
"readme": "ERROR: No README data found!",
"repository": {
"type": "git",
"url": "git+https://github.com/ljharb/qs.git"
},
"scripts": {
"coverage": "covert test",
"dist": "mkdirp dist && browserify --standalone Qs lib/index.js > dist/qs.js",
"lint": "eslint lib/*.js text/*.js",
"prepublish": "npm run dist",
"pretest": "npm run --silent readme && npm run --silent lint",
"readme": "evalmd README.md",
"test": "npm run --silent coverage",
"tests-only": "node test"
},
"version": "6.2.1"
}

qs

A querystring parsing and stringifying library with some added security.

Build Status

Lead Maintainer: Jordan Harband

The qs module was originally created and maintained by TJ Holowaychuk.

Usage

var qs = require('qs');
var assert = require('assert');

var obj = qs.parse('a=c');
assert.deepEqual(obj, { a: 'c' });

var str = qs.stringify(obj);
assert.equal(str, 'a=c');

Parsing Objects

qs.parse(string, [options]);

qs allows you to create nested objects within your query strings, by surrounding the name of sub-keys with square brackets []. For example, the string 'foo[bar]=baz' converts to:

assert.deepEqual(qs.parse('foo[bar]=baz'), {
  foo: {
    bar: 'baz'
  }
});

When using the plainObjects option the parsed value is returned as a plain object, created via Object.create(null) and as such you should be aware that prototype methods will not exist on it and a user may set those names to whatever value they like:

var plainObject = qs.parse('a[hasOwnProperty]=b', { plainObjects: true });
assert.deepEqual(plainObject, { a: { hasOwnProperty: 'b' } });

By default parameters that would overwrite properties on the object prototype are ignored, if you wish to keep the data from those fields either use plainObjects as mentioned above, or set allowPrototypes to true which will allow user input to overwrite those properties. WARNING It is generally a bad idea to enable this option as it can cause problems when attempting to use the properties that have been overwritten. Always be careful with this option.

var protoObject = qs.parse('a[hasOwnProperty]=b', { allowPrototypes: true });
assert.deepEqual(protoObject, { a: { hasOwnProperty: 'b' } });

URI encoded strings work too:

assert.deepEqual(qs.parse('a%5Bb%5D=c'), {
  a: { b: 'c' }
});

You can also nest your objects, like 'foo[bar][baz]=foobarbaz':

assert.deepEqual(qs.parse('foo[bar][baz]=foobarbaz'), {
  foo: {
    bar: {
      baz: 'foobarbaz'
    }
  }
});

By default, when nesting objects qs will only parse up to 5 children deep. This means if you attempt to parse a string like 'a[b][c][d][e][f][g][h][i]=j' your resulting object will be:

var expected = {
  a: {
    b: {
      c: {
        d: {
          e: {
            f: {
              '[g][h][i]': 'j'
            }
          }
        }
      }
    }
  }
};
var string = 'a[b][c][d][e][f][g][h][i]=j';
assert.deepEqual(qs.parse(string), expected);

This depth can be overridden by passing a depth option to qs.parse(string, [options]):

var deep = qs.parse('a[b][c][d][e][f][g][h][i]=j', { depth: 1 });
assert.deepEqual(deep, { a: { b: { '[c][d][e][f][g][h][i]': 'j' } } });

The depth limit helps mitigate abuse when qs is used to parse user input, and it is recommended to keep it a reasonably small number.

For similar reasons, by default qs will only parse up to 1000 parameters. This can be overridden by passing a parameterLimit option:

var limited = qs.parse('a=b&c=d', { parameterLimit: 1 });
assert.deepEqual(limited, { a: 'b' });

An optional delimiter can also be passed:

var delimited = qs.parse('a=b;c=d', { delimiter: ';' });
assert.deepEqual(delimited, { a: 'b', c: 'd' });

Delimiters can be a regular expression too:

var regexed = qs.parse('a=b;c=d,e=f', { delimiter: /[;,]/ });
assert.deepEqual(regexed, { a: 'b', c: 'd', e: 'f' });

Option allowDots can be used to enable dot notation:

var withDots = qs.parse('a.b=c', { allowDots: true });
assert.deepEqual(withDots, { a: { b: 'c' } });

Parsing Arrays

qs can also parse arrays using a similar [] notation:

var withArray = qs.parse('a[]=b&a[]=c');
assert.deepEqual(withArray, { a: ['b', 'c'] });

You may specify an index as well:

var withIndexes = qs.parse('a[1]=c&a[0]=b');
assert.deepEqual(withIndexes, { a: ['b', 'c'] });

Note that the only difference between an index in an array and a key in an object is that the value between the brackets must be a number to create an array. When creating arrays with specific indices, qs will compact a sparse array to only the existing values preserving their order:

var noSparse = qs.parse('a[1]=b&a[15]=c');
assert.deepEqual(noSparse, { a: ['b', 'c'] });

Note that an empty string is also a value, and will be preserved:

var withEmptyString = qs.parse('a[]=&a[]=b');
assert.deepEqual(withEmptyString, { a: ['', 'b'] });

var withIndexedEmptyString = qs.parse('a[0]=b&a[1]=&a[2]=c');
assert.deepEqual(withIndexedEmptyString, { a: ['b', '', 'c'] });

qs will also limit specifying indices in an array to a maximum index of 20. Any array members with an index of greater than 20 will instead be converted to an object with the index as the key:

var withMaxIndex = qs.parse('a[100]=b');
assert.deepEqual(withMaxIndex, { a: { '100': 'b' } });

This limit can be overridden by passing an arrayLimit option:

var withArrayLimit = qs.parse('a[1]=b', { arrayLimit: 0 });
assert.deepEqual(withArrayLimit, { a: { '1': 'b' } });

To disable array parsing entirely, set parseArrays to false.

var noParsingArrays = qs.parse('a[]=b', { parseArrays: false });
assert.deepEqual(noParsingArrays, { a: { '0': 'b' } });

If you mix notations, qs will merge the two items into an object:

var mixedNotation = qs.parse('a[0]=b&a[b]=c');
assert.deepEqual(mixedNotation, { a: { '0': 'b', b: 'c' } });

You can also create arrays of objects:

var arraysOfObjects = qs.parse('a[][b]=c');
assert.deepEqual(arraysOfObjects, { a: [{ b: 'c' }] });

Stringifying

qs.stringify(object, [options]);

When stringifying, qs by default URI encodes output. Objects are stringified as you would expect:

assert.equal(qs.stringify({ a: 'b' }), 'a=b');
assert.equal(qs.stringify({ a: { b: 'c' } }), 'a%5Bb%5D=c');

This encoding can be disabled by setting the encode option to false:

var unencoded = qs.stringify({ a: { b: 'c' } }, { encode: false });
assert.equal(unencoded, 'a[b]=c');

This encoding can also be replaced by a custom encoding method set as encoder option:

var encoded = qs.stringify({ a: { b: 'c' } }, { encoder: function (str) {
  // Passed in values `a`, `b`, `c`
  return // Return encoded string
}})

(Note: the encoder option does not apply if encode is false)

Analogue to the encoder there is a decoder option for parse to override decoding of properties and values:

var decoded = qs.parse('x=z', { decoder: function (str) {
  // Passed in values `x`, `z`
  return // Return decoded string
}})

Examples beyond this point will be shown as though the output is not URI encoded for clarity. Please note that the return values in these cases will be URI encoded during real usage.

When arrays are stringified, by default they are given explicit indices:

qs.stringify({ a: ['b', 'c', 'd'] });
// 'a[0]=b&a[1]=c&a[2]=d'

You may override this by setting the indices option to false:

qs.stringify({ a: ['b', 'c', 'd'] }, { indices: false });
// 'a=b&a=c&a=d'

You may use the arrayFormat option to specify the format of the output array

qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'indices' })
// 'a[0]=b&a[1]=c'
qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'brackets' })
// 'a[]=b&a[]=c'
qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'repeat' })
// 'a=b&a=c'

Empty strings and null values will omit the value, but the equals sign (=) remains in place:

assert.equal(qs.stringify({ a: '' }), 'a=');

Properties that are set to undefined will be omitted entirely:

assert.equal(qs.stringify({ a: null, b: undefined }), 'a=');

The delimiter may be overridden with stringify as well:

assert.equal(qs.stringify({ a: 'b', c: 'd' }, { delimiter: ';' }), 'a=b;c=d');

Finally, you can use the filter option to restrict which keys will be included in the stringified output. If you pass a function, it will be called for each key to obtain the replacement value. Otherwise, if you pass an array, it will be used to select properties and array indices for stringification:

function filterFunc(prefix, value) {
  if (prefix == 'b') {
    // Return an `undefined` value to omit a property.
    return;
  }
  if (prefix == 'e[f]') {
    return value.getTime();
  }
  if (prefix == 'e[g][0]') {
    return value * 2;
  }
  return value;
}
qs.stringify({ a: 'b', c: 'd', e: { f: new Date(123), g: [2] } }, { filter: filterFunc });
// 'a=b&c=d&e[f]=123&e[g][0]=4'
qs.stringify({ a: 'b', c: 'd', e: 'f' }, { filter: ['a', 'e'] });
// 'a=b&e=f'
qs.stringify({ a: ['b', 'c', 'd'], e: 'f' }, { filter: ['a', 0, 2] });
// 'a[0]=b&a[2]=d'

Handling of null values

By default, null values are treated like empty strings:

var withNull = qs.stringify({ a: null, b: '' });
assert.equal(withNull, 'a=&b=');

Parsing does not distinguish between parameters with and without equal signs. Both are converted to empty strings.

var equalsInsensitive = qs.parse('a&b=');
assert.deepEqual(equalsInsensitive, { a: '', b: '' });

To distinguish between null values and empty strings use the strictNullHandling flag. In the result string the null values have no = sign:

var strictNull = qs.stringify({ a: null, b: '' }, { strictNullHandling: true });
assert.equal(strictNull, 'a&b=');

To parse values without = back to null use the strictNullHandling flag:

var parsedStrictNull = qs.parse('a&b=', { strictNullHandling: true });
assert.deepEqual(parsedStrictNull, { a: null, b: '' });

To completely skip rendering keys with null values, use the skipNulls flag:

var nullsSkipped = qs.stringify({ a: 'b', c: null}, { skipNulls: true });
assert.equal(nullsSkipped, 'a=b');

Dealing with special character sets

By default the encoding and decoding of characters is done in utf-8. If you wish to encode querystrings to a different character set (i.e. Shift JIS) you can use the qs-iconv library:

var encoder = require('qs-iconv/encoder')('shift_jis');
var shiftJISEncoded = qs.stringify({ a: 'こんにちは!' }, { encoder: encoder });
assert.equal(shiftJISEncoded, 'a=%82%B1%82%F1%82%C9%82%BF%82%CD%81I');

This also works for decoding of query strings:

var decoder = require('qs-iconv/decoder')('shift_jis');
var obj = qs.parse('a=%82%B1%82%F1%82%C9%82%BF%82%CD%81I', { decoder: decoder });
assert.deepEqual(obj, { a: 'こんにちは!' });
require('./parse');
require('./stringify');
require('./utils');
'use strict';
var test = require('tape');
var qs = require('../');
var iconv = require('iconv-lite');
test('parse()', function (t) {
t.test('parses a simple string', function (st) {
st.deepEqual(qs.parse('0=foo'), { '0': 'foo' });
st.deepEqual(qs.parse('foo=c++'), { foo: 'c ' });
st.deepEqual(qs.parse('a[>=]=23'), { a: { '>=': '23' } });
st.deepEqual(qs.parse('a[<=>]==23'), { a: { '<=>': '=23' } });
st.deepEqual(qs.parse('a[==]=23'), { a: { '==': '23' } });
st.deepEqual(qs.parse('foo', { strictNullHandling: true }), { foo: null });
st.deepEqual(qs.parse('foo'), { foo: '' });
st.deepEqual(qs.parse('foo='), { foo: '' });
st.deepEqual(qs.parse('foo=bar'), { foo: 'bar' });
st.deepEqual(qs.parse(' foo = bar = baz '), { ' foo ': ' bar = baz ' });
st.deepEqual(qs.parse('foo=bar=baz'), { foo: 'bar=baz' });
st.deepEqual(qs.parse('foo=bar&bar=baz'), { foo: 'bar', bar: 'baz' });
st.deepEqual(qs.parse('foo2=bar2&baz2='), { foo2: 'bar2', baz2: '' });
st.deepEqual(qs.parse('foo=bar&baz', { strictNullHandling: true }), { foo: 'bar', baz: null });
st.deepEqual(qs.parse('foo=bar&baz'), { foo: 'bar', baz: '' });
st.deepEqual(qs.parse('cht=p3&chd=t:60,40&chs=250x100&chl=Hello|World'), {
cht: 'p3',
chd: 't:60,40',
chs: '250x100',
chl: 'Hello|World'
});
st.end();
});
t.test('allows enabling dot notation', function (st) {
st.deepEqual(qs.parse('a.b=c'), { 'a.b': 'c' });
st.deepEqual(qs.parse('a.b=c', { allowDots: true }), { a: { b: 'c' } });
st.end();
});
t.deepEqual(qs.parse('a[b]=c'), { a: { b: 'c' } }, 'parses a single nested string');
t.deepEqual(qs.parse('a[b][c]=d'), { a: { b: { c: 'd' } } }, 'parses a double nested string');
t.deepEqual(
qs.parse('a[b][c][d][e][f][g][h]=i'),
{ a: { b: { c: { d: { e: { f: { '[g][h]': 'i' } } } } } } },
'defaults to a depth of 5'
);
t.test('only parses one level when depth = 1', function (st) {
st.deepEqual(qs.parse('a[b][c]=d', { depth: 1 }), { a: { b: { '[c]': 'd' } } });
st.deepEqual(qs.parse('a[b][c][d]=e', { depth: 1 }), { a: { b: { '[c][d]': 'e' } } });
st.end();
});
t.deepEqual(qs.parse('a=b&a=c'), { a: ['b', 'c'] }, 'parses a simple array');
t.test('parses an explicit array', function (st) {
st.deepEqual(qs.parse('a[]=b'), { a: ['b'] });
st.deepEqual(qs.parse('a[]=b&a[]=c'), { a: ['b', 'c'] });
st.deepEqual(qs.parse('a[]=b&a[]=c&a[]=d'), { a: ['b', 'c', 'd'] });
st.end();
});
t.test('parses a mix of simple and explicit arrays', function (st) {
st.deepEqual(qs.parse('a=b&a[]=c'), { a: ['b', 'c'] });
st.deepEqual(qs.parse('a[]=b&a=c'), { a: ['b', 'c'] });
st.deepEqual(qs.parse('a[0]=b&a=c'), { a: ['b', 'c'] });
st.deepEqual(qs.parse('a=b&a[0]=c'), { a: ['b', 'c'] });
st.deepEqual(qs.parse('a[1]=b&a=c'), { a: ['b', 'c'] });
st.deepEqual(qs.parse('a=b&a[1]=c'), { a: ['b', 'c'] });
st.end();
});
t.test('parses a nested array', function (st) {
st.deepEqual(qs.parse('a[b][]=c&a[b][]=d'), { a: { b: ['c', 'd'] } });
st.deepEqual(qs.parse('a[>=]=25'), { a: { '>=': '25' } });
st.end();
});
t.test('allows to specify array indices', function (st) {
st.deepEqual(qs.parse('a[1]=c&a[0]=b&a[2]=d'), { a: ['b', 'c', 'd'] });
st.deepEqual(qs.parse('a[1]=c&a[0]=b'), { a: ['b', 'c'] });
st.deepEqual(qs.parse('a[1]=c'), { a: ['c'] });
st.end();
});
t.test('limits specific array indices to 20', function (st) {
st.deepEqual(qs.parse('a[20]=a'), { a: ['a'] });
st.deepEqual(qs.parse('a[21]=a'), { a: { '21': 'a' } });
st.end();
});
t.deepEqual(qs.parse('a[12b]=c'), { a: { '12b': 'c' } }, 'supports keys that begin with a number');
t.test('supports encoded = signs', function (st) {
st.deepEqual(qs.parse('he%3Dllo=th%3Dere'), { 'he=llo': 'th=ere' });
st.end();
});
t.test('is ok with url encoded strings', function (st) {
st.deepEqual(qs.parse('a[b%20c]=d'), { a: { 'b c': 'd' } });
st.deepEqual(qs.parse('a[b]=c%20d'), { a: { b: 'c d' } });
st.end();
});
t.test('allows brackets in the value', function (st) {
st.deepEqual(qs.parse('pets=["tobi"]'), { pets: '["tobi"]' });
st.deepEqual(qs.parse('operators=[">=", "<="]'), { operators: '[">=", "<="]' });
st.end();
});
t.test('allows empty values', function (st) {
st.deepEqual(qs.parse(''), {});
st.deepEqual(qs.parse(null), {});
st.deepEqual(qs.parse(undefined), {});
st.end();
});
t.test('transforms arrays to objects', function (st) {
st.deepEqual(qs.parse('foo[0]=bar&foo[bad]=baz'), { foo: { '0': 'bar', bad: 'baz' } });
st.deepEqual(qs.parse('foo[bad]=baz&foo[0]=bar'), { foo: { bad: 'baz', '0': 'bar' } });
st.deepEqual(qs.parse('foo[bad]=baz&foo[]=bar'), { foo: { bad: 'baz', '0': 'bar' } });
st.deepEqual(qs.parse('foo[]=bar&foo[bad]=baz'), { foo: { '0': 'bar', bad: 'baz' } });
st.deepEqual(qs.parse('foo[bad]=baz&foo[]=bar&foo[]=foo'), { foo: { bad: 'baz', '0': 'bar', '1': 'foo' } });
st.deepEqual(qs.parse('foo[0][a]=a&foo[0][b]=b&foo[1][a]=aa&foo[1][b]=bb'), { foo: [{ a: 'a', b: 'b' }, { a: 'aa', b: 'bb' }] });
st.deepEqual(qs.parse('a[]=b&a[t]=u&a[hasOwnProperty]=c', { allowPrototypes: false }), { a: { '0': 'b', c: true, t: 'u' } });
st.deepEqual(qs.parse('a[]=b&a[t]=u&a[hasOwnProperty]=c', { allowPrototypes: true }), { a: { '0': 'b', t: 'u', hasOwnProperty: 'c' } });
st.deepEqual(qs.parse('a[]=b&a[hasOwnProperty]=c&a[x]=y', { allowPrototypes: false }), { a: { '0': 'b', '1': 'c', x: 'y' } });
st.deepEqual(qs.parse('a[]=b&a[hasOwnProperty]=c&a[x]=y', { allowPrototypes: true }), { a: { '0': 'b', hasOwnProperty: 'c', x: 'y' } });
st.end();
});
t.test('transforms arrays to objects (dot notation)', function (st) {
st.deepEqual(qs.parse('foo[0].baz=bar&fool.bad=baz', { allowDots: true }), { foo: [{ baz: 'bar' }], fool: { bad: 'baz' } });
st.deepEqual(qs.parse('foo[0].baz=bar&fool.bad.boo=baz', { allowDots: true }), { foo: [{ baz: 'bar' }], fool: { bad: { boo: 'baz' } } });
st.deepEqual(qs.parse('foo[0][0].baz=bar&fool.bad=baz', { allowDots: true }), { foo: [[{ baz: 'bar' }]], fool: { bad: 'baz' } });
st.deepEqual(qs.parse('foo[0].baz[0]=15&foo[0].bar=2', { allowDots: true }), { foo: [{ baz: ['15'], bar: '2' }] });
st.deepEqual(qs.parse('foo[0].baz[0]=15&foo[0].baz[1]=16&foo[0].bar=2', { allowDots: true }), { foo: [{ baz: ['15', '16'], bar: '2' }] });
st.deepEqual(qs.parse('foo.bad=baz&foo[0]=bar', { allowDots: true }), { foo: { bad: 'baz', '0': 'bar' } });
st.deepEqual(qs.parse('foo.bad=baz&foo[]=bar', { allowDots: true }), { foo: { bad: 'baz', '0': 'bar' } });
st.deepEqual(qs.parse('foo[]=bar&foo.bad=baz', { allowDots: true }), { foo: { '0': 'bar', bad: 'baz' } });
st.deepEqual(qs.parse('foo.bad=baz&foo[]=bar&foo[]=foo', { allowDots: true }), { foo: { bad: 'baz', '0': 'bar', '1': 'foo' } });
st.deepEqual(qs.parse('foo[0].a=a&foo[0].b=b&foo[1].a=aa&foo[1].b=bb', { allowDots: true }), { foo: [{ a: 'a', b: 'b' }, { a: 'aa', b: 'bb' }] });
st.end();
});
t.deepEqual(qs.parse('a[b]=c&a=d'), { a: { b: 'c', d: true } }, 'can add keys to objects');
t.test('correctly prunes undefined values when converting an array to an object', function (st) {
st.deepEqual(qs.parse('a[2]=b&a[99999999]=c'), { a: { '2': 'b', '99999999': 'c' } });
st.end();
});
t.test('supports malformed uri characters', function (st) {
st.deepEqual(qs.parse('{%:%}', { strictNullHandling: true }), { '{%:%}': null });
st.deepEqual(qs.parse('{%:%}='), { '{%:%}': '' });
st.deepEqual(qs.parse('foo=%:%}'), { foo: '%:%}' });
st.end();
});
t.test('doesn\'t produce empty keys', function (st) {
st.deepEqual(qs.parse('_r=1&'), { '_r': '1' });
st.end();
});
t.test('cannot access Object prototype', function (st) {
qs.parse('constructor[prototype][bad]=bad');
qs.parse('bad[constructor][prototype][bad]=bad');
st.equal(typeof Object.prototype.bad, 'undefined');
st.end();
});
t.test('parses arrays of objects', function (st) {
st.deepEqual(qs.parse('a[][b]=c'), { a: [{ b: 'c' }] });
st.deepEqual(qs.parse('a[0][b]=c'), { a: [{ b: 'c' }] });
st.end();
});
t.test('allows for empty strings in arrays', function (st) {
st.deepEqual(qs.parse('a[]=b&a[]=&a[]=c'), { a: ['b', '', 'c'] });
st.deepEqual(
qs.parse('a[0]=b&a[1]&a[2]=c&a[19]=', { strictNullHandling: true, arrayLimit: 20 }),
{ a: ['b', null, 'c', ''] },
'with arrayLimit 20 + array indices: null then empty string works'
);
st.deepEqual(
qs.parse('a[]=b&a[]&a[]=c&a[]=', { strictNullHandling: true, arrayLimit: 0 }),
{ a: ['b', null, 'c', ''] },
'with arrayLimit 0 + array brackets: null then empty string works'
);
st.deepEqual(
qs.parse('a[0]=b&a[1]=&a[2]=c&a[19]', { strictNullHandling: true, arrayLimit: 20 }),
{ a: ['b', '', 'c', null] },
'with arrayLimit 20 + array indices: empty string then null works'
);
st.deepEqual(
qs.parse('a[]=b&a[]=&a[]=c&a[]', { strictNullHandling: true, arrayLimit: 0 }),
{ a: ['b', '', 'c', null] },
'with arrayLimit 0 + array brackets: empty string then null works'
);
st.deepEqual(
qs.parse('a[]=&a[]=b&a[]=c'),
{ a: ['', 'b', 'c'] },
'array brackets: empty strings work'
);
st.end();
});
t.test('compacts sparse arrays', function (st) {
st.deepEqual(qs.parse('a[10]=1&a[2]=2'), { a: ['2', '1'] });
st.deepEqual(qs.parse('a[1][b][2][c]=1'), { a: [{ b: [{ c: '1' }] }] });
st.deepEqual(qs.parse('a[1][2][3][c]=1'), { a: [[[{ c: '1' }]]] });
st.deepEqual(qs.parse('a[1][2][3][c][1]=1'), { a: [[[{ c: ['1'] }]]] });
st.end();
});
t.test('parses semi-parsed strings', function (st) {
st.deepEqual(qs.parse({ 'a[b]': 'c' }), { a: { b: 'c' } });
st.deepEqual(qs.parse({ 'a[b]': 'c', 'a[d]': 'e' }), { a: { b: 'c', d: 'e' } });
st.end();
});
t.test('parses buffers correctly', function (st) {
var b = new Buffer('test');
st.deepEqual(qs.parse({ a: b }), { a: b });
st.end();
});
t.test('continues parsing when no parent is found', function (st) {
st.deepEqual(qs.parse('[]=&a=b'), { '0': '', a: 'b' });
st.deepEqual(qs.parse('[]&a=b', { strictNullHandling: true }), { '0': null, a: 'b' });
st.deepEqual(qs.parse('[foo]=bar'), { foo: 'bar' });
st.end();
});
t.test('does not error when parsing a very long array', function (st) {
var str = 'a[]=a';
while (Buffer.byteLength(str) < 128 * 1024) {
str = str + '&' + str;
}
st.doesNotThrow(function () { qs.parse(str); });
st.end();
});
t.test('should not throw when a native prototype has an enumerable property', { parallel: false }, function (st) {
Object.prototype.crash = '';
Array.prototype.crash = '';
st.doesNotThrow(qs.parse.bind(null, 'a=b'));
st.deepEqual(qs.parse('a=b'), { a: 'b' });
st.doesNotThrow(qs.parse.bind(null, 'a[][b]=c'));
st.deepEqual(qs.parse('a[][b]=c'), { a: [{ b: 'c' }] });
delete Object.prototype.crash;
delete Array.prototype.crash;
st.end();
});
t.test('parses a string with an alternative string delimiter', function (st) {
st.deepEqual(qs.parse('a=b;c=d', { delimiter: ';' }), { a: 'b', c: 'd' });
st.end();
});
t.test('parses a string with an alternative RegExp delimiter', function (st) {
st.deepEqual(qs.parse('a=b; c=d', { delimiter: /[;,] */ }), { a: 'b', c: 'd' });
st.end();
});
t.test('does not use non-splittable objects as delimiters', function (st) {
st.deepEqual(qs.parse('a=b&c=d', { delimiter: true }), { a: 'b', c: 'd' });
st.end();
});
t.test('allows overriding parameter limit', function (st) {
st.deepEqual(qs.parse('a=b&c=d', { parameterLimit: 1 }), { a: 'b' });
st.end();
});
t.test('allows setting the parameter limit to Infinity', function (st) {
st.deepEqual(qs.parse('a=b&c=d', { parameterLimit: Infinity }), { a: 'b', c: 'd' });
st.end();
});
t.test('allows overriding array limit', function (st) {
st.deepEqual(qs.parse('a[0]=b', { arrayLimit: -1 }), { a: { '0': 'b' } });
st.deepEqual(qs.parse('a[-1]=b', { arrayLimit: -1 }), { a: { '-1': 'b' } });
st.deepEqual(qs.parse('a[0]=b&a[1]=c', { arrayLimit: 0 }), { a: { '0': 'b', '1': 'c' } });
st.end();
});
t.test('allows disabling array parsing', function (st) {
st.deepEqual(qs.parse('a[0]=b&a[1]=c', { parseArrays: false }), { a: { '0': 'b', '1': 'c' } });
st.end();
});
t.test('parses an object', function (st) {
var input = {
'user[name]': { 'pop[bob]': 3 },
'user[email]': null
};
var expected = {
user: {
name: { 'pop[bob]': 3 },
email: null
}
};
var result = qs.parse(input);
st.deepEqual(result, expected);
st.end();
});
t.test('parses an object in dot notation', function (st) {
var input = {
'user.name': { 'pop[bob]': 3 },
'user.email.': null
};
var expected = {
user: {
name: { 'pop[bob]': 3 },
email: null
}
};
var result = qs.parse(input, { allowDots: true });
st.deepEqual(result, expected);
st.end();
});
t.test('parses an object and not child values', function (st) {
var input = {
'user[name]': { 'pop[bob]': { 'test': 3 } },
'user[email]': null
};
var expected = {
user: {
name: { 'pop[bob]': { 'test': 3 } },
email: null
}
};
var result = qs.parse(input);
st.deepEqual(result, expected);
st.end();
});
t.test('does not blow up when Buffer global is missing', function (st) {
var tempBuffer = global.Buffer;
delete global.Buffer;
var result = qs.parse('a=b&c=d');
global.Buffer = tempBuffer;
st.deepEqual(result, { a: 'b', c: 'd' });
st.end();
});
t.test('does not crash when parsing circular references', function (st) {
var a = {};
a.b = a;
var parsed;
st.doesNotThrow(function () {
parsed = qs.parse({ 'foo[bar]': 'baz', 'foo[baz]': a });
});
st.equal('foo' in parsed, true, 'parsed has "foo" property');
st.equal('bar' in parsed.foo, true);
st.equal('baz' in parsed.foo, true);
st.equal(parsed.foo.bar, 'baz');
st.deepEqual(parsed.foo.baz, a);
st.end();
});
t.test('parses plain objects correctly', function (st) {
var a = Object.create(null);
a.b = 'c';
st.deepEqual(qs.parse(a), { b: 'c' });
var result = qs.parse({ a: a });
st.equal('a' in result, true, 'result has "a" property');
st.deepEqual(result.a, a);
st.end();
});
t.test('parses dates correctly', function (st) {
var now = new Date();
st.deepEqual(qs.parse({ a: now }), { a: now });
st.end();
});
t.test('parses regular expressions correctly', function (st) {
var re = /^test$/;
st.deepEqual(qs.parse({ a: re }), { a: re });
st.end();
});
t.test('can allow overwriting prototype properties', function (st) {
st.deepEqual(qs.parse('a[hasOwnProperty]=b', { allowPrototypes: true }), { a: { hasOwnProperty: 'b' } }, { prototype: false });
st.deepEqual(qs.parse('hasOwnProperty=b', { allowPrototypes: true }), { hasOwnProperty: 'b' }, { prototype: false });
st.end();
});
t.test('can return plain objects', function (st) {
var expected = Object.create(null);
expected.a = Object.create(null);
expected.a.b = 'c';
expected.a.hasOwnProperty = 'd';
st.deepEqual(qs.parse('a[b]=c&a[hasOwnProperty]=d', { plainObjects: true }), expected);
st.deepEqual(qs.parse(null, { plainObjects: true }), Object.create(null));
var expectedArray = Object.create(null);
expectedArray.a = Object.create(null);
expectedArray.a['0'] = 'b';
expectedArray.a.c = 'd';
st.deepEqual(qs.parse('a[]=b&a[c]=d', { plainObjects: true }), expectedArray);
st.end();
});
t.test('can parse with custom encoding', function (st) {
st.deepEqual(qs.parse('%8c%a7=%91%e5%8d%e3%95%7b', {
decoder: function (str) {
var reg = /\%([0-9A-F]{2})/ig;
var result = [];
var parts;
var last = 0;
while (parts = reg.exec(str)) {
result.push(parseInt(parts[1], 16));
last = parts.index + parts[0].length;
}
return iconv.decode(new Buffer(result), 'shift_jis').toString();
}
}), { 県: '大阪府' });
st.end();
});
t.test('throws error with wrong decoder', function (st) {
st.throws(function () {
qs.parse({}, {
decoder: 'string'
});
}, new TypeError('Decoder has to be a function.'));
st.end();
});
});
'use strict';
var test = require('tape');
var qs = require('../');
var iconv = require('iconv-lite');
test('stringify()', function (t) {
t.test('stringifies a querystring object', function (st) {
st.equal(qs.stringify({ a: 'b' }), 'a=b');
st.equal(qs.stringify({ a: 1 }), 'a=1');
st.equal(qs.stringify({ a: 1, b: 2 }), 'a=1&b=2');
st.equal(qs.stringify({ a: 'A_Z' }), 'a=A_Z');
st.equal(qs.stringify({ a: '€' }), 'a=%E2%82%AC');
st.equal(qs.stringify({ a: '' }), 'a=%EE%80%80');
st.equal(qs.stringify({ a: 'א' }), 'a=%D7%90');
st.equal(qs.stringify({ a: '𐐷' }), 'a=%F0%90%90%B7');
st.end();
});
t.test('stringifies a nested object', function (st) {
st.equal(qs.stringify({ a: { b: 'c' } }), 'a%5Bb%5D=c');
st.equal(qs.stringify({ a: { b: { c: { d: 'e' } } } }), 'a%5Bb%5D%5Bc%5D%5Bd%5D=e');
st.end();
});
t.test('stringifies a nested object with dots notation', function (st) {
st.equal(qs.stringify({ a: { b: 'c' } }, { allowDots: true }), 'a.b=c');
st.equal(qs.stringify({ a: { b: { c: { d: 'e' } } } }, { allowDots: true }), 'a.b.c.d=e');
st.end();
});
t.test('stringifies an array value', function (st) {
st.equal(qs.stringify({ a: ['b', 'c', 'd'] }), 'a%5B0%5D=b&a%5B1%5D=c&a%5B2%5D=d');
st.end();
});
t.test('omits nulls when asked', function (st) {
st.equal(qs.stringify({ a: 'b', c: null }, { skipNulls: true }), 'a=b');
st.end();
});
t.test('omits nested nulls when asked', function (st) {
st.equal(qs.stringify({ a: { b: 'c', d: null } }, { skipNulls: true }), 'a%5Bb%5D=c');
st.end();
});
t.test('omits array indices when asked', function (st) {
st.equal(qs.stringify({ a: ['b', 'c', 'd'] }, { indices: false }), 'a=b&a=c&a=d');
st.end();
});
t.test('stringifies a nested array value', function (st) {
st.equal(qs.stringify({ a: { b: ['c', 'd'] } }), 'a%5Bb%5D%5B0%5D=c&a%5Bb%5D%5B1%5D=d');
st.end();
});
t.test('stringifies a nested array value with dots notation', function (st) {
st.equal(qs.stringify({ a: { b: ['c', 'd'] } }, { allowDots: true, encode: false }), 'a.b[0]=c&a.b[1]=d');
st.end();
});
t.test('stringifies an object inside an array', function (st) {
st.equal(qs.stringify({ a: [{ b: 'c' }] }), 'a%5B0%5D%5Bb%5D=c');
st.equal(qs.stringify({ a: [{ b: { c: [1] } }] }), 'a%5B0%5D%5Bb%5D%5Bc%5D%5B0%5D=1');
st.end();
});
t.test('stringifies an array with mixed objects and primitives', function (st) {
st.equal(qs.stringify({ a: [{ b: 1 }, 2, 3] }, { encode: false }), 'a[0][b]=1&a[1]=2&a[2]=3');
st.end();
});
t.test('stringifies an object inside an array with dots notation', function (st) {
st.equal(qs.stringify({ a: [{ b: 'c' }] }, { allowDots: true, encode: false }), 'a[0].b=c');
st.equal(qs.stringify({ a: [{ b: { c: [1] } }] }, { allowDots: true, encode: false }), 'a[0].b.c[0]=1');
st.end();
});
t.test('does not omit object keys when indices = false', function (st) {
st.equal(qs.stringify({ a: [{ b: 'c' }] }, { indices: false }), 'a%5Bb%5D=c');
st.end();
});
t.test('uses indices notation for arrays when indices=true', function (st) {
st.equal(qs.stringify({ a: ['b', 'c'] }, { indices: true }), 'a%5B0%5D=b&a%5B1%5D=c');
st.end();
});
t.test('uses indices notation for arrays when no arrayFormat is specified', function (st) {
st.equal(qs.stringify({ a: ['b', 'c'] }), 'a%5B0%5D=b&a%5B1%5D=c');
st.end();
});
t.test('uses indices notation for arrays when no arrayFormat=indices', function (st) {
st.equal(qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'indices' }), 'a%5B0%5D=b&a%5B1%5D=c');
st.end();
});
t.test('uses repeat notation for arrays when no arrayFormat=repeat', function (st) {
st.equal(qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'repeat' }), 'a=b&a=c');
st.end();
});
t.test('uses brackets notation for arrays when no arrayFormat=brackets', function (st) {
st.equal(qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'brackets' }), 'a%5B%5D=b&a%5B%5D=c');
st.end();
});
t.test('stringifies a complicated object', function (st) {
st.equal(qs.stringify({ a: { b: 'c', d: 'e' } }), 'a%5Bb%5D=c&a%5Bd%5D=e');
st.end();
});
t.test('stringifies an empty value', function (st) {
st.equal(qs.stringify({ a: '' }), 'a=');
st.equal(qs.stringify({ a: null }, { strictNullHandling: true }), 'a');
st.equal(qs.stringify({ a: '', b: '' }), 'a=&b=');
st.equal(qs.stringify({ a: null, b: '' }, { strictNullHandling: true }), 'a&b=');
st.equal(qs.stringify({ a: { b: '' } }), 'a%5Bb%5D=');
st.equal(qs.stringify({ a: { b: null } }, { strictNullHandling: true }), 'a%5Bb%5D');
st.equal(qs.stringify({ a: { b: null } }, { strictNullHandling: false }), 'a%5Bb%5D=');
st.end();
});
t.test('stringifies an empty object', function (st) {
var obj = Object.create(null);
obj.a = 'b';
st.equal(qs.stringify(obj), 'a=b');
st.end();
});
t.test('returns an empty string for invalid input', function (st) {
st.equal(qs.stringify(undefined), '');
st.equal(qs.stringify(false), '');
st.equal(qs.stringify(null), '');
st.equal(qs.stringify(''), '');
st.end();
});
t.test('stringifies an object with an empty object as a child', function (st) {
var obj = {
a: Object.create(null)
};
obj.a.b = 'c';
st.equal(qs.stringify(obj), 'a%5Bb%5D=c');
st.end();
});
t.test('drops keys with a value of undefined', function (st) {
st.equal(qs.stringify({ a: undefined }), '');
st.equal(qs.stringify({ a: { b: undefined, c: null } }, { strictNullHandling: true }), 'a%5Bc%5D');
st.equal(qs.stringify({ a: { b: undefined, c: null } }, { strictNullHandling: false }), 'a%5Bc%5D=');
st.equal(qs.stringify({ a: { b: undefined, c: '' } }), 'a%5Bc%5D=');
st.end();
});
t.test('url encodes values', function (st) {
st.equal(qs.stringify({ a: 'b c' }), 'a=b%20c');
st.end();
});
t.test('stringifies a date', function (st) {
var now = new Date();
var str = 'a=' + encodeURIComponent(now.toISOString());
st.equal(qs.stringify({ a: now }), str);
st.end();
});
t.test('stringifies the weird object from qs', function (st) {
st.equal(qs.stringify({ 'my weird field': '~q1!2"\'w$5&7/z8)?' }), 'my%20weird%20field=~q1%212%22%27w%245%267%2Fz8%29%3F');
st.end();
});
t.test('skips properties that are part of the object prototype', function (st) {
Object.prototype.crash = 'test';
st.equal(qs.stringify({ a: 'b' }), 'a=b');
st.equal(qs.stringify({ a: { b: 'c' } }), 'a%5Bb%5D=c');
delete Object.prototype.crash;
st.end();
});
t.test('stringifies boolean values', function (st) {
st.equal(qs.stringify({ a: true }), 'a=true');
st.equal(qs.stringify({ a: { b: true } }), 'a%5Bb%5D=true');
st.equal(qs.stringify({ b: false }), 'b=false');
st.equal(qs.stringify({ b: { c: false } }), 'b%5Bc%5D=false');
st.end();
});
t.test('stringifies buffer values', function (st) {
st.equal(qs.stringify({ a: new Buffer('test') }), 'a=test');
st.equal(qs.stringify({ a: { b: new Buffer('test') } }), 'a%5Bb%5D=test');
st.end();
});
t.test('stringifies an object using an alternative delimiter', function (st) {
st.equal(qs.stringify({ a: 'b', c: 'd' }, { delimiter: ';' }), 'a=b;c=d');
st.end();
});
t.test('doesn\'t blow up when Buffer global is missing', function (st) {
var tempBuffer = global.Buffer;
delete global.Buffer;
var result = qs.stringify({ a: 'b', c: 'd' });
global.Buffer = tempBuffer;
st.equal(result, 'a=b&c=d');
st.end();
});
t.test('selects properties when filter=array', function (st) {
st.equal(qs.stringify({ a: 'b' }, { filter: ['a'] }), 'a=b');
st.equal(qs.stringify({ a: 1 }, { filter: [] }), '');
st.equal(qs.stringify({ a: { b: [1, 2, 3, 4], c: 'd' }, c: 'f' }, { filter: ['a', 'b', 0, 2] }), 'a%5Bb%5D%5B0%5D=1&a%5Bb%5D%5B2%5D=3');
st.end();
});
t.test('supports custom representations when filter=function', function (st) {
var calls = 0;
var obj = { a: 'b', c: 'd', e: { f: new Date(1257894000000) } };
var filterFunc = function (prefix, value) {
calls++;
if (calls === 1) {
st.equal(prefix, '', 'prefix is empty');
st.equal(value, obj);
} else if (prefix === 'c') {
return;
} else if (value instanceof Date) {
st.equal(prefix, 'e[f]');
return value.getTime();
}
return value;
};
st.equal(qs.stringify(obj, { filter: filterFunc }), 'a=b&e%5Bf%5D=1257894000000');
st.equal(calls, 5);
st.end();
});
t.test('can disable uri encoding', function (st) {
st.equal(qs.stringify({ a: 'b' }, { encode: false }), 'a=b');
st.equal(qs.stringify({ a: { b: 'c' } }, { encode: false }), 'a[b]=c');
st.equal(qs.stringify({ a: 'b', c: null }, { strictNullHandling: true, encode: false }), 'a=b&c');
st.end();
});
t.test('can sort the keys', function (st) {
var sort = function (a, b) { return a.localeCompare(b); };
st.equal(qs.stringify({ a: 'c', z: 'y', b: 'f' }, { sort: sort }), 'a=c&b=f&z=y');
st.equal(qs.stringify({ a: 'c', z: { j: 'a', i: 'b' }, b: 'f' }, { sort: sort }), 'a=c&b=f&z%5Bi%5D=b&z%5Bj%5D=a');
st.end();
});
t.test('can sort the keys at depth 3 or more too', function (st) {
var sort = function (a, b) { return a.localeCompare(b); };
st.equal(qs.stringify({ a: 'a', z: { zj: {zjb: 'zjb', zja: 'zja'}, zi: {zib: 'zib', zia: 'zia'} }, b: 'b' }, { sort: sort, encode: false }), 'a=a&b=b&z[zi][zia]=zia&z[zi][zib]=zib&z[zj][zja]=zja&z[zj][zjb]=zjb');
st.equal(qs.stringify({ a: 'a', z: { zj: {zjb: 'zjb', zja: 'zja'}, zi: {zib: 'zib', zia: 'zia'} }, b: 'b' }, { sort: null, encode: false }), 'a=a&z[zj][zjb]=zjb&z[zj][zja]=zja&z[zi][zib]=zib&z[zi][zia]=zia&b=b');
st.end();
});
t.test('can stringify with custom encoding', function (st) {
st.equal(qs.stringify({ 県: '大阪府', '': ''}, {
encoder: function (str) {
if (str.length === 0) {
return '';
}
var buf = iconv.encode(str, 'shiftjis');
var result = [];
for (var i=0; i < buf.length; ++i) {
result.push(buf.readUInt8(i).toString(16));
}
return '%' + result.join('%');
}
}), '%8c%a7=%91%e5%8d%e3%95%7b&=');
st.end();
});
t.test('throws error with wrong encoder', function (st) {
st.throws(function () {
qs.stringify({}, {
encoder: 'string'
});
}, new TypeError('Encoder has to be a function.'));
st.end();
});
t.test('can use custom encoder for a buffer object', {
skip: typeof Buffer === 'undefined'
}, function (st) {
st.equal(qs.stringify({ a: new Buffer([1]) }, {
encoder: function (buffer) {
if (typeof buffer === 'string') {
return buffer;
}
return String.fromCharCode(buffer.readUInt8(0) + 97);
}
}), 'a=b');
st.end();
});
});
'use strict';
var test = require('tape');
var utils = require('../lib/utils');
test('merge()', function (t) {
t.deepEqual(utils.merge({ a: 'b' }, { a: 'c' }), { a: ['b', 'c'] }, 'merges two objects with the same key');
t.end();
});
{
"_args": [
[
{
"raw": "body-parser",
"scope": null,
"escapedName": "body-parser",
"name": "body-parser",
"rawSpec": "",
"spec": "latest",
"type": "tag"
},
"C:\\xampp\\htdocs\\cafe"
]
],
"_from": "body-parser@latest",
"_id": "body-parser@1.16.0",
"_inCache": true,
"_location": "/body-parser",
"_nodeVersion": "4.6.1",
"_npmOperationalInternal": {
"host": "packages-12-west.internal.npmjs.com",
"tmp": "tmp/body-parser-1.16.0.tgz_1484710891328_0.08588228072039783"
},
"_npmUser": {
"name": "dougwilson",
"email": "doug@somethingdoug.com"
},
"_npmVersion": "2.15.9",
"_phantomChildren": {},
"_requested": {
"raw": "body-parser",
"scope": null,
"escapedName": "body-parser",
"name": "body-parser",
"rawSpec": "",
"spec": "latest",
"type": "tag"
},
"_requiredBy": [
"#USER"
],
"_resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.16.0.tgz",
"_shasum": "924a5e472c6229fb9d69b85a20d5f2532dec788b",
"_shrinkwrap": null,
"_spec": "body-parser",
"_where": "C:\\xampp\\htdocs\\cafe",
"bugs": {
"url": "https://github.com/expressjs/body-parser/issues"
},
"contributors": [
{
"name": "Douglas Christopher Wilson",
"email": "doug@somethingdoug.com"
},
{
"name": "Jonathan Ong",
"email": "me@jongleberry.com",
"url": "http://jongleberry.com"
}
],
"dependencies": {
"bytes": "2.4.0",
"content-type": "~1.0.2",
"debug": "2.6.0",
"depd": "~1.1.0",
"http-errors": "~1.5.1",
"iconv-lite": "0.4.15",
"on-finished": "~2.3.0",
"qs": "6.2.1",
"raw-body": "~2.2.0",
"type-is": "~1.6.14"
},
"description": "Node.js body parsing middleware",
"devDependencies": {
"eslint": "3.13.1",
"eslint-config-standard": "6.2.1",
"eslint-plugin-markdown": "1.0.0-beta.3",
"eslint-plugin-promise": "3.4.0",
"eslint-plugin-standard": "2.0.1",
"istanbul": "0.4.5",
"methods": "1.1.2",
"mocha": "2.5.3",
"supertest": "1.1.0"
},
"directories": {},
"dist": {
"shasum": "924a5e472c6229fb9d69b85a20d5f2532dec788b",
"tarball": "https://registry.npmjs.org/body-parser/-/body-parser-1.16.0.tgz"
},
"engines": {
"node": ">= 0.8"
},
"files": [
"lib/",
"LICENSE",
"HISTORY.md",
"index.js"
],
"gitHead": "c5a73d51483310f8443043d3927c2557993f3416",
"homepage": "https://github.com/expressjs/body-parser#readme",
"license": "MIT",
"maintainers": [
{
"name": "dougwilson",
"email": "doug@somethingdoug.com"
}
],
"name": "body-parser",
"optionalDependencies": {},
"readme": "ERROR: No README data found!",
"repository": {
"type": "git",
"url": "git+https://github.com/expressjs/body-parser.git"
},
"scripts": {
"lint": "eslint --plugin markdown --ext js,md .",
"test": "mocha --require test/support/env --reporter spec --check-leaks --bail test/",
"test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --require test/support/env --reporter dot --check-leaks test/",
"test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --require test/support/env --reporter spec --check-leaks test/"
},
"version": "1.16.0"
}

body-parser

NPM Version NPM Downloads Build Status Test Coverage Gratipay

Node.js body parsing middleware.

Parse incoming request bodies in a middleware before your handlers, available under the req.body property.

Learn about the anatomy of an HTTP transaction in Node.js.

This does not handle multipart bodies, due to their complex and typically large nature. For multipart bodies, you may be interested in the following modules:

This module provides the following parsers:

Other body parsers you might be interested in:

Installation

$ npm install body-parser

API

var bodyParser = require('body-parser')

The bodyParser object exposes various factories to create middlewares. All middlewares will populate the req.body property with the parsed body, or an empty object ({}) if there was no body to parse (or an error was returned).

The various errors returned by this module are described in the errors section.

bodyParser.json(options)

Returns middleware that only parses json. This parser accepts any Unicode encoding of the body and supports automatic inflation of gzip and deflate encodings.

A new body object containing the parsed data is populated on the request object after the middleware (i.e. req.body).

Options

The json function takes an option options object that may contain any of the following keys:

inflate

When set to true, then deflated (compressed) bodies will be inflated; when false, deflated bodies are rejected. Defaults to true.

limit

Controls the maximum request body size. If this is a number, then the value specifies the number of bytes; if it is a string, the value is passed to the bytes library for parsing. Defaults to '100kb'.

reviver

The reviver option is passed directly to JSON.parse as the second argument. You can find more information on this argument in the MDN documentation about JSON.parse.

strict

When set to true, will only accept arrays and objects; when false will accept anything JSON.parse accepts. Defaults to true.

type

The type option is used to determine what media type the middleware will parse. This option can be a function or a string. If a string, type option is passed directly to the type-is library and this can be an extension name (like json), a mime type (like application/json), or a mime type with a wildcard (like */* or */json). If a function, the type option is called as fn(req) and the request is parsed if it returns a truthy value. Defaults to application/json.

verify

The verify option, if supplied, is called as verify(req, res, buf, encoding), where buf is a Buffer of the raw request body and encoding is the encoding of the request. The parsing can be aborted by throwing an error.

bodyParser.raw(options)

Returns middleware that parses all bodies as a Buffer. This parser supports automatic inflation of gzip and deflate encodings.

A new body object containing the parsed data is populated on the request object after the middleware (i.e. req.body). This will be a Buffer object of the body.

Options

The raw function takes an option options object that may contain any of the following keys:

inflate

When set to true, then deflated (compressed) bodies will be inflated; when false, deflated bodies are rejected. Defaults to true.

limit

Controls the maximum request body size. If this is a number, then the value specifies the number of bytes; if it is a string, the value is passed to the bytes library for parsing. Defaults to '100kb'.

type

The type option is used to determine what media type the middleware will parse. This option can be a function or a string. If a string, type option is passed directly to the type-is library and this can be an extension name (like bin), a mime type (like application/octet-stream), or a mime type with a wildcard (like */* or application/*). If a function, the type option is called as fn(req) and the request is parsed if it returns a truthy value. Defaults to application/octet-stream.

verify

The verify option, if supplied, is called as verify(req, res, buf, encoding), where buf is a Buffer of the raw request body and encoding is the encoding of the request. The parsing can be aborted by throwing an error.

bodyParser.text(options)

Returns middleware that parses all bodies as a string. This parser supports automatic inflation of gzip and deflate encodings.

A new body string containing the parsed data is populated on the request object after the middleware (i.e. req.body). This will be a string of the body.

Options

The text function takes an option options object that may contain any of the following keys:

defaultCharset

Specify the default character set for the text content if the charset is not specified in the Content-Type header of the request. Defaults to utf-8.

inflate

When set to true, then deflated (compressed) bodies will be inflated; when false, deflated bodies are rejected. Defaults to true.

limit

Controls the maximum request body size. If this is a number, then the value specifies the number of bytes; if it is a string, the value is passed to the bytes library for parsing. Defaults to '100kb'.

type

The type option is used to determine what media type the middleware will parse. This option can be a function or a string. If a string, type option is passed directly to the type-is library and this can be an extension name (like txt), a mime type (like text/plain), or a mime type with a wildcard (like */* or text/*). If a function, the type option is called as fn(req) and the request is parsed if it returns a truthy value. Defaults to text/plain.

verify

The verify option, if supplied, is called as verify(req, res, buf, encoding), where buf is a Buffer of the raw request body and encoding is the encoding of the request. The parsing can be aborted by throwing an error.

bodyParser.urlencoded(options)

Returns middleware that only parses urlencoded bodies. This parser accepts only UTF-8 encoding of the body and supports automatic inflation of gzip and deflate encodings.

A new body object containing the parsed data is populated on the request object after the middleware (i.e. req.body). This object will contain key-value pairs, where the value can be a string or array (when extended is false), or any type (when extended is true).

Options

The urlencoded function takes an option options object that may contain any of the following keys:

extended

The extended option allows to choose between parsing the URL-encoded data with the querystring library (when false) or the qs library (when true). The "extended" syntax allows for rich objects and arrays to be encoded into the URL-encoded format, allowing for a JSON-like experience with URL-encoded. For more information, please see the qs library.

Defaults to true, but using the default has been deprecated. Please research into the difference between qs and querystring and choose the appropriate setting.

inflate

When set to true, then deflated (compressed) bodies will be inflated; when false, deflated bodies are rejected. Defaults to true.

limit

Controls the maximum request body size. If this is a number, then the value specifies the number of bytes; if it is a string, the value is passed to the bytes library for parsing. Defaults to '100kb'.

parameterLimit

The parameterLimit option controls the maximum number of parameters that are allowed in the URL-encoded data. If a request contains more parameters than this value, a 413 will be returned to the client. Defaults to 1000.

type

The type option is used to determine what media type the middleware will parse. This option can be a function or a string. If a string, type option is passed directly to the type-is library and this can be an extension name (like urlencoded), a mime type (like application/x-www-form-urlencoded), or a mime type with a wildcard (like */x-www-form-urlencoded). If a function, the type option is called as fn(req) and the request is parsed if it returns a truthy value. Defaults to application/x-www-form-urlencoded.

verify

The verify option, if supplied, is called as verify(req, res, buf, encoding), where buf is a Buffer of the raw request body and encoding is the encoding of the request. The parsing can be aborted by throwing an error.

Errors

The middlewares provided by this module create errors depending on the error condition during parsing. The errors will typically have a status property that contains the suggested HTTP response code and a body property containing the read body, if available.

The following are the common errors emitted, though any error can come through for various reasons.

content encoding unsupported

This error will occur when the request had a Content-Encoding header that contained an encoding but the "inflation" option was set to false. The status property is set to 415.

request aborted

This error will occur when the request is aborted by the client before reading the body has finished. The received property will be set to the number of bytes received before the request was aborted and the expected property is set to the number of expected bytes. The status property is set to 400.

request entity too large

This error will occur when the request body's size is larger than the "limit" option. The limit property will be set to the byte limit and the length property will be set to the request body's length. The status property is set to 413.

request size did not match content length

This error will occur when the request's length did not match the length from the Content-Length header. This typically occurs when the request is malformed, typically when the Content-Length header was calculated based on characters instead of bytes. The status property is set to 400.

stream encoding should not be set

This error will occur when something called the req.setEncoding method prior to this middleware. This module operates directly on bytes only and you cannot call req.setEncoding when using this module. The status property is set to 500.

unsupported charset "BOGUS"

This error will occur when the request had a charset parameter in the Content-Type header, but the iconv-lite module does not support it OR the parser does not support it. The charset is contained in the message as well as in the charset property. The status property is set to 415.

unsupported content encoding "bogus"

This error will occur when the request had a Content-Encoding header that contained an unsupported encoding. The encoding is contained in the message as well as in the encoding property. The status property is set to 415.

Examples

Express/Connect top-level generic

This example demonstrates adding a generic JSON and URL-encoded parser as a top-level middleware, which will parse the bodies of all incoming requests. This is the simplest setup.

var express = require('express')
var bodyParser = require('body-parser')

var app = express()

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))

// parse application/json
app.use(bodyParser.json())

app.use(function (req, res) {
  res.setHeader('Content-Type', 'text/plain')
  res.write('you posted:\n')
  res.end(JSON.stringify(req.body, null, 2))
})

Express route-specific

This example demonstrates adding body parsers specifically to the routes that need them. In general, this is the most recommended way to use body-parser with Express.

var express = require('express')
var bodyParser = require('body-parser')

var app = express()

// create application/json parser
var jsonParser = bodyParser.json()

// create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false })

// POST /login gets urlencoded bodies
app.post('/login', urlencodedParser, function (req, res) {
  if (!req.body) return res.sendStatus(400)
  res.send('welcome, ' + req.body.username)
})

// POST /api/users gets JSON bodies
app.post('/api/users', jsonParser, function (req, res) {
  if (!req.body) return res.sendStatus(400)
  // create user in req.body
})

Change accepted type for parsers

All the parsers accept a type option which allows you to change the Content-Type that the middleware will parse.

var express = require('express')
var bodyParser = require('body-parser')

var app = express()

// parse various different custom JSON types as JSON
app.use(bodyParser.json({ type: 'application/*+json' }))

// parse some custom thing into a Buffer
app.use(bodyParser.raw({ type: 'application/vnd.custom-type' }))

// parse an HTML body into a string
app.use(bodyParser.text({ type: 'text/html' }))

License

MIT

2.4.0 / 2016-06-01

  • Add option "unitSeparator"

2.3.0 / 2016-02-15

  • Drop partial bytes on all parsed units
  • Fix non-finite numbers to .format to return null
  • Fix parsing byte string that looks like hex
  • perf: hoist regular expressions

2.2.0 / 2015-11-13

  • add option "decimalPlaces"
  • add option "fixedDecimals"

2.1.0 / 2015-05-21

  • add .format export
  • add .parse export

2.0.2 / 2015-05-20

  • remove map recreation
  • remove unnecessary object construction

2.0.1 / 2015-05-07

  • fix browserify require
  • remove node.extend dependency

2.0.0 / 2015-04-12

  • add option "case"
  • add option "thousandsSeparator"
  • return "null" on invalid parse input
  • support proper round-trip: bytes(bytes(num)) === num
  • units no longer case sensitive when parsing

1.0.0 / 2014-05-05

  • add negative support. fixes #6

0.3.0 / 2014-03-19

  • added terabyte support

0.2.1 / 2013-04-01

  • add .component

0.2.0 / 2012-10-28

  • bytes(200).should.eql('200b')

0.1.0 / 2012-07-04

  • add bytes to string conversion [yields]
/*!
* bytes
* Copyright(c) 2012-2014 TJ Holowaychuk
* Copyright(c) 2015 Jed Watson
* MIT Licensed
*/
'use strict';
/**
* Module exports.
* @public
*/
module.exports = bytes;
module.exports.format = format;
module.exports.parse = parse;
/**
* Module variables.
* @private
*/
var formatThousandsRegExp = /\B(?=(\d{3})+(?!\d))/g;
var formatDecimalsRegExp = /(?:\.0*|(\.[^0]+)0+)$/;
var map = {
b: 1,
kb: 1 << 10,
mb: 1 << 20,
gb: 1 << 30,
tb: ((1 << 30) * 1024)
};
// TODO: use is-finite module?
var numberIsFinite = Number.isFinite || function (v) { return typeof v === 'number' && isFinite(v); };
var parseRegExp = /^((-|\+)?(\d+(?:\.\d+)?)) *(kb|mb|gb|tb)$/i;
/**
* Convert the given value in bytes into a string or parse to string to an integer in bytes.
*
* @param {string|number} value
* @param {{
* case: [string],
* decimalPlaces: [number]
* fixedDecimals: [boolean]
* thousandsSeparator: [string]
* unitSeparator: [string]
* }} [options] bytes options.
*
* @returns {string|number|null}
*/
function bytes(value, options) {
if (typeof value === 'string') {
return parse(value);
}
if (typeof value === 'number') {
return format(value, options);
}
return null;
}
/**
* Format the given value in bytes into a string.
*
* If the value is negative, it is kept as such. If it is a float,
* it is rounded.
*
* @param {number} value
* @param {object} [options]
* @param {number} [options.decimalPlaces=2]
* @param {number} [options.fixedDecimals=false]
* @param {string} [options.thousandsSeparator=]
* @param {string} [options.unitSeparator=]
*
* @returns {string|null}
* @public
*/
function format(value, options) {
if (!numberIsFinite(value)) {
return null;
}
var mag = Math.abs(value);
var thousandsSeparator = (options && options.thousandsSeparator) || '';
var unitSeparator = (options && options.unitSeparator) || '';
var decimalPlaces = (options && options.decimalPlaces !== undefined) ? options.decimalPlaces : 2;
var fixedDecimals = Boolean(options && options.fixedDecimals);
var unit = 'B';
if (mag >= map.tb) {
unit = 'TB';
} else if (mag >= map.gb) {
unit = 'GB';
} else if (mag >= map.mb) {
unit = 'MB';
} else if (mag >= map.kb) {
unit = 'kB';
}
var val = value / map[unit.toLowerCase()];
var str = val.toFixed(decimalPlaces);
if (!fixedDecimals) {
str = str.replace(formatDecimalsRegExp, '$1');
}
if (thousandsSeparator) {
str = str.replace(formatThousandsRegExp, thousandsSeparator);
}
return str + unitSeparator + unit;
}
/**
* Parse the string value into an integer in bytes.
*
* If no unit is given, it is assumed the value is in bytes.
*
* @param {number|string} val
*
* @returns {number|null}
* @public
*/
function parse(val) {
if (typeof val === 'number' && !isNaN(val)) {
return val;
}
if (typeof val !== 'string') {
return null;
}
// Test if the string passed is valid
var results = parseRegExp.exec(val);
var floatValue;
var unit = 'b';
if (!results) {
// Nothing could be extracted from the given string
floatValue = parseInt(val, 10);
unit = 'b'
} else {
// Retrieve the value and the unit
floatValue = parseFloat(results[1]);
unit = results[4].toLowerCase();
}
return Math.floor(map[unit] * floatValue);
}
(The MIT License)
Copyright (c) 2012-2014 TJ Holowaychuk <tj@vision-media.ca>
Copyright (c) 2015 Jed Watson <jed.watson@me.com>
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.
{
"_args": [
[
{
"raw": "bytes@2.4.0",
"scope": null,
"escapedName": "bytes",
"name": "bytes",
"rawSpec": "2.4.0",
"spec": "2.4.0",
"type": "version"
},
"C:\\xampp\\htdocs\\cafe\\node_modules\\body-parser"
]
],
"_from": "bytes@2.4.0",
"_id": "bytes@2.4.0",
"_inCache": true,
"_location": "/bytes",
"_npmOperationalInternal": {
"host": "packages-16-east.internal.npmjs.com",
"tmp": "tmp/bytes-2.4.0.tgz_1464812473023_0.6271433881483972"
},
"_npmUser": {
"name": "dougwilson",
"email": "doug@somethingdoug.com"
},
"_npmVersion": "1.4.28",
"_phantomChildren": {},
"_requested": {
"raw": "bytes@2.4.0",
"scope": null,
"escapedName": "bytes",
"name": "bytes",
"rawSpec": "2.4.0",
"spec": "2.4.0",
"type": "version"
},
"_requiredBy": [
"/body-parser",
"/raw-body"
],
"_resolved": "https://registry.npmjs.org/bytes/-/bytes-2.4.0.tgz",
"_shasum": "7d97196f9d5baf7f6935e25985549edd2a6c2339",
"_shrinkwrap": null,
"_spec": "bytes@2.4.0",
"_where": "C:\\xampp\\htdocs\\cafe\\node_modules\\body-parser",
"author": {
"name": "TJ Holowaychuk",
"email": "tj@vision-media.ca",
"url": "http://tjholowaychuk.com"
},
"bugs": {
"url": "https://github.com/visionmedia/bytes.js/issues"
},
"component": {
"scripts": {
"bytes/index.js": "index.js"
}
},
"contributors": [
{
"name": "Jed Watson",
"email": "jed.watson@me.com"
},
{
"name": "Théo FIDRY",
"email": "theo.fidry@gmail.com"
}
],
"dependencies": {},
"description": "Utility to parse a string bytes to bytes and vice-versa",
"devDependencies": {
"mocha": "1.21.5"
},
"directories": {},
"dist": {
"shasum": "7d97196f9d5baf7f6935e25985549edd2a6c2339",
"tarball": "https://registry.npmjs.org/bytes/-/bytes-2.4.0.tgz"
},
"files": [
"History.md",
"LICENSE",
"Readme.md",
"index.js"
],
"gitHead": "2a598442bdfa796df8d01a96cc54495cda550e70",
"homepage": "https://github.com/visionmedia/bytes.js",
"keywords": [
"byte",
"bytes",
"utility",
"parse",
"parser",
"convert",
"converter"
],
"license": "MIT",
"maintainers": [
{
"name": "dougwilson",
"email": "doug@somethingdoug.com"
},
{
"name": "tjholowaychuk",
"email": "tj@vision-media.ca"
}
],
"name": "bytes",
"optionalDependencies": {},
"readme": "ERROR: No README data found!",
"repository": {
"type": "git",
"url": "git+https://github.com/visionmedia/bytes.js.git"
},
"scripts": {
"test": "mocha --check-leaks --reporter spec"
},
"version": "2.4.0"
}

Bytes utility

NPM Version NPM Downloads Build Status

Utility to parse a string bytes (ex: 1TB) to bytes (1099511627776) and vice-versa.

Usage

var bytes = require('bytes');

bytes.format(number value, [options]): string|null

Format the given value in bytes into a string. If the value is negative, it is kept as such. If it is a float, it is rounded.

Arguments

Name Type Description
value number Value in bytes
options Object Conversion options

Options

Property Type Description
decimalPlaces number|null Maximum number of decimal places to include in output. Default value to 2.
fixedDecimals boolean|null Whether to always display the maximum number of decimal places. Default value to false
thousandsSeparator string|null Example of values: ' ', ',' and .... Default value to ' '.
unitSeparator string|null Separator to use between number and unit. Default value to ''.

Returns

Name Type Description
results string|null Return null upon error. String value otherwise.

Example

bytes(1024);
// output: '1kB'

bytes(1000);
// output: '1000B'

bytes(1000, {thousandsSeparator: ' '});
// output: '1 000B'

bytes(1024 * 1.7, {decimalPlaces: 0});
// output: '2kB'

bytes(1024, {unitSeparator: ' '});
// output: '1 kB'

bytes.parse(string value): number|null

Parse the string value into an integer in bytes. If no unit is given, it is assumed the value is in bytes.

Supported units and abbreviations are as follows and are case-insensitive:

  • "b" for bytes
  • "kb" for kilobytes
  • "mb" for megabytes
  • "gb" for gigabytes
  • "tb" for terabytes

The units are in powers of two, not ten. This means 1kb = 1024b according to this parser.

Arguments

Name Type Description
value string String to parse.

Returns

Name Type Description
results number|null Return null upon error. Value in bytes otherwise.

Example

bytes('1kB');
// output: 1024

bytes('1024');
// output: 1024

Installation

npm install bytes --save
component install visionmedia/bytes.js

License

npm

1.0.0 / 2013-01-24

  • remove lame magical getters

0.0.1 / 2010-01-03

  • Initial release
module.exports = function(){
var orig = Error.prepareStackTrace;
Error.prepareStackTrace = function(_, stack){ return stack; };
var err = new Error;
Error.captureStackTrace(err, arguments.callee);
var stack = err.stack;
Error.prepareStackTrace = orig;
return stack;
};
test:
@./node_modules/.bin/mocha \
--require should
.PHONY: test
{
"_args": [
[
{
"raw": "callsite@1.0.0",
"scope": null,
"escapedName": "callsite",
"name": "callsite",
"rawSpec": "1.0.0",
"spec": "1.0.0",
"type": "version"
},
"C:\\xampp\\htdocs\\cafe\\node_modules\\better-assert"
]
],
"_from": "callsite@1.0.0",
"_id": "callsite@1.0.0",
"_inCache": true,
"_location": "/callsite",
"_npmUser": {
"name": "tjholowaychuk",
"email": "tj@vision-media.ca"
},
"_npmVersion": "1.2.2",
"_phantomChildren": {},
"_requested": {
"raw": "callsite@1.0.0",
"scope": null,
"escapedName": "callsite",
"name": "callsite",
"rawSpec": "1.0.0",
"spec": "1.0.0",
"type": "version"
},
"_requiredBy": [
"/better-assert"
],
"_resolved": "https://registry.npmjs.org/callsite/-/callsite-1.0.0.tgz",
"_shasum": "280398e5d664bd74038b6f0905153e6e8af1bc20",
"_shrinkwrap": null,
"_spec": "callsite@1.0.0",
"_where": "C:\\xampp\\htdocs\\cafe\\node_modules\\better-assert",
"author": {
"name": "TJ Holowaychuk",
"email": "tj@vision-media.ca"
},
"dependencies": {},
"description": "access to v8's CallSites",
"devDependencies": {
"mocha": "*",
"should": "*"
},
"directories": {},
"dist": {
"shasum": "280398e5d664bd74038b6f0905153e6e8af1bc20",
"tarball": "https://registry.npmjs.org/callsite/-/callsite-1.0.0.tgz"
},
"engines": {
"node": "*"
},
"keywords": [
"stack",
"trace",
"line"
],
"main": "index",
"maintainers": [
{
"name": "tjholowaychuk",
"email": "tj@vision-media.ca"
}
],
"name": "callsite",
"optionalDependencies": {},
"readme": "ERROR: No README data found!",
"version": "1.0.0"
}

callstack

Access to v8's "raw" CallSites.

Installation

$ npm install callsite

Example

var stack = require('callsite');

foo();

function foo() {
  bar();
}

function bar() {
  baz();
}

function baz() {
  console.log();
  stack().forEach(function(site){
    console.log('  \033[36m%s\033[90m in %s:%d\033[0m'
      , site.getFunctionName() || 'anonymous'
      , site.getFileName()
      , site.getLineNumber());
  });
  console.log();
}

Why?

Because you can do weird, stupid, clever, wacky things such as:

License

MIT

var charenc = {
// UTF-8 encoding
utf8: {
// Convert a string to a byte array
stringToBytes: function(str) {
return charenc.bin.stringToBytes(unescape(encodeURIComponent(str)));
},
// Convert a byte array to a string
bytesToString: function(bytes) {
return decodeURIComponent(escape(charenc.bin.bytesToString(bytes)));
}
},
// Binary encoding
bin: {
// Convert a string to a byte array
stringToBytes: function(str) {
for (var bytes = [], i = 0; i < str.length; i++)
bytes.push(str.charCodeAt(i) & 0xFF);
return bytes;
},
// Convert a byte array to a string
bytesToString: function(bytes) {
for (var str = [], i = 0; i < bytes.length; i++)
str.push(String.fromCharCode(bytes[i]));
return str.join('');
}
}
};
module.exports = charenc;

Copyright © 2011, Paul Vorbach. All rights reserved. Copyright © 2009, Jeff Mott. All rights reserved.

All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

  • Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
  • Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
  • Neither the name Crypto-JS nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

{
"_args": [
[
{
"raw": "charenc@~0.0.1",
"scope": null,
"escapedName": "charenc",
"name": "charenc",
"rawSpec": "~0.0.1",
"spec": ">=0.0.1 <0.1.0",
"type": "range"
},
"C:\\xampp\\htdocs\\cafe\\node_modules\\md5"
]
],
"_from": "charenc@>=0.0.1 <0.1.0",
"_id": "charenc@0.0.2",
"_inCache": true,
"_location": "/charenc",
"_nodeVersion": "4.4.5",
"_npmOperationalInternal": {
"host": "packages-12-west.internal.npmjs.com",
"tmp": "tmp/charenc-0.0.2.tgz_1482450158427_0.9801697849761695"
},
"_npmUser": {
"name": "pvorb",
"email": "paul@vorba.ch"
},
"_npmVersion": "3.9.3",
"_phantomChildren": {},
"_requested": {
"raw": "charenc@~0.0.1",
"scope": null,
"escapedName": "charenc",
"name": "charenc",
"rawSpec": "~0.0.1",
"spec": ">=0.0.1 <0.1.0",
"type": "range"
},
"_requiredBy": [
"/md5"
],
"_resolved": "https://registry.npmjs.org/charenc/-/charenc-0.0.2.tgz",
"_shasum": "c0a1d2f3a7092e03774bfa83f14c0fc5790a8667",
"_shrinkwrap": null,
"_spec": "charenc@~0.0.1",
"_where": "C:\\xampp\\htdocs\\cafe\\node_modules\\md5",
"author": {
"name": "Paul Vorbach",
"email": "paul@vorb.de",
"url": "http://vorb.de"
},
"bugs": {
"url": "https://github.com/pvorb/node-charenc/issues"
},
"dependencies": {},
"description": "character encoding utilities",
"devDependencies": {},
"directories": {},
"dist": {
"shasum": "c0a1d2f3a7092e03774bfa83f14c0fc5790a8667",
"tarball": "https://registry.npmjs.org/charenc/-/charenc-0.0.2.tgz"
},
"engines": {
"node": "*"
},
"gitHead": "01d66efb429d0cb242b2dd5af2ce338554fd3e54",
"homepage": "https://github.com/pvorb/node-charenc#readme",
"license": "BSD-3-Clause",
"main": "charenc.js",
"maintainers": [
{
"name": "pvorb",
"email": "paul@vorb.de"
}
],
"name": "charenc",
"optionalDependencies": {},
"readme": "ERROR: No README data found!",
"repository": {
"type": "git",
"url": "git://github.com/pvorb/node-charenc.git"
},
"scripts": {},
"tags": [
"utf8",
"binary",
"byte",
"string"
],
"version": "0.0.2"
}
**enc** provides crypto character encoding utilities.
{
"name": "bind",
"version": "1.0.0",
"description": "function binding utility",
"keywords": [
"bind",
"utility"
],
"dependencies": {},
"scripts": [
"index.js"
]
}

1.0.0 / 2014-05-27

  • index: use slice ref (#7, @viatropos)
  • package: rename package to "component-bind"
  • package: add "repository" field (#6, @repoify)
  • package: add "component" section

0.0.1 / 2010-01-03

  • Initial release
/**
* Slice reference.
*/
var slice = [].slice;
/**
* Bind `obj` to `fn`.
*
* @param {Object} obj
* @param {Function|String} fn or string
* @return {Function}
* @api public
*/
module.exports = function(obj, fn){
if ('string' == typeof fn) fn = obj[fn];
if ('function' != typeof fn) throw new Error('bind() requires a function');
var args = slice.call(arguments, 2);
return function(){
return fn.apply(obj, args.concat(slice.call(arguments)));
}
};
test:
@./node_modules/.bin/mocha \
--require should \
--reporter spec
.PHONY: test
{
"_args": [
[
{
"raw": "component-bind@1.0.0",
"scope": null,
"escapedName": "component-bind",
"name": "component-bind",
"rawSpec": "1.0.0",
"spec": "1.0.0",
"type": "version"
},
"C:\\xampp\\htdocs\\cafe\\node_modules\\socket.io-client"
]
],
"_from": "component-bind@1.0.0",
"_id": "component-bind@1.0.0",
"_inCache": true,
"_location": "/component-bind",
"_npmUser": {
"name": "tootallnate",
"email": "nathan@tootallnate.net"
},
"_npmVersion": "1.4.9",
"_phantomChildren": {},
"_requested": {
"raw": "component-bind@1.0.0",
"scope": null,
"escapedName": "component-bind",
"name": "component-bind",
"rawSpec": "1.0.0",
"spec": "1.0.0",
"type": "version"
},
"_requiredBy": [
"/socket.io-client"
],
"_resolved": "https://registry.npmjs.org/component-bind/-/component-bind-1.0.0.tgz",
"_shasum": "00c608ab7dcd93897c0009651b1d3a8e1e73bbd1",
"_shrinkwrap": null,
"_spec": "component-bind@1.0.0",
"_where": "C:\\xampp\\htdocs\\cafe\\node_modules\\socket.io-client",
"bugs": {
"url": "https://github.com/component/bind/issues"
},
"component": {
"scripts": {
"bind/index.js": "index.js"
}
},
"dependencies": {},
"description": "function binding utility",
"devDependencies": {
"mocha": "*",
"should": "*"
},
"directories": {},
"dist": {
"shasum": "00c608ab7dcd93897c0009651b1d3a8e1e73bbd1",
"tarball": "https://registry.npmjs.org/component-bind/-/component-bind-1.0.0.tgz"
},
"homepage": "https://github.com/component/bind",
"keywords": [
"bind",
"utility"
],
"maintainers": [
{
"name": "tootallnate",
"email": "nathan@tootallnate.net"
}
],
"name": "component-bind",
"optionalDependencies": {},
"readme": "ERROR: No README data found!",
"repository": {
"type": "git",
"url": "git+https://github.com/component/bind.git"
},
"version": "1.0.0"
}

bind

Function binding utility.

Installation

$ component install component/bind

API

bind(obj, fn)

should bind the function to the given object.

var tobi = { name: 'tobi' };

function name() {
  return this.name;
}

var fn = bind(tobi, name);
fn().should.equal('tobi');

bind(obj, fn, ...)

should curry the remaining arguments.

function add(a, b) {
  return a + b;
}

bind(null, add)(1, 2).should.equal(3);
bind(null, add, 1)(2).should.equal(3);
bind(null, add, 1, 2)().should.equal(3);

bind(obj, name)

should bind the method of the given name.

var tobi = { name: 'tobi' };

tobi.getName = function() {
  return this.name;
};

var fn = bind(tobi, 'getName');
fn().should.equal('tobi');

License

MIT

node_js:
- "0.8"
- "0.10"
language: node_js
{
"name": "emitter",
"description": "Event emitter",
"keywords": [
"emitter",
"events"
],
"version": "1.1.2",
"license": "MIT",
"main": "index.js",
"homepage": "https://github.com/component/emitter",
"ignore": [
"**/.*",
"node_modules",
"bower_components",
"test",
"Makefile",
"package.json",
"component.json"
]
}
{
"name": "emitter",
"repo": "component/emitter",
"description": "Event emitter",
"keywords": [
"emitter",
"events"
],
"version": "1.1.2",
"scripts": [
"index.js"
],
"license": "MIT"
}

1.1.2 / 2014-02-10

  • package: rename to "component-emitter"
  • package: update "main" and "component" fields
  • Add license to Readme (same format as the other components)
  • created .npmignore
  • travis stuff

1.1.1 / 2013-12-01

  • fix .once adding .on to the listener
  • docs: Emitter#off()
  • component: add .repo prop

1.1.0 / 2013-10-20

  • add .addEventListener() and .removeEventListener() aliases

1.0.1 / 2013-06-27

  • add support for legacy ie

1.0.0 / 2013-02-26

  • add .off() support for removing all listeners

0.0.6 / 2012-10-08

  • add this._callbacks initialization to prevent funky gotcha

0.0.5 / 2012-09-07

  • fix Emitter.call(this) usage

0.0.3 / 2012-07-11

  • add .listeners()
  • rename .has() to .hasListeners()

0.0.2 / 2012-06-28

  • fix .off() with .once()-registered callbacks
/**
* Expose `Emitter`.
*/
module.exports = Emitter;
/**
* Initialize a new `Emitter`.
*
* @api public
*/
function Emitter(obj) {
if (obj) return mixin(obj);
};
/**
* Mixin the emitter properties.
*
* @param {Object} obj
* @return {Object}
* @api private
*/
function mixin(obj) {
for (var key in Emitter.prototype) {
obj[key] = Emitter.prototype[key];
}
return obj;
}
/**
* Listen on the given `event` with `fn`.
*
* @param {String} event
* @param {Function} fn
* @return {Emitter}
* @api public
*/
Emitter.prototype.on =
Emitter.prototype.addEventListener = function(event, fn){
this._callbacks = this._callbacks || {};
(this._callbacks[event] = this._callbacks[event] || [])
.push(fn);
return this;
};
/**
* Adds an `event` listener that will be invoked a single
* time then automatically removed.
*
* @param {String} event
* @param {Function} fn
* @return {Emitter}
* @api public
*/
Emitter.prototype.once = function(event, fn){
var self = this;
this._callbacks = this._callbacks || {};
function on() {
self.off(event, on);
fn.apply(this, arguments);
}
on.fn = fn;
this.on(event, on);
return this;
};
/**
* Remove the given callback for `event` or all
* registered callbacks.
*
* @param {String} event
* @param {Function} fn
* @return {Emitter}
* @api public
*/
Emitter.prototype.off =
Emitter.prototype.removeListener =
Emitter.prototype.removeAllListeners =
Emitter.prototype.removeEventListener = function(event, fn){
this._callbacks = this._callbacks || {};
// all
if (0 == arguments.length) {
this._callbacks = {};
return this;
}
// specific event
var callbacks = this._callbacks[event];
if (!callbacks) return this;
// remove all handlers
if (1 == arguments.length) {
delete this._callbacks[event];
return this;
}
// remove specific handler
var cb;
for (var i = 0; i < callbacks.length; i++) {
cb = callbacks[i];
if (cb === fn || cb.fn === fn) {
callbacks.splice(i, 1);
break;
}
}
return this;
};
/**
* Emit `event` with the given args.
*
* @param {String} event
* @param {Mixed} ...
* @return {Emitter}
*/
Emitter.prototype.emit = function(event){
this._callbacks = this._callbacks || {};
var args = [].slice.call(arguments, 1)
, callbacks = this._callbacks[event];
if (callbacks) {
callbacks = callbacks.slice(0);
for (var i = 0, len = callbacks.length; i < len; ++i) {
callbacks[i].apply(this, args);
}
}
return this;
};
/**
* Return array of callbacks for `event`.
*
* @param {String} event
* @return {Array}
* @api public
*/
Emitter.prototype.listeners = function(event){
this._callbacks = this._callbacks || {};
return this._callbacks[event] || [];
};
/**
* Check if this emitter has `event` handlers.
*
* @param {String} event
* @return {Boolean}
* @api public
*/
Emitter.prototype.hasListeners = function(event){
return !! this.listeners(event).length;
};
test:
@./node_modules/.bin/mocha \
--require should \
--reporter spec
.PHONY: test
{
"_args": [
[
{
"raw": "component-emitter@1.1.2",
"scope": null,
"escapedName": "component-emitter",
"name": "component-emitter",
"rawSpec": "1.1.2",
"spec": "1.1.2",
"type": "version"
},
"C:\\xampp\\htdocs\\cafe\\node_modules\\socket.io-parser"
]
],
"_from": "component-emitter@1.1.2",
"_id": "component-emitter@1.1.2",
"_inCache": true,
"_location": "/component-emitter",
"_npmUser": {
"name": "tootallnate",
"email": "nathan@tootallnate.net"
},
"_npmVersion": "1.3.24",
"_phantomChildren": {},
"_requested": {
"raw": "component-emitter@1.1.2",
"scope": null,
"escapedName": "component-emitter",
"name": "component-emitter",
"rawSpec": "1.1.2",
"spec": "1.1.2",
"type": "version"
},
"_requiredBy": [
"/socket.io-parser"
],
"_resolved": "https://registry.npmjs.org/component-emitter/-/component-emitter-1.1.2.tgz",
"_shasum": "296594f2753daa63996d2af08d15a95116c9aec3",
"_shrinkwrap": null,
"_spec": "component-emitter@1.1.2",
"_where": "C:\\xampp\\htdocs\\cafe\\node_modules\\socket.io-parser",
"bugs": {
"url": "https://github.com/component/emitter/issues"
},
"component": {
"scripts": {
"emitter/index.js": "index.js"
}
},
"dependencies": {},
"description": "Event emitter",
"devDependencies": {
"mocha": "*",
"should": "*"
},
"directories": {},
"dist": {
"shasum": "296594f2753daa63996d2af08d15a95116c9aec3",
"tarball": "https://registry.npmjs.org/component-emitter/-/component-emitter-1.1.2.tgz"
},
"homepage": "https://github.com/component/emitter",
"main": "index.js",
"maintainers": [
{
"name": "tootallnate",
"email": "nathan@tootallnate.net"
}
],
"name": "component-emitter",
"optionalDependencies": {},
"readme": "ERROR: No README data found!",
"repository": {
"type": "git",
"url": "git+https://github.com/component/emitter.git"
},
"scripts": {
"test": "make test"
},
"version": "1.1.2"
}

Emitter Build Status

Event emitter component.

Installation

$ component install component/emitter

API

Emitter(obj)

The Emitter may also be used as a mixin. For example a "plain" object may become an emitter, or you may extend an existing prototype.

As an Emitter instance:

var Emitter = require('emitter');
var emitter = new Emitter;
emitter.emit('something');

As a mixin:

var Emitter = require('emitter');
var user = { name: 'tobi' };
Emitter(user);

user.emit('im a user');

As a prototype mixin:

var Emitter = require('emitter');
Emitter(User.prototype);

Emitter#on(event, fn)

Register an event handler fn.

Emitter#once(event, fn)

Register a single-shot event handler fn, removed immediately after it is invoked the first time.

Emitter#off(event, fn)

  • Pass event and fn to remove a listener.
  • Pass event to remove all listeners on that event.
  • Pass nothing to remove all listeners on all events.

Emitter#emit(event, ...)

Emit an event with variable option args.

Emitter#listeners(event)

Return an array of callbacks, or an empty array.

Emitter#hasListeners(event)

Check if this emitter has event handlers.

License

MIT

{
"name": "inherit",
"description": "Prototype inheritance utility",
"version": "0.0.3",
"keywords": ["inherit", "utility"],
"dependencies": {},
"scripts": [
"index.js"
]
}

0.0.2 / 2012-09-03

  • fix typo in package.json
module.exports = function(a, b){
var fn = function(){};
fn.prototype = b.prototype;
a.prototype = new fn;
a.prototype.constructor = a;
};
build: components index.js
@component build
components:
@Component install
clean:
rm -fr build components template.js
test:
@node_modules/.bin/mocha \
--require should \
--reporter spec
.PHONY: clean test
{
"_args": [
[
{
"raw": "component-inherit@0.0.3",
"scope": null,
"escapedName": "component-inherit",
"name": "component-inherit",
"rawSpec": "0.0.3",
"spec": "0.0.3",
"type": "version"
},
"C:\\xampp\\htdocs\\cafe\\node_modules\\engine.io-client"
]
],
"_from": "component-inherit@0.0.3",
"_id": "component-inherit@0.0.3",
"_inCache": true,
"_location": "/component-inherit",
"_npmUser": {
"name": "coreh",
"email": "thecoreh@gmail.com"
},
"_npmVersion": "1.3.24",
"_phantomChildren": {},
"_requested": {
"raw": "component-inherit@0.0.3",
"scope": null,
"escapedName": "component-inherit",
"name": "component-inherit",
"rawSpec": "0.0.3",
"spec": "0.0.3",
"type": "version"
},
"_requiredBy": [
"/engine.io-client"
],
"_resolved": "https://registry.npmjs.org/component-inherit/-/component-inherit-0.0.3.tgz",
"_shasum": "645fc4adf58b72b649d5cae65135619db26ff143",
"_shrinkwrap": null,
"_spec": "component-inherit@0.0.3",
"_where": "C:\\xampp\\htdocs\\cafe\\node_modules\\engine.io-client",
"bugs": {
"url": "https://github.com/component/inherit/issues"
},
"component": {
"scripts": {
"inherit/index.js": "index.js"
}
},
"dependencies": {},
"description": "Prototype inheritance utility",
"devDependencies": {},
"directories": {},
"dist": {
"shasum": "645fc4adf58b72b649d5cae65135619db26ff143",
"tarball": "https://registry.npmjs.org/component-inherit/-/component-inherit-0.0.3.tgz"
},
"homepage": "https://github.com/component/inherit",
"keywords": [
"inherit",
"utility"
],
"maintainers": [
{
"name": "coreh",
"email": "thecoreh@gmail.com"
}
],
"name": "component-inherit",
"optionalDependencies": {},
"readme": "ERROR: No README data found!",
"repository": {
"type": "git",
"url": "git+https://github.com/component/inherit.git"
},
"version": "0.0.3"
}

inherit

Prototype inheritance utility.

Installation

$ component install component/inherit

Example

var inherit = require('inherit');

function Human() {}
function Woman() {}

inherit(Woman, Human);

License

MIT

/**
* Module dependencies.
*/
var inherit = require('..');
describe('inherit(a, b)', function(){
it('should inherit b\'s prototype', function(){
function Loki(){}
function Animal(){}
Animal.prototype.species = 'unknown';
inherit(Loki, Animal);
var loki = new Loki;
loki.species.should.equal('unknown');
loki.constructor.should.equal(Loki);
})
})

0.5.2 / 2016-12-08

  • Fix parse to accept any linear whitespace character

0.5.1 / 2016-01-17

  • perf: enable strict mode

0.5.0 / 2014-10-11

  • Add parse function

0.4.0 / 2014-09-21

  • Expand non-Unicode filename to the full ISO-8859-1 charset

0.3.0 / 2014-09-20

  • Add fallback option
  • Add type option

0.2.0 / 2014-09-19

  • Reduce ambiguity of file names with hex escape in buggy browsers

0.1.2 / 2014-09-19

  • Fix periodic invalid Unicode filename header

0.1.1 / 2014-09-19

  • Fix invalid characters appearing in filename* parameter

0.1.0 / 2014-09-18

  • Make the filename argument optional

0.0.0 / 2014-09-18

  • Initial release
/*!
* content-disposition
* Copyright(c) 2014 Douglas Christopher Wilson
* MIT Licensed
*/
'use strict'
/**
* Module exports.
*/
module.exports = contentDisposition
module.exports.parse = parse
/**
* Module dependencies.
*/
var basename = require('path').basename
/**
* RegExp to match non attr-char, *after* encodeURIComponent (i.e. not including "%")
*/
var ENCODE_URL_ATTR_CHAR_REGEXP = /[\x00-\x20"'()*,/:;<=>?@[\\\]{}\x7f]/g // eslint-disable-line no-control-regex
/**
* RegExp to match percent encoding escape.
*/
var HEX_ESCAPE_REGEXP = /%[0-9A-Fa-f]{2}/
var HEX_ESCAPE_REPLACE_REGEXP = /%([0-9A-Fa-f]{2})/g
/**
* RegExp to match non-latin1 characters.
*/
var NON_LATIN1_REGEXP = /[^\x20-\x7e\xa0-\xff]/g
/**
* RegExp to match quoted-pair in RFC 2616
*
* quoted-pair = "\" CHAR
* CHAR = <any US-ASCII character (octets 0 - 127)>
*/
var QESC_REGEXP = /\\([\u0000-\u007f])/g
/**
* RegExp to match chars that must be quoted-pair in RFC 2616
*/
var QUOTE_REGEXP = /([\\"])/g
/**
* RegExp for various RFC 2616 grammar
*
* parameter = token "=" ( token | quoted-string )
* token = 1*<any CHAR except CTLs or separators>
* separators = "(" | ")" | "<" | ">" | "@"
* | "," | ";" | ":" | "\" | <">
* | "/" | "[" | "]" | "?" | "="
* | "{" | "}" | SP | HT
* quoted-string = ( <"> *(qdtext | quoted-pair ) <"> )
* qdtext = <any TEXT except <">>
* quoted-pair = "\" CHAR
* CHAR = <any US-ASCII character (octets 0 - 127)>
* TEXT = <any OCTET except CTLs, but including LWS>
* LWS = [CRLF] 1*( SP | HT )
* CRLF = CR LF
* CR = <US-ASCII CR, carriage return (13)>
* LF = <US-ASCII LF, linefeed (10)>
* SP = <US-ASCII SP, space (32)>
* HT = <US-ASCII HT, horizontal-tab (9)>
* CTL = <any US-ASCII control character (octets 0 - 31) and DEL (127)>
* OCTET = <any 8-bit sequence of data>
*/
var PARAM_REGEXP = /;[\x09\x20]*([!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*=[\x09\x20]*("(?:[\x20!\x23-\x5b\x5d-\x7e\x80-\xff]|\\[\x20-\x7e])*"|[!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*/g // eslint-disable-line no-control-regex
var TEXT_REGEXP = /^[\x20-\x7e\x80-\xff]+$/
var TOKEN_REGEXP = /^[!#$%&'*+.0-9A-Z^_`a-z|~-]+$/
/**
* RegExp for various RFC 5987 grammar
*
* ext-value = charset "'" [ language ] "'" value-chars
* charset = "UTF-8" / "ISO-8859-1" / mime-charset
* mime-charset = 1*mime-charsetc
* mime-charsetc = ALPHA / DIGIT
* / "!" / "#" / "$" / "%" / "&"
* / "+" / "-" / "^" / "_" / "`"
* / "{" / "}" / "~"
* language = ( 2*3ALPHA [ extlang ] )
* / 4ALPHA
* / 5*8ALPHA
* extlang = *3( "-" 3ALPHA )
* value-chars = *( pct-encoded / attr-char )
* pct-encoded = "%" HEXDIG HEXDIG
* attr-char = ALPHA / DIGIT
* / "!" / "#" / "$" / "&" / "+" / "-" / "."
* / "^" / "_" / "`" / "|" / "~"
*/
var EXT_VALUE_REGEXP = /^([A-Za-z0-9!#$%&+\-^_`{}~]+)'(?:[A-Za-z]{2,3}(?:-[A-Za-z]{3}){0,3}|[A-Za-z]{4,8}|)'((?:%[0-9A-Fa-f]{2}|[A-Za-z0-9!#$&+.^_`|~-])+)$/
/**
* RegExp for various RFC 6266 grammar
*
* disposition-type = "inline" | "attachment" | disp-ext-type
* disp-ext-type = token
* disposition-parm = filename-parm | disp-ext-parm
* filename-parm = "filename" "=" value
* | "filename*" "=" ext-value
* disp-ext-parm = token "=" value
* | ext-token "=" ext-value
* ext-token = <the characters in token, followed by "*">
*/
var DISPOSITION_TYPE_REGEXP = /^([!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*(?:$|;)/ // eslint-disable-line no-control-regex
/**
* Create an attachment Content-Disposition header.
*
* @param {string} [filename]
* @param {object} [options]
* @param {string} [options.type=attachment]
* @param {string|boolean} [options.fallback=true]
* @return {string}
* @api public
*/
function contentDisposition (filename, options) {
var opts = options || {}
// get type
var type = opts.type || 'attachment'
// get parameters
var params = createparams(filename, opts.fallback)
// format into string
return format(new ContentDisposition(type, params))
}
/**
* Create parameters object from filename and fallback.
*
* @param {string} [filename]
* @param {string|boolean} [fallback=true]
* @return {object}
* @api private
*/
function createparams (filename, fallback) {
if (filename === undefined) {
return
}
var params = {}
if (typeof filename !== 'string') {
throw new TypeError('filename must be a string')
}
// fallback defaults to true
if (fallback === undefined) {
fallback = true
}
if (typeof fallback !== 'string' && typeof fallback !== 'boolean') {
throw new TypeError('fallback must be a string or boolean')
}
if (typeof fallback === 'string' && NON_LATIN1_REGEXP.test(fallback)) {
throw new TypeError('fallback must be ISO-8859-1 string')
}
// restrict to file base name
var name = basename(filename)
// determine if name is suitable for quoted string
var isQuotedString = TEXT_REGEXP.test(name)
// generate fallback name
var fallbackName = typeof fallback !== 'string'
? fallback && getlatin1(name)
: basename(fallback)
var hasFallback = typeof fallbackName === 'string' && fallbackName !== name
// set extended filename parameter
if (hasFallback || !isQuotedString || HEX_ESCAPE_REGEXP.test(name)) {
params['filename*'] = name
}
// set filename parameter
if (isQuotedString || hasFallback) {
params.filename = hasFallback
? fallbackName
: name
}
return params
}
/**
* Format object to Content-Disposition header.
*
* @param {object} obj
* @param {string} obj.type
* @param {object} [obj.parameters]
* @return {string}
* @api private
*/
function format (obj) {
var parameters = obj.parameters
var type = obj.type
if (!type || typeof type !== 'string' || !TOKEN_REGEXP.test(type)) {
throw new TypeError('invalid type')
}
// start with normalized type
var string = String(type).toLowerCase()
// append parameters
if (parameters && typeof parameters === 'object') {
var param
var params = Object.keys(parameters).sort()
for (var i = 0; i < params.length; i++) {
param = params[i]
var val = param.substr(-1) === '*'
? ustring(parameters[param])
: qstring(parameters[param])
string += '; ' + param + '=' + val
}
}
return string
}
/**
* Decode a RFC 6987 field value (gracefully).
*
* @param {string} str
* @return {string}
* @api private
*/
function decodefield (str) {
var match = EXT_VALUE_REGEXP.exec(str)
if (!match) {
throw new TypeError('invalid extended field value')
}
var charset = match[1].toLowerCase()
var encoded = match[2]
var value
// to binary string
var binary = encoded.replace(HEX_ESCAPE_REPLACE_REGEXP, pdecode)
switch (charset) {
case 'iso-8859-1':
value = getlatin1(binary)
break
case 'utf-8':
value = new Buffer(binary, 'binary').toString('utf8')
break
default:
throw new TypeError('unsupported charset in extended field')
}
return value
}
/**
* Get ISO-8859-1 version of string.
*
* @param {string} val
* @return {string}
* @api private
*/
function getlatin1 (val) {
// simple Unicode -> ISO-8859-1 transformation
return String(val).replace(NON_LATIN1_REGEXP, '?')
}
/**
* Parse Content-Disposition header string.
*
* @param {string} string
* @return {object}
* @api private
*/
function parse (string) {
if (!string || typeof string !== 'string') {
throw new TypeError('argument string is required')
}
var match = DISPOSITION_TYPE_REGEXP.exec(string)
if (!match) {
throw new TypeError('invalid type format')
}
// normalize type
var index = match[0].length
var type = match[1].toLowerCase()
var key
var names = []
var params = {}
var value
// calculate index to start at
index = PARAM_REGEXP.lastIndex = match[0].substr(-1) === ';'
? index - 1
: index
// match parameters
while ((match = PARAM_REGEXP.exec(string))) {
if (match.index !== index) {
throw new TypeError('invalid parameter format')
}
index += match[0].length
key = match[1].toLowerCase()
value = match[2]
if (names.indexOf(key) !== -1) {
throw new TypeError('invalid duplicate parameter')
}
names.push(key)
if (key.indexOf('*') + 1 === key.length) {
// decode extended value
key = key.slice(0, -1)
value = decodefield(value)
// overwrite existing value
params[key] = value
continue
}
if (typeof params[key] === 'string') {
continue
}
if (value[0] === '"') {
// remove quotes and escapes
value = value
.substr(1, value.length - 2)
.replace(QESC_REGEXP, '$1')
}
params[key] = value
}
if (index !== -1 && index !== string.length) {
throw new TypeError('invalid parameter format')
}
return new ContentDisposition(type, params)
}
/**
* Percent decode a single character.
*
* @param {string} str
* @param {string} hex
* @return {string}
* @api private
*/
function pdecode (str, hex) {
return String.fromCharCode(parseInt(hex, 16))
}
/**
* Percent encode a single character.
*
* @param {string} char
* @return {string}
* @api private
*/
function pencode (char) {
var hex = String(char)
.charCodeAt(0)
.toString(16)
.toUpperCase()
return hex.length === 1
? '%0' + hex
: '%' + hex
}
/**
* Quote a string for HTTP.
*
* @param {string} val
* @return {string}
* @api private
*/
function qstring (val) {
var str = String(val)
return '"' + str.replace(QUOTE_REGEXP, '\\$1') + '"'
}
/**
* Encode a Unicode string for HTTP (RFC 5987).
*
* @param {string} val
* @return {string}
* @api private
*/
function ustring (val) {
var str = String(val)
// percent encode as UTF-8
var encoded = encodeURIComponent(str)
.replace(ENCODE_URL_ATTR_CHAR_REGEXP, pencode)
return 'UTF-8\'\'' + encoded
}
/**
* Class for parsed Content-Disposition header for v8 optimization
*/
function ContentDisposition (type, parameters) {
this.type = type
this.parameters = parameters
}
(The MIT License)
Copyright (c) 2014 Douglas Christopher Wilson
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.
{
"_args": [
[
{
"raw": "content-disposition@0.5.2",
"scope": null,
"escapedName": "content-disposition",
"name": "content-disposition",
"rawSpec": "0.5.2",
"spec": "0.5.2",
"type": "version"
},
"C:\\xampp\\htdocs\\cafe\\node_modules\\express"
]
],
"_from": "content-disposition@0.5.2",
"_id": "content-disposition@0.5.2",
"_inCache": true,
"_location": "/content-disposition",
"_nodeVersion": "4.6.0",
"_npmOperationalInternal": {
"host": "packages-18-east.internal.npmjs.com",
"tmp": "tmp/content-disposition-0.5.2.tgz_1481246224565_0.35659545403905213"
},
"_npmUser": {
"name": "dougwilson",
"email": "doug@somethingdoug.com"
},
"_npmVersion": "2.15.9",
"_phantomChildren": {},
"_requested": {
"raw": "content-disposition@0.5.2",
"scope": null,
"escapedName": "content-disposition",
"name": "content-disposition",
"rawSpec": "0.5.2",
"spec": "0.5.2",
"type": "version"
},
"_requiredBy": [
"/express"
],
"_resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.2.tgz",
"_shasum": "0cf68bb9ddf5f2be7961c3a85178cb85dba78cb4",
"_shrinkwrap": null,
"_spec": "content-disposition@0.5.2",
"_where": "C:\\xampp\\htdocs\\cafe\\node_modules\\express",
"bugs": {
"url": "https://github.com/jshttp/content-disposition/issues"
},
"contributors": [
{
"name": "Douglas Christopher Wilson",
"email": "doug@somethingdoug.com"
}
],
"dependencies": {},
"description": "Create and parse Content-Disposition header",
"devDependencies": {
"eslint": "3.11.1",
"eslint-config-standard": "6.2.1",
"eslint-plugin-promise": "3.3.0",
"eslint-plugin-standard": "2.0.1",
"istanbul": "0.4.5",
"mocha": "1.21.5"
},
"directories": {},
"dist": {
"shasum": "0cf68bb9ddf5f2be7961c3a85178cb85dba78cb4",
"tarball": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.2.tgz"
},
"engines": {
"node": ">= 0.6"
},
"files": [
"LICENSE",
"HISTORY.md",
"README.md",
"index.js"
],
"gitHead": "2a08417377cf55678c9f870b305f3c6c088920f3",
"homepage": "https://github.com/jshttp/content-disposition#readme",
"keywords": [
"content-disposition",
"http",
"rfc6266",
"res"
],
"license": "MIT",
"maintainers": [
{
"name": "dougwilson",
"email": "doug@somethingdoug.com"
}
],
"name": "content-disposition",
"optionalDependencies": {},
"readme": "ERROR: No README data found!",
"repository": {
"type": "git",
"url": "git+https://github.com/jshttp/content-disposition.git"
},
"scripts": {
"lint": "eslint .",
"test": "mocha --reporter spec --bail --check-leaks test/",
"test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/",
"test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/"
},
"version": "0.5.2"
}

content-disposition

NPM Version NPM Downloads Node.js Version Build Status Test Coverage

Create and parse HTTP Content-Disposition header

Installation

$ npm install content-disposition

API

var contentDisposition = require('content-disposition')

contentDisposition(filename, options)

Create an attachment Content-Disposition header value using the given file name, if supplied. The filename is optional and if no file name is desired, but you want to specify options, set filename to undefined.

res.setHeader('Content-Disposition', contentDisposition('∫ maths.pdf'))

note HTTP headers are of the ISO-8859-1 character set. If you are writing this header through a means different from setHeader in Node.js, you'll want to specify the 'binary' encoding in Node.js.

Options

contentDisposition accepts these properties in the options object.

fallback

If the filename option is outside ISO-8859-1, then the file name is actually stored in a supplemental field for clients that support Unicode file names and a ISO-8859-1 version of the file name is automatically generated.

This specifies the ISO-8859-1 file name to override the automatic generation or disables the generation all together, defaults to true.

  • A string will specify the ISO-8859-1 file name to use in place of automatic generation.
  • false will disable including a ISO-8859-1 file name and only include the Unicode version (unless the file name is already ISO-8859-1).
  • true will enable automatic generation if the file name is outside ISO-8859-1.

If the filename option is ISO-8859-1 and this option is specified and has a different value, then the filename option is encoded in the extended field and this set as the fallback field, even though they are both ISO-8859-1.

type

Specifies the disposition type, defaults to "attachment". This can also be "inline", or any other value (all values except inline are treated like attachment, but can convey additional information if both parties agree to it). The type is normalized to lower-case.

contentDisposition.parse(string)

var disposition = contentDisposition.parse('attachment; filename="EURO rates.txt"; filename*=UTF-8\'\'%e2%82%ac%20rates.txt');

Parse a Content-Disposition header string. This automatically handles extended ("Unicode") parameters by decoding them and providing them under the standard parameter name. This will return an object with the following properties (examples are shown for the string 'attachment; filename="EURO rates.txt"; filename*=UTF-8\'\'%e2%82%ac%20rates.txt'):

  • type: The disposition type (always lower case). Example: 'attachment'

  • parameters: An object of the parameters in the disposition (name of parameter always lower case and extended versions replace non-extended versions). Example: {filename: "€ rates.txt"}

Examples

Send a file for download

var contentDisposition = require('content-disposition')
var destroy = require('destroy')
var http = require('http')
var onFinished = require('on-finished')

var filePath = '/path/to/public/plans.pdf'

http.createServer(function onRequest(req, res) {
  // set headers
  res.setHeader('Content-Type', 'application/pdf')
  res.setHeader('Content-Disposition', contentDisposition(filePath))

  // send file
  var stream = fs.createReadStream(filePath)
  stream.pipe(res)
  onFinished(res, function (err) {
    destroy(stream)
  })
})

Testing

$ npm test

References

License

MIT

1.0.2 / 2016-05-09

  • perf: enable strict mode

1.0.1 / 2015-02-13

  • Improve missing Content-Type header error message

1.0.0 / 2015-02-01

  • Initial implementation, derived from media-typer@0.3.0
/*!
* content-type
* Copyright(c) 2015 Douglas Christopher Wilson
* MIT Licensed
*/
'use strict'
/**
* RegExp to match *( ";" parameter ) in RFC 7231 sec 3.1.1.1
*
* parameter = token "=" ( token / quoted-string )
* token = 1*tchar
* tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*"
* / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~"
* / DIGIT / ALPHA
* ; any VCHAR, except delimiters
* quoted-string = DQUOTE *( qdtext / quoted-pair ) DQUOTE
* qdtext = HTAB / SP / %x21 / %x23-5B / %x5D-7E / obs-text
* obs-text = %x80-FF
* quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text )
*/
var paramRegExp = /; *([!#$%&'\*\+\-\.\^_`\|~0-9A-Za-z]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'\*\+\-\.\^_`\|~0-9A-Za-z]+) */g
var textRegExp = /^[\u000b\u0020-\u007e\u0080-\u00ff]+$/
var tokenRegExp = /^[!#$%&'\*\+\-\.\^_`\|~0-9A-Za-z]+$/
/**
* RegExp to match quoted-pair in RFC 7230 sec 3.2.6
*
* quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text )
* obs-text = %x80-FF
*/
var qescRegExp = /\\([\u000b\u0020-\u00ff])/g
/**
* RegExp to match chars that must be quoted-pair in RFC 7230 sec 3.2.6
*/
var quoteRegExp = /([\\"])/g
/**
* RegExp to match type in RFC 6838
*
* media-type = type "/" subtype
* type = token
* subtype = token
*/
var typeRegExp = /^[!#$%&'\*\+\-\.\^_`\|~0-9A-Za-z]+\/[!#$%&'\*\+\-\.\^_`\|~0-9A-Za-z]+$/
/**
* Module exports.
* @public
*/
exports.format = format
exports.parse = parse
/**
* Format object to media type.
*
* @param {object} obj
* @return {string}
* @public
*/
function format(obj) {
if (!obj || typeof obj !== 'object') {
throw new TypeError('argument obj is required')
}
var parameters = obj.parameters
var type = obj.type
if (!type || !typeRegExp.test(type)) {
throw new TypeError('invalid type')
}
var string = type
// append parameters
if (parameters && typeof parameters === 'object') {
var param
var params = Object.keys(parameters).sort()
for (var i = 0; i < params.length; i++) {
param = params[i]
if (!tokenRegExp.test(param)) {
throw new TypeError('invalid parameter name')
}
string += '; ' + param + '=' + qstring(parameters[param])
}
}
return string
}
/**
* Parse media type to object.
*
* @param {string|object} string
* @return {Object}
* @public
*/
function parse(string) {
if (!string) {
throw new TypeError('argument string is required')
}
if (typeof string === 'object') {
// support req/res-like objects as argument
string = getcontenttype(string)
if (typeof string !== 'string') {
throw new TypeError('content-type header is missing from object');
}
}
if (typeof string !== 'string') {
throw new TypeError('argument string is required to be a string')
}
var index = string.indexOf(';')
var type = index !== -1
? string.substr(0, index).trim()
: string.trim()
if (!typeRegExp.test(type)) {
throw new TypeError('invalid media type')
}
var key
var match
var obj = new ContentType(type.toLowerCase())
var value
paramRegExp.lastIndex = index
while (match = paramRegExp.exec(string)) {
if (match.index !== index) {
throw new TypeError('invalid parameter format')
}
index += match[0].length
key = match[1].toLowerCase()
value = match[2]
if (value[0] === '"') {
// remove quotes and escapes
value = value
.substr(1, value.length - 2)
.replace(qescRegExp, '$1')
}
obj.parameters[key] = value
}
if (index !== -1 && index !== string.length) {
throw new TypeError('invalid parameter format')
}
return obj
}
/**
* Get content-type from req/res objects.
*
* @param {object}
* @return {Object}
* @private
*/
function getcontenttype(obj) {
if (typeof obj.getHeader === 'function') {
// res-like
return obj.getHeader('content-type')
}
if (typeof obj.headers === 'object') {
// req-like
return obj.headers && obj.headers['content-type']
}
}
/**
* Quote a string if necessary.
*
* @param {string} val
* @return {string}
* @private
*/
function qstring(val) {
var str = String(val)
// no need to quote tokens
if (tokenRegExp.test(str)) {
return str
}
if (str.length > 0 && !textRegExp.test(str)) {
throw new TypeError('invalid parameter value')
}
return '"' + str.replace(quoteRegExp, '\\$1') + '"'
}
/**
* Class to represent a content type.
* @private
*/
function ContentType(type) {
this.parameters = Object.create(null)
this.type = type
}
(The MIT License)
Copyright (c) 2015 Douglas Christopher Wilson
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.
{
"_args": [
[
{
"raw": "content-type@~1.0.2",
"scope": null,
"escapedName": "content-type",
"name": "content-type",
"rawSpec": "~1.0.2",
"spec": ">=1.0.2 <1.1.0",
"type": "range"
},
"C:\\xampp\\htdocs\\cafe\\node_modules\\express"
]
],
"_from": "content-type@>=1.0.2 <1.1.0",
"_id": "content-type@1.0.2",
"_inCache": true,
"_location": "/content-type",
"_nodeVersion": "4.4.3",
"_npmOperationalInternal": {
"host": "packages-12-west.internal.npmjs.com",
"tmp": "tmp/content-type-1.0.2.tgz_1462852785748_0.5491233412176371"
},
"_npmUser": {
"name": "dougwilson",
"email": "doug@somethingdoug.com"
},
"_npmVersion": "2.15.1",
"_phantomChildren": {},
"_requested": {
"raw": "content-type@~1.0.2",
"scope": null,
"escapedName": "content-type",
"name": "content-type",
"rawSpec": "~1.0.2",
"spec": ">=1.0.2 <1.1.0",
"type": "range"
},
"_requiredBy": [
"/express"
],
"_resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.2.tgz",
"_shasum": "b7d113aee7a8dd27bd21133c4dc2529df1721eed",
"_shrinkwrap": null,
"_spec": "content-type@~1.0.2",
"_where": "C:\\xampp\\htdocs\\cafe\\node_modules\\express",
"author": {
"name": "Douglas Christopher Wilson",
"email": "doug@somethingdoug.com"
},
"bugs": {
"url": "https://github.com/jshttp/content-type/issues"
},
"dependencies": {},
"description": "Create and parse HTTP Content-Type header",
"devDependencies": {
"istanbul": "0.4.3",
"mocha": "~1.21.5"
},
"directories": {},
"dist": {
"shasum": "b7d113aee7a8dd27bd21133c4dc2529df1721eed",
"tarball": "https://registry.npmjs.org/content-type/-/content-type-1.0.2.tgz"
},
"engines": {
"node": ">= 0.6"
},
"files": [
"LICENSE",
"HISTORY.md",
"README.md",
"index.js"
],
"gitHead": "8118763adfbbac80cf1254191889330aec8b8be7",
"homepage": "https://github.com/jshttp/content-type#readme",
"keywords": [
"content-type",
"http",
"req",
"res",
"rfc7231"
],
"license": "MIT",
"maintainers": [
{
"name": "dougwilson",
"email": "doug@somethingdoug.com"
}
],
"name": "content-type",
"optionalDependencies": {},
"readme": "ERROR: No README data found!",
"repository": {
"type": "git",
"url": "git+https://github.com/jshttp/content-type.git"
},
"scripts": {
"test": "mocha --reporter spec --check-leaks --bail test/",
"test-ci": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/",
"test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/"
},
"version": "1.0.2"
}

content-type

NPM Version NPM Downloads Node.js Version Build Status Test Coverage

Create and parse HTTP Content-Type header according to RFC 7231

Installation

$ npm install content-type

API

var contentType = require('content-type')

contentType.parse(string)

var obj = contentType.parse('image/svg+xml; charset=utf-8')

Parse a content type string. This will return an object with the following properties (examples are shown for the string 'image/svg+xml; charset=utf-8'):

  • type: The media type (the type and subtype, always lower case). Example: 'image/svg+xml'

  • parameters: An object of the parameters in the media type (name of parameter always lower case). Example: {charset: 'utf-8'}

Throws a TypeError if the string is missing or invalid.

contentType.parse(req)

var obj = contentType.parse(req)

Parse the content-type header from the given req. Short-cut for contentType.parse(req.headers['content-type']).

Throws a TypeError if the Content-Type header is missing or invalid.

contentType.parse(res)

var obj = contentType.parse(res)

Parse the content-type header set on the given res. Short-cut for contentType.parse(res.getHeader('content-type')).

Throws a TypeError if the Content-Type header is missing or invalid.

contentType.format(obj)

var str = contentType.format({type: 'image/svg+xml'})

Format an object into a content type string. This will return a string of the content type for the given object with the following properties (examples are shown that produce the string 'image/svg+xml; charset=utf-8'):

  • type: The media type (will be lower-cased). Example: 'image/svg+xml'

  • parameters: An object of the parameters in the media type (name of the parameter will be lower-cased). Example: {charset: 'utf-8'}

Throws a TypeError if the object contains an invalid type or parameter names.

License

MIT

diff --git a/lib/util.js b/lib/util.js
index a03e874..9074e8e 100644
--- a/lib/util.js
+++ b/lib/util.js
@@ -19,430 +19,6 @@
// 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);
- }
-
- // 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)) {
- // Format -0 as '-0'. Strict equality won't distinguish 0 from -0,
- // so instead we use the fact that 1 / -0 < 0 whereas 1 / 0 > 0 .
- if (value === 0 && 1 / value < 0)
- return ctx.stylize('-0', 'number');
- 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) {
@@ -522,166 +98,10 @@ function isPrimitive(arg) {
exports.isPrimitive = isPrimitive;
function isBuffer(arg) {
- return arg instanceof Buffer;
+ return Buffer.isBuffer(arg);
}
exports.isBuffer = 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 = function(ctor, superCtor) {
- ctor.super_ = superCtor;
- ctor.prototype = Object.create(superCtor.prototype, {
- constructor: {
- value: ctor,
- enumerable: false,
- writable: true,
- configurable: true
- }
- });
-};
-
-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);
-}
-
-
-// Deprecated old stuff.
-
-exports.p = exports.deprecate(function() {
- for (var i = 0, len = arguments.length; i < len; ++i) {
- console.error(exports.inspect(arguments[i]));
- }
-}, 'util.p: Use console.error() instead');
-
-
-exports.exec = exports.deprecate(function() {
- return require('child_process').exec.apply(this, arguments);
-}, 'util.exec is now called `child_process.exec`.');
-
-
-exports.print = exports.deprecate(function() {
- for (var i = 0, len = arguments.length; i < len; ++i) {
- process.stdout.write(String(arguments[i]));
- }
-}, 'util.print: Use console.log instead');
-
-
-exports.puts = exports.deprecate(function() {
- for (var i = 0, len = arguments.length; i < len; ++i) {
- process.stdout.write(arguments[i] + '\n');
- }
-}, 'util.puts: Use console.log instead');
-
-
-exports.debug = exports.deprecate(function(x) {
- process.stderr.write('DEBUG: ' + x + '\n');
-}, 'util.debug: Use console.error instead');
-
-
-exports.error = exports.deprecate(function(x) {
- for (var i = 0, len = arguments.length; i < len; ++i) {
- process.stderr.write(arguments[i] + '\n');
- }
-}, 'util.error: Use console.error instead');
-
-
-exports.pump = exports.deprecate(function(readStream, writeStream, callback) {
- var callbackCalled = false;
-
- function call(a, b, c) {
- if (callback && !callbackCalled) {
- callback(a, b, c);
- callbackCalled = true;
- }
- }
-
- readStream.addListener('data', function(chunk) {
- if (writeStream.write(chunk) === false) readStream.pause();
- });
-
- writeStream.addListener('drain', function() {
- readStream.resume();
- });
-
- readStream.addListener('end', function() {
- writeStream.end();
- });
-
- readStream.addListener('close', function() {
- call();
- });
-
- readStream.addListener('error', function(err) {
- writeStream.end();
- call(err);
- });
-
- writeStream.addListener('error', function(err) {
- readStream.destroy();
- call(err);
- });
-}, 'util.pump(): Use readableStream.pipe() instead');
-
-
-var uv;
-exports._errnoException = function(err, syscall) {
- if (isUndefined(uv)) uv = process.binding('uv');
- var errname = uv.errname(err);
- var e = new Error(syscall + ' ' + errname);
- e.code = errname;
- e.errno = errname;
- e.syscall = syscall;
- return e;
-};
+}
// 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(arg) {
if (Array.isArray) {
return Array.isArray(arg);
}
return objectToString(arg) === '[object Array]';
}
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 objectToString(re) === '[object RegExp]';
}
exports.isRegExp = isRegExp;
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
exports.isObject = isObject;
function isDate(d) {
return objectToString(d) === '[object Date]';
}
exports.isDate = isDate;
function isError(e) {
return (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 = Buffer.isBuffer;
function objectToString(o) {
return Object.prototype.toString.call(o);
}
Copyright Node.js contributors. All rights reserved.
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.
{
"_args": [
[
{
"raw": "core-util-is@~1.0.0",
"scope": null,
"escapedName": "core-util-is",
"name": "core-util-is",
"rawSpec": "~1.0.0",
"spec": ">=1.0.0 <1.1.0",
"type": "range"
},
"C:\\xampp\\htdocs\\cafe\\node_modules\\readable-stream"
]
],
"_from": "core-util-is@>=1.0.0 <1.1.0",
"_id": "core-util-is@1.0.2",
"_inCache": true,
"_location": "/core-util-is",
"_nodeVersion": "4.0.0",
"_npmUser": {
"name": "isaacs",
"email": "i@izs.me"
},
"_npmVersion": "3.3.2",
"_phantomChildren": {},
"_requested": {
"raw": "core-util-is@~1.0.0",
"scope": null,
"escapedName": "core-util-is",
"name": "core-util-is",
"rawSpec": "~1.0.0",
"spec": ">=1.0.0 <1.1.0",
"type": "range"
},
"_requiredBy": [
"/readable-stream"
],
"_resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz",
"_shasum": "b5fd54220aa2bc5ab57aab7140c940754503c1a7",
"_shrinkwrap": null,
"_spec": "core-util-is@~1.0.0",
"_where": "C:\\xampp\\htdocs\\cafe\\node_modules\\readable-stream",
"author": {
"name": "Isaac Z. Schlueter",
"email": "i@izs.me",
"url": "http://blog.izs.me/"
},
"bugs": {
"url": "https://github.com/isaacs/core-util-is/issues"
},
"dependencies": {},
"description": "The `util.is*` functions introduced in Node v0.12.",
"devDependencies": {
"tap": "^2.3.0"
},
"directories": {},
"dist": {
"shasum": "b5fd54220aa2bc5ab57aab7140c940754503c1a7",
"tarball": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz"
},
"gitHead": "a177da234df5638b363ddc15fa324619a38577c8",
"homepage": "https://github.com/isaacs/core-util-is#readme",
"keywords": [
"util",
"isBuffer",
"isArray",
"isNumber",
"isString",
"isRegExp",
"isThis",
"isThat",
"polyfill"
],
"license": "MIT",
"main": "lib/util.js",
"maintainers": [
{
"name": "isaacs",
"email": "i@izs.me"
}
],
"name": "core-util-is",
"optionalDependencies": {},
"readme": "ERROR: No README data found!",
"repository": {
"type": "git",
"url": "git://github.com/isaacs/core-util-is.git"
},
"scripts": {
"test": "tap test.js"
},
"version": "1.0.2"
}

core-util-is

The util.is* functions introduced in Node v0.12.

var assert = require('tap');
var t = require('./lib/util');
assert.equal(t.isArray([]), true);
assert.equal(t.isArray({}), false);
assert.equal(t.isBoolean(null), false);
assert.equal(t.isBoolean(true), true);
assert.equal(t.isBoolean(false), true);
assert.equal(t.isNull(null), true);
assert.equal(t.isNull(undefined), false);
assert.equal(t.isNull(false), false);
assert.equal(t.isNull(), false);
assert.equal(t.isNullOrUndefined(null), true);
assert.equal(t.isNullOrUndefined(undefined), true);
assert.equal(t.isNullOrUndefined(false), false);
assert.equal(t.isNullOrUndefined(), true);
assert.equal(t.isNumber(null), false);
assert.equal(t.isNumber('1'), false);
assert.equal(t.isNumber(1), true);
assert.equal(t.isString(null), false);
assert.equal(t.isString('1'), true);
assert.equal(t.isString(1), false);
assert.equal(t.isSymbol(null), false);
assert.equal(t.isSymbol('1'), false);
assert.equal(t.isSymbol(1), false);
assert.equal(t.isSymbol(Symbol()), true);
assert.equal(t.isUndefined(null), false);
assert.equal(t.isUndefined(undefined), true);
assert.equal(t.isUndefined(false), false);
assert.equal(t.isUndefined(), true);
assert.equal(t.isRegExp(null), false);
assert.equal(t.isRegExp('1'), false);
assert.equal(t.isRegExp(new RegExp()), true);
assert.equal(t.isObject({}), true);
assert.equal(t.isObject([]), true);
assert.equal(t.isObject(new RegExp()), true);
assert.equal(t.isObject(new Date()), true);
assert.equal(t.isDate(null), false);
assert.equal(t.isDate('1'), false);
assert.equal(t.isDate(new Date()), true);
assert.equal(t.isError(null), false);
assert.equal(t.isError({ err: true }), false);
assert.equal(t.isError(new Error()), true);
assert.equal(t.isFunction(null), false);
assert.equal(t.isFunction({ }), false);
assert.equal(t.isFunction(function() {}), true);
assert.equal(t.isPrimitive(null), true);
assert.equal(t.isPrimitive(''), true);
assert.equal(t.isPrimitive(0), true);
assert.equal(t.isPrimitive(new Date()), false);
assert.equal(t.isBuffer(null), false);
assert.equal(t.isBuffer({}), false);
assert.equal(t.isBuffer(new Buffer(0)), true);
'use strict';
var _buffer = require('buffer');
var _create_buffer = require('./create_buffer');
var _create_buffer2 = _interopRequireDefault(_create_buffer);
var _define_crc = require('./define_crc');
var _define_crc2 = _interopRequireDefault(_define_crc);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
module.exports = (0, _define_crc2.default)('crc1', function (buf, previous) {
if (!_buffer.Buffer.isBuffer(buf)) buf = (0, _create_buffer2.default)(buf);
var crc = ~~previous;
var accum = 0;
for (var index = 0; index < buf.length; index++) {
var byte = buf[index];
accum += byte;
}
crc += accum % 256;
return crc % 256;
});
'use strict';
var _buffer = require('buffer');
var _create_buffer = require('./create_buffer');
var _create_buffer2 = _interopRequireDefault(_create_buffer);
var _define_crc = require('./define_crc');
var _define_crc2 = _interopRequireDefault(_define_crc);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// Generated by `./pycrc.py --algorithm=table-driven --model=crc-16 --generate=c`
var TABLE = [0x0000, 0xc0c1, 0xc181, 0x0140, 0xc301, 0x03c0, 0x0280, 0xc241, 0xc601, 0x06c0, 0x0780, 0xc741, 0x0500, 0xc5c1, 0xc481, 0x0440, 0xcc01, 0x0cc0, 0x0d80, 0xcd41, 0x0f00, 0xcfc1, 0xce81, 0x0e40, 0x0a00, 0xcac1, 0xcb81, 0x0b40, 0xc901, 0x09c0, 0x0880, 0xc841, 0xd801, 0x18c0, 0x1980, 0xd941, 0x1b00, 0xdbc1, 0xda81, 0x1a40, 0x1e00, 0xdec1, 0xdf81, 0x1f40, 0xdd01, 0x1dc0, 0x1c80, 0xdc41, 0x1400, 0xd4c1, 0xd581, 0x1540, 0xd701, 0x17c0, 0x1680, 0xd641, 0xd201, 0x12c0, 0x1380, 0xd341, 0x1100, 0xd1c1, 0xd081, 0x1040, 0xf001, 0x30c0, 0x3180, 0xf141, 0x3300, 0xf3c1, 0xf281, 0x3240, 0x3600, 0xf6c1, 0xf781, 0x3740, 0xf501, 0x35c0, 0x3480, 0xf441, 0x3c00, 0xfcc1, 0xfd81, 0x3d40, 0xff01, 0x3fc0, 0x3e80, 0xfe41, 0xfa01, 0x3ac0, 0x3b80, 0xfb41, 0x3900, 0xf9c1, 0xf881, 0x3840, 0x2800, 0xe8c1, 0xe981, 0x2940, 0xeb01, 0x2bc0, 0x2a80, 0xea41, 0xee01, 0x2ec0, 0x2f80, 0xef41, 0x2d00, 0xedc1, 0xec81, 0x2c40, 0xe401, 0x24c0, 0x2580, 0xe541, 0x2700, 0xe7c1, 0xe681, 0x2640, 0x2200, 0xe2c1, 0xe381, 0x2340, 0xe101, 0x21c0, 0x2080, 0xe041, 0xa001, 0x60c0, 0x6180, 0xa141, 0x6300, 0xa3c1, 0xa281, 0x6240, 0x6600, 0xa6c1, 0xa781, 0x6740, 0xa501, 0x65c0, 0x6480, 0xa441, 0x6c00, 0xacc1, 0xad81, 0x6d40, 0xaf01, 0x6fc0, 0x6e80, 0xae41, 0xaa01, 0x6ac0, 0x6b80, 0xab41, 0x6900, 0xa9c1, 0xa881, 0x6840, 0x7800, 0xb8c1, 0xb981, 0x7940, 0xbb01, 0x7bc0, 0x7a80, 0xba41, 0xbe01, 0x7ec0, 0x7f80, 0xbf41, 0x7d00, 0xbdc1, 0xbc81, 0x7c40, 0xb401, 0x74c0, 0x7580, 0xb541, 0x7700, 0xb7c1, 0xb681, 0x7640, 0x7200, 0xb2c1, 0xb381, 0x7340, 0xb101, 0x71c0, 0x7080, 0xb041, 0x5000, 0x90c1, 0x9181, 0x5140, 0x9301, 0x53c0, 0x5280, 0x9241, 0x9601, 0x56c0, 0x5780, 0x9741, 0x5500, 0x95c1, 0x9481, 0x5440, 0x9c01, 0x5cc0, 0x5d80, 0x9d41, 0x5f00, 0x9fc1, 0x9e81, 0x5e40, 0x5a00, 0x9ac1, 0x9b81, 0x5b40, 0x9901, 0x59c0, 0x5880, 0x9841, 0x8801, 0x48c0, 0x4980, 0x8941, 0x4b00, 0x8bc1, 0x8a81, 0x4a40, 0x4e00, 0x8ec1, 0x8f81, 0x4f40, 0x8d01, 0x4dc0, 0x4c80, 0x8c41, 0x4400, 0x84c1, 0x8581, 0x4540, 0x8701, 0x47c0, 0x4680, 0x8641, 0x8201, 0x42c0, 0x4380, 0x8341, 0x4100, 0x81c1, 0x8081, 0x4040];
if (typeof Int32Array !== 'undefined') TABLE = new Int32Array(TABLE);
module.exports = (0, _define_crc2.default)('crc-16', function (buf, previous) {
if (!_buffer.Buffer.isBuffer(buf)) buf = (0, _create_buffer2.default)(buf);
var crc = ~~previous;
for (var index = 0; index < buf.length; index++) {
var byte = buf[index];
crc = (TABLE[(crc ^ byte) & 0xff] ^ crc >> 8) & 0xffff;
}
return crc;
});
'use strict';
var _buffer = require('buffer');
var _create_buffer = require('./create_buffer');
var _create_buffer2 = _interopRequireDefault(_create_buffer);
var _define_crc = require('./define_crc');
var _define_crc2 = _interopRequireDefault(_define_crc);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// Generated by `./pycrc.py --algorithm=table-driven --model=ccitt --generate=c`
var TABLE = [0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50a5, 0x60c6, 0x70e7, 0x8108, 0x9129, 0xa14a, 0xb16b, 0xc18c, 0xd1ad, 0xe1ce, 0xf1ef, 0x1231, 0x0210, 0x3273, 0x2252, 0x52b5, 0x4294, 0x72f7, 0x62d6, 0x9339, 0x8318, 0xb37b, 0xa35a, 0xd3bd, 0xc39c, 0xf3ff, 0xe3de, 0x2462, 0x3443, 0x0420, 0x1401, 0x64e6, 0x74c7, 0x44a4, 0x5485, 0xa56a, 0xb54b, 0x8528, 0x9509, 0xe5ee, 0xf5cf, 0xc5ac, 0xd58d, 0x3653, 0x2672, 0x1611, 0x0630, 0x76d7, 0x66f6, 0x5695, 0x46b4, 0xb75b, 0xa77a, 0x9719, 0x8738, 0xf7df, 0xe7fe, 0xd79d, 0xc7bc, 0x48c4, 0x58e5, 0x6886, 0x78a7, 0x0840, 0x1861, 0x2802, 0x3823, 0xc9cc, 0xd9ed, 0xe98e, 0xf9af, 0x8948, 0x9969, 0xa90a, 0xb92b, 0x5af5, 0x4ad4, 0x7ab7, 0x6a96, 0x1a71, 0x0a50, 0x3a33, 0x2a12, 0xdbfd, 0xcbdc, 0xfbbf, 0xeb9e, 0x9b79, 0x8b58, 0xbb3b, 0xab1a, 0x6ca6, 0x7c87, 0x4ce4, 0x5cc5, 0x2c22, 0x3c03, 0x0c60, 0x1c41, 0xedae, 0xfd8f, 0xcdec, 0xddcd, 0xad2a, 0xbd0b, 0x8d68, 0x9d49, 0x7e97, 0x6eb6, 0x5ed5, 0x4ef4, 0x3e13, 0x2e32, 0x1e51, 0x0e70, 0xff9f, 0xefbe, 0xdfdd, 0xcffc, 0xbf1b, 0xaf3a, 0x9f59, 0x8f78, 0x9188, 0x81a9, 0xb1ca, 0xa1eb, 0xd10c, 0xc12d, 0xf14e, 0xe16f, 0x1080, 0x00a1, 0x30c2, 0x20e3, 0x5004, 0x4025, 0x7046, 0x6067, 0x83b9, 0x9398, 0xa3fb, 0xb3da, 0xc33d, 0xd31c, 0xe37f, 0xf35e, 0x02b1, 0x1290, 0x22f3, 0x32d2, 0x4235, 0x5214, 0x6277, 0x7256, 0xb5ea, 0xa5cb, 0x95a8, 0x8589, 0xf56e, 0xe54f, 0xd52c, 0xc50d, 0x34e2, 0x24c3, 0x14a0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405, 0xa7db, 0xb7fa, 0x8799, 0x97b8, 0xe75f, 0xf77e, 0xc71d, 0xd73c, 0x26d3, 0x36f2, 0x0691, 0x16b0, 0x6657, 0x7676, 0x4615, 0x5634, 0xd94c, 0xc96d, 0xf90e, 0xe92f, 0x99c8, 0x89e9, 0xb98a, 0xa9ab, 0x5844, 0x4865, 0x7806, 0x6827, 0x18c0, 0x08e1, 0x3882, 0x28a3, 0xcb7d, 0xdb5c, 0xeb3f, 0xfb1e, 0x8bf9, 0x9bd8, 0xabbb, 0xbb9a, 0x4a75, 0x5a54, 0x6a37, 0x7a16, 0x0af1, 0x1ad0, 0x2ab3, 0x3a92, 0xfd2e, 0xed0f, 0xdd6c, 0xcd4d, 0xbdaa, 0xad8b, 0x9de8, 0x8dc9, 0x7c26, 0x6c07, 0x5c64, 0x4c45, 0x3ca2, 0x2c83, 0x1ce0, 0x0cc1, 0xef1f, 0xff3e, 0xcf5d, 0xdf7c, 0xaf9b, 0xbfba, 0x8fd9, 0x9ff8, 0x6e17, 0x7e36, 0x4e55, 0x5e74, 0x2e93, 0x3eb2, 0x0ed1, 0x1ef0];
if (typeof Int32Array !== 'undefined') TABLE = new Int32Array(TABLE);
module.exports = (0, _define_crc2.default)('ccitt', function (buf, previous) {
if (!_buffer.Buffer.isBuffer(buf)) buf = (0, _create_buffer2.default)(buf);
var crc = typeof previous !== 'undefined' ? ~~previous : 0xffff;
for (var index = 0; index < buf.length; index++) {
var byte = buf[index];
crc = (TABLE[(crc >> 8 ^ byte) & 0xff] ^ crc << 8) & 0xffff;
}
return crc;
});
'use strict';
var _buffer = require('buffer');
var _create_buffer = require('./create_buffer');
var _create_buffer2 = _interopRequireDefault(_create_buffer);
var _define_crc = require('./define_crc');
var _define_crc2 = _interopRequireDefault(_define_crc);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// Generated by `./pycrc.py --algorithm=table-driven --model=kermit --generate=c`
var TABLE = [0x0000, 0x1189, 0x2312, 0x329b, 0x4624, 0x57ad, 0x6536, 0x74bf, 0x8c48, 0x9dc1, 0xaf5a, 0xbed3, 0xca6c, 0xdbe5, 0xe97e, 0xf8f7, 0x1081, 0x0108, 0x3393, 0x221a, 0x56a5, 0x472c, 0x75b7, 0x643e, 0x9cc9, 0x8d40, 0xbfdb, 0xae52, 0xdaed, 0xcb64, 0xf9ff, 0xe876, 0x2102, 0x308b, 0x0210, 0x1399, 0x6726, 0x76af, 0x4434, 0x55bd, 0xad4a, 0xbcc3, 0x8e58, 0x9fd1, 0xeb6e, 0xfae7, 0xc87c, 0xd9f5, 0x3183, 0x200a, 0x1291, 0x0318, 0x77a7, 0x662e, 0x54b5, 0x453c, 0xbdcb, 0xac42, 0x9ed9, 0x8f50, 0xfbef, 0xea66, 0xd8fd, 0xc974, 0x4204, 0x538d, 0x6116, 0x709f, 0x0420, 0x15a9, 0x2732, 0x36bb, 0xce4c, 0xdfc5, 0xed5e, 0xfcd7, 0x8868, 0x99e1, 0xab7a, 0xbaf3, 0x5285, 0x430c, 0x7197, 0x601e, 0x14a1, 0x0528, 0x37b3, 0x263a, 0xdecd, 0xcf44, 0xfddf, 0xec56, 0x98e9, 0x8960, 0xbbfb, 0xaa72, 0x6306, 0x728f, 0x4014, 0x519d, 0x2522, 0x34ab, 0x0630, 0x17b9, 0xef4e, 0xfec7, 0xcc5c, 0xddd5, 0xa96a, 0xb8e3, 0x8a78, 0x9bf1, 0x7387, 0x620e, 0x5095, 0x411c, 0x35a3, 0x242a, 0x16b1, 0x0738, 0xffcf, 0xee46, 0xdcdd, 0xcd54, 0xb9eb, 0xa862, 0x9af9, 0x8b70, 0x8408, 0x9581, 0xa71a, 0xb693, 0xc22c, 0xd3a5, 0xe13e, 0xf0b7, 0x0840, 0x19c9, 0x2b52, 0x3adb, 0x4e64, 0x5fed, 0x6d76, 0x7cff, 0x9489, 0x8500, 0xb79b, 0xa612, 0xd2ad, 0xc324, 0xf1bf, 0xe036, 0x18c1, 0x0948, 0x3bd3, 0x2a5a, 0x5ee5, 0x4f6c, 0x7df7, 0x6c7e, 0xa50a, 0xb483, 0x8618, 0x9791, 0xe32e, 0xf2a7, 0xc03c, 0xd1b5, 0x2942, 0x38cb, 0x0a50, 0x1bd9, 0x6f66, 0x7eef, 0x4c74, 0x5dfd, 0xb58b, 0xa402, 0x9699, 0x8710, 0xf3af, 0xe226, 0xd0bd, 0xc134, 0x39c3, 0x284a, 0x1ad1, 0x0b58, 0x7fe7, 0x6e6e, 0x5cf5, 0x4d7c, 0xc60c, 0xd785, 0xe51e, 0xf497, 0x8028, 0x91a1, 0xa33a, 0xb2b3, 0x4a44, 0x5bcd, 0x6956, 0x78df, 0x0c60, 0x1de9, 0x2f72, 0x3efb, 0xd68d, 0xc704, 0xf59f, 0xe416, 0x90a9, 0x8120, 0xb3bb, 0xa232, 0x5ac5, 0x4b4c, 0x79d7, 0x685e, 0x1ce1, 0x0d68, 0x3ff3, 0x2e7a, 0xe70e, 0xf687, 0xc41c, 0xd595, 0xa12a, 0xb0a3, 0x8238, 0x93b1, 0x6b46, 0x7acf, 0x4854, 0x59dd, 0x2d62, 0x3ceb, 0x0e70, 0x1ff9, 0xf78f, 0xe606, 0xd49d, 0xc514, 0xb1ab, 0xa022, 0x92b9, 0x8330, 0x7bc7, 0x6a4e, 0x58d5, 0x495c, 0x3de3, 0x2c6a, 0x1ef1, 0x0f78];
if (typeof Int32Array !== 'undefined') TABLE = new Int32Array(TABLE);
module.exports = (0, _define_crc2.default)('kermit', function (buf, previous) {
if (!_buffer.Buffer.isBuffer(buf)) buf = (0, _create_buffer2.default)(buf);
var crc = typeof previous !== 'undefined' ? ~~previous : 0x0000;
for (var index = 0; index < buf.length; index++) {
var byte = buf[index];
crc = (TABLE[(crc ^ byte) & 0xff] ^ crc >> 8) & 0xffff;
}
return crc;
});
'use strict';
var _buffer = require('buffer');
var _create_buffer = require('./create_buffer');
var _create_buffer2 = _interopRequireDefault(_create_buffer);
var _define_crc = require('./define_crc');
var _define_crc2 = _interopRequireDefault(_define_crc);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// Generated by `./pycrc.py --algorithm=table-driven --model=crc-16-modbus --generate=c`
var TABLE = [0x0000, 0xc0c1, 0xc181, 0x0140, 0xc301, 0x03c0, 0x0280, 0xc241, 0xc601, 0x06c0, 0x0780, 0xc741, 0x0500, 0xc5c1, 0xc481, 0x0440, 0xcc01, 0x0cc0, 0x0d80, 0xcd41, 0x0f00, 0xcfc1, 0xce81, 0x0e40, 0x0a00, 0xcac1, 0xcb81, 0x0b40, 0xc901, 0x09c0, 0x0880, 0xc841, 0xd801, 0x18c0, 0x1980, 0xd941, 0x1b00, 0xdbc1, 0xda81, 0x1a40, 0x1e00, 0xdec1, 0xdf81, 0x1f40, 0xdd01, 0x1dc0, 0x1c80, 0xdc41, 0x1400, 0xd4c1, 0xd581, 0x1540, 0xd701, 0x17c0, 0x1680, 0xd641, 0xd201, 0x12c0, 0x1380, 0xd341, 0x1100, 0xd1c1, 0xd081, 0x1040, 0xf001, 0x30c0, 0x3180, 0xf141, 0x3300, 0xf3c1, 0xf281, 0x3240, 0x3600, 0xf6c1, 0xf781, 0x3740, 0xf501, 0x35c0, 0x3480, 0xf441, 0x3c00, 0xfcc1, 0xfd81, 0x3d40, 0xff01, 0x3fc0, 0x3e80, 0xfe41, 0xfa01, 0x3ac0, 0x3b80, 0xfb41, 0x3900, 0xf9c1, 0xf881, 0x3840, 0x2800, 0xe8c1, 0xe981, 0x2940, 0xeb01, 0x2bc0, 0x2a80, 0xea41, 0xee01, 0x2ec0, 0x2f80, 0xef41, 0x2d00, 0xedc1, 0xec81, 0x2c40, 0xe401, 0x24c0, 0x2580, 0xe541, 0x2700, 0xe7c1, 0xe681, 0x2640, 0x2200, 0xe2c1, 0xe381, 0x2340, 0xe101, 0x21c0, 0x2080, 0xe041, 0xa001, 0x60c0, 0x6180, 0xa141, 0x6300, 0xa3c1, 0xa281, 0x6240, 0x6600, 0xa6c1, 0xa781, 0x6740, 0xa501, 0x65c0, 0x6480, 0xa441, 0x6c00, 0xacc1, 0xad81, 0x6d40, 0xaf01, 0x6fc0, 0x6e80, 0xae41, 0xaa01, 0x6ac0, 0x6b80, 0xab41, 0x6900, 0xa9c1, 0xa881, 0x6840, 0x7800, 0xb8c1, 0xb981, 0x7940, 0xbb01, 0x7bc0, 0x7a80, 0xba41, 0xbe01, 0x7ec0, 0x7f80, 0xbf41, 0x7d00, 0xbdc1, 0xbc81, 0x7c40, 0xb401, 0x74c0, 0x7580, 0xb541, 0x7700, 0xb7c1, 0xb681, 0x7640, 0x7200, 0xb2c1, 0xb381, 0x7340, 0xb101, 0x71c0, 0x7080, 0xb041, 0x5000, 0x90c1, 0x9181, 0x5140, 0x9301, 0x53c0, 0x5280, 0x9241, 0x9601, 0x56c0, 0x5780, 0x9741, 0x5500, 0x95c1, 0x9481, 0x5440, 0x9c01, 0x5cc0, 0x5d80, 0x9d41, 0x5f00, 0x9fc1, 0x9e81, 0x5e40, 0x5a00, 0x9ac1, 0x9b81, 0x5b40, 0x9901, 0x59c0, 0x5880, 0x9841, 0x8801, 0x48c0, 0x4980, 0x8941, 0x4b00, 0x8bc1, 0x8a81, 0x4a40, 0x4e00, 0x8ec1, 0x8f81, 0x4f40, 0x8d01, 0x4dc0, 0x4c80, 0x8c41, 0x4400, 0x84c1, 0x8581, 0x4540, 0x8701, 0x47c0, 0x4680, 0x8641, 0x8201, 0x42c0, 0x4380, 0x8341, 0x4100, 0x81c1, 0x8081, 0x4040];
if (typeof Int32Array !== 'undefined') TABLE = new Int32Array(TABLE);
module.exports = (0, _define_crc2.default)('crc-16-modbus', function (buf, previous) {
if (!_buffer.Buffer.isBuffer(buf)) buf = (0, _create_buffer2.default)(buf);
var crc = typeof previous !== 'undefined' ? ~~previous : 0xffff;
for (var index = 0; index < buf.length; index++) {
var byte = buf[index];
crc = (TABLE[(crc ^ byte) & 0xff] ^ crc >> 8) & 0xffff;
}
return crc;
});
'use strict';
var _buffer = require('buffer');
var _create_buffer = require('./create_buffer');
var _create_buffer2 = _interopRequireDefault(_create_buffer);
var _define_crc = require('./define_crc');
var _define_crc2 = _interopRequireDefault(_define_crc);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
module.exports = (0, _define_crc2.default)('xmodem', function (buf, previous) {
if (!_buffer.Buffer.isBuffer(buf)) buf = (0, _create_buffer2.default)(buf);
var crc = typeof previous !== 'undefined' ? ~~previous : 0x0;
for (var index = 0; index < buf.length; index++) {
var byte = buf[index];
var code = crc >>> 8 & 0xFF;
code ^= byte & 0xFF;
code ^= code >>> 4;
crc = crc << 8 & 0xFFFF;
crc ^= code;
code = code << 5 & 0xFFFF;
crc ^= code;
code = code << 7 & 0xFFFF;
crc ^= code;
}
return crc;
});
'use strict';
var _buffer = require('buffer');
var _create_buffer = require('./create_buffer');
var _create_buffer2 = _interopRequireDefault(_create_buffer);
var _define_crc = require('./define_crc');
var _define_crc2 = _interopRequireDefault(_define_crc);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// Generated by `./pycrc.py --algorithm=table-drive --model=crc-24 --generate=c`
var TABLE = [0x000000, 0x864cfb, 0x8ad50d, 0x0c99f6, 0x93e6e1, 0x15aa1a, 0x1933ec, 0x9f7f17, 0xa18139, 0x27cdc2, 0x2b5434, 0xad18cf, 0x3267d8, 0xb42b23, 0xb8b2d5, 0x3efe2e, 0xc54e89, 0x430272, 0x4f9b84, 0xc9d77f, 0x56a868, 0xd0e493, 0xdc7d65, 0x5a319e, 0x64cfb0, 0xe2834b, 0xee1abd, 0x685646, 0xf72951, 0x7165aa, 0x7dfc5c, 0xfbb0a7, 0x0cd1e9, 0x8a9d12, 0x8604e4, 0x00481f, 0x9f3708, 0x197bf3, 0x15e205, 0x93aefe, 0xad50d0, 0x2b1c2b, 0x2785dd, 0xa1c926, 0x3eb631, 0xb8faca, 0xb4633c, 0x322fc7, 0xc99f60, 0x4fd39b, 0x434a6d, 0xc50696, 0x5a7981, 0xdc357a, 0xd0ac8c, 0x56e077, 0x681e59, 0xee52a2, 0xe2cb54, 0x6487af, 0xfbf8b8, 0x7db443, 0x712db5, 0xf7614e, 0x19a3d2, 0x9fef29, 0x9376df, 0x153a24, 0x8a4533, 0x0c09c8, 0x00903e, 0x86dcc5, 0xb822eb, 0x3e6e10, 0x32f7e6, 0xb4bb1d, 0x2bc40a, 0xad88f1, 0xa11107, 0x275dfc, 0xdced5b, 0x5aa1a0, 0x563856, 0xd074ad, 0x4f0bba, 0xc94741, 0xc5deb7, 0x43924c, 0x7d6c62, 0xfb2099, 0xf7b96f, 0x71f594, 0xee8a83, 0x68c678, 0x645f8e, 0xe21375, 0x15723b, 0x933ec0, 0x9fa736, 0x19ebcd, 0x8694da, 0x00d821, 0x0c41d7, 0x8a0d2c, 0xb4f302, 0x32bff9, 0x3e260f, 0xb86af4, 0x2715e3, 0xa15918, 0xadc0ee, 0x2b8c15, 0xd03cb2, 0x567049, 0x5ae9bf, 0xdca544, 0x43da53, 0xc596a8, 0xc90f5e, 0x4f43a5, 0x71bd8b, 0xf7f170, 0xfb6886, 0x7d247d, 0xe25b6a, 0x641791, 0x688e67, 0xeec29c, 0x3347a4, 0xb50b5f, 0xb992a9, 0x3fde52, 0xa0a145, 0x26edbe, 0x2a7448, 0xac38b3, 0x92c69d, 0x148a66, 0x181390, 0x9e5f6b, 0x01207c, 0x876c87, 0x8bf571, 0x0db98a, 0xf6092d, 0x7045d6, 0x7cdc20, 0xfa90db, 0x65efcc, 0xe3a337, 0xef3ac1, 0x69763a, 0x578814, 0xd1c4ef, 0xdd5d19, 0x5b11e2, 0xc46ef5, 0x42220e, 0x4ebbf8, 0xc8f703, 0x3f964d, 0xb9dab6, 0xb54340, 0x330fbb, 0xac70ac, 0x2a3c57, 0x26a5a1, 0xa0e95a, 0x9e1774, 0x185b8f, 0x14c279, 0x928e82, 0x0df195, 0x8bbd6e, 0x872498, 0x016863, 0xfad8c4, 0x7c943f, 0x700dc9, 0xf64132, 0x693e25, 0xef72de, 0xe3eb28, 0x65a7d3, 0x5b59fd, 0xdd1506, 0xd18cf0, 0x57c00b, 0xc8bf1c, 0x4ef3e7, 0x426a11, 0xc426ea, 0x2ae476, 0xaca88d, 0xa0317b, 0x267d80, 0xb90297, 0x3f4e6c, 0x33d79a, 0xb59b61, 0x8b654f, 0x0d29b4, 0x01b042, 0x87fcb9, 0x1883ae, 0x9ecf55, 0x9256a3, 0x141a58, 0xefaaff, 0x69e604, 0x657ff2, 0xe33309, 0x7c4c1e, 0xfa00e5, 0xf69913, 0x70d5e8, 0x4e2bc6, 0xc8673d, 0xc4fecb, 0x42b230, 0xddcd27, 0x5b81dc, 0x57182a, 0xd154d1, 0x26359f, 0xa07964, 0xace092, 0x2aac69, 0xb5d37e, 0x339f85, 0x3f0673, 0xb94a88, 0x87b4a6, 0x01f85d, 0x0d61ab, 0x8b2d50, 0x145247, 0x921ebc, 0x9e874a, 0x18cbb1, 0xe37b16, 0x6537ed, 0x69ae1b, 0xefe2e0, 0x709df7, 0xf6d10c, 0xfa48fa, 0x7c0401, 0x42fa2f, 0xc4b6d4, 0xc82f22, 0x4e63d9, 0xd11cce, 0x575035, 0x5bc9c3, 0xdd8538];
if (typeof Int32Array !== 'undefined') TABLE = new Int32Array(TABLE);
module.exports = (0, _define_crc2.default)('crc-24', function (buf, previous) {
if (!_buffer.Buffer.isBuffer(buf)) buf = (0, _create_buffer2.default)(buf);
var crc = typeof previous !== 'undefined' ? ~~previous : 0xb704ce;
for (var index = 0; index < buf.length; index++) {
var byte = buf[index];
crc = (TABLE[(crc >> 16 ^ byte) & 0xff] ^ crc << 8) & 0xffffff;
}
return crc;
});
'use strict';
var _buffer = require('buffer');
var _create_buffer = require('./create_buffer');
var _create_buffer2 = _interopRequireDefault(_create_buffer);
var _define_crc = require('./define_crc');
var _define_crc2 = _interopRequireDefault(_define_crc);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// Generated by `./pycrc.py --algorithm=table-driven --model=crc-32 --generate=c`
var TABLE = [0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59, 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433, 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950, 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65, 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f, 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b, 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d, 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242, 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777, 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9, 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693, 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d];
if (typeof Int32Array !== 'undefined') TABLE = new Int32Array(TABLE);
module.exports = (0, _define_crc2.default)('crc-32', function (buf, previous) {
if (!_buffer.Buffer.isBuffer(buf)) buf = (0, _create_buffer2.default)(buf);
var crc = previous === 0 ? 0 : ~~previous ^ -1;
for (var index = 0; index < buf.length; index++) {
var byte = buf[index];
crc = TABLE[(crc ^ byte) & 0xff] ^ crc >>> 8;
}
return crc ^ -1;
});
'use strict';
var _buffer = require('buffer');
var _create_buffer = require('./create_buffer');
var _create_buffer2 = _interopRequireDefault(_create_buffer);
var _define_crc = require('./define_crc');
var _define_crc2 = _interopRequireDefault(_define_crc);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// Generated by `./pycrc.py --algorithm=table-driven --model=crc-8 --generate=c`
var TABLE = [0x00, 0x07, 0x0e, 0x09, 0x1c, 0x1b, 0x12, 0x15, 0x38, 0x3f, 0x36, 0x31, 0x24, 0x23, 0x2a, 0x2d, 0x70, 0x77, 0x7e, 0x79, 0x6c, 0x6b, 0x62, 0x65, 0x48, 0x4f, 0x46, 0x41, 0x54, 0x53, 0x5a, 0x5d, 0xe0, 0xe7, 0xee, 0xe9, 0xfc, 0xfb, 0xf2, 0xf5, 0xd8, 0xdf, 0xd6, 0xd1, 0xc4, 0xc3, 0xca, 0xcd, 0x90, 0x97, 0x9e, 0x99, 0x8c, 0x8b, 0x82, 0x85, 0xa8, 0xaf, 0xa6, 0xa1, 0xb4, 0xb3, 0xba, 0xbd, 0xc7, 0xc0, 0xc9, 0xce, 0xdb, 0xdc, 0xd5, 0xd2, 0xff, 0xf8, 0xf1, 0xf6, 0xe3, 0xe4, 0xed, 0xea, 0xb7, 0xb0, 0xb9, 0xbe, 0xab, 0xac, 0xa5, 0xa2, 0x8f, 0x88, 0x81, 0x86, 0x93, 0x94, 0x9d, 0x9a, 0x27, 0x20, 0x29, 0x2e, 0x3b, 0x3c, 0x35, 0x32, 0x1f, 0x18, 0x11, 0x16, 0x03, 0x04, 0x0d, 0x0a, 0x57, 0x50, 0x59, 0x5e, 0x4b, 0x4c, 0x45, 0x42, 0x6f, 0x68, 0x61, 0x66, 0x73, 0x74, 0x7d, 0x7a, 0x89, 0x8e, 0x87, 0x80, 0x95, 0x92, 0x9b, 0x9c, 0xb1, 0xb6, 0xbf, 0xb8, 0xad, 0xaa, 0xa3, 0xa4, 0xf9, 0xfe, 0xf7, 0xf0, 0xe5, 0xe2, 0xeb, 0xec, 0xc1, 0xc6, 0xcf, 0xc8, 0xdd, 0xda, 0xd3, 0xd4, 0x69, 0x6e, 0x67, 0x60, 0x75, 0x72, 0x7b, 0x7c, 0x51, 0x56, 0x5f, 0x58, 0x4d, 0x4a, 0x43, 0x44, 0x19, 0x1e, 0x17, 0x10, 0x05, 0x02, 0x0b, 0x0c, 0x21, 0x26, 0x2f, 0x28, 0x3d, 0x3a, 0x33, 0x34, 0x4e, 0x49, 0x40, 0x47, 0x52, 0x55, 0x5c, 0x5b, 0x76, 0x71, 0x78, 0x7f, 0x6a, 0x6d, 0x64, 0x63, 0x3e, 0x39, 0x30, 0x37, 0x22, 0x25, 0x2c, 0x2b, 0x06, 0x01, 0x08, 0x0f, 0x1a, 0x1d, 0x14, 0x13, 0xae, 0xa9, 0xa0, 0xa7, 0xb2, 0xb5, 0xbc, 0xbb, 0x96, 0x91, 0x98, 0x9f, 0x8a, 0x8d, 0x84, 0x83, 0xde, 0xd9, 0xd0, 0xd7, 0xc2, 0xc5, 0xcc, 0xcb, 0xe6, 0xe1, 0xe8, 0xef, 0xfa, 0xfd, 0xf4, 0xf3];
if (typeof Int32Array !== 'undefined') TABLE = new Int32Array(TABLE);
module.exports = (0, _define_crc2.default)('crc-8', function (buf, previous) {
if (!_buffer.Buffer.isBuffer(buf)) buf = (0, _create_buffer2.default)(buf);
var crc = ~~previous;
for (var index = 0; index < buf.length; index++) {
var byte = buf[index];
crc = TABLE[(crc ^ byte) & 0xff] & 0xff;
}
return crc;
});
'use strict';
var _buffer = require('buffer');
var _create_buffer = require('./create_buffer');
var _create_buffer2 = _interopRequireDefault(_create_buffer);
var _define_crc = require('./define_crc');
var _define_crc2 = _interopRequireDefault(_define_crc);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// Generated by `./pycrc.py --algorithm=table-driven --model=dallas-1-wire --generate=c`
var TABLE = [0x00, 0x5e, 0xbc, 0xe2, 0x61, 0x3f, 0xdd, 0x83, 0xc2, 0x9c, 0x7e, 0x20, 0xa3, 0xfd, 0x1f, 0x41, 0x9d, 0xc3, 0x21, 0x7f, 0xfc, 0xa2, 0x40, 0x1e, 0x5f, 0x01, 0xe3, 0xbd, 0x3e, 0x60, 0x82, 0xdc, 0x23, 0x7d, 0x9f, 0xc1, 0x42, 0x1c, 0xfe, 0xa0, 0xe1, 0xbf, 0x5d, 0x03, 0x80, 0xde, 0x3c, 0x62, 0xbe, 0xe0, 0x02, 0x5c, 0xdf, 0x81, 0x63, 0x3d, 0x7c, 0x22, 0xc0, 0x9e, 0x1d, 0x43, 0xa1, 0xff, 0x46, 0x18, 0xfa, 0xa4, 0x27, 0x79, 0x9b, 0xc5, 0x84, 0xda, 0x38, 0x66, 0xe5, 0xbb, 0x59, 0x07, 0xdb, 0x85, 0x67, 0x39, 0xba, 0xe4, 0x06, 0x58, 0x19, 0x47, 0xa5, 0xfb, 0x78, 0x26, 0xc4, 0x9a, 0x65, 0x3b, 0xd9, 0x87, 0x04, 0x5a, 0xb8, 0xe6, 0xa7, 0xf9, 0x1b, 0x45, 0xc6, 0x98, 0x7a, 0x24, 0xf8, 0xa6, 0x44, 0x1a, 0x99, 0xc7, 0x25, 0x7b, 0x3a, 0x64, 0x86, 0xd8, 0x5b, 0x05, 0xe7, 0xb9, 0x8c, 0xd2, 0x30, 0x6e, 0xed, 0xb3, 0x51, 0x0f, 0x4e, 0x10, 0xf2, 0xac, 0x2f, 0x71, 0x93, 0xcd, 0x11, 0x4f, 0xad, 0xf3, 0x70, 0x2e, 0xcc, 0x92, 0xd3, 0x8d, 0x6f, 0x31, 0xb2, 0xec, 0x0e, 0x50, 0xaf, 0xf1, 0x13, 0x4d, 0xce, 0x90, 0x72, 0x2c, 0x6d, 0x33, 0xd1, 0x8f, 0x0c, 0x52, 0xb0, 0xee, 0x32, 0x6c, 0x8e, 0xd0, 0x53, 0x0d, 0xef, 0xb1, 0xf0, 0xae, 0x4c, 0x12, 0x91, 0xcf, 0x2d, 0x73, 0xca, 0x94, 0x76, 0x28, 0xab, 0xf5, 0x17, 0x49, 0x08, 0x56, 0xb4, 0xea, 0x69, 0x37, 0xd5, 0x8b, 0x57, 0x09, 0xeb, 0xb5, 0x36, 0x68, 0x8a, 0xd4, 0x95, 0xcb, 0x29, 0x77, 0xf4, 0xaa, 0x48, 0x16, 0xe9, 0xb7, 0x55, 0x0b, 0x88, 0xd6, 0x34, 0x6a, 0x2b, 0x75, 0x97, 0xc9, 0x4a, 0x14, 0xf6, 0xa8, 0x74, 0x2a, 0xc8, 0x96, 0x15, 0x4b, 0xa9, 0xf7, 0xb6, 0xe8, 0x0a, 0x54, 0xd7, 0x89, 0x6b, 0x35];
if (typeof Int32Array !== 'undefined') TABLE = new Int32Array(TABLE);
module.exports = (0, _define_crc2.default)('dallas-1-wire', function (buf, previous) {
if (!_buffer.Buffer.isBuffer(buf)) buf = (0, _create_buffer2.default)(buf);
var crc = ~~previous;
for (var index = 0; index < buf.length; index++) {
var byte = buf[index];
crc = TABLE[(crc ^ byte) & 0xff] & 0xff;
}
return crc;
});
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _buffer = require('buffer');
var createBuffer = _buffer.Buffer.from && _buffer.Buffer.alloc && _buffer.Buffer.allocUnsafe && _buffer.Buffer.allocUnsafeSlow ? _buffer.Buffer.from
// support for Node < 5.10
: function (val) {
return new _buffer.Buffer(val);
};
exports.default = createBuffer;
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = function (model, calc) {
var fn = function fn(buf, previous) {
return calc(buf, previous) >>> 0;
};
fn.signed = calc;
fn.unsigned = fn;
fn.model = model;
return fn;
};
'use strict';
module.exports = {
crc1: require('./crc1'),
crc8: require('./crc8'),
crc81wire: require('./crc8_1wire'),
crc16: require('./crc16'),
crc16ccitt: require('./crc16_ccitt'),
crc16modbus: require('./crc16_modbus'),
crc16xmodem: require('./crc16_xmodem'),
crc16kermit: require('./crc16_kermit'),
crc24: require('./crc24'),
crc32: require('./crc32')
};
The MIT License (MIT)
Copyright 2014 Alex Gorbatchev
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.
{
"_args": [
[
{
"raw": "crc@3.4.4",
"scope": null,
"escapedName": "crc",
"name": "crc",
"rawSpec": "3.4.4",
"spec": "3.4.4",
"type": "version"
},
"C:\\xampp\\htdocs\\cafe\\node_modules\\express-session"
]
],
"_from": "crc@3.4.4",
"_id": "crc@3.4.4",
"_inCache": true,
"_location": "/crc",
"_nodeVersion": "6.9.2",
"_npmOperationalInternal": {
"host": "packages-18-east.internal.npmjs.com",
"tmp": "tmp/crc-3.4.4.tgz_1481570747807_0.07623594417236745"
},
"_npmUser": {
"name": "alexgorbatchev",
"email": "alex.gorbatchev@gmail.com"
},
"_npmVersion": "3.10.9",
"_phantomChildren": {},
"_requested": {
"raw": "crc@3.4.4",
"scope": null,
"escapedName": "crc",
"name": "crc",
"rawSpec": "3.4.4",
"spec": "3.4.4",
"type": "version"
},
"_requiredBy": [
"/express-session"
],
"_resolved": "https://registry.npmjs.org/crc/-/crc-3.4.4.tgz",
"_shasum": "9da1e980e3bd44fc5c93bf5ab3da3378d85e466b",
"_shrinkwrap": null,
"_spec": "crc@3.4.4",
"_where": "C:\\xampp\\htdocs\\cafe\\node_modules\\express-session",
"author": {
"name": "Alex Gorbatchev",
"url": "https://github.com/alexgorbatchev"
},
"bugs": {
"url": "https://github.com/alexgorbatchev/node-crc/issues"
},
"dependencies": {},
"description": "Module for calculating Cyclic Redundancy Check (CRC) for Node.js and the Browser.",
"devDependencies": {
"babel-cli": "^6.3.15",
"babel-core": "^6.1.21",
"babel-preset-es2015": "^6.1.18",
"beautify-benchmark": "^0.2.4",
"benchmark": "^1.0.0",
"buffer-crc32": "^0.2.3",
"chai": "^3.4.1",
"mocha": "*",
"seedrandom": "^2.3.6"
},
"directories": {},
"dist": {
"shasum": "9da1e980e3bd44fc5c93bf5ab3da3378d85e466b",
"tarball": "https://registry.npmjs.org/crc/-/crc-3.4.4.tgz"
},
"files": [
"lib"
],
"gitHead": "360367e1ae930d8663679aff89bb79705947c08c",
"homepage": "https://github.com/alexgorbatchev/node-crc",
"keywords": [
"crc"
],
"license": "MIT",
"main": "./lib/index.js",
"maintainers": [
{
"name": "alexgorbatchev",
"email": "alex.gorbatchev@gmail.com"
}
],
"name": "crc",
"optionalDependencies": {},
"readme": "ERROR: No README data found!",
"repository": {
"type": "git",
"url": "git://github.com/alexgorbatchev/node-crc.git"
},
"scripts": {
"pretest": "cd src && babel --out-dir ../lib *.js",
"test": "mocha test/*.test.js"
},
"version": "3.4.4"
}

crc

GitTip Dependency status devDependency Status Build Status

NPM

Module for calculating Cyclic Redundancy Check (CRC) for Node.js and the Browser.

Important: Node >= 6.3.0 < 6.9.2

There's was a bug in Node #9342 that affected CRC calculation if Buffer.split() is used (see issue discussion for details). This affected all version starting from 6.3.0 up to but not including 6.9.2. The patch #9341 was released in 6.9.2. If you are upgrading and seeing odd CRC calculation mismatches, this might be the reason.

Features

  • Full test suite comparing values against reference pycrc implementation.
  • Pure JavaScript implementation, no dependencies.
  • Provides CRC tables for optimized calculations.
  • Provides support for the following CRC algorithms:
    • CRC1 crc.crc1(…)
    • CRC8 crc.crc8(…)
    • CRC8 1-Wire crc.crc81wire(…)
    • CRC16 crc.crc16(…)
    • CRC16 CCITT crc.crc16ccitt(…)
    • CRC16 Modbus crc.crc16modbus(…)
    • CRC16 Kermit crc.crc16kermit(…)
    • CRC16 XModem crc.crc16xmodem(…)
    • CRC24 crc.crc24(…)
    • CRC32 crc.crc32(…)

Installation

npm install crc

Usage

Calculate a CRC32:

var crc = require('crc');

crc.crc32('hello').toString(16);
// "3610a686"

Calculate a CRC32 of a file:

crc.crc32(fs.readFileSync('README.md', 'utf8')).toString(16);
// "127ad531"

Or using a Buffer:

crc.crc32(fs.readFileSync('README.md')).toString(16);
// "127ad531"

Incrementally calculate a CRC32:

value = crc.crc32('one');
value = crc.crc32('two', value);
value = crc.crc32('three', value);
value.toString(16);
// "9e1c092"

Running tests

npm test

Thanks!

pycrc library is which the source of all of the CRC tables.

License

The MIT License (MIT)

Copyright (c) 2014 Alex Gorbatchev

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() {
var base64map
= 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',
crypt = {
// Bit-wise rotation left
rotl: function(n, b) {
return (n << b) | (n >>> (32 - b));
},
// Bit-wise rotation right
rotr: function(n, b) {
return (n << (32 - b)) | (n >>> b);
},
// Swap big-endian to little-endian and vice versa
endian: function(n) {
// If number given, swap endian
if (n.constructor == Number) {
return crypt.rotl(n, 8) & 0x00FF00FF | crypt.rotl(n, 24) & 0xFF00FF00;
}
// Else, assume array and swap all items
for (var i = 0; i < n.length; i++)
n[i] = crypt.endian(n[i]);
return n;
},
// Generate an array of any length of random bytes
randomBytes: function(n) {
for (var bytes = []; n > 0; n--)
bytes.push(Math.floor(Math.random() * 256));
return bytes;
},
// Convert a byte array to big-endian 32-bit words
bytesToWords: function(bytes) {
for (var words = [], i = 0, b = 0; i < bytes.length; i++, b += 8)
words[b >>> 5] |= bytes[i] << (24 - b % 32);
return words;
},
// Convert big-endian 32-bit words to a byte array
wordsToBytes: function(words) {
for (var bytes = [], b = 0; b < words.length * 32; b += 8)
bytes.push((words[b >>> 5] >>> (24 - b % 32)) & 0xFF);
return bytes;
},
// Convert a byte array to a hex string
bytesToHex: function(bytes) {
for (var hex = [], i = 0; i < bytes.length; i++) {
hex.push((bytes[i] >>> 4).toString(16));
hex.push((bytes[i] & 0xF).toString(16));
}
return hex.join('');
},
// Convert a hex string to a byte array
hexToBytes: function(hex) {
for (var bytes = [], c = 0; c < hex.length; c += 2)
bytes.push(parseInt(hex.substr(c, 2), 16));
return bytes;
},
// Convert a byte array to a base-64 string
bytesToBase64: function(bytes) {
for (var base64 = [], i = 0; i < bytes.length; i += 3) {
var triplet = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2];
for (var j = 0; j < 4; j++)
if (i * 8 + j * 6 <= bytes.length * 8)
base64.push(base64map.charAt((triplet >>> 6 * (3 - j)) & 0x3F));
else
base64.push('=');
}
return base64.join('');
},
// Convert a base-64 string to a byte array
base64ToBytes: function(base64) {
// Remove non-base-64 characters
base64 = base64.replace(/[^A-Z0-9+\/]/ig, '');
for (var bytes = [], i = 0, imod4 = 0; i < base64.length;
imod4 = ++i % 4) {
if (imod4 == 0) continue;
bytes.push(((base64map.indexOf(base64.charAt(i - 1))
& (Math.pow(2, -2 * imod4 + 8) - 1)) << (imod4 * 2))
| (base64map.indexOf(base64.charAt(i)) >>> (6 - imod4 * 2)));
}
return bytes;
}
};
module.exports = crypt;
})();

Copyright © 2011, Paul Vorbach. All rights reserved. Copyright © 2009, Jeff Mott. All rights reserved.

All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

  • Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
  • Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
  • Neither the name Crypto-JS nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

{
"_args": [
[
{
"raw": "crypt@~0.0.1",
"scope": null,
"escapedName": "crypt",
"name": "crypt",
"rawSpec": "~0.0.1",
"spec": ">=0.0.1 <0.1.0",
"type": "range"
},
"C:\\xampp\\htdocs\\cafe\\node_modules\\md5"
]
],
"_from": "crypt@>=0.0.1 <0.1.0",
"_id": "crypt@0.0.2",
"_inCache": true,
"_location": "/crypt",
"_nodeVersion": "4.4.5",
"_npmOperationalInternal": {
"host": "packages-18-east.internal.npmjs.com",
"tmp": "tmp/crypt-0.0.2.tgz_1482450046585_0.08984375675208867"
},
"_npmUser": {
"name": "pvorb",
"email": "paul@vorba.ch"
},
"_npmVersion": "3.9.3",
"_phantomChildren": {},
"_requested": {
"raw": "crypt@~0.0.1",
"scope": null,
"escapedName": "crypt",
"name": "crypt",
"rawSpec": "~0.0.1",
"spec": ">=0.0.1 <0.1.0",
"type": "range"
},
"_requiredBy": [
"/md5"
],
"_resolved": "https://registry.npmjs.org/crypt/-/crypt-0.0.2.tgz",
"_shasum": "88d7ff7ec0dfb86f713dc87bbb42d044d3e6c41b",
"_shrinkwrap": null,
"_spec": "crypt@~0.0.1",
"_where": "C:\\xampp\\htdocs\\cafe\\node_modules\\md5",
"author": {
"name": "Paul Vorbach",
"email": "paul@vorb.de",
"url": "http://vorb.de"
},
"bugs": {
"url": "https://github.com/pvorb/node-crypt/issues"
},
"dependencies": {},
"description": "utilities for encryption and hashing",
"devDependencies": {},
"directories": {},
"dist": {
"shasum": "88d7ff7ec0dfb86f713dc87bbb42d044d3e6c41b",
"tarball": "https://registry.npmjs.org/crypt/-/crypt-0.0.2.tgz"
},
"engines": {
"node": "*"
},
"gitHead": "b275e2cde03cab40206dbb2a551b781f51feca3f",
"homepage": "https://github.com/pvorb/node-crypt#readme",
"license": "BSD-3-Clause",
"main": "crypt.js",
"maintainers": [
{
"name": "pvorb",
"email": "paul@vorb.de"
}
],
"name": "crypt",
"optionalDependencies": {},
"readme": "ERROR: No README data found!",
"repository": {
"type": "git",
"url": "git://github.com/pvorb/node-crypt.git"
},
"scripts": {},
"tags": [
"hash",
"security"
],
"version": "0.0.2"
}

crypt provides utilities for encryption and hashing

support
test
examples
example
*.sock
dist
{
"name": "visionmedia-debug",
"main": "dist/debug.js",
"version": "2.2.0",
"homepage": "https://github.com/visionmedia/debug",
"authors": [
"TJ Holowaychuk <tj@vision-media.ca>"
],
"description": "visionmedia-debug",
"moduleType": [
"amd",
"es6",
"globals",
"node"
],
"keywords": [
"visionmedia",
"debug"
],
"license": "MIT",
"ignore": [
"**/.*",
"node_modules",
"bower_components",
"test",
"tests"
]
}
/**
* This is the web browser implementation of `debug()`.
*
* Expose `debug()` as the module.
*/
exports = module.exports = require('./debug');
exports.log = log;
exports.formatArgs = formatArgs;
exports.save = save;
exports.load = load;
exports.useColors = useColors;
exports.storage = 'undefined' != typeof chrome
&& 'undefined' != typeof chrome.storage
? chrome.storage.local
: localstorage();
/**
* Colors.
*/
exports.colors = [
'lightseagreen',
'forestgreen',
'goldenrod',
'dodgerblue',
'darkorchid',
'crimson'
];
/**
* Currently only WebKit-based Web Inspectors, Firefox >= v31,
* and the Firebug extension (any Firefox version) are known
* to support "%c" CSS customizations.
*
* TODO: add a `localStorage` variable to explicitly enable/disable colors
*/
function useColors() {
// is webkit? http://stackoverflow.com/a/16459606/376773
return ('WebkitAppearance' in document.documentElement.style) ||
// is firebug? http://stackoverflow.com/a/398120/376773
(window.console && (console.firebug || (console.exception && console.table))) ||
// is firefox >= v31?
// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
(navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31);
}
/**
* Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
*/
exports.formatters.j = function(v) {
return JSON.stringify(v);
};
/**
* Colorize log arguments if enabled.
*
* @api public
*/
function formatArgs() {
var args = arguments;
var useColors = this.useColors;
args[0] = (useColors ? '%c' : '')
+ this.namespace
+ (useColors ? ' %c' : ' ')
+ args[0]
+ (useColors ? '%c ' : ' ')
+ '+' + exports.humanize(this.diff);
if (!useColors) return args;
var c = 'color: ' + this.color;
args = [args[0], c, 'color: inherit'].concat(Array.prototype.slice.call(args, 1));
// the final "%c" is somewhat tricky, because there could be other
// arguments passed either before or after the %c, so we need to
// figure out the correct index to insert the CSS into
var index = 0;
var lastC = 0;
args[0].replace(/%[a-z%]/g, function(match) {
if ('%%' === match) return;
index++;
if ('%c' === match) {
// we only are interested in the *last* %c
// (the user may have provided their own)
lastC = index;
}
});
args.splice(lastC, 0, c);
return args;
}
/**
* Invokes `console.log()` when available.
* No-op when `console.log` is not a "function".
*
* @api public
*/
function log() {
// this hackery is required for IE8/9, where
// the `console.log` function doesn't have 'apply'
return 'object' === typeof console
&& console.log
&& Function.prototype.apply.call(console.log, console, arguments);
}
/**
* Save `namespaces`.
*
* @param {String} namespaces
* @api private
*/
function save(namespaces) {
try {
if (null == namespaces) {
exports.storage.removeItem('debug');
} else {
exports.storage.debug = namespaces;
}
} catch(e) {}
}
/**
* Load `namespaces`.
*
* @return {String} returns the previously persisted debug modes
* @api private
*/
function load() {
var r;
try {
r = exports.storage.debug;
} catch(e) {}
return r;
}
/**
* Enable namespaces listed in `localStorage.debug` initially.
*/
exports.enable(load());
/**
* Localstorage attempts to return the localstorage.
*
* This is necessary because safari throws
* when a user disables cookies/localstorage
* and you attempt to access it.
*
* @return {LocalStorage}
* @api private
*/
function localstorage(){
try {
return window.localStorage;
} catch (e) {}
}
{
"name": "debug",
"repo": "visionmedia/debug",
"description": "small debugging utility",
"version": "2.2.0",
"keywords": [
"debug",
"log",
"debugger"
],
"main": "browser.js",
"scripts": [
"browser.js",
"debug.js"
],
"dependencies": {
"rauchg/ms.js": "0.7.1"
}
}
/**
* This is the common logic for both the Node.js and web browser
* implementations of `debug()`.
*
* Expose `debug()` as the module.
*/
exports = module.exports = debug;
exports.coerce = coerce;
exports.disable = disable;
exports.enable = enable;
exports.enabled = enabled;
exports.humanize = require('ms');
/**
* The currently active debug mode names, and names to skip.
*/
exports.names = [];
exports.skips = [];
/**
* Map of special "%n" handling functions, for the debug "format" argument.
*
* Valid key names are a single, lowercased letter, i.e. "n".
*/
exports.formatters = {};
/**
* Previously assigned color.
*/
var prevColor = 0;
/**
* Previous log timestamp.
*/
var prevTime;
/**
* Select a color.
*
* @return {Number}
* @api private
*/
function selectColor() {
return exports.colors[prevColor++ % exports.colors.length];
}
/**
* Create a debugger with the given `namespace`.
*
* @param {String} namespace
* @return {Function}
* @api public
*/
function debug(namespace) {
// define the `disabled` version
function disabled() {
}
disabled.enabled = false;
// define the `enabled` version
function enabled() {
var self = enabled;
// set `diff` timestamp
var curr = +new Date();
var ms = curr - (prevTime || curr);
self.diff = ms;
self.prev = prevTime;
self.curr = curr;
prevTime = curr;
// add the `color` if not set
if (null == self.useColors) self.useColors = exports.useColors();
if (null == self.color && self.useColors) self.color = selectColor();
var args = Array.prototype.slice.call(arguments);
args[0] = exports.coerce(args[0]);
if ('string' !== typeof args[0]) {
// anything else let's inspect with %o
args = ['%o'].concat(args);
}
// apply any `formatters` transformations
var index = 0;
args[0] = args[0].replace(/%([a-z%])/g, function(match, format) {
// if we encounter an escaped % then don't increase the array index
if (match === '%%') return match;
index++;
var formatter = exports.formatters[format];
if ('function' === typeof formatter) {
var val = args[index];
match = formatter.call(self, val);
// now we need to remove `args[index]` since it's inlined in the `format`
args.splice(index, 1);
index--;
}
return match;
});
if ('function' === typeof exports.formatArgs) {
args = exports.formatArgs.apply(self, args);
}
var logFn = enabled.log || exports.log || console.log.bind(console);
logFn.apply(self, args);
}
enabled.enabled = true;
var fn = exports.enabled(namespace) ? enabled : disabled;
fn.namespace = namespace;
return fn;
}
/**
* Enables a debug mode by namespaces. This can include modes
* separated by a colon and wildcards.
*
* @param {String} namespaces
* @api public
*/
function enable(namespaces) {
exports.save(namespaces);
var split = (namespaces || '').split(/[\s,]+/);
var len = split.length;
for (var i = 0; i < len; i++) {
if (!split[i]) continue; // ignore empty strings
namespaces = split[i].replace(/\*/g, '.*?');
if (namespaces[0] === '-') {
exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
} else {
exports.names.push(new RegExp('^' + namespaces + '$'));
}
}
}
/**
* Disable debug output.
*
* @api public
*/
function disable() {
exports.enable('');
}
/**
* Returns true if the given mode name is enabled, false otherwise.
*
* @param {String} name
* @return {Boolean}
* @api public
*/
function enabled(name) {
var i, len;
for (i = 0, len = exports.skips.length; i < len; i++) {
if (exports.skips[i].test(name)) {
return false;
}
}
for (i = 0, len = exports.names.length; i < len; i++) {
if (exports.names[i].test(name)) {
return true;
}
}
return false;
}
/**
* Coerce `val`.
*
* @param {Mixed} val
* @return {Mixed}
* @api private
*/
function coerce(val) {
if (val instanceof Error) return val.stack || val.message;
return val;
}

2.2.0 / 2015-05-09

  • package: update "ms" to v0.7.1 (#202, @dougwilson)
  • README: add logging to file example (#193, @DanielOchoa)
  • README: fixed a typo (#191, @amir-s)
  • browser: expose storage (#190, @stephenmathieson)
  • Makefile: add a distclean target (#189, @stephenmathieson)

2.1.3 / 2015-03-13

  • Updated stdout/stderr example (#186)
  • Updated example/stdout.js to match debug current behaviour
  • Renamed example/stderr.js to stdout.js
  • Update Readme.md (#184)
  • replace high intensity foreground color for bold (#182, #183)

2.1.2 / 2015-03-01

  • dist: recompile
  • update "ms" to v0.7.0
  • package: update "browserify" to v9.0.3
  • component: fix "ms.js" repo location
  • changed bower package name
  • updated documentation about using debug in a browser
  • fix: security error on safari (#167, #168, @yields)

2.1.1 / 2014-12-29

  • browser: use typeof to check for console existence
  • browser: check for console.log truthiness (fix IE 8/9)
  • browser: add support for Chrome apps
  • Readme: added Windows usage remarks
  • Add bower.json to properly support bower install

2.1.0 / 2014-10-15

  • node: implement DEBUG_FD env variable support
  • package: update "browserify" to v6.1.0
  • package: add "license" field to package.json (#135, @panuhorsmalahti)

2.0.0 / 2014-09-01

  • package: update "browserify" to v5.11.0
  • node: use stderr rather than stdout for logging (#29, @stephenmathieson)

1.0.4 / 2014-07-15

  • dist: recompile
  • example: remove console.info() log usage
  • example: add "Content-Type" UTF-8 header to browser example
  • browser: place %c marker after the space character
  • browser: reset the "content" color via color: inherit
  • browser: add colors support for Firefox >= v31
  • debug: prefer an instance log() function over the global one (#119)
  • Readme: update documentation about styled console logs for FF v31 (#116, @wryk)

1.0.3 / 2014-07-09

  • Add support for multiple wildcards in namespaces (#122, @seegno)
  • browser: fix lint

1.0.2 / 2014-06-10

  • browser: update color palette (#113, @gscottolson)
  • common: make console logging function configurable (#108, @timoxley)
  • node: fix %o colors on old node <= 0.8.x
  • Makefile: find node path using shell/which (#109, @timoxley)

1.0.1 / 2014-06-06

  • browser: use removeItem() to clear localStorage
  • browser, node: don't set DEBUG if namespaces is undefined (#107, @leedm777)
  • package: add "contributors" section
  • node: fix comment typo
  • README: list authors

1.0.0 / 2014-06-04

  • make ms diff be global, not be scope
  • debug: ignore empty strings in enable()
  • node: make DEBUG_COLORS able to disable coloring
  • *: export the colors array
  • npmignore: don't publish the dist dir
  • Makefile: refactor to use browserify
  • package: add "browserify" as a dev dependency
  • Readme: add Web Inspector Colors section
  • node: reset terminal color for the debug content
  • node: map "%o" to util.inspect()
  • browser: map "%j" to JSON.stringify()
  • debug: add custom "formatters"
  • debug: use "ms" module for humanizing the diff
  • Readme: add "bash" syntax highlighting
  • browser: add Firebug color support
  • browser: add colors for WebKit browsers
  • node: apply log to console
  • rewrite: abstract common logic for Node & browsers
  • add .jshintrc file

0.8.1 / 2014-04-14

  • package: re-add the "component" section

0.8.0 / 2014-03-30

  • add enable() method for nodejs. Closes #27
  • change from stderr to stdout
  • remove unnecessary index.js file

0.7.4 / 2013-11-13

  • remove "browserify" key from package.json (fixes something in browserify)

0.7.3 / 2013-10-30

  • fix: catch localStorage security error when cookies are blocked (Chrome)
  • add debug(err) support. Closes #46
  • add .browser prop to package.json. Closes #42

0.7.2 / 2013-02-06

  • fix package.json
  • fix: Mobile Safari (private mode) is broken with debug
  • fix: Use unicode to send escape character to shell instead of octal to work with strict mode javascript

0.7.1 / 2013-02-05

  • add repository URL to package.json
  • add DEBUG_COLORED to force colored output
  • add browserify support
  • fix component. Closes #24

0.7.0 / 2012-05-04

  • Added .component to package.json
  • Added debug.component.js build

0.6.0 / 2012-03-16

  • Added support for "-" prefix in DEBUG [Vinay Pulim]
  • Added .enabled flag to the node version [TooTallNate]

0.5.0 / 2012-02-02

  • Added: humanize diffs. Closes #8
  • Added debug.disable() to the CS variant
  • Removed padding. Closes #10
  • Fixed: persist client-side variant again. Closes #9

0.4.0 / 2012-02-01

  • Added browser variant support for older browsers [TooTallNate]
  • Added debug.enable('project:*') to browser variant [TooTallNate]
  • Added padding to diff (moved it to the right)

0.3.0 / 2012-01-26

  • Added millisecond diff when isatty, otherwise UTC string

0.2.0 / 2012-01-22

  • Added wildcard support

0.1.0 / 2011-12-02

  • Added: remove colors unless stderr isatty [TooTallNate]

0.0.1 / 2010-01-03

  • Initial release
# get Makefile directory name: http://stackoverflow.com/a/5982798/376773
THIS_MAKEFILE_PATH:=$(word $(words $(MAKEFILE_LIST)),$(MAKEFILE_LIST))
THIS_DIR:=$(shell cd $(dir $(THIS_MAKEFILE_PATH));pwd)
# BIN directory
BIN := $(THIS_DIR)/node_modules/.bin
# applications
NODE ?= $(shell which node)
NPM ?= $(NODE) $(shell which npm)
BROWSERIFY ?= $(NODE) $(BIN)/browserify
all: dist/debug.js
install: node_modules
clean:
@rm -rf dist
dist:
@mkdir -p $@
dist/debug.js: node_modules browser.js debug.js dist
@$(BROWSERIFY) \
--standalone debug \
. > $@
distclean: clean
@rm -rf node_modules
node_modules: package.json
@NODE_ENV= $(NPM) install
@touch node_modules
.PHONY: all install clean distclean
/**
* Module dependencies.
*/
var tty = require('tty');
var util = require('util');
/**
* This is the Node.js implementation of `debug()`.
*
* Expose `debug()` as the module.
*/
exports = module.exports = require('./debug');
exports.log = log;
exports.formatArgs = formatArgs;
exports.save = save;
exports.load = load;
exports.useColors = useColors;
/**
* Colors.
*/
exports.colors = [6, 2, 3, 4, 5, 1];
/**
* The file descriptor to write the `debug()` calls to.
* Set the `DEBUG_FD` env variable to override with another value. i.e.:
*
* $ DEBUG_FD=3 node script.js 3>debug.log
*/
var fd = parseInt(process.env.DEBUG_FD, 10) || 2;
var stream = 1 === fd ? process.stdout :
2 === fd ? process.stderr :
createWritableStdioStream(fd);
/**
* Is stdout a TTY? Colored output is enabled when `true`.
*/
function useColors() {
var debugColors = (process.env.DEBUG_COLORS || '').trim().toLowerCase();
if (0 === debugColors.length) {
return tty.isatty(fd);
} else {
return '0' !== debugColors
&& 'no' !== debugColors
&& 'false' !== debugColors
&& 'disabled' !== debugColors;
}
}
/**
* Map %o to `util.inspect()`, since Node doesn't do that out of the box.
*/
var inspect = (4 === util.inspect.length ?
// node <= 0.8.x
function (v, colors) {
return util.inspect(v, void 0, void 0, colors);
} :
// node > 0.8.x
function (v, colors) {
return util.inspect(v, { colors: colors });
}
);
exports.formatters.o = function(v) {
return inspect(v, this.useColors)
.replace(/\s*\n\s*/g, ' ');
};
/**
* Adds ANSI color escape codes if enabled.
*
* @api public
*/
function formatArgs() {
var args = arguments;
var useColors = this.useColors;
var name = this.namespace;
if (useColors) {
var c = this.color;
args[0] = ' \u001b[3' + c + ';1m' + name + ' '
+ '\u001b[0m'
+ args[0] + '\u001b[3' + c + 'm'
+ ' +' + exports.humanize(this.diff) + '\u001b[0m';
} else {
args[0] = new Date().toUTCString()
+ ' ' + name + ' ' + args[0];
}
return args;
}
/**
* Invokes `console.error()` with the specified arguments.
*/
function log() {
return stream.write(util.format.apply(this, arguments) + '\n');
}
/**
* Save `namespaces`.
*
* @param {String} namespaces
* @api private
*/
function save(namespaces) {
if (null == namespaces) {
// If you set a process.env field to null or undefined, it gets cast to the
// string 'null' or 'undefined'. Just delete instead.
delete process.env.DEBUG;
} else {
process.env.DEBUG = namespaces;
}
}
/**
* Load `namespaces`.
*
* @return {String} returns the previously persisted debug modes
* @api private
*/
function load() {
return process.env.DEBUG;
}
/**
* Copied from `node/src/node.js`.
*
* XXX: It's lame that node doesn't expose this API out-of-the-box. It also
* relies on the undocumented `tty_wrap.guessHandleType()` which is also lame.
*/
function createWritableStdioStream (fd) {
var stream;
var tty_wrap = process.binding('tty_wrap');
// Note stream._type is used for test-module-load-list.js
switch (tty_wrap.guessHandleType(fd)) {
case 'TTY':
stream = new tty.WriteStream(fd);
stream._type = 'tty';
// Hack to have stream not keep the event loop alive.
// See https://github.com/joyent/node/issues/1726
if (stream._handle && stream._handle.unref) {
stream._handle.unref();
}
break;
case 'FILE':
var fs = require('fs');
stream = new fs.SyncWriteStream(fd, { autoClose: false });
stream._type = 'fs';
break;
case 'PIPE':
case 'TCP':
var net = require('net');
stream = new net.Socket({
fd: fd,
readable: false,
writable: true
});
// FIXME Should probably have an option in net.Socket to create a
// stream from an existing fd which is writable only. But for now
// we'll just add this hack and set the `readable` member to false.
// Test: ./node test/fixtures/echo.js < /etc/passwd
stream.readable = false;
stream.read = null;
stream._type = 'pipe';
// FIXME Hack to have stream not keep the event loop alive.
// See https://github.com/joyent/node/issues/1726
if (stream._handle && stream._handle.unref) {
stream._handle.unref();
}
break;
default:
// Probably an error on in uv_guess_handle()
throw new Error('Implement me. Unknown stream file type!');
}
// For supporting legacy API we put the FD here.
stream.fd = fd;
stream._isStdio = true;
return stream;
}
/**
* Enable namespaces listed in `process.env.DEBUG` initially.
*/
exports.enable(load());
{
"_args": [
[
{
"raw": "debug@~2.2.0",
"scope": null,
"escapedName": "debug",
"name": "debug",
"rawSpec": "~2.2.0",
"spec": ">=2.2.0 <2.3.0",
"type": "range"
},
"C:\\xampp\\htdocs\\cafe\\node_modules\\express"
]
],
"_from": "debug@>=2.2.0 <2.3.0",
"_id": "debug@2.2.0",
"_inCache": true,
"_location": "/debug",
"_nodeVersion": "0.12.2",
"_npmUser": {
"name": "tootallnate",
"email": "nathan@tootallnate.net"
},
"_npmVersion": "2.7.4",
"_phantomChildren": {},
"_requested": {
"raw": "debug@~2.2.0",
"scope": null,
"escapedName": "debug",
"name": "debug",
"rawSpec": "~2.2.0",
"spec": ">=2.2.0 <2.3.0",
"type": "range"
},
"_requiredBy": [
"/express",
"/finalhandler",
"/send"
],
"_resolved": "https://registry.npmjs.org/debug/-/debug-2.2.0.tgz",
"_shasum": "f87057e995b1a1f6ae6a4960664137bc56f039da",
"_shrinkwrap": null,
"_spec": "debug@~2.2.0",
"_where": "C:\\xampp\\htdocs\\cafe\\node_modules\\express",
"author": {
"name": "TJ Holowaychuk",
"email": "tj@vision-media.ca"
},
"browser": "./browser.js",
"bugs": {
"url": "https://github.com/visionmedia/debug/issues"
},
"component": {
"scripts": {
"debug/index.js": "browser.js",
"debug/debug.js": "debug.js"
}
},
"contributors": [
{
"name": "Nathan Rajlich",
"email": "nathan@tootallnate.net",
"url": "http://n8.io"
}
],
"dependencies": {
"ms": "0.7.1"
},
"description": "small debugging utility",
"devDependencies": {
"browserify": "9.0.3",
"mocha": "*"
},
"directories": {},
"dist": {
"shasum": "f87057e995b1a1f6ae6a4960664137bc56f039da",
"tarball": "https://registry.npmjs.org/debug/-/debug-2.2.0.tgz"
},
"gitHead": "b38458422b5aa8aa6d286b10dfe427e8a67e2b35",
"homepage": "https://github.com/visionmedia/debug",
"keywords": [
"debug",
"log",
"debugger"
],
"license": "MIT",
"main": "./node.js",
"maintainers": [
{
"name": "tjholowaychuk",
"email": "tj@vision-media.ca"
},
{
"name": "tootallnate",
"email": "nathan@tootallnate.net"
}
],
"name": "debug",
"optionalDependencies": {},
"readme": "ERROR: No README data found!",
"repository": {
"type": "git",
"url": "git://github.com/visionmedia/debug.git"
},
"scripts": {},
"version": "2.2.0"
}

debug

tiny node.js debugging utility modelled after node core's debugging technique.

Installation

$ npm install debug

Usage

With debug you simply invoke the exported function to generate your debug function, passing it a name which will determine if a noop function is returned, or a decorated console.error, so all of the console format string goodies you're used to work fine. A unique color is selected per-function for visibility.

Example app.js:

var debug = require('debug')('http')
  , http = require('http')
  , name = 'My App';

// fake app

debug('booting %s', name);

http.createServer(function(req, res){
  debug(req.method + ' ' + req.url);
  res.end('hello\n');
}).listen(3000, function(){
  debug('listening');
});

// fake worker of some kind

require('./worker');

Example worker.js:

var debug = require('debug')('worker');

setInterval(function(){
  debug('doing some work');
}, 1000);

The DEBUG environment variable is then used to enable these based on space or comma-delimited names. Here are some examples:

debug http and worker

debug worker

Windows note

On Windows the environment variable is set using the set command.

set DEBUG=*,-not_this

Then, run the program to be debugged as usual.

Millisecond diff

When actively developing an application it can be useful to see when the time spent between one debug() call and the next. Suppose for example you invoke debug() before requesting a resource, and after as well, the "+NNNms" will show you how much time was spent between calls.

When stdout is not a TTY, Date#toUTCString() is used, making it more useful for logging the debug information as shown below:

Conventions

If you're using this in one or more of your libraries, you should use the name of your library so that developers may toggle debugging as desired without guessing names. If you have more than one debuggers you should prefix them with your library name and use ":" to separate features. For example "bodyParser" from Connect would then be "connect:bodyParser".

Wildcards

The * character may be used as a wildcard. Suppose for example your library has debuggers named "connect:bodyParser", "connect:compress", "connect:session", instead of listing all three with DEBUG=connect:bodyParser,connect:compress,connect:session, you may simply do DEBUG=connect:*, or to run everything using this module simply use DEBUG=*.

You can also exclude specific debuggers by prefixing them with a "-" character. For example, DEBUG=*,-connect:* would include all debuggers except those starting with "connect:".

Browser support

Debug works in the browser as well, currently persisted by localStorage. Consider the situation shown below where you have worker:a and worker:b, and wish to debug both. Somewhere in the code on your page, include:

window.myDebug = require("debug");

("debug" is a global object in the browser so we give this object a different name.) When your page is open in the browser, type the following in the console:

myDebug.enable("worker:*")

Refresh the page. Debug output will continue to be sent to the console until it is disabled by typing myDebug.disable() in the console.

a = debug('worker:a');
b = debug('worker:b');

setInterval(function(){
  a('doing some work');
}, 1000);

setInterval(function(){
  b('doing some work');
}, 1200);

Web Inspector Colors

Colors are also enabled on "Web Inspectors" that understand the %c formatting option. These are WebKit web inspectors, Firefox (since version 31) and the Firebug plugin for Firefox (any version).

Colored output looks something like:

stderr vs stdout

You can set an alternative logging method per-namespace by overriding the log method on a per-namespace or globally:

Example stdout.js:

var debug = require('debug');
var error = debug('app:error');

// by default stderr is used
error('goes to stderr!');

var log = debug('app:log');
// set this namespace to log via console.log
log.log = console.log.bind(console); // don't forget to bind to console!
log('goes to stdout');
error('still goes to stderr!');

// set all output to go via console.info
// overrides all per-namespace log settings
debug.log = console.info.bind(console);
error('now goes to stdout via console.info');
log('still goes to stdout, but via console.info now');

Save debug output to a file

You can save all debug statements to a file by piping them.

Example:

$ DEBUG_FD=3 node your-app.js 3> whatever.log

Authors

  • TJ Holowaychuk
  • Nathan Rajlich

License

(The MIT License)

Copyright (c) 2014 TJ Holowaychuk <tj@vision-media.ca>

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.

1.1.0 / 2015-09-14

  • Enable strict mode in more places
  • Support io.js 3.x
  • Support io.js 2.x
  • Support web browser loading
    • Requires bundler like Browserify or webpack

1.0.1 / 2015-04-07

  • Fix TypeErrors when under 'use strict' code
  • Fix useless type name on auto-generated messages
  • Support io.js 1.x
  • Support Node.js 0.12

1.0.0 / 2014-09-17

  • No changes

0.4.5 / 2014-09-09

  • Improve call speed to functions using the function wrapper
  • Support Node.js 0.6

0.4.4 / 2014-07-27

  • Work-around v8 generating empty stack traces

0.4.3 / 2014-07-26

  • Fix exception when global Error.stackTraceLimit is too low

0.4.2 / 2014-07-19

  • Correct call site for wrapped functions and properties

0.4.1 / 2014-07-19

  • Improve automatic message generation for function properties

0.4.0 / 2014-07-19

  • Add TRACE_DEPRECATION environment variable
  • Remove non-standard grey color from color output
  • Support --no-deprecation argument
  • Support --trace-deprecation argument
  • Support deprecate.property(fn, prop, message)

0.3.0 / 2014-06-16

  • Add NO_DEPRECATION environment variable

0.2.0 / 2014-06-15

  • Add deprecate.property(obj, prop, message)
  • Remove supports-color dependency for node.js 0.8

0.1.0 / 2014-06-15

  • Add deprecate.function(fn, message)
  • Add process.on('deprecation', fn) emitter
  • Automatically generate message when omitted from deprecate()

0.0.1 / 2014-06-15

  • Fix warning for dynamic calls at singe call site

0.0.0 / 2014-06-15

  • Initial implementation
/*!
* depd
* Copyright(c) 2014-2015 Douglas Christopher Wilson
* MIT Licensed
*/
/**
* Module dependencies.
*/
var callSiteToString = require('./lib/compat').callSiteToString
var eventListenerCount = require('./lib/compat').eventListenerCount
var relative = require('path').relative
/**
* Module exports.
*/
module.exports = depd
/**
* Get the path to base files on.
*/
var basePath = process.cwd()
/**
* Determine if namespace is contained in the string.
*/
function containsNamespace(str, namespace) {
var val = str.split(/[ ,]+/)
namespace = String(namespace).toLowerCase()
for (var i = 0 ; i < val.length; i++) {
if (!(str = val[i])) continue;
// namespace contained
if (str === '*' || str.toLowerCase() === namespace) {
return true
}
}
return false
}
/**
* Convert a data descriptor to accessor descriptor.
*/
function convertDataDescriptorToAccessor(obj, prop, message) {
var descriptor = Object.getOwnPropertyDescriptor(obj, prop)
var value = descriptor.value
descriptor.get = function getter() { return value }
if (descriptor.writable) {
descriptor.set = function setter(val) { return value = val }
}
delete descriptor.value
delete descriptor.writable
Object.defineProperty(obj, prop, descriptor)
return descriptor
}
/**
* Create arguments string to keep arity.
*/
function createArgumentsString(arity) {
var str = ''
for (var i = 0; i < arity; i++) {
str += ', arg' + i
}
return str.substr(2)
}
/**
* Create stack string from stack.
*/
function createStackString(stack) {
var str = this.name + ': ' + this.namespace
if (this.message) {
str += ' deprecated ' + this.message
}
for (var i = 0; i < stack.length; i++) {
str += '\n at ' + callSiteToString(stack[i])
}
return str
}
/**
* Create deprecate for namespace in caller.
*/
function depd(namespace) {
if (!namespace) {
throw new TypeError('argument namespace is required')
}
var stack = getStack()
var site = callSiteLocation(stack[1])
var file = site[0]
function deprecate(message) {
// call to self as log
log.call(deprecate, message)
}
deprecate._file = file
deprecate._ignored = isignored(namespace)
deprecate._namespace = namespace
deprecate._traced = istraced(namespace)
deprecate._warned = Object.create(null)
deprecate.function = wrapfunction
deprecate.property = wrapproperty
return deprecate
}
/**
* Determine if namespace is ignored.
*/
function isignored(namespace) {
/* istanbul ignore next: tested in a child processs */
if (process.noDeprecation) {
// --no-deprecation support
return true
}
var str = process.env.NO_DEPRECATION || ''
// namespace ignored
return containsNamespace(str, namespace)
}
/**
* Determine if namespace is traced.
*/
function istraced(namespace) {
/* istanbul ignore next: tested in a child processs */
if (process.traceDeprecation) {
// --trace-deprecation support
return true
}
var str = process.env.TRACE_DEPRECATION || ''
// namespace traced
return containsNamespace(str, namespace)
}
/**
* Display deprecation message.
*/
function log(message, site) {
var haslisteners = eventListenerCount(process, 'deprecation') !== 0
// abort early if no destination
if (!haslisteners && this._ignored) {
return
}
var caller
var callFile
var callSite
var i = 0
var seen = false
var stack = getStack()
var file = this._file
if (site) {
// provided site
callSite = callSiteLocation(stack[1])
callSite.name = site.name
file = callSite[0]
} else {
// get call site
i = 2
site = callSiteLocation(stack[i])
callSite = site
}
// get caller of deprecated thing in relation to file
for (; i < stack.length; i++) {
caller = callSiteLocation(stack[i])
callFile = caller[0]
if (callFile === file) {
seen = true
} else if (callFile === this._file) {
file = this._file
} else if (seen) {
break
}
}
var key = caller
? site.join(':') + '__' + caller.join(':')
: undefined
if (key !== undefined && key in this._warned) {
// already warned
return
}
this._warned[key] = true
// generate automatic message from call site
if (!message) {
message = callSite === site || !callSite.name
? defaultMessage(site)
: defaultMessage(callSite)
}
// emit deprecation if listeners exist
if (haslisteners) {
var err = DeprecationError(this._namespace, message, stack.slice(i))
process.emit('deprecation', err)
return
}
// format and write message
var format = process.stderr.isTTY
? formatColor
: formatPlain
var msg = format.call(this, message, caller, stack.slice(i))
process.stderr.write(msg + '\n', 'utf8')
return
}
/**
* Get call site location as array.
*/
function callSiteLocation(callSite) {
var file = callSite.getFileName() || '<anonymous>'
var line = callSite.getLineNumber()
var colm = callSite.getColumnNumber()
if (callSite.isEval()) {
file = callSite.getEvalOrigin() + ', ' + file
}
var site = [file, line, colm]
site.callSite = callSite
site.name = callSite.getFunctionName()
return site
}
/**
* Generate a default message from the site.
*/
function defaultMessage(site) {
var callSite = site.callSite
var funcName = site.name
// make useful anonymous name
if (!funcName) {
funcName = '<anonymous@' + formatLocation(site) + '>'
}
var context = callSite.getThis()
var typeName = context && callSite.getTypeName()
// ignore useless type name
if (typeName === 'Object') {
typeName = undefined
}
// make useful type name
if (typeName === 'Function') {
typeName = context.name || typeName
}
return typeName && callSite.getMethodName()
? typeName + '.' + funcName
: funcName
}
/**
* Format deprecation message without color.
*/
function formatPlain(msg, caller, stack) {
var timestamp = new Date().toUTCString()
var formatted = timestamp
+ ' ' + this._namespace
+ ' deprecated ' + msg
// add stack trace
if (this._traced) {
for (var i = 0; i < stack.length; i++) {
formatted += '\n at ' + callSiteToString(stack[i])
}
return formatted
}
if (caller) {
formatted += ' at ' + formatLocation(caller)
}
return formatted
}
/**
* Format deprecation message with color.
*/
function formatColor(msg, caller, stack) {
var formatted = '\x1b[36;1m' + this._namespace + '\x1b[22;39m' // bold cyan
+ ' \x1b[33;1mdeprecated\x1b[22;39m' // bold yellow
+ ' \x1b[0m' + msg + '\x1b[39m' // reset
// add stack trace
if (this._traced) {
for (var i = 0; i < stack.length; i++) {
formatted += '\n \x1b[36mat ' + callSiteToString(stack[i]) + '\x1b[39m' // cyan
}
return formatted
}
if (caller) {
formatted += ' \x1b[36m' + formatLocation(caller) + '\x1b[39m' // cyan
}
return formatted
}
/**
* Format call site location.
*/
function formatLocation(callSite) {
return relative(basePath, callSite[0])
+ ':' + callSite[1]
+ ':' + callSite[2]
}
/**
* Get the stack as array of call sites.
*/
function getStack() {
var limit = Error.stackTraceLimit
var obj = {}
var prep = Error.prepareStackTrace
Error.prepareStackTrace = prepareObjectStackTrace
Error.stackTraceLimit = Math.max(10, limit)
// capture the stack
Error.captureStackTrace(obj)
// slice this function off the top
var stack = obj.stack.slice(1)
Error.prepareStackTrace = prep
Error.stackTraceLimit = limit
return stack
}
/**
* Capture call site stack from v8.
*/
function prepareObjectStackTrace(obj, stack) {
return stack
}
/**
* Return a wrapped function in a deprecation message.
*/
function wrapfunction(fn, message) {
if (typeof fn !== 'function') {
throw new TypeError('argument fn must be a function')
}
var args = createArgumentsString(fn.length)
var deprecate = this
var stack = getStack()
var site = callSiteLocation(stack[1])
site.name = fn.name
var deprecatedfn = eval('(function (' + args + ') {\n'
+ '"use strict"\n'
+ 'log.call(deprecate, message, site)\n'
+ 'return fn.apply(this, arguments)\n'
+ '})')
return deprecatedfn
}
/**
* Wrap property in a deprecation message.
*/
function wrapproperty(obj, prop, message) {
if (!obj || (typeof obj !== 'object' && typeof obj !== 'function')) {
throw new TypeError('argument obj must be object')
}
var descriptor = Object.getOwnPropertyDescriptor(obj, prop)
if (!descriptor) {
throw new TypeError('must call property on owner object')
}
if (!descriptor.configurable) {
throw new TypeError('property must be configurable')
}
var deprecate = this
var stack = getStack()
var site = callSiteLocation(stack[1])
// set site name
site.name = prop
// convert data descriptor
if ('value' in descriptor) {
descriptor = convertDataDescriptorToAccessor(obj, prop, message)
}
var get = descriptor.get
var set = descriptor.set
// wrap getter
if (typeof get === 'function') {
descriptor.get = function getter() {
log.call(deprecate, message, site)
return get.apply(this, arguments)
}
}
// wrap setter
if (typeof set === 'function') {
descriptor.set = function setter() {
log.call(deprecate, message, site)
return set.apply(this, arguments)
}
}
Object.defineProperty(obj, prop, descriptor)
}
/**
* Create DeprecationError for deprecation
*/
function DeprecationError(namespace, message, stack) {
var error = new Error()
var stackString
Object.defineProperty(error, 'constructor', {
value: DeprecationError
})
Object.defineProperty(error, 'message', {
configurable: true,
enumerable: false,
value: message,
writable: true
})
Object.defineProperty(error, 'name', {
enumerable: false,
configurable: true,
value: 'DeprecationError',
writable: true
})
Object.defineProperty(error, 'namespace', {
configurable: true,
enumerable: false,
value: namespace,
writable: true
})
Object.defineProperty(error, 'stack', {
configurable: true,
enumerable: false,
get: function () {
if (stackString !== undefined) {
return stackString
}
// prepare stack trace
return stackString = createStackString.call(this, stack)
},
set: function setter(val) {
stackString = val
}
})
return error
}
/*!
* depd
* Copyright(c) 2015 Douglas Christopher Wilson
* MIT Licensed
*/
'use strict'
/**
* Module exports.
* @public
*/
module.exports = depd
/**
* Create deprecate for namespace in caller.
*/
function depd(namespace) {
if (!namespace) {
throw new TypeError('argument namespace is required')
}
function deprecate(message) {
// no-op in browser
}
deprecate._file = undefined
deprecate._ignored = true
deprecate._namespace = namespace
deprecate._traced = false
deprecate._warned = Object.create(null)
deprecate.function = wrapfunction
deprecate.property = wrapproperty
return deprecate
}
/**
* Return a wrapped function in a deprecation message.
*
* This is a no-op version of the wrapper, which does nothing but call
* validation.
*/
function wrapfunction(fn, message) {
if (typeof fn !== 'function') {
throw new TypeError('argument fn must be a function')
}
return fn
}
/**
* Wrap property in a deprecation message.
*
* This is a no-op version of the wrapper, which does nothing but call
* validation.
*/
function wrapproperty(obj, prop, message) {
if (!obj || (typeof obj !== 'object' && typeof obj !== 'function')) {
throw new TypeError('argument obj must be object')
}
var descriptor = Object.getOwnPropertyDescriptor(obj, prop)
if (!descriptor) {
throw new TypeError('must call property on owner object')
}
if (!descriptor.configurable) {
throw new TypeError('property must be configurable')
}
return
}
/*!
* depd
* Copyright(c) 2014 Douglas Christopher Wilson
* MIT Licensed
*/
'use strict'
/**
* Module exports.
*/
module.exports = bufferConcat
/**
* Concatenate an array of Buffers.
*/
function bufferConcat(bufs) {
var length = 0
for (var i = 0, len = bufs.length; i < len; i++) {
length += bufs[i].length
}
var buf = new Buffer(length)
var pos = 0
for (var i = 0, len = bufs.length; i < len; i++) {
bufs[i].copy(buf, pos)
pos += bufs[i].length
}
return buf
}
/*!
* depd
* Copyright(c) 2014 Douglas Christopher Wilson
* MIT Licensed
*/
'use strict'
/**
* Module exports.
*/
module.exports = callSiteToString
/**
* Format a CallSite file location to a string.
*/
function callSiteFileLocation(callSite) {
var fileName
var fileLocation = ''
if (callSite.isNative()) {
fileLocation = 'native'
} else if (callSite.isEval()) {
fileName = callSite.getScriptNameOrSourceURL()
if (!fileName) {
fileLocation = callSite.getEvalOrigin()
}
} else {
fileName = callSite.getFileName()
}
if (fileName) {
fileLocation += fileName
var lineNumber = callSite.getLineNumber()
if (lineNumber != null) {
fileLocation += ':' + lineNumber
var columnNumber = callSite.getColumnNumber()
if (columnNumber) {
fileLocation += ':' + columnNumber
}
}
}
return fileLocation || 'unknown source'
}
/**
* Format a CallSite to a string.
*/
function callSiteToString(callSite) {
var addSuffix = true
var fileLocation = callSiteFileLocation(callSite)
var functionName = callSite.getFunctionName()
var isConstructor = callSite.isConstructor()
var isMethodCall = !(callSite.isToplevel() || isConstructor)
var line = ''
if (isMethodCall) {
var methodName = callSite.getMethodName()
var typeName = getConstructorName(callSite)
if (functionName) {
if (typeName && functionName.indexOf(typeName) !== 0) {
line += typeName + '.'
}
line += functionName
if (methodName && functionName.lastIndexOf('.' + methodName) !== functionName.length - methodName.length - 1) {
line += ' [as ' + methodName + ']'
}
} else {
line += typeName + '.' + (methodName || '<anonymous>')
}
} else if (isConstructor) {
line += 'new ' + (functionName || '<anonymous>')
} else if (functionName) {
line += functionName
} else {
addSuffix = false
line += fileLocation
}
if (addSuffix) {
line += ' (' + fileLocation + ')'
}
return line
}
/**
* Get constructor name of reviver.
*/
function getConstructorName(obj) {
var receiver = obj.receiver
return (receiver.constructor && receiver.constructor.name) || null
}
/*!
* depd
* Copyright(c) 2015 Douglas Christopher Wilson
* MIT Licensed
*/
'use strict'
/**
* Module exports.
* @public
*/
module.exports = eventListenerCount
/**
* Get the count of listeners on an event emitter of a specific type.
*/
function eventListenerCount(emitter, type) {
return emitter.listeners(type).length
}
/*!
* depd
* Copyright(c) 2014-2015 Douglas Christopher Wilson
* MIT Licensed
*/
'use strict'
/**
* Module dependencies.
* @private
*/
var Buffer = require('buffer')
var EventEmitter = require('events').EventEmitter
/**
* Module exports.
* @public
*/
lazyProperty(module.exports, 'bufferConcat', function bufferConcat() {
return Buffer.concat || require('./buffer-concat')
})
lazyProperty(module.exports, 'callSiteToString', function callSiteToString() {
var limit = Error.stackTraceLimit
var obj = {}
var prep = Error.prepareStackTrace
function prepareObjectStackTrace(obj, stack) {
return stack
}
Error.prepareStackTrace = prepareObjectStackTrace
Error.stackTraceLimit = 2
// capture the stack
Error.captureStackTrace(obj)
// slice the stack
var stack = obj.stack.slice()
Error.prepareStackTrace = prep
Error.stackTraceLimit = limit
return stack[0].toString ? toString : require('./callsite-tostring')
})
lazyProperty(module.exports, 'eventListenerCount', function eventListenerCount() {
return EventEmitter.listenerCount || require('./event-listener-count')
})
/**
* Define a lazy property.
*/
function lazyProperty(obj, prop, getter) {
function get() {
var val = getter()
Object.defineProperty(obj, prop, {
configurable: true,
enumerable: true,
value: val
})
return val
}
Object.defineProperty(obj, prop, {
configurable: true,
enumerable: true,
get: get
})
}
/**
* Call toString() on the obj
*/
function toString(obj) {
return obj.toString()
}
(The MIT License)
Copyright (c) 2014-2015 Douglas Christopher Wilson
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.
{
"_args": [
[
{
"raw": "depd@~1.1.0",
"scope": null,
"escapedName": "depd",
"name": "depd",
"rawSpec": "~1.1.0",
"spec": ">=1.1.0 <1.2.0",
"type": "range"
},
"C:\\xampp\\htdocs\\cafe\\node_modules\\express"
]
],
"_from": "depd@>=1.1.0 <1.2.0",
"_id": "depd@1.1.0",
"_inCache": true,
"_location": "/depd",
"_npmUser": {
"name": "dougwilson",
"email": "doug@somethingdoug.com"
},
"_npmVersion": "1.4.28",
"_phantomChildren": {},
"_requested": {
"raw": "depd@~1.1.0",
"scope": null,
"escapedName": "depd",
"name": "depd",
"rawSpec": "~1.1.0",
"spec": ">=1.1.0 <1.2.0",
"type": "range"
},
"_requiredBy": [
"/express",
"/send"
],
"_resolved": "https://registry.npmjs.org/depd/-/depd-1.1.0.tgz",
"_shasum": "e1bd82c6aab6ced965b97b88b17ed3e528ca18c3",
"_shrinkwrap": null,
"_spec": "depd@~1.1.0",
"_where": "C:\\xampp\\htdocs\\cafe\\node_modules\\express",
"author": {
"name": "Douglas Christopher Wilson",
"email": "doug@somethingdoug.com"
},
"browser": "lib/browser/index.js",
"bugs": {
"url": "https://github.com/dougwilson/nodejs-depd/issues"
},
"dependencies": {},
"description": "Deprecate all the things",
"devDependencies": {
"beautify-benchmark": "0.2.4",
"benchmark": "1.0.0",
"istanbul": "0.3.5",
"mocha": "~1.21.5"
},
"directories": {},
"dist": {
"shasum": "e1bd82c6aab6ced965b97b88b17ed3e528ca18c3",
"tarball": "https://registry.npmjs.org/depd/-/depd-1.1.0.tgz"
},
"engines": {
"node": ">= 0.6"
},
"files": [
"lib/",
"History.md",
"LICENSE",
"index.js",
"Readme.md"
],
"gitHead": "78c659de20283e3a6bee92bda455e6daff01686a",
"homepage": "https://github.com/dougwilson/nodejs-depd",
"keywords": [
"deprecate",
"deprecated"
],
"license": "MIT",
"maintainers": [
{
"name": "dougwilson",
"email": "doug@somethingdoug.com"
}
],
"name": "depd",
"optionalDependencies": {},
"readme": "ERROR: No README data found!",
"repository": {
"type": "git",
"url": "git+https://github.com/dougwilson/nodejs-depd.git"
},
"scripts": {
"bench": "node benchmark/index.js",
"test": "mocha --reporter spec --bail test/",
"test-ci": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --no-exit test/",
"test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot test/"
},
"version": "1.1.0"
}

depd

NPM Version NPM Downloads Node.js Version Linux Build Windows Build Coverage Status Gratipay

Deprecate all the things

With great modules comes great responsibility; mark things deprecated!

Install

This module is installed directly using npm:

$ npm install depd

This module can also be bundled with systems like Browserify or webpack, though by default this module will alter it's API to no longer display or track deprecations.

API

var deprecate = require('depd')('my-module')

This library allows you to display deprecation messages to your users. This library goes above and beyond with deprecation warnings by introspection of the call stack (but only the bits that it is interested in).

Instead of just warning on the first invocation of a deprecated function and never again, this module will warn on the first invocation of a deprecated function per unique call site, making it ideal to alert users of all deprecated uses across the code base, rather than just whatever happens to execute first.

The deprecation warnings from this module also include the file and line information for the call into the module that the deprecated function was in.

NOTE this library has a similar interface to the debug module, and this module uses the calling file to get the boundary for the call stacks, so you should always create a new deprecate object in each file and not within some central file.

depd(namespace)

Create a new deprecate function that uses the given namespace name in the messages and will display the call site prior to the stack entering the file this function was called from. It is highly suggested you use the name of your module as the namespace.

deprecate(message)

Call this function from deprecated code to display a deprecation message. This message will appear once per unique caller site. Caller site is the first call site in the stack in a different file from the caller of this function.

If the message is omitted, a message is generated for you based on the site of the deprecate() call and will display the name of the function called, similar to the name displayed in a stack trace.

deprecate.function(fn, message)

Call this function to wrap a given function in a deprecation message on any call to the function. An optional message can be supplied to provide a custom message.

deprecate.property(obj, prop, message)

Call this function to wrap a given property on object in a deprecation message on any accessing or setting of the property. An optional message can be supplied to provide a custom message.

The method must be called on the object where the property belongs (not inherited from the prototype).

If the property is a data descriptor, it will be converted to an accessor descriptor in order to display the deprecation message.

process.on('deprecation', fn)

This module will allow easy capturing of deprecation errors by emitting the errors as the type "deprecation" on the global process. If there are no listeners for this type, the errors are written to STDERR as normal, but if there are any listeners, nothing will be written to STDERR and instead only emitted. From there, you can write the errors in a different format or to a logging source.

The error represents the deprecation and is emitted only once with the same rules as writing to STDERR. The error has the following properties:

  • message - This is the message given by the library
  • name - This is always 'DeprecationError'
  • namespace - This is the namespace the deprecation came from
  • stack - This is the stack of the call to the deprecated thing

Example error.stack output:

DeprecationError: my-cool-module deprecated oldfunction
    at Object.<anonymous> ([eval]-wrapper:6:22)
    at Module._compile (module.js:456:26)
    at evalScript (node.js:532:25)
    at startup (node.js:80:7)
    at node.js:902:3

process.env.NO_DEPRECATION

As a user of modules that are deprecated, the environment variable NO_DEPRECATION is provided as a quick solution to silencing deprecation warnings from being output. The format of this is similar to that of DEBUG:

$ NO_DEPRECATION=my-module,othermod node app.js

This will suppress deprecations from being output for "my-module" and "othermod". The value is a list of comma-separated namespaces. To suppress every warning across all namespaces, use the value * for a namespace.

Providing the argument --no-deprecation to the node executable will suppress all deprecations (only available in Node.js 0.8 or higher).

NOTE This will not suppress the deperecations given to any "deprecation" event listeners, just the output to STDERR.

process.env.TRACE_DEPRECATION

As a user of modules that are deprecated, the environment variable TRACE_DEPRECATION is provided as a solution to getting more detailed location information in deprecation warnings by including the entire stack trace. The format of this is the same as NO_DEPRECATION:

$ TRACE_DEPRECATION=my-module,othermod node app.js

This will include stack traces for deprecations being output for "my-module" and "othermod". The value is a list of comma-separated namespaces. To trace every warning across all namespaces, use the value * for a namespace.

Providing the argument --trace-deprecation to the node executable will trace all deprecations (only available in Node.js 0.8 or higher).

NOTE This will not trace the deperecations silenced by NO_DEPRECATION.

Display

message

When a user calls a function in your library that you mark deprecated, they will see the following written to STDERR (in the given colors, similar colors and layout to the debug module):

bright cyan    bright yellow
|              |          reset       cyan
|              |          |           |
▼              ▼          ▼           ▼
my-cool-module deprecated oldfunction [eval]-wrapper:6:22
▲              ▲          ▲           ▲
|              |          |           |
namespace      |          |           location of mycoolmod.oldfunction() call
               |          deprecation message
               the word "deprecated"

If the user redirects their STDERR to a file or somewhere that does not support colors, they see (similar layout to the debug module):

Sun, 15 Jun 2014 05:21:37 GMT my-cool-module deprecated oldfunction at [eval]-wrapper:6:22
▲                             ▲              ▲          ▲              ▲
|                             |              |          |              |
timestamp of message          namespace      |          |             location of mycoolmod.oldfunction() call
                                             |          deprecation message
                                             the word "deprecated"

Examples

Deprecating all calls to a function

This will display a deprecated message about "oldfunction" being deprecated from "my-module" on STDERR.

var deprecate = require('depd')('my-cool-module')

// message automatically derived from function name
// Object.oldfunction
exports.oldfunction = deprecate.function(function oldfunction() {
  // all calls to function are deprecated
})

// specific message
exports.oldfunction = deprecate.function(function () {
  // all calls to function are deprecated
}, 'oldfunction')

Conditionally deprecating a function call

This will display a deprecated message about "weirdfunction" being deprecated from "my-module" on STDERR when called with less than 2 arguments.

var deprecate = require('depd')('my-cool-module')

exports.weirdfunction = function () {
  if (arguments.length < 2) {
    // calls with 0 or 1 args are deprecated
    deprecate('weirdfunction args < 2')
  }
}

When calling deprecate as a function, the warning is counted per call site within your own module, so you can display different deprecations depending on different situations and the users will still get all the warnings:

var deprecate = require('depd')('my-cool-module')

exports.weirdfunction = function () {
  if (arguments.length < 2) {
    // calls with 0 or 1 args are deprecated
    deprecate('weirdfunction args < 2')
  } else if (typeof arguments[0] !== 'string') {
    // calls with non-string first argument are deprecated
    deprecate('weirdfunction non-string first arg')
  }
}

Deprecating property access

This will display a deprecated message about "oldprop" being deprecated from "my-module" on STDERR when accessed. A deprecation will be displayed when setting the value and when getting the value.

var deprecate = require('depd')('my-cool-module')

exports.oldprop = 'something'

// message automatically derives from property name
deprecate.property(exports, 'oldprop')

// explicit message
deprecate.property(exports, 'oldprop', 'oldprop >= 0.10')

License

MIT

/*!
* destroy
* Copyright(c) 2014 Jonathan Ong
* MIT Licensed
*/
'use strict'
/**
* Module dependencies.
* @private
*/
var ReadStream = require('fs').ReadStream
var Stream = require('stream')
/**
* Module exports.
* @public
*/
module.exports = destroy
/**
* Destroy a stream.
*
* @param {object} stream
* @public
*/
function destroy(stream) {
if (stream instanceof ReadStream) {
return destroyReadStream(stream)
}
if (!(stream instanceof Stream)) {
return stream
}
if (typeof stream.destroy === 'function') {
stream.destroy()
}
return stream
}
/**
* Destroy a ReadStream.
*
* @param {object} stream
* @private
*/
function destroyReadStream(stream) {
stream.destroy()
if (typeof stream.close === 'function') {
// node.js core bug work-around
stream.on('open', onOpenClose)
}
return stream
}
/**
* On open handler to close stream.
* @private
*/
function onOpenClose() {
if (typeof this.fd === 'number') {
// actually close down the fd
this.close()
}
}
The MIT License (MIT)
Copyright (c) 2014 Jonathan Ong me@jongleberry.com
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.
{
"_args": [
[
{
"raw": "destroy@~1.0.4",
"scope": null,
"escapedName": "destroy",
"name": "destroy",
"rawSpec": "~1.0.4",
"spec": ">=1.0.4 <1.1.0",
"type": "range"
},
"C:\\xampp\\htdocs\\cafe\\node_modules\\send"
]
],
"_from": "destroy@>=1.0.4 <1.1.0",
"_id": "destroy@1.0.4",
"_inCache": true,
"_location": "/destroy",
"_npmUser": {
"name": "dougwilson",
"email": "doug@somethingdoug.com"
},
"_npmVersion": "1.4.28",
"_phantomChildren": {},
"_requested": {
"raw": "destroy@~1.0.4",
"scope": null,
"escapedName": "destroy",
"name": "destroy",
"rawSpec": "~1.0.4",
"spec": ">=1.0.4 <1.1.0",
"type": "range"
},
"_requiredBy": [
"/send"
],
"_resolved": "https://registry.npmjs.org/destroy/-/destroy-1.0.4.tgz",
"_shasum": "978857442c44749e4206613e37946205826abd80",
"_shrinkwrap": null,
"_spec": "destroy@~1.0.4",
"_where": "C:\\xampp\\htdocs\\cafe\\node_modules\\send",
"author": {
"name": "Jonathan Ong",
"email": "me@jongleberry.com",
"url": "http://jongleberry.com"
},
"bugs": {
"url": "https://github.com/stream-utils/destroy/issues"
},
"contributors": [
{
"name": "Douglas Christopher Wilson",
"email": "doug@somethingdoug.com"
}
],
"dependencies": {},
"description": "destroy a stream if possible",
"devDependencies": {
"istanbul": "0.4.2",
"mocha": "2.3.4"
},
"directories": {},
"dist": {
"shasum": "978857442c44749e4206613e37946205826abd80",
"tarball": "https://registry.npmjs.org/destroy/-/destroy-1.0.4.tgz"
},
"files": [
"index.js",
"LICENSE"
],
"gitHead": "86edea01456f5fa1027f6a47250c34c713cbcc3b",
"homepage": "https://github.com/stream-utils/destroy",
"keywords": [
"stream",
"streams",
"destroy",
"cleanup",
"leak",
"fd"
],
"license": "MIT",
"maintainers": [
{
"name": "jongleberry",
"email": "jonathanrichardong@gmail.com"
},
{
"name": "dougwilson",
"email": "doug@somethingdoug.com"
}
],
"name": "destroy",
"optionalDependencies": {},
"readme": "ERROR: No README data found!",
"repository": {
"type": "git",
"url": "git+https://github.com/stream-utils/destroy.git"
},
"scripts": {
"test": "mocha --reporter spec",
"test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot",
"test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter dot"
},
"version": "1.0.4"
}

Destroy

NPM version Build status Test coverage License Downloads Gittip

Destroy a stream.

This module is meant to ensure a stream gets destroyed, handling different APIs and Node.js bugs.

API

var destroy = require('destroy')

destroy(stream)

Destroy the given stream. In most cases, this is identical to a simple stream.destroy() call. The rules are as follows for a given stream:

  1. If the stream is an instance of ReadStream, then call stream.destroy() and add a listener to the open event to call stream.close() if it is fired. This is for a Node.js bug that will leak a file descriptor if .destroy() is called before open.
  2. If the stream is not an instance of Stream, then nothing happens.
  3. If the stream has a .destroy() method, then call it.

The function returns the stream passed in as the argument.

Example

var destroy = require('destroy')

var fs = require('fs')
var stream = fs.createReadStream('package.json')

// ... and later
destroy(stream)
/* See LICENSE file for terms of use */
/*
* Text diff implementation.
*
* This library supports the following APIS:
* JsDiff.diffChars: Character by character diff
* JsDiff.diffWords: Word (as defined by \b regex) diff which ignores whitespace
* JsDiff.diffLines: Line based diff
*
* JsDiff.diffCss: Diff targeted at CSS content
*
* These methods are based on the implementation proposed in
* "An O(ND) Difference Algorithm and its Variations" (Myers, 1986).
* http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.4.6927
*/
var JsDiff = (function() {
/*jshint maxparams: 5*/
function clonePath(path) {
return { newPos: path.newPos, components: path.components.slice(0) };
}
function removeEmpty(array) {
var ret = [];
for (var i = 0; i < array.length; i++) {
if (array[i]) {
ret.push(array[i]);
}
}
return ret;
}
function escapeHTML(s) {
var n = s;
n = n.replace(/&/g, '&amp;');
n = n.replace(/</g, '&lt;');
n = n.replace(/>/g, '&gt;');
n = n.replace(/"/g, '&quot;');
return n;
}
var Diff = function(ignoreWhitespace) {
this.ignoreWhitespace = ignoreWhitespace;
};
Diff.prototype = {
diff: function(oldString, newString) {
// Handle the identity case (this is due to unrolling editLength == 0
if (newString === oldString) {
return [{ value: newString }];
}
if (!newString) {
return [{ value: oldString, removed: true }];
}
if (!oldString) {
return [{ value: newString, added: true }];
}
newString = this.tokenize(newString);
oldString = this.tokenize(oldString);
var newLen = newString.length, oldLen = oldString.length;
var maxEditLength = newLen + oldLen;
var bestPath = [{ newPos: -1, components: [] }];
// Seed editLength = 0
var oldPos = this.extractCommon(bestPath[0], newString, oldString, 0);
if (bestPath[0].newPos+1 >= newLen && oldPos+1 >= oldLen) {
return bestPath[0].components;
}
for (var editLength = 1; editLength <= maxEditLength; editLength++) {
for (var diagonalPath = -1*editLength; diagonalPath <= editLength; diagonalPath+=2) {
var basePath;
var addPath = bestPath[diagonalPath-1],
removePath = bestPath[diagonalPath+1];
oldPos = (removePath ? removePath.newPos : 0) - diagonalPath;
if (addPath) {
// No one else is going to attempt to use this value, clear it
bestPath[diagonalPath-1] = undefined;
}
var canAdd = addPath && addPath.newPos+1 < newLen;
var canRemove = removePath && 0 <= oldPos && oldPos < oldLen;
if (!canAdd && !canRemove) {
bestPath[diagonalPath] = undefined;
continue;
}
// Select the diagonal that we want to branch from. We select the prior
// path whose position in the new string is the farthest from the origin
// and does not pass the bounds of the diff graph
if (!canAdd || (canRemove && addPath.newPos < removePath.newPos)) {
basePath = clonePath(removePath);
this.pushComponent(basePath.components, oldString[oldPos], undefined, true);
} else {
basePath = clonePath(addPath);
basePath.newPos++;
this.pushComponent(basePath.components, newString[basePath.newPos], true, undefined);
}
var oldPos = this.extractCommon(basePath, newString, oldString, diagonalPath);
if (basePath.newPos+1 >= newLen && oldPos+1 >= oldLen) {
return basePath.components;
} else {
bestPath[diagonalPath] = basePath;
}
}
}
},
pushComponent: function(components, value, added, removed) {
var last = components[components.length-1];
if (last && last.added === added && last.removed === removed) {
// We need to clone here as the component clone operation is just
// as shallow array clone
components[components.length-1] =
{value: this.join(last.value, value), added: added, removed: removed };
} else {
components.push({value: value, added: added, removed: removed });
}
},
extractCommon: function(basePath, newString, oldString, diagonalPath) {
var newLen = newString.length,
oldLen = oldString.length,
newPos = basePath.newPos,
oldPos = newPos - diagonalPath;
while (newPos+1 < newLen && oldPos+1 < oldLen && this.equals(newString[newPos+1], oldString[oldPos+1])) {
newPos++;
oldPos++;
this.pushComponent(basePath.components, newString[newPos], undefined, undefined);
}
basePath.newPos = newPos;
return oldPos;
},
equals: function(left, right) {
var reWhitespace = /\S/;
if (this.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right)) {
return true;
} else {
return left === right;
}
},
join: function(left, right) {
return left + right;
},
tokenize: function(value) {
return value;
}
};
var CharDiff = new Diff();
var WordDiff = new Diff(true);
var WordWithSpaceDiff = new Diff();
WordDiff.tokenize = WordWithSpaceDiff.tokenize = function(value) {
return removeEmpty(value.split(/(\s+|\b)/));
};
var CssDiff = new Diff(true);
CssDiff.tokenize = function(value) {
return removeEmpty(value.split(/([{}:;,]|\s+)/));
};
var LineDiff = new Diff();
LineDiff.tokenize = function(value) {
var retLines = [],
lines = value.split(/^/m);
for(var i = 0; i < lines.length; i++) {
var line = lines[i],
lastLine = lines[i - 1];
// Merge lines that may contain windows new lines
if (line == '\n' && lastLine && lastLine[lastLine.length - 1] === '\r') {
retLines[retLines.length - 1] += '\n';
} else if (line) {
retLines.push(line);
}
}
return retLines;
};
return {
Diff: Diff,
diffChars: function(oldStr, newStr) { return CharDiff.diff(oldStr, newStr); },
diffWords: function(oldStr, newStr) { return WordDiff.diff(oldStr, newStr); },
diffWordsWithSpace: function(oldStr, newStr) { return WordWithSpaceDiff.diff(oldStr, newStr); },
diffLines: function(oldStr, newStr) { return LineDiff.diff(oldStr, newStr); },
diffCss: function(oldStr, newStr) { return CssDiff.diff(oldStr, newStr); },
createPatch: function(fileName, oldStr, newStr, oldHeader, newHeader) {
var ret = [];
ret.push('Index: ' + fileName);
ret.push('===================================================================');
ret.push('--- ' + fileName + (typeof oldHeader === 'undefined' ? '' : '\t' + oldHeader));
ret.push('+++ ' + fileName + (typeof newHeader === 'undefined' ? '' : '\t' + newHeader));
var diff = LineDiff.diff(oldStr, newStr);
if (!diff[diff.length-1].value) {
diff.pop(); // Remove trailing newline add
}
diff.push({value: '', lines: []}); // Append an empty value to make cleanup easier
function contextLines(lines) {
return lines.map(function(entry) { return ' ' + entry; });
}
function eofNL(curRange, i, current) {
var last = diff[diff.length-2],
isLast = i === diff.length-2,
isLastOfType = i === diff.length-3 && (current.added !== last.added || current.removed !== last.removed);
// Figure out if this is the last line for the given file and missing NL
if (!/\n$/.test(current.value) && (isLast || isLastOfType)) {
curRange.push('\\ No newline at end of file');
}
}
var oldRangeStart = 0, newRangeStart = 0, curRange = [],
oldLine = 1, newLine = 1;
for (var i = 0; i < diff.length; i++) {
var current = diff[i],
lines = current.lines || current.value.replace(/\n$/, '').split('\n');
current.lines = lines;
if (current.added || current.removed) {
if (!oldRangeStart) {
var prev = diff[i-1];
oldRangeStart = oldLine;
newRangeStart = newLine;
if (prev) {
curRange = contextLines(prev.lines.slice(-4));
oldRangeStart -= curRange.length;
newRangeStart -= curRange.length;
}
}
curRange.push.apply(curRange, lines.map(function(entry) { return (current.added?'+':'-') + entry; }));
eofNL(curRange, i, current);
if (current.added) {
newLine += lines.length;
} else {
oldLine += lines.length;
}
} else {
if (oldRangeStart) {
// Close out any changes that have been output (or join overlapping)
if (lines.length <= 8 && i < diff.length-2) {
// Overlapping
curRange.push.apply(curRange, contextLines(lines));
} else {
// end the range and output
var contextSize = Math.min(lines.length, 4);
ret.push(
'@@ -' + oldRangeStart + ',' + (oldLine-oldRangeStart+contextSize)
+ ' +' + newRangeStart + ',' + (newLine-newRangeStart+contextSize)
+ ' @@');
ret.push.apply(ret, curRange);
ret.push.apply(ret, contextLines(lines.slice(0, contextSize)));
if (lines.length <= 4) {
eofNL(ret, i, current);
}
oldRangeStart = 0; newRangeStart = 0; curRange = [];
}
}
oldLine += lines.length;
newLine += lines.length;
}
}
return ret.join('\n') + '\n';
},
applyPatch: function(oldStr, uniDiff) {
var diffstr = uniDiff.split('\n');
var diff = [];
var remEOFNL = false,
addEOFNL = false;
for (var i = (diffstr[0][0]==='I'?4:0); i < diffstr.length; i++) {
if(diffstr[i][0] === '@') {
var meh = diffstr[i].split(/@@ -(\d+),(\d+) \+(\d+),(\d+) @@/);
diff.unshift({
start:meh[3],
oldlength:meh[2],
oldlines:[],
newlength:meh[4],
newlines:[]
});
} else if(diffstr[i][0] === '+') {
diff[0].newlines.push(diffstr[i].substr(1));
} else if(diffstr[i][0] === '-') {
diff[0].oldlines.push(diffstr[i].substr(1));
} else if(diffstr[i][0] === ' ') {
diff[0].newlines.push(diffstr[i].substr(1));
diff[0].oldlines.push(diffstr[i].substr(1));
} else if(diffstr[i][0] === '\\') {
if (diffstr[i-1][0] === '+') {
remEOFNL = true;
} else if(diffstr[i-1][0] === '-') {
addEOFNL = true;
}
}
}
var str = oldStr.split('\n');
for (var i = diff.length - 1; i >= 0; i--) {
var d = diff[i];
for (var j = 0; j < d.oldlength; j++) {
if(str[d.start-1+j] !== d.oldlines[j]) {
return false;
}
}
Array.prototype.splice.apply(str,[d.start-1,+d.oldlength].concat(d.newlines));
}
if (remEOFNL) {
while (!str[str.length-1]) {
str.pop();
}
} else if (addEOFNL) {
str.push('');
}
return str.join('\n');
},
convertChangesToXML: function(changes){
var ret = [];
for ( var i = 0; i < changes.length; i++) {
var change = changes[i];
if (change.added) {
ret.push('<ins>');
} else if (change.removed) {
ret.push('<del>');
}
ret.push(escapeHTML(change.value));
if (change.added) {
ret.push('</ins>');
} else if (change.removed) {
ret.push('</del>');
}
}
return ret.join('');
},
// See: http://code.google.com/p/google-diff-match-patch/wiki/API
convertChangesToDMP: function(changes){
var ret = [], change;
for ( var i = 0; i < changes.length; i++) {
change = changes[i];
ret.push([(change.added ? 1 : change.removed ? -1 : 0), change.value]);
}
return ret;
}
};
})();
if (typeof module !== 'undefined') {
module.exports = JsDiff;
}
{
"_args": [
[
{
"raw": "diff@~1.0.8",
"scope": null,
"escapedName": "diff",
"name": "diff",
"rawSpec": "~1.0.8",
"spec": ">=1.0.8 <1.1.0",
"type": "range"
},
"C:\\xampp\\htdocs\\cafe\\node_modules\\vows"
]
],
"_from": "diff@>=1.0.8 <1.1.0",
"_id": "diff@1.0.8",
"_inCache": true,
"_location": "/diff",
"_npmUser": {
"name": "kpdecker",
"email": "kpdecker@gmail.com"
},
"_npmVersion": "1.3.11",
"_phantomChildren": {},
"_requested": {
"raw": "diff@~1.0.8",
"scope": null,
"escapedName": "diff",
"name": "diff",
"rawSpec": "~1.0.8",
"spec": ">=1.0.8 <1.1.0",
"type": "range"
},
"_requiredBy": [
"/vows"
],
"_resolved": "https://registry.npmjs.org/diff/-/diff-1.0.8.tgz",
"_shasum": "343276308ec991b7bc82267ed55bc1411f971666",
"_shrinkwrap": null,
"_spec": "diff@~1.0.8",
"_where": "C:\\xampp\\htdocs\\cafe\\node_modules\\vows",
"bugs": {
"url": "http://github.com/kpdecker/jsdiff/issues",
"email": "kpdecker@gmail.com"
},
"dependencies": {},
"description": "A javascript text diff implementation.",
"devDependencies": {
"colors": "~0.6.2",
"mocha": "~1.6",
"should": "~1.2"
},
"directories": {},
"dist": {
"shasum": "343276308ec991b7bc82267ed55bc1411f971666",
"tarball": "https://registry.npmjs.org/diff/-/diff-1.0.8.tgz"
},
"engines": {
"node": ">=0.3.1"
},
"files": [
"diff.js"
],
"homepage": "https://github.com/kpdecker/jsdiff#readme",
"keywords": [
"diff",
"javascript"
],
"licenses": [
{
"type": "BSD",
"url": "http://github.com/kpdecker/jsdiff/blob/master/LICENSE"
}
],
"main": "./diff",
"maintainers": [
{
"name": "kpdecker",
"email": "kpdecker@gmail.com"
}
],
"name": "diff",
"optionalDependencies": {},
"readme": "ERROR: No README data found!",
"repository": {
"type": "git",
"url": "git://github.com/kpdecker/jsdiff.git"
},
"scripts": {
"test": "node_modules/.bin/mocha test/*.js"
},
"version": "1.0.8"
}

jsdiff

Build Status

A javascript text differencing implementation.

Based on the algorithm proposed in "An O(ND) Difference Algorithm and its Variations" (Myers, 1986).

Installation

npm install diff

or

git clone git://github.com/kpdecker/jsdiff.git

API

  • JsDiff.diffChars(oldStr, newStr) - diffs two blocks of text, comparing character by character.

    Returns a list of change objects (See below).

  • JsDiff.diffWords(oldStr, newStr) - diffs two blocks of text, comparing word by word.

    Returns a list of change objects (See below).

  • JsDiff.diffLines(oldStr, newStr) - diffs two blocks of text, comparing line by line.

    Returns a list of change objects (See below).

  • JsDiff.diffCss(oldStr, newStr) - diffs two blocks of text, comparing CSS tokens.

    Returns a list of change objects (See below).

  • JsDiff.createPatch(fileName, oldStr, newStr, oldHeader, newHeader) - creates a unified diff patch.

    Parameters:

    • fileName : String to be output in the filename sections of the patch
    • oldStr : Original string value
    • newStr : New string value
    • oldHeader : Additional information to include in the old file header
    • newHeader : Additional information to include in thew new file header
  • JsDiff.applyPatch(oldStr, diffStr) - applies a unified diff patch.

    Return a string containing new version of provided data.

  • convertChangesToXML(changes) - converts a list of changes to a serialized XML format

Change Objects

Many of the methods above return change objects. These objects are consist of the following fields:

  • value: Text content
  • added: True if the value was inserted into the new string
  • removed: True of the value was removed from the old string

Note that some cases may omit a particular flag field. Comparison on the flag fields should always be done in a truthy or falsy manner.

Examples

Basic example in Node

require('colors')
var jsdiff = require('diff');

var one = 'beep boop';
var other = 'beep boob blah';

var diff = jsdiff.diffChars(one, other);

diff.forEach(function(part){
  // green for additions, red for deletions
  // grey for common parts
  var color = part.added ? 'green' :
    part.removed ? 'red' : 'grey';
  process.stderr.write(part.value[color]);
});

console.log()

Running the above program should yield

Node Example

Basic example in a web page

<pre id="display"></pre>
<script src="diff.js"></script>
<script>
var one = 'beep boop';
var other = 'beep boob blah';

var diff = JsDiff.diffChars(one, other);

diff.forEach(function(part){
  // green for additions, red for deletions
  // grey for common parts
  var color = part.added ? 'green' :
    part.removed ? 'red' : 'grey';
  var span = document.createElement('span');
  span.style.color = color;
  span.appendChild(document
    .createTextNode(part.value));
  display.appendChild(span);
});
</script>

Open the above .html file in a browser and you should see

Node Example

Full online demo

License

Software License Agreement (BSD License)

Copyright (c) 2009-2011, Kevin Decker kpdecker@gmail.com

All rights reserved.

Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

  • Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.

  • Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

  • Neither the name of Kevin Decker nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Bitdeli Badge

/*!
* ee-first
* Copyright(c) 2014 Jonathan Ong
* MIT Licensed
*/
'use strict'
/**
* Module exports.
* @public
*/
module.exports = first
/**
* Get the first event in a set of event emitters and event pairs.
*
* @param {array} stuff
* @param {function} done
* @public
*/
function first(stuff, done) {
if (!Array.isArray(stuff))
throw new TypeError('arg must be an array of [ee, events...] arrays')
var cleanups = []
for (var i = 0; i < stuff.length; i++) {
var arr = stuff[i]
if (!Array.isArray(arr) || arr.length < 2)
throw new TypeError('each array member must be [ee, events...]')
var ee = arr[0]
for (var j = 1; j < arr.length; j++) {
var event = arr[j]
var fn = listener(event, callback)
// listen to the event
ee.on(event, fn)
// push this listener to the list of cleanups
cleanups.push({
ee: ee,
event: event,
fn: fn,
})
}
}
function callback() {
cleanup()
done.apply(null, arguments)
}
function cleanup() {
var x
for (var i = 0; i < cleanups.length; i++) {
x = cleanups[i]
x.ee.removeListener(x.event, x.fn)
}
}
function thunk(fn) {
done = fn
}
thunk.cancel = cleanup
return thunk
}
/**
* Create the event listener.
* @private
*/
function listener(event, done) {
return function onevent(arg1) {
var args = new Array(arguments.length)
var ee = this
var err = event === 'error'
? arg1
: null
// copy args to prevent arguments escaping scope
for (var i = 0; i < args.length; i++) {
args[i] = arguments[i]
}
done(err, ee, event, args)
}
}
The MIT License (MIT)
Copyright (c) 2014 Jonathan Ong me@jongleberry.com
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.
{
"_args": [
[
{
"raw": "ee-first@1.1.1",
"scope": null,
"escapedName": "ee-first",
"name": "ee-first",
"rawSpec": "1.1.1",
"spec": "1.1.1",
"type": "version"
},
"C:\\xampp\\htdocs\\cafe\\node_modules\\on-finished"
]
],
"_from": "ee-first@1.1.1",
"_id": "ee-first@1.1.1",
"_inCache": true,
"_location": "/ee-first",
"_npmUser": {
"name": "dougwilson",
"email": "doug@somethingdoug.com"
},
"_npmVersion": "1.4.28",
"_phantomChildren": {},
"_requested": {
"raw": "ee-first@1.1.1",
"scope": null,
"escapedName": "ee-first",
"name": "ee-first",
"rawSpec": "1.1.1",
"spec": "1.1.1",
"type": "version"
},
"_requiredBy": [
"/on-finished"
],
"_resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz",
"_shasum": "590c61156b0ae2f4f0255732a158b266bc56b21d",
"_shrinkwrap": null,
"_spec": "ee-first@1.1.1",
"_where": "C:\\xampp\\htdocs\\cafe\\node_modules\\on-finished",
"author": {
"name": "Jonathan Ong",
"email": "me@jongleberry.com",
"url": "http://jongleberry.com"
},
"bugs": {
"url": "https://github.com/jonathanong/ee-first/issues"
},
"contributors": [
{
"name": "Douglas Christopher Wilson",
"email": "doug@somethingdoug.com"
}
],
"dependencies": {},
"description": "return the first event in a set of ee/event pairs",
"devDependencies": {
"istanbul": "0.3.9",
"mocha": "2.2.5"
},
"directories": {},
"dist": {
"shasum": "590c61156b0ae2f4f0255732a158b266bc56b21d",
"tarball": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz"
},
"files": [
"index.js",
"LICENSE"
],
"gitHead": "512e0ce4cc3643f603708f965a97b61b1a9c0441",
"homepage": "https://github.com/jonathanong/ee-first",
"license": "MIT",
"maintainers": [
{
"name": "jongleberry",
"email": "jonathanrichardong@gmail.com"
},
{
"name": "dougwilson",
"email": "doug@somethingdoug.com"
}
],
"name": "ee-first",
"optionalDependencies": {},
"readme": "ERROR: No README data found!",
"repository": {
"type": "git",
"url": "git+https://github.com/jonathanong/ee-first.git"
},
"scripts": {
"test": "mocha --reporter spec --bail --check-leaks test/",
"test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/",
"test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/"
},
"version": "1.1.1"
}

EE First

NPM version Build status Test coverage License Downloads Gittip

Get the first event in a set of event emitters and event pairs, then clean up after itself.

Install

$ npm install ee-first

API

var first = require('ee-first')

first(arr, listener)

Invoke listener on the first event from the list specified in arr. arr is an array of arrays, with each array in the format [ee, ...event]. listener will be called only once, the first time any of the given events are emitted. If error is one of the listened events, then if that fires first, the listener will be given the err argument.

The listener is invoked as listener(err, ee, event, args), where err is the first argument emitted from an error event, if applicable; ee is the event emitter that fired; event is the string event name that fired; and args is an array of the arguments that were emitted on the event.

var ee1 = new EventEmitter()
var ee2 = new EventEmitter()

first([
  [ee1, 'close', 'end', 'error'],
  [ee2, 'error']
], function (err, ee, event, args) {
  // listener invoked
})

.cancel()

The group of listeners can be cancelled before being invoked and have all the event listeners removed from the underlying event emitters.

var thunk = first([
  [ee1, 'close', 'end', 'error'],
  [ee2, 'error']
], function (err, ee, event, args) {
  // listener invoked
})

// cancel and clean up
thunk.cancel()

1.0.1 / 2016-06-09

  • Fix encoding unpaired surrogates at start/end of string

1.0.0 / 2016-06-08

  • Initial release
/*!
* encodeurl
* Copyright(c) 2016 Douglas Christopher Wilson
* MIT Licensed
*/
'use strict'
/**
* Module exports.
* @public
*/
module.exports = encodeUrl
/**
* RegExp to match non-URL code points, *after* encoding (i.e. not including "%")
* and including invalid escape sequences.
* @private
*/
var ENCODE_CHARS_REGEXP = /(?:[^\x21\x25\x26-\x3B\x3D\x3F-\x5B\x5D\x5F\x61-\x7A\x7E]|%(?:[^0-9A-Fa-f]|[0-9A-Fa-f][^0-9A-Fa-f]))+/g
/**
* RegExp to match unmatched surrogate pair.
* @private
*/
var UNMATCHED_SURROGATE_PAIR_REGEXP = /(^|[^\uD800-\uDBFF])[\uDC00-\uDFFF]|[\uD800-\uDBFF]([^\uDC00-\uDFFF]|$)/g
/**
* String to replace unmatched surrogate pair with.
* @private
*/
var UNMATCHED_SURROGATE_PAIR_REPLACE = '$1\uFFFD$2'
/**
* Encode a URL to a percent-encoded form, excluding already-encoded sequences.
*
* This function will take an already-encoded URL and encode all the non-URL
* code points. This function will not encode the "%" character unless it is
* not part of a valid sequence (`%20` will be left as-is, but `%foo` will
* be encoded as `%25foo`).
*
* This encode is meant to be "safe" and does not throw errors. It will try as
* hard as it can to properly encode the given URL, including replacing any raw,
* unpaired surrogate pairs with the Unicode replacement character prior to
* encoding.
*
* @param {string} url
* @return {string}
* @public
*/
function encodeUrl (url) {
return String(url)
.replace(UNMATCHED_SURROGATE_PAIR_REGEXP, UNMATCHED_SURROGATE_PAIR_REPLACE)
.replace(ENCODE_CHARS_REGEXP, encodeURI)
}
(The MIT License)
Copyright (c) 2016 Douglas Christopher Wilson
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.
{
"_args": [
[
{
"raw": "encodeurl@~1.0.1",
"scope": null,
"escapedName": "encodeurl",
"name": "encodeurl",
"rawSpec": "~1.0.1",
"spec": ">=1.0.1 <1.1.0",
"type": "range"
},
"C:\\xampp\\htdocs\\cafe\\node_modules\\express"
]
],
"_from": "encodeurl@>=1.0.1 <1.1.0",
"_id": "encodeurl@1.0.1",
"_inCache": true,
"_location": "/encodeurl",
"_nodeVersion": "4.4.3",
"_npmOperationalInternal": {
"host": "packages-12-west.internal.npmjs.com",
"tmp": "tmp/encodeurl-1.0.1.tgz_1465519736251_0.09314409433864057"
},
"_npmUser": {
"name": "dougwilson",
"email": "doug@somethingdoug.com"
},
"_npmVersion": "2.15.1",
"_phantomChildren": {},
"_requested": {
"raw": "encodeurl@~1.0.1",
"scope": null,
"escapedName": "encodeurl",
"name": "encodeurl",
"rawSpec": "~1.0.1",
"spec": ">=1.0.1 <1.1.0",
"type": "range"
},
"_requiredBy": [
"/express",
"/send",
"/serve-static"
],
"_resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-1.0.1.tgz",
"_shasum": "79e3d58655346909fe6f0f45a5de68103b294d20",
"_shrinkwrap": null,
"_spec": "encodeurl@~1.0.1",
"_where": "C:\\xampp\\htdocs\\cafe\\node_modules\\express",
"bugs": {
"url": "https://github.com/pillarjs/encodeurl/issues"
},
"contributors": [
{
"name": "Douglas Christopher Wilson",
"email": "doug@somethingdoug.com"
}
],
"dependencies": {},
"description": "Encode a URL to a percent-encoded form, excluding already-encoded sequences",
"devDependencies": {
"eslint": "2.11.1",
"eslint-config-standard": "5.3.1",
"eslint-plugin-promise": "1.3.2",
"eslint-plugin-standard": "1.3.2",
"istanbul": "0.4.3",
"mocha": "2.5.3"
},
"directories": {},
"dist": {
"shasum": "79e3d58655346909fe6f0f45a5de68103b294d20",
"tarball": "https://registry.npmjs.org/encodeurl/-/encodeurl-1.0.1.tgz"
},
"engines": {
"node": ">= 0.8"
},
"files": [
"LICENSE",
"HISTORY.md",
"README.md",
"index.js"
],
"gitHead": "39ed0c235fed4cea7d012038fd6bb0480561d226",
"homepage": "https://github.com/pillarjs/encodeurl#readme",
"keywords": [
"encode",
"encodeurl",
"url"
],
"license": "MIT",
"maintainers": [
{
"name": "dougwilson",
"email": "doug@somethingdoug.com"
}
],
"name": "encodeurl",
"optionalDependencies": {},
"readme": "ERROR: No README data found!",
"repository": {
"type": "git",
"url": "git+https://github.com/pillarjs/encodeurl.git"
},
"scripts": {
"lint": "eslint **/*.js",
"test": "mocha --reporter spec --bail --check-leaks test/",
"test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/",
"test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/"
},
"version": "1.0.1"
}

encodeurl

NPM Version NPM Downloads Node.js Version Build Status Test Coverage

Encode a URL to a percent-encoded form, excluding already-encoded sequences

Installation

$ npm install encodeurl

API

var encodeUrl = require('encodeurl')

encodeUrl(url)

Encode a URL to a percent-encoded form, excluding already-encoded sequences.

This function will take an already-encoded URL and encode all the non-URL code points (as UTF-8 byte sequences). This function will not encode the "%" character unless it is not part of a valid sequence (%20 will be left as-is, but %foo will be encoded as %25foo).

This encode is meant to be "safe" and does not throw errors. It will try as hard as it can to properly encode the given URL, including replacing any raw, unpaired surrogate pairs with the Unicode replacement character prior to encoding.

This function is similar to the intrinsic function encodeURI, except it will not encode the % character if that is part of a valid sequence, will not encode [ and ] (for IPv6 hostnames) and will replace raw, unpaired surrogate pairs with the Unicode replacement character (instead of throwing).

Examples

Encode a URL containing user-controled data

var encodeUrl = require('encodeurl')
var escapeHtml = require('escape-html')

http.createServer(function onRequest (req, res) {
  // get encoded form of inbound url
  var url = encodeUrl(req.url)

  // create html message
  var body = '<p>Location ' + escapeHtml(url) + ' not found</p>'

  // send a 404
  res.statusCode = 404
  res.setHeader('Content-Type', 'text/html; charset=UTF-8')
  res.setHeader('Content-Length', String(Buffer.byteLength(body, 'utf-8')))
  res.end(body, 'utf-8')
})

Encode a URL for use in a header field

var encodeUrl = require('encodeurl')
var escapeHtml = require('escape-html')
var url = require('url')

http.createServer(function onRequest (req, res) {
  // parse inbound url
  var href = url.parse(req)

  // set new host for redirect
  href.host = 'localhost'
  href.protocol = 'https:'
  href.slashes = true

  // create location header
  var location = encodeUrl(url.format(href))

  // create html message
  var body = '<p>Redirecting to new site: ' + escapeHtml(location) + '</p>'

  // send a 301
  res.statusCode = 301
  res.setHeader('Content-Type', 'text/html; charset=UTF-8')
  res.setHeader('Content-Length', String(Buffer.byteLength(body, 'utf-8')))
  res.setHeader('Location', location)
  res.end(body, 'utf-8')
})

Testing

$ npm test
$ npm run lint

References

License

MIT

1.8.2 / 2016-12-11

  • [chore] Bump engine.io-parser to version 1.3.2 (#523)

1.8.1 / 2016-11-27

  • [fix] Only add defined callbacks to the stack (#447)

1.8.0 / 2016-11-20

  • [fix] Fixed regression creating connection over https from node (#513)
  • [fix] Fixed regression creating connection over wss from node (#514)
  • [feature] Enable definition of timeouts for xhr-polling (#456)
  • [feature] Added flag forceNode to override the normal behavior of prefering Browser based implementations. (#469)
  • [feature] add localAddress option (#487)
  • [chore] update dependencies (#516)
  • [chore] Speed up lint by avoiding '**/*.js' matching pattern (#517)
  • [chore] Bump debug to version 2.3.3 (#520)

1.7.2 / 2016-10-24

  • [fix] Set accept header to / to support react app proxy (#508)
  • [fix] remove a workaround for ios (#465)
  • [fix] onPacket now emits data on 'closing' state as well (#484)
  • [fix] Obfuscate ActiveXObject occurrences (#509)
  • [docs] Add missing onlyBinaryUpgrades option in the docs (#510)
  • [chore] Add Github issue and PR templates (#511)

1.7.1 / 2016-10-20

  • [fix] Define "requestsCount" var and "requests" hash unconditionally (#490)
  • [perf] Add all properties to the socket in the constructor (#488)
  • [chore] Update zuul browser settings (#504)
  • [chore] Bump engine.io-parser to 1.3.1 (#505)
  • [chore] Use more-specific imports for StealJS compatibility (#467)

1.7.0 / 2016-10-05

  • [fix] Revert "default rejectUnauthorized to true" (#496)
  • [fix] Use xhr.responseText if xhr.response is not provided (#483)
  • [fix] Fix issue with errors during WebSocket creation not being caught (#475)
  • [style] Add missing semi-colon (#501)
  • [chore] Add gulp & babel in the build process (#455)
  • [chore] Add eslint (#458)
  • [chore] Bump zuul (#464)
  • [chore] Remove unused submodule (#466)
  • [chore] Bumping ws to 1.1.1 (#478)
  • [chore] Update zuul browser settings following EOL notices (#486)
  • [chore] Bump engine.io-parser (#492)
  • [chore] Make the build status badge point towards master (#497)
  • [chore] Bump zuul to 3.11.0 & zuul-ngrok to 4.0.0 (#498)
  • [chore] Restrict files included in npm package (#499)

1.6.11 / 2016-06-23

  • bump version

1.6.10 / 2016-06-23

  • bump version

1.6.9 / 2016-05-02

  • default rejectUnauthorized to true

1.6.8 / 2016-01-25

  • safely resolve ws module

1.6.7 / 2016-01-10

  • prevent ws from being added to the bundle
  • added jsonp fix for when no <script> is found

1.6.6 / 2016-01-07

  • support: add fallback to global for nativescript [@ligaz]
  • exclude ws instead of ignoring it from build [@lpinca]

1.6.5 / 2016-01-05

  • package: bump ws for sec advisory

1.6.4 / 2015-12-04

  • ipv6 url support
  • README: fix the description of the timestampRequests option
  • transports: use yeast to generate the cache busting id
  • fix arraybuffer > base64 for binary sends

1.6.3 / 2015-12-01

  • remove compress option from control packets
  • threshold for permessage-deflate

1.6.2 / 2015-11-30

  • package: bump ws for memory fix with compression
  • fix response parsing error for polling (unused)

1.6.1 / 2015-11-28

  • fix packet options that ws changes [Nibbler999]
  • package: use published engine.io-parser

1.6.0 / 2015-11-28

  • test with travis containers
  • socket: remove duplicate declaration (fixes #434)
  • package: bump debug (fixes #433)
  • bump zuul and zuul-ngrok
  • package: fix repository url
  • bump ws for several improvements
  • fix rejectUnauthorized bug
  • websocket: improve firing of drain in websocket transport
  • socket: clean up buffers right after close event
  • change semantics of the write callback for polling (fire upon flush instead drain)
  • socket: fix host parsing for IPv6 URLs
  • socket: handle parser errors appropriately
  • expose ping and pong events
  • enable supportsBinary when running as a node client
  • introduce extraHeaders support
  • fix error when passing WebSocket#send second argument on Safari
  • support compression

1.5.4 / 2015-09-09

  • package: bump engine.io-parser

1.5.3 / 2015-09-09

  • package: bump ws to fix node 0.4.0

1.5.2 / 2015-07-09

  • package: bump ws to fix windows build issues

1.5.1 / 2015-01-19

  • do not rely on git(1) for dep, point to tarball instead

1.5.0 / 2015-01-18

  • package: bump engine.io-parser
  • fix IE tests firing too many connections [rase-]
  • fix default port detection when host is specified [defunctzombie]
  • add support for custom SSL options in constructor [rase-]
  • only call xhr.abort() on error cases in polling-xhr [samcday]

1.4.3 / 2014-11-21

  • support: make the build system work with the latest browserify
  • test: remove test with partial browser support
  • Fixed calls to addEventListener in old browsers

1.4.2 / 2014-10-27

  • remove invalid value for strict mode
  • IE10 should prefer using XHR2 over XDR because it's safer
  • fixed transport close deferring logic [nkzawa]
  • wait for buffer to be drained before closing [nkzawa]

1.4.1 / 2014-10-03

  • Fixed "jsonp polling iframe removal error"
  • Move ws upgrade needing connection tests to a block checking browser support.
  • check readyState in sendPacket and close on upgradeError too
  • defer close while upgrading a transport

1.4.0 / 2014-09-03

  • add matrix support for travis runs.
  • add enablesXDR option to turn on XDomainRequest
  • package: bump browserify
  • package: bump engine.io-parser
  • style and close socket after assert
  • add support for jsonp option to turn it off

1.3.1 / 2014-06-19

  • transport: catch utf8 decode errors

1.3.0 / 2014-06-13

  • smaller inherits utility
  • fix a test for ws
  • upgrade emitter dep to not rely on tarball

1.2.2 / 2014-05-30

  • package: bump engine.io-parser for binary utf8 fix

1.2.1 / 2014-05-22

  • build

1.2.0 / 2014-05-18

  • removed flashsocket, moving to userland
  • new build

1.1.1 / 2014-05-14

  • jsonp-polling: fixed newline double escaping
  • package: bump parser
  • remove legacy Socket#onopen call
  • added tests for multibyte strings

1.1.0 / 2014-04-27

  • bump zuul version
  • renamed removeAllListeners to cleanup
  • use inherits package instead of inherit
  • removed all references to util.js
  • fix if statement in FlashWS.ready method
  • polling-jsonp: prevent spurious errors from being emitted when the window is unloaded
  • polling-xhr: fix a comment and remove unneeded document reference
  • enforce cache busting for all user agents
  • JSONP and test fixes for fails in IE
  • package: bump engine.io-parser
  • polling-xhr: abort the request when the window is unloaded

1.0.5 / 2014-03-18

  • package: bump engine.io-parser for android binary fix

1.0.4 / 2014-03-14

  • no base64 encoding for no reason when using websockets

1.0.3 / 2014-03-12

  • fix browserify

1.0.2 / 2014-03-12

  • bump engine.io-parser
  • made parseJSON and parseURI from util their own modules [gkoren]
  • clean up tests
  • clean up browserify

1.0.1 / 2014-03-06

  • package: bump engine.io-parser

1.0.0 / 2014-03-06

  • run browserify without shims
  • emit socket upgrade event after upgrade done
  • better feature detection for XHR2
  • added rememberUpgrade option
  • binary support

0.9.0 / 2014-02-09

  • Fix simple host:port URLs and IPV6 [bmalehorn]
  • Fix XHR cleanup method [poohlty]
  • Match semantics of close event with WebSocket. If an error occurs and open hadn't fired before, we still emit close as per WebSocket spec [mokesmokes].
  • Removed SPEC (now in engine.io-protocol repository)
  • Remove Socket#open docs (private API) [mokesmokes]

0.8.2 / 2014-01-18

  • polling-xhr: avoid catching user-thrown errors
  • util: remove unused hasCORS
  • polling: remove deferring for faster startup (fixes #174)
  • engine now works perfectly on workers

0.8.1 / 2014-01-17

  • package: bump debug to fix localStorage issue (fixes #213)
  • remove duplicate xmlhttprequest code
  • add iphone automated testing
  • bump zuul to 1.3.0 to improve tests performance
  • use invalid ip address for incorrect connection test
  • Fix GH-224, remove sockets array

0.8.0 / 2014-01-05

  • socket: emit upgrade errors as upgradeError instead of error

0.7.14 / 2014-01-01

  • test: increase timeouts for network tests
  • test: whitelist globals
  • test: improve socket closing test
  • polling: improve url timestamp for ie11 and allow force disabling
  • polling-xhr: handle errors for xhr creation (fixes access denied issues)
  • polling-xhr: style
  • socket: more instrumentation for transport creation
  • socket: allow explicit false for timestampRequests
  • socket: accept null as first argument
  • Makefile: cleanup
  • .travis: deprecate 0.6

0.7.13 / 2013-12-20

  • use jsonp in favor of XDomainRequest to preserve Cookie headers in all situations [3rd-eden] (fixes #217)
  • run zuul tests after node tests [defunctzombie]
  • add zuul support for easier browser testing [defunctzombie]

0.7.12 / 2013-11-11

  • engine.io: updated build to fix WebSocket constructor issue
  • package: move browserify into devDeps

0.7.11 / 2013-11-06

  • AMD support
  • Makefile: build now smaller thanks to browserify
  • add browserify support

0.7.10 / 2013-10-28

  • fixed issue which prevented IE9 and under to pass Cookies to server during handshake
  • package: update "ws" to v0.4.31
  • fixed - there is no host property only hostname
  • fixed - flash socket creation
  • fixed - emit errors thrown by xhr.send()

0.7.9 / 2013-08-30

  • websocket: pass undefined as the WebSocket "protocols"

0.7.8 / 2013-08-30

  • package: update "ws"

0.7.7 / 2013-08-30

  • package: bump ws to 0.4.30
  • websocket: no more env sniffing, just require ws [TooTallNate]
  • websocket: remove the "bufferedAmount" checking logic [TooTallNate]

0.7.6 / 2013-08-30

  • package: revert ws to avoid upgrade fail now

0.7.5 / 2013-08-30

  • package: bump ws to 0.4.30

0.7.4 / 2013-08-25

  • package: rolling back to ws 0.4.25 due to disconnection bug

0.7.3 / 2013-08-23

  • noop bump

0.7.2 / 2013-08-23

  • transports: fix WebSocket transport in the web browser (again)

0.7.1 / 2013-08-23

  • transports: fix WebSocket transport in the web browser
  • package: upgrade "ws" to v0.4.29

0.7.0 / 2013-08-23

  • socket: add agent option
  • package: point "xmlhttprequest" to our LearnBoost fork for agent support
  • package: specify a newer version of "ws" that includes agent support
  • util: use "component/has-cors"
  • transport: fix whitespace
  • util: use "component/global"
  • package: Add repository field to readme
  • socket: Don't lose packets writen during upgrade after a re-open
  • socket: use a consistent "debug" name for socket.js
  • package: Update emitter dep to 1.0.1 for old IE support

0.6.3 / 2013-06-21

  • fix check readyState in polling transport (Naoyuki Kanezawa)
  • use http url in npm dependencies for emitter (Eric Schoffstall)

0.6.2 / 2013-06-15

  • transports: improve polling orderly close (fixes #164)
  • socket: ignore further transport communication upon onClose
  • socket: added missing socket#onerror support
  • socket: don't call socket#onclose if previous state was not open
  • transports: fix iOS5 crash issue
  • Makefile: extra precaution when building to avoid 0.6.0 build problem

0.6.1 / 2013-06-06

  • engine.io: fixed build

0.6.0 / 2013-05-31

  • does not emit close on incorrect socket connection
  • use indexof component for ie8 and below
  • improved x-domain handling
  • introduce public ping api
  • added drain event
  • fix flush and flushComplete events
  • fixed drain bug splicing with upgrading
  • add support for callbacks with socket.send()

0.5.0 / 2013-03-16

  • socket: implement qs support for string
  • added query.EIO to take protocol version from parser
  • use istanbul for code coverage
  • integrated engine.io-protocol 0.3.0
  • updated ws
  • fixed JSONPPolling iframe removal error
  • changed error message to match xhr error message on jsonp transport script tag
  • Added onerror handler for script tag in jsonp transport
  • remove uid qs
  • Added missing colon in payload. Thanks @lsm

0.4.3 / 2013-02-08

  • package: removed unusued parser.js

0.4.2 / 2013-02-08

  • polling-jsonp: fix ie6 JSONP on SSL
  • close also if socket.readyState is on "opening"
  • parser.js: removed the file package.json: added the engine.io-parser dependency everything else: switched to engine.io-parser
  • fix "TypeError: Object # has no method 'global'"
  • client now ignores unsupported upgrades
  • 0.4.1 / 2013-01-18

    • do not shadow global XMLHttpRequest
    • socket: added data event (as synonym to message)
    • socket: remove resource and fix path
    • socket: fixed access to opts
    • test: fixed transports tests
    • socket: constructor can accept uri/opts simultaneously
    • SPEC: simplified: removed resource from SPEC
    • socket: proper host/hostname support
    • socket: ensure onclose idempotency
    • socket: added onerror instrumentation
    • socket: fix style
    • use window to detect platform and fix global reference
    • *: fix references to global (fixes #79)

    0.4.0 / 2012-12-09

    • *: now based on component(1)
    • *: module now exports Socket
    • socket: export constructors, utils and protocol
    • *: implemented emitter component
    • *: removed browserbuild and preprocessor instructions

    0.3.10 / 2012-12-03

    • socket: fix closing the socket in an open listener [mmastrac]
    • socket: perform ping interval/timer cleanup [mmastrac]
    • fix SPEC (packages -> packets) [jxck]
    • socket: handle probe's transport errors [indutny]

    0.3.9 / 2012-10-23

    • socket: fix hostname instead of host
    • socket: avoid duplicate port defaults

    0.3.8 / 2012-10-23

    • socket: introduce introspection hooks
    • socket: introduced host and port location defaults
    • flashsocket: obfuscate activex (fixes #31)
    • README: documented reconnect (closes #45)
    • socket: unset id upon close
    • socket: clear transport listeners upon force close

    0.3.7 / 2012-10-21

    • fix version [quackingduck]
    • ping timeout gets reset upon any packet received [indutny]
    • timeout fixes [cadorn, indutny]
    • transport: fix xdomain detection in absence of location.port (GH-38)
    • socket: fix passing false as secure getting overridden
    • socket: default secure to true for SSL-served pages
    • socket: fix default port for SSL when secure is not supplied

    0.3.6 / 2012-10-16

    • socket: reset timeout on any incoming data [indutny]

    0.3.5 / 2012-10-14

    • new build

    0.3.4 / 2012-10-14

    • package: fix component exports

    0.3.3 / 2012-10-10

    • socket: fix secure default value discovery [quackingduck]

    0.3.2 / 2012-10-08

    • Bump

    0.3.1 / 2012-10-08

    • socket: added write alias for send
    • package: added component

    0.3.0 / 2012-09-04

    • IE's XDomainRequest cannot do requests that go from HTTPS to HTTP or HTTP to HTTPS [mixu]
    • Switch to client-initiated ping, and set interval in handshake [cadorn]

    0.2.2 / 2012-08-26

    • polling-jsonp: allow unneeded global leak (fixes #41)
    • polling-jsonp: allow for multiple eio's in the same page

    0.2.1 / 2012-08-13

    • Bump

    0.2.0 / 2012-08-06

    • polling: introduced poll and pollComplete (formerly poll) events

    0.1.2 / 2012-08-02

    • Bump

    0.1.1 / 2012-08-01

    • Added options for request timestamping
    • Made timestamp query param customizable
    • Added automatic timestamping for Android

    0.1.0 / 2012-07-03

    • Initial release.
(The MIT License)
Copyright (c) 2014-2015 Automattic <dev@cloudup.com>
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.

Engine.IO client

Build Status NPM version

This is the client for Engine.IO, the implementation of transport-based cross-browser/cross-device bi-directional communication layer for Socket.IO.

How to use

Standalone

You can find an engine.io.js file in this repository, which is a standalone build you can use as follows:

<script src="/path/to/engine.io.js"></script>
<script>
  // eio = Socket
  var socket = eio('ws://localhost');
  socket.on('open', function(){
    socket.on('message', function(data){});
    socket.on('close', function(){});
  });
</script>

With browserify

Engine.IO is a commonjs module, which means you can include it by using require on the browser and package using browserify:

  1. install the client package

    $ npm install engine.io-client
  2. write your app code

    var socket = require('engine.io-client')('ws://localhost');
    socket.on('open', function(){
      socket.on('message', function(data){});
      socket.on('close', function(){});
    });
  3. build your app bundle

    $ browserify app.js > bundle.js
  4. include on your page

    <script src="/path/to/bundle.js"></script>

Sending and receiving binary

<script src="/path/to/engine.io.js"></script>
<script>
  var socket = new eio.Socket('ws://localhost/');
  socket.binaryType = 'blob';
  socket.on('open', function () {
    socket.send(new Int8Array(5));
    socket.on('message', function(blob){});
    socket.on('close', function(){ });
  });
</script>

Node.JS

Add engine.io-client to your package.json and then:

var socket = require('engine.io-client')('ws://localhost');
socket.on('open', function(){
  socket.on('message', function(data){});
  socket.on('close', function(){});
});

Node.js with certificates

var opts = {
  key: fs.readFileSync('test/fixtures/client.key'),
  cert: fs.readFileSync('test/fixtures/client.crt'),
  ca: fs.readFileSync('test/fixtures/ca.crt')
};

var socket = require('engine.io-client')('ws://localhost', opts);
socket.on('open', function(){
  socket.on('message', function(data){});
  socket.on('close', function(){});
});

Node.js with extraHeaders

var opts = {
  extraHeaders: {
    'X-Custom-Header-For-My-Project': 'my-secret-access-token',
    'Cookie': 'user_session=NI2JlCKF90aE0sJZD9ZzujtdsUqNYSBYxzlTsvdSUe35ZzdtVRGqYFr0kdGxbfc5gUOkR9RGp20GVKza; path=/; expires=Tue, 07-Apr-2015 18:18:08 GMT; secure; HttpOnly'
  }
};

var socket = require('engine.io-client')('ws://localhost', opts);
socket.on('open', function(){
  socket.on('message', function(data){});
  socket.on('close', function(){});
});

Features

  • Lightweight
  • Runs on browser and node.js seamlessly
  • Transports are independent of Engine
    • Easy to debug
    • Easy to unit test
  • Runs inside HTML5 WebWorker
  • Can send and receive binary data
    • Receives as ArrayBuffer or Blob when in browser, and Buffer or ArrayBuffer in Node
    • When XHR2 or WebSockets are used, binary is emitted directly. Otherwise binary is encoded into base64 strings, and decoded when binary types are supported.
    • With browsers that don't support ArrayBuffer, an object { base64: true, data: dataAsBase64String } is emitted on the message event.

API

Socket

The client class. Mixes in Emitter. Exposed as eio in the browser standalone build.

Properties

  • protocol (Number): protocol revision number
  • binaryType (String) : can be set to 'arraybuffer' or 'blob' in browsers, and buffer or arraybuffer in Node. Blob is only used in browser if it's supported.

Events

  • open
    • Fired upon successful connection.
  • message
    • Fired when data is received from the server.
    • Arguments
      • String | ArrayBuffer: utf-8 encoded data or ArrayBuffer containing binary data
  • close
    • Fired upon disconnection. In compliance with the WebSocket API spec, this event may be fired even if the open event does not occur (i.e. due to connection error or close()).
  • error
    • Fired when an error occurs.
  • flush
    • Fired upon completing a buffer flush
  • drain
    • Fired after drain event of transport if writeBuffer is empty
  • upgradeError
    • Fired if an error occurs with a transport we're trying to upgrade to.
  • upgrade
    • Fired upon upgrade success, after the new transport is set
  • ping
    • Fired upon flushing a ping packet (ie: actual packet write out)
  • pong
    • Fired upon receiving a pong packet.

Methods

  • constructor
    • Initializes the client
    • Parameters
      • String uri
      • Object: optional, options object
    • Options
      • agent (http.Agent): http.Agent to use, defaults to false (NodeJS only)
      • upgrade (Boolean): defaults to true, whether the client should try to upgrade the transport from long-polling to something better.
      • forceJSONP (Boolean): forces JSONP for polling transport.
      • jsonp (Boolean): determines whether to use JSONP when necessary for polling. If disabled (by settings to false) an error will be emitted (saying "No transports available") if no other transports are available. If another transport is available for opening a connection (e.g. WebSocket) that transport will be used instead.
      • forceBase64 (Boolean): forces base 64 encoding for polling transport even when XHR2 responseType is available and WebSocket even if the used standard supports binary.
      • enablesXDR (Boolean): enables XDomainRequest for IE8 to avoid loading bar flashing with click sound. default to false because XDomainRequest has a flaw of not sending cookie.
      • timestampRequests (Boolean): whether to add the timestamp with each transport request. Note: polling requests are always stamped unless this option is explicitly set to false (false)
      • timestampParam (String): timestamp parameter (t)
      • policyPort (Number): port the policy server listens on (843)
      • path (String): path to connect to, default is /engine.io
      • transports (Array): a list of transports to try (in order). Defaults to ['polling', 'websocket']. Engine always attempts to connect directly with the first one, provided the feature detection test for it passes.
      • rememberUpgrade (Boolean): defaults to false. If true and if the previous websocket connection to the server succeeded, the connection attempt will bypass the normal upgrade process and will initially try websocket. A connection attempt following a transport error will use the normal upgrade process. It is recommended you turn this on only when using SSL/TLS connections, or if you know that your network does not block websockets.
      • pfx (String): Certificate, Private key and CA certificates to use for SSL. Can be used in Node.js client environment to manually specify certificate information.
      • key (String): Private key to use for SSL. Can be used in Node.js client environment to manually specify certificate information.
      • passphrase (String): A string of passphrase for the private key or pfx. Can be used in Node.js client environment to manually specify certificate information.
      • cert (String): Public x509 certificate to use. Can be used in Node.js client environment to manually specify certificate information.
      • ca (String|Array): An authority certificate or array of authority certificates to check the remote host against.. Can be used in Node.js client environment to manually specify certificate information.
      • ciphers (String): A string describing the ciphers to use or exclude. Consult the cipher format list for details on the format. Can be used in Node.js client environment to manually specify certificate information.
      • rejectUnauthorized (Boolean): If true, the server certificate is verified against the list of supplied CAs. An 'error' event is emitted if verification fails. Verification happens at the connection level, before the HTTP request is sent. Can be used in Node.js client environment to manually specify certificate information.
      • perMessageDeflate (Object|Boolean): parameters of the WebSocket permessage-deflate extension (see ws module api docs). Set to false to disable. (true)
        • threshold (Number): data is compressed only if the byte size is above this value. This option is ignored on the browser. (1024)
      • extraHeaders (Object): Headers that will be passed for each request to the server (via xhr-polling and via websockets). These values then can be used during handshake or for special proxies. Can only be used in Node.js client environment.
      • onlyBinaryUpgrades (Boolean): whether transport upgrades should be restricted to transports supporting binary data (false)
      • requestTimeout (Number): Timeout for xhr-polling requests in milliseconds (0)
      • forceNode (Boolean): Uses NodeJS implementation for websockets - even if there is a native Browser-Websocket available, which is preferred by default over the NodeJS implementation. (This is useful when using hybrid platforms like nw.js or electron) (false, NodeJS only)
      • localAddress (String): the local IP address to connect to
  • send
    • Sends a message to the server
    • Parameters
      • String | ArrayBuffer | ArrayBufferView | Blob: data to send
      • Object: optional, options object
      • Function: optional, callback upon drain
    • Options
      • compress (Boolean): whether to compress sending data. This option is ignored and forced to be true on the browser. (true)
  • close
    • Disconnects the client.

Transport

The transport class. Private. Inherits from EventEmitter.

Events

  • poll: emitted by polling transports upon starting a new request
  • pollComplete: emitted by polling transports upon completing a request
  • drain: emitted by polling transports upon a buffer drain

Tests

engine.io-client is used to test engine. Running the engine.io test suite ensures the client works and vice-versa.

Browser tests are run using zuul. You can run the tests locally using the following command.

./node_modules/.bin/zuul --local 8080 -- test/index.js

Additionally, engine.io-client has a standalone test suite you can run with make test which will run node.js and browser tests. You must have zuul setup with a saucelabs account.

Support

The support channels for engine.io-client are the same as socket.io:

Development

To contribute patches, run tests or benchmarks, make sure to clone the repository:

git clone git://github.com/socketio/engine.io-client.git

Then:

cd engine.io-client
npm install

See the Tests section above for how to run tests before submitting any patches.

License

MIT - Copyright (c) 2014 Automattic, Inc.

This file has been truncated, but you can view the full file.
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory();
else if(typeof define === 'function' && define.amd)
define([], factory);
else if(typeof exports === 'object')
exports["eio"] = factory();
else
root["eio"] = factory();
})(this, function() {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
module.exports = __webpack_require__(1);
/***/ },
/* 1 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
module.exports = __webpack_require__(2);
/**
* Exports parser
*
* @api public
*
*/
module.exports.parser = __webpack_require__(9);
/***/ },
/* 2 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(global) {'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
/**
* Module dependencies.
*/
var transports = __webpack_require__(3);
var Emitter = __webpack_require__(19);
var debug = __webpack_require__(23)('engine.io-client:socket');
var index = __webpack_require__(30);
var parser = __webpack_require__(9);
var parseuri = __webpack_require__(31);
var parsejson = __webpack_require__(32);
var parseqs = __webpack_require__(20);
/**
* Module exports.
*/
module.exports = Socket;
/**
* Socket constructor.
*
* @param {String|Object} uri or options
* @param {Object} options
* @api public
*/
function Socket(uri, opts) {
if (!(this instanceof Socket)) return new Socket(uri, opts);
opts = opts || {};
if (uri && 'object' === (typeof uri === 'undefined' ? 'undefined' : _typeof(uri))) {
opts = uri;
uri = null;
}
if (uri) {
uri = parseuri(uri);
opts.hostname = uri.host;
opts.secure = uri.protocol === 'https' || uri.protocol === 'wss';
opts.port = uri.port;
if (uri.query) opts.query = uri.query;
} else if (opts.host) {
opts.hostname = parseuri(opts.host).host;
}
this.secure = null != opts.secure ? opts.secure : global.location && 'https:' === location.protocol;
if (opts.hostname && !opts.port) {
// if no port is specified manually, use the protocol default
opts.port = this.secure ? '443' : '80';
}
this.agent = opts.agent || false;
this.hostname = opts.hostname || (global.location ? location.hostname : 'localhost');
this.port = opts.port || (global.location && location.port ? location.port : this.secure ? 443 : 80);
this.query = opts.query || {};
if ('string' === typeof this.query) this.query = parseqs.decode(this.query);
this.upgrade = false !== opts.upgrade;
this.path = (opts.path || '/engine.io').replace(/\/$/, '') + '/';
this.forceJSONP = !!opts.forceJSONP;
this.jsonp = false !== opts.jsonp;
this.forceBase64 = !!opts.forceBase64;
this.enablesXDR = !!opts.enablesXDR;
this.timestampParam = opts.timestampParam || 't';
this.timestampRequests = opts.timestampRequests;
this.transports = opts.transports || ['polling', 'websocket'];
this.readyState = '';
this.writeBuffer = [];
this.prevBufferLen = 0;
this.policyPort = opts.policyPort || 843;
this.rememberUpgrade = opts.rememberUpgrade || false;
this.binaryType = null;
this.onlyBinaryUpgrades = opts.onlyBinaryUpgrades;
this.perMessageDeflate = false !== opts.perMessageDeflate ? opts.perMessageDeflate || {} : false;
if (true === this.perMessageDeflate) this.perMessageDeflate = {};
if (this.perMessageDeflate && null == this.perMessageDeflate.threshold) {
this.perMessageDeflate.threshold = 1024;
}
// SSL options for Node.js client
this.pfx = opts.pfx || null;
this.key = opts.key || null;
this.passphrase = opts.passphrase || null;
this.cert = opts.cert || null;
this.ca = opts.ca || null;
this.ciphers = opts.ciphers || null;
this.rejectUnauthorized = opts.rejectUnauthorized === undefined ? null : opts.rejectUnauthorized;
this.forceNode = !!opts.forceNode;
// other options for Node.js client
var freeGlobal = (typeof global === 'undefined' ? 'undefined' : _typeof(global)) === 'object' && global;
if (freeGlobal.global === freeGlobal) {
if (opts.extraHeaders && Object.keys(opts.extraHeaders).length > 0) {
this.extraHeaders = opts.extraHeaders;
}
if (opts.localAddress) {
this.localAddress = opts.localAddress;
}
}
// set on handshake
this.id = null;
this.upgrades = null;
this.pingInterval = null;
this.pingTimeout = null;
// set on heartbeat
this.pingIntervalTimer = null;
this.pingTimeoutTimer = null;
this.open();
}
Socket.priorWebsocketSuccess = false;
/**
* Mix in `Emitter`.
*/
Emitter(Socket.prototype);
/**
* Protocol version.
*
* @api public
*/
Socket.protocol = parser.protocol; // this is an int
/**
* Expose deps for legacy compatibility
* and standalone browser access.
*/
Socket.Socket = Socket;
Socket.Transport = __webpack_require__(8);
Socket.transports = __webpack_require__(3);
Socket.parser = __webpack_require__(9);
/**
* Creates transport of the given type.
*
* @param {String} transport name
* @return {Transport}
* @api private
*/
Socket.prototype.createTransport = function (name) {
debug('creating transport "%s"', name);
var query = clone(this.query);
// append engine.io protocol identifier
query.EIO = parser.protocol;
// transport name
query.transport = name;
// session id if we already have one
if (this.id) query.sid = this.id;
var transport = new transports[name]({
agent: this.agent,
hostname: this.hostname,
port: this.port,
secure: this.secure,
path: this.path,
query: query,
forceJSONP: this.forceJSONP,
jsonp: this.jsonp,
forceBase64: this.forceBase64,
enablesXDR: this.enablesXDR,
timestampRequests: this.timestampRequests,
timestampParam: this.timestampParam,
policyPort: this.policyPort,
socket: this,
pfx: this.pfx,
key: this.key,
passphrase: this.passphrase,
cert: this.cert,
ca: this.ca,
ciphers: this.ciphers,
rejectUnauthorized: this.rejectUnauthorized,
perMessageDeflate: this.perMessageDeflate,
extraHeaders: this.extraHeaders,
forceNode: this.forceNode,
localAddress: this.localAddress
});
return transport;
};
function clone(obj) {
var o = {};
for (var i in obj) {
if (obj.hasOwnProperty(i)) {
o[i] = obj[i];
}
}
return o;
}
/**
* Initializes transport to use and starts probe.
*
* @api private
*/
Socket.prototype.open = function () {
var transport;
if (this.rememberUpgrade && Socket.priorWebsocketSuccess && this.transports.indexOf('websocket') !== -1) {
transport = 'websocket';
} else if (0 === this.transports.length) {
// Emit error on next tick so it can be listened to
var self = this;
setTimeout(function () {
self.emit('error', 'No transports available');
}, 0);
return;
} else {
transport = this.transports[0];
}
this.readyState = 'opening';
// Retry with the next transport if the transport is disabled (jsonp: false)
try {
transport = this.createTransport(transport);
} catch (e) {
this.transports.shift();
this.open();
return;
}
transport.open();
this.setTransport(transport);
};
/**
* Sets the c
View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment