Skip to content
Permalink
Browse files
refactor to make the common code be a setup function (#507)
This is so that we can make both a Node.js instance and
web browser instance for when `--inspect` is used in Node.js.
  • Loading branch information
TooTallNate authored and thebigredgeek committed Oct 11, 2017
1 parent f073e05 commit 71169065b5262f9858ac78cc0b688c84a438f290
Show file tree
Hide file tree
Showing 4 changed files with 272 additions and 275 deletions.
@@ -1,10 +1,7 @@
/**
* 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;
@@ -66,19 +63,6 @@ function useColors() {
(typeof navigator !== 'undefined' && 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.
*
@@ -93,7 +77,7 @@ function formatArgs(args) {
+ (useColors ? ' %c' : ' ')
+ args[0]
+ (useColors ? '%c ' : ' ')
+ '+' + exports.humanize(this.diff);
+ '+' + module.exports.humanize(this.diff);

if (!useColors) return;

@@ -171,12 +155,6 @@ function load() {
return r;
}

/**
* Enable namespaces listed in `localStorage.debug` initially.
*/

exports.enable(load());

/**
* Localstorage attempts to return the localstorage.
*
@@ -193,3 +171,19 @@ function localstorage() {
return window.localStorage;
} catch (e) {}
}

module.exports = require('./common')(exports);

var formatters = module.exports.formatters;

/**
* Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
*/

formatters.j = function(v) {
try {
return JSON.stringify(v);
} catch (err) {
return '[UnexpectedJSONParseError]: ' + err.message;
}
};
@@ -0,0 +1,235 @@

/**
* This is the common logic for both the Node.js and web browser
* implementations of `debug()`.
*/

module.exports = function setup(env) {
createDebug.debug = createDebug['default'] = createDebug;
createDebug.coerce = coerce;
createDebug.disable = disable;
createDebug.enable = enable;
createDebug.enabled = enabled;
createDebug.humanize = require('ms');

Object.keys(env).forEach(function(key) {
createDebug[key] = env[key];
});

/**
* Active `debug` instances.
*/
createDebug.instances = [];

/**
* The currently active debug mode names, and names to skip.
*/

createDebug.names = [];
createDebug.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".
*/

createDebug.formatters = {};

/**
* 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 createDebug.colors[Math.abs(hash) % createDebug.colors.length];
}
createDebug.selectColor = selectColor;

/**
* Create a debugger with the given `namespace`.
*
* @param {String} namespace
* @return {Function}
* @api public
*/

function createDebug(namespace) {
var prevTime;

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] = createDebug.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 = createDebug.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.)
createDebug.formatArgs.call(self, args);

var logFn = self.log || createDebug.log;
logFn.apply(self, args);
}

debug.namespace = namespace;
debug.enabled = createDebug.enabled(namespace);
debug.useColors = createDebug.useColors();
debug.color = selectColor(namespace);
debug.destroy = destroy;
//debug.formatArgs = formatArgs;
//debug.rawLog = rawLog;

// env-specific initialization logic for debug instances
if ('function' === typeof createDebug.init) {
createDebug.init(debug);
}

createDebug.instances.push(debug);

return debug;
}

function destroy () {
var index = createDebug.instances.indexOf(this);
if (index !== -1) {
createDebug.instances.splice(index, 1);
return true;
} else {
return false;
}
}

/**
* Enables a debug mode by namespaces. This can include modes
* separated by a colon and wildcards.
*
* @param {String} namespaces
* @api public
*/

function enable(namespaces) {
createDebug.save(namespaces);

createDebug.names = [];
createDebug.skips = [];

var i;
var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
var len = split.length;

for (i = 0; i < len; i++) {
if (!split[i]) continue; // ignore empty strings
namespaces = split[i].replace(/\*/g, '.*?');
if (namespaces[0] === '-') {
createDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
} else {
createDebug.names.push(new RegExp('^' + namespaces + '$'));
}
}

for (i = 0; i < createDebug.instances.length; i++) {
var instance = createDebug.instances[i];
instance.enabled = createDebug.enabled(instance.namespace);
}
}

/**
* Disable debug output.
*
* @api public
*/

function disable() {
createDebug.enable('');
}

/**
* Returns true if the given mode name is enabled, false otherwise.
*
* @param {String} name
* @return {Boolean}
* @api public
*/

function enabled(name) {
if (name[name.length - 1] === '*') {
return true;
}
var i, len;
for (i = 0, len = createDebug.skips.length; i < len; i++) {
if (createDebug.skips[i].test(name)) {
return false;
}
}
for (i = 0, len = createDebug.names.length; i < len; i++) {
if (createDebug.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;
}

createDebug.enable(createDebug.load());

return createDebug;
}

0 comments on commit 7116906

Please sign in to comment.