react / react-0.13.3 / examples / basic-commonjs / node_modules / browserify / node_modules / util / util.js
80708 views// Copyright Joyent, Inc. and other Node contributors.1//2// Permission is hereby granted, free of charge, to any person obtaining a3// copy of this software and associated documentation files (the4// "Software"), to deal in the Software without restriction, including5// without limitation the rights to use, copy, modify, merge, publish,6// distribute, sublicense, and/or sell copies of the Software, and to permit7// persons to whom the Software is furnished to do so, subject to the8// following conditions:9//10// The above copyright notice and this permission notice shall be included11// in all copies or substantial portions of the Software.12//13// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS14// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF15// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN16// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,17// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR18// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE19// USE OR OTHER DEALINGS IN THE SOFTWARE.2021var formatRegExp = /%[sdj%]/g;22exports.format = function(f) {23if (!isString(f)) {24var objects = [];25for (var i = 0; i < arguments.length; i++) {26objects.push(inspect(arguments[i]));27}28return objects.join(' ');29}3031var i = 1;32var args = arguments;33var len = args.length;34var str = String(f).replace(formatRegExp, function(x) {35if (x === '%%') return '%';36if (i >= len) return x;37switch (x) {38case '%s': return String(args[i++]);39case '%d': return Number(args[i++]);40case '%j':41try {42return JSON.stringify(args[i++]);43} catch (_) {44return '[Circular]';45}46default:47return x;48}49});50for (var x = args[i]; i < len; x = args[++i]) {51if (isNull(x) || !isObject(x)) {52str += ' ' + x;53} else {54str += ' ' + inspect(x);55}56}57return str;58};596061// Mark that a method should not be used.62// Returns a modified function which warns once by default.63// If --no-deprecation is set, then it is a no-op.64exports.deprecate = function(fn, msg) {65// Allow for deprecating things in the process of starting up.66if (isUndefined(global.process)) {67return function() {68return exports.deprecate(fn, msg).apply(this, arguments);69};70}7172if (process.noDeprecation === true) {73return fn;74}7576var warned = false;77function deprecated() {78if (!warned) {79if (process.throwDeprecation) {80throw new Error(msg);81} else if (process.traceDeprecation) {82console.trace(msg);83} else {84console.error(msg);85}86warned = true;87}88return fn.apply(this, arguments);89}9091return deprecated;92};939495var debugs = {};96var debugEnviron;97exports.debuglog = function(set) {98if (isUndefined(debugEnviron))99debugEnviron = process.env.NODE_DEBUG || '';100set = set.toUpperCase();101if (!debugs[set]) {102if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {103var pid = process.pid;104debugs[set] = function() {105var msg = exports.format.apply(exports, arguments);106console.error('%s %d: %s', set, pid, msg);107};108} else {109debugs[set] = function() {};110}111}112return debugs[set];113};114115116/**117* Echos the value of a value. Trys to print the value out118* in the best way possible given the different types.119*120* @param {Object} obj The object to print out.121* @param {Object} opts Optional options object that alters the output.122*/123/* legacy: obj, showHidden, depth, colors*/124function inspect(obj, opts) {125// default options126var ctx = {127seen: [],128stylize: stylizeNoColor129};130// legacy...131if (arguments.length >= 3) ctx.depth = arguments[2];132if (arguments.length >= 4) ctx.colors = arguments[3];133if (isBoolean(opts)) {134// legacy...135ctx.showHidden = opts;136} else if (opts) {137// got an "options" object138exports._extend(ctx, opts);139}140// set default options141if (isUndefined(ctx.showHidden)) ctx.showHidden = false;142if (isUndefined(ctx.depth)) ctx.depth = 2;143if (isUndefined(ctx.colors)) ctx.colors = false;144if (isUndefined(ctx.customInspect)) ctx.customInspect = true;145if (ctx.colors) ctx.stylize = stylizeWithColor;146return formatValue(ctx, obj, ctx.depth);147}148exports.inspect = inspect;149150151// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics152inspect.colors = {153'bold' : [1, 22],154'italic' : [3, 23],155'underline' : [4, 24],156'inverse' : [7, 27],157'white' : [37, 39],158'grey' : [90, 39],159'black' : [30, 39],160'blue' : [34, 39],161'cyan' : [36, 39],162'green' : [32, 39],163'magenta' : [35, 39],164'red' : [31, 39],165'yellow' : [33, 39]166};167168// Don't use 'blue' not visible on cmd.exe169inspect.styles = {170'special': 'cyan',171'number': 'yellow',172'boolean': 'yellow',173'undefined': 'grey',174'null': 'bold',175'string': 'green',176'date': 'magenta',177// "name": intentionally not styling178'regexp': 'red'179};180181182function stylizeWithColor(str, styleType) {183var style = inspect.styles[styleType];184185if (style) {186return '\u001b[' + inspect.colors[style][0] + 'm' + str +187'\u001b[' + inspect.colors[style][1] + 'm';188} else {189return str;190}191}192193194function stylizeNoColor(str, styleType) {195return str;196}197198199function arrayToHash(array) {200var hash = {};201202array.forEach(function(val, idx) {203hash[val] = true;204});205206return hash;207}208209210function formatValue(ctx, value, recurseTimes) {211// Provide a hook for user-specified inspect functions.212// Check that value is an object with an inspect function on it213if (ctx.customInspect &&214value &&215isFunction(value.inspect) &&216// Filter out the util module, it's inspect function is special217value.inspect !== exports.inspect &&218// Also filter out any prototype objects using the circular check.219!(value.constructor && value.constructor.prototype === value)) {220var ret = value.inspect(recurseTimes, ctx);221if (!isString(ret)) {222ret = formatValue(ctx, ret, recurseTimes);223}224return ret;225}226227// Primitive types cannot have properties228var primitive = formatPrimitive(ctx, value);229if (primitive) {230return primitive;231}232233// Look up the keys of the object.234var keys = Object.keys(value);235var visibleKeys = arrayToHash(keys);236237if (ctx.showHidden) {238keys = Object.getOwnPropertyNames(value);239}240241// IE doesn't make error fields non-enumerable242// http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx243if (isError(value)244&& (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {245return formatError(value);246}247248// Some type of object without properties can be shortcutted.249if (keys.length === 0) {250if (isFunction(value)) {251var name = value.name ? ': ' + value.name : '';252return ctx.stylize('[Function' + name + ']', 'special');253}254if (isRegExp(value)) {255return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');256}257if (isDate(value)) {258return ctx.stylize(Date.prototype.toString.call(value), 'date');259}260if (isError(value)) {261return formatError(value);262}263}264265var base = '', array = false, braces = ['{', '}'];266267// Make Array say that they are Array268if (isArray(value)) {269array = true;270braces = ['[', ']'];271}272273// Make functions say that they are functions274if (isFunction(value)) {275var n = value.name ? ': ' + value.name : '';276base = ' [Function' + n + ']';277}278279// Make RegExps say that they are RegExps280if (isRegExp(value)) {281base = ' ' + RegExp.prototype.toString.call(value);282}283284// Make dates with properties first say the date285if (isDate(value)) {286base = ' ' + Date.prototype.toUTCString.call(value);287}288289// Make error with message first say the error290if (isError(value)) {291base = ' ' + formatError(value);292}293294if (keys.length === 0 && (!array || value.length == 0)) {295return braces[0] + base + braces[1];296}297298if (recurseTimes < 0) {299if (isRegExp(value)) {300return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');301} else {302return ctx.stylize('[Object]', 'special');303}304}305306ctx.seen.push(value);307308var output;309if (array) {310output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);311} else {312output = keys.map(function(key) {313return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);314});315}316317ctx.seen.pop();318319return reduceToSingleString(output, base, braces);320}321322323function formatPrimitive(ctx, value) {324if (isUndefined(value))325return ctx.stylize('undefined', 'undefined');326if (isString(value)) {327var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')328.replace(/'/g, "\\'")329.replace(/\\"/g, '"') + '\'';330return ctx.stylize(simple, 'string');331}332if (isNumber(value))333return ctx.stylize('' + value, 'number');334if (isBoolean(value))335return ctx.stylize('' + value, 'boolean');336// For some reason typeof null is "object", so special case here.337if (isNull(value))338return ctx.stylize('null', 'null');339}340341342function formatError(value) {343return '[' + Error.prototype.toString.call(value) + ']';344}345346347function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {348var output = [];349for (var i = 0, l = value.length; i < l; ++i) {350if (hasOwnProperty(value, String(i))) {351output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,352String(i), true));353} else {354output.push('');355}356}357keys.forEach(function(key) {358if (!key.match(/^\d+$/)) {359output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,360key, true));361}362});363return output;364}365366367function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {368var name, str, desc;369desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };370if (desc.get) {371if (desc.set) {372str = ctx.stylize('[Getter/Setter]', 'special');373} else {374str = ctx.stylize('[Getter]', 'special');375}376} else {377if (desc.set) {378str = ctx.stylize('[Setter]', 'special');379}380}381if (!hasOwnProperty(visibleKeys, key)) {382name = '[' + key + ']';383}384if (!str) {385if (ctx.seen.indexOf(desc.value) < 0) {386if (isNull(recurseTimes)) {387str = formatValue(ctx, desc.value, null);388} else {389str = formatValue(ctx, desc.value, recurseTimes - 1);390}391if (str.indexOf('\n') > -1) {392if (array) {393str = str.split('\n').map(function(line) {394return ' ' + line;395}).join('\n').substr(2);396} else {397str = '\n' + str.split('\n').map(function(line) {398return ' ' + line;399}).join('\n');400}401}402} else {403str = ctx.stylize('[Circular]', 'special');404}405}406if (isUndefined(name)) {407if (array && key.match(/^\d+$/)) {408return str;409}410name = JSON.stringify('' + key);411if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {412name = name.substr(1, name.length - 2);413name = ctx.stylize(name, 'name');414} else {415name = name.replace(/'/g, "\\'")416.replace(/\\"/g, '"')417.replace(/(^"|"$)/g, "'");418name = ctx.stylize(name, 'string');419}420}421422return name + ': ' + str;423}424425426function reduceToSingleString(output, base, braces) {427var numLinesEst = 0;428var length = output.reduce(function(prev, cur) {429numLinesEst++;430if (cur.indexOf('\n') >= 0) numLinesEst++;431return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;432}, 0);433434if (length > 60) {435return braces[0] +436(base === '' ? '' : base + '\n ') +437' ' +438output.join(',\n ') +439' ' +440braces[1];441}442443return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];444}445446447// NOTE: These type checking functions intentionally don't use `instanceof`448// because it is fragile and can be easily faked with `Object.create()`.449function isArray(ar) {450return Array.isArray(ar);451}452exports.isArray = isArray;453454function isBoolean(arg) {455return typeof arg === 'boolean';456}457exports.isBoolean = isBoolean;458459function isNull(arg) {460return arg === null;461}462exports.isNull = isNull;463464function isNullOrUndefined(arg) {465return arg == null;466}467exports.isNullOrUndefined = isNullOrUndefined;468469function isNumber(arg) {470return typeof arg === 'number';471}472exports.isNumber = isNumber;473474function isString(arg) {475return typeof arg === 'string';476}477exports.isString = isString;478479function isSymbol(arg) {480return typeof arg === 'symbol';481}482exports.isSymbol = isSymbol;483484function isUndefined(arg) {485return arg === void 0;486}487exports.isUndefined = isUndefined;488489function isRegExp(re) {490return isObject(re) && objectToString(re) === '[object RegExp]';491}492exports.isRegExp = isRegExp;493494function isObject(arg) {495return typeof arg === 'object' && arg !== null;496}497exports.isObject = isObject;498499function isDate(d) {500return isObject(d) && objectToString(d) === '[object Date]';501}502exports.isDate = isDate;503504function isError(e) {505return isObject(e) &&506(objectToString(e) === '[object Error]' || e instanceof Error);507}508exports.isError = isError;509510function isFunction(arg) {511return typeof arg === 'function';512}513exports.isFunction = isFunction;514515function isPrimitive(arg) {516return arg === null ||517typeof arg === 'boolean' ||518typeof arg === 'number' ||519typeof arg === 'string' ||520typeof arg === 'symbol' || // ES6 symbol521typeof arg === 'undefined';522}523exports.isPrimitive = isPrimitive;524525exports.isBuffer = require('./support/isBuffer');526527function objectToString(o) {528return Object.prototype.toString.call(o);529}530531532function pad(n) {533return n < 10 ? '0' + n.toString(10) : n.toString(10);534}535536537var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',538'Oct', 'Nov', 'Dec'];539540// 26 Feb 16:19:34541function timestamp() {542var d = new Date();543var time = [pad(d.getHours()),544pad(d.getMinutes()),545pad(d.getSeconds())].join(':');546return [d.getDate(), months[d.getMonth()], time].join(' ');547}548549550// log is just a thin wrapper to console.log that prepends a timestamp551exports.log = function() {552console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));553};554555556/**557* Inherit the prototype methods from one constructor into another.558*559* The Function.prototype.inherits from lang.js rewritten as a standalone560* function (not on Function.prototype). NOTE: If this file is to be loaded561* during bootstrapping this function needs to be rewritten using some native562* functions as prototype setup using normal JavaScript does not work as563* expected during bootstrapping (see mirror.js in r114903).564*565* @param {function} ctor Constructor function which needs to inherit the566* prototype.567* @param {function} superCtor Constructor function to inherit prototype from.568*/569exports.inherits = require('inherits');570571exports._extend = function(origin, add) {572// Don't do anything if add isn't an object573if (!add || !isObject(add)) return origin;574575var keys = Object.keys(add);576var i = keys.length;577while (i--) {578origin[keys[i]] = add[keys[i]];579}580return origin;581};582583function hasOwnProperty(obj, prop) {584return Object.prototype.hasOwnProperty.call(obj, prop);585}586587588