From 436c5a81b4f974c9aef8d5f50e8e69676779b123 Mon Sep 17 00:00:00 2001 From: Lucas Hrabovsky Date: Wed, 22 Jun 2016 13:45:46 -0400 Subject: [PATCH 1/2] Finally found time to reorganize code --- .eslintrc | 9 ++ .jsfmtrc | 174 ++++++++++++++++++++++++++++++ browser.js | 168 +---------------------------- index.js | 8 +- lib/browser-console.js | 171 +++++++++++++++++++++++++++++ debug.js => lib/common.js | 99 +++++++++-------- lib/index.js | 12 +++ lib/stream.js | 195 +++++++++++++++++++++++++++++++++ node.js | 222 +------------------------------------- package.json | 7 +- 10 files changed, 620 insertions(+), 445 deletions(-) create mode 100644 .eslintrc create mode 100644 .jsfmtrc create mode 100644 lib/browser-console.js rename debug.js => lib/common.js (80%) create mode 100644 lib/index.js create mode 100644 lib/stream.js diff --git a/.eslintrc b/.eslintrc new file mode 100644 index 00000000..42452669 --- /dev/null +++ b/.eslintrc @@ -0,0 +1,9 @@ +{ + "env": { + "es6": true + }, + "rules": { + "strict": 0 + }, + "extends": ["mongodb-js/node"] +} diff --git a/.jsfmtrc b/.jsfmtrc new file mode 100644 index 00000000..a0cecd6b --- /dev/null +++ b/.jsfmtrc @@ -0,0 +1,174 @@ +{ + "preset": "default", + "plugins": [ + "esformatter-quotes", + "esformatter-semicolons", + "esformatter-braces", + "esformatter-quote-props", + "esformatter-dot-notation", + "esformatter-var-each", + "esformatter-parseint", + "esformatter-eol-last", + "esformatter-spaced-lined-comment", + "esformatter-remove-trailing-commas" + ], + "quotes": { + "type": "single", + "avoidEscape": false + }, + "indent": { + "value": " " + }, + "whiteSpace" : { + "value" : " ", + "removeTrailing" : 1, + "before" : { + "ArrayExpressionOpening" : 0, + "ArrayExpressionClosing" : 0, + "ArrayExpressionComma" : 0, + "ArgumentComma" : 0, + "ArgumentList" : 0, + "ArgumentListArrayExpression" : 0, + "ArgumentListFunctionExpression" : 0, + "ArgumentListObjectExpression" : 0, + "AssignmentOperator" : 1, + "BinaryExpression": 0, + "BinaryExpressionOperator" : 1, + "BlockComment" : 1, + "CallExpression" : -1, + "CatchParameterList" : 0, + "CatchOpeningBrace" : 1, + "CatchClosingBrace" : 1, + "CatchKeyword" : 1, + "CommaOperator" : 0, + "ConditionalExpressionConsequent" : 1, + "ConditionalExpressionAlternate" : 1, + "DoWhileStatementOpeningBrace" : 1, + "DoWhileStatementClosingBrace" : 1, + "DoWhileStatementConditional" : 1, + "EmptyStatement" : 0, + "ExpressionClosingParentheses" : 0, + "FinallyKeyword" : -1, + "FinallyOpeningBrace" : 1, + "FinallyClosingBrace" : 1, + "ForInStatement" : 1, + "ForInStatementExpressionOpening" : 1, + "ForInStatementExpressionClosing" : 0, + "ForInStatementOpeningBrace" : 1, + "ForInStatementClosingBrace" : 1, + "ForStatement" : 1, + "ForStatementExpressionOpening" : 1, + "ForStatementExpressionClosing" : 0, + "ForStatementOpeningBrace" : 1, + "ForStatementClosingBrace" : 1, + "ForStatementSemicolon" : 0, + "FunctionDeclarationOpeningBrace" : 1, + "FunctionDeclarationClosingBrace" : 1, + "FunctionExpressionOpeningBrace" : 1, + "FunctionExpressionClosingBrace" : 1, + "IfStatementConditionalOpening" : 1, + "IfStatementConditionalClosing" : 0, + "IfStatementOpeningBrace" : 1, + "IfStatementClosingBrace" : 1, + "ElseStatementOpeningBrace" : 1, + "ElseStatementClosingBrace" : 1, + "ElseIfStatementOpeningBrace" : 1, + "ElseIfStatementClosingBrace" : 1, + "MemberExpressionClosing" : 0, + "LineComment" : 1, + "LogicalExpressionOperator" : 1, + "Property" : 1, + "PropertyValue" : 1, + "ParameterComma" : 0, + "ParameterList" : 0, + "SwitchDiscriminantOpening" : 1, + "SwitchDiscriminantClosing" : 0, + "ThrowKeyword": 1, + "TryKeyword": -1, + "TryOpeningBrace" : 1, + "TryClosingBrace" : 1, + "UnaryExpressionOperator": 0, + "VariableName" : 1, + "VariableValue" : 1, + "WhileStatementConditionalOpening" : 1, + "WhileStatementConditionalClosing" : 0, + "WhileStatementOpeningBrace" : 1, + "WhileStatementClosingBrace" : 1 + }, + + "after" : { + "ArrayExpressionOpening" : 0, + "ArrayExpressionClosing" : 0, + "ArrayExpressionComma" : 1, + "ArgumentComma" : 1, + "ArgumentList" : 0, + "ArgumentListArrayExpression" : 0, + "ArgumentListFunctionExpression" : 0, + "ArgumentListObjectExpression" : 0, + "AssignmentOperator" : 1, + "BinaryExpression": 0, + "BinaryExpressionOperator" : 1, + "BlockComment" : 1, + "CallExpression" : 0, + "CatchParameterList" : 0, + "CatchOpeningBrace" : 1, + "CatchClosingBrace" : 1, + "CatchKeyword" : 1, + "CommaOperator" : 1, + "ConditionalExpressionConsequent" : 1, + "ConditionalExpressionTest" : 1, + "DoWhileStatementOpeningBrace" : 1, + "DoWhileStatementClosingBrace" : 1, + "DoWhileStatementBody" : 1, + "EmptyStatement" : 0, + "ExpressionOpeningParentheses" : 0, + "FinallyKeyword" : -1, + "FinallyOpeningBrace" : 1, + "FinallyClosingBrace" : 1, + "ForInStatement" : 1, + "ForInStatementExpressionOpening" : 0, + "ForInStatementExpressionClosing" : 1, + "ForInStatementOpeningBrace" : 1, + "ForInStatementClosingBrace" : 1, + "ForStatement" : 1, + "ForStatementExpressionOpening" : 0, + "ForStatementExpressionClosing" : 1, + "ForStatementClosingBrace" : 1, + "ForStatementOpeningBrace" : 1, + "ForStatementSemicolon" : 1, + "FunctionReservedWord": 0, + "FunctionName" : 0, + "FunctionExpressionOpeningBrace" : 1, + "FunctionExpressionClosingBrace" : 0, + "FunctionDeclarationOpeningBrace" : 0, + "FunctionDeclarationClosingBrace" : 0, + "IfStatementConditionalOpening" : 0, + "IfStatementConditionalClosing" : 1, + "IfStatementOpeningBrace" : 1, + "IfStatementClosingBrace" : 1, + "ElseStatementOpeningBrace" : 1, + "ElseStatementClosingBrace" : 1, + "ElseIfStatementOpeningBrace" : 1, + "ElseIfStatementClosingBrace" : 1, + "MemberExpressionOpening" : 0, + "LogicalExpressionOperator" : 1, + "ObjectExpressionClosingBrace": 0, + "PropertyName" : 0, + "PropertyValue" : 0, + "ParameterComma" : 1, + "ParameterList" : 0, + "SwitchDiscriminantOpening" : 0, + "SwitchDiscriminantClosing" : 1, + "ThrowKeyword": 1, + "TryKeyword": -1, + "TryOpeningBrace" : 1, + "TryClosingBrace" : 1, + "UnaryExpressionOperator": 0, + "VariableName" : 1, + "WhileStatementConditionalOpening" : 0, + "WhileStatementConditionalClosing" : 1, + "WhileStatementOpeningBrace" : 1, + "WhileStatementClosingBrace" : 1 + } + } +} diff --git a/browser.js b/browser.js index 7c764522..fc631a8c 100644 --- a/browser.js +++ b/browser.js @@ -1,168 +1,4 @@ - /** - * This is the web browser implementation of `debug()`. - * - * Expose `debug()` as the module. + * Browserify entry point. */ - -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) {} -} +module.exports = require('./lib'); diff --git a/index.js b/index.js index 67e21ecf..bb0a047c 100644 --- a/index.js +++ b/index.js @@ -1,7 +1 @@ -// var isRenderer = require('is-electron-renderer'); -// if (isRenderer) { -module.exports = require('./browser.js'); -module.exports.isRenderer = require('is-electron-renderer'); -// } else { -// module.exports = require('./node.js'); -// } +module.exports = require('./lib'); diff --git a/lib/browser-console.js b/lib/browser-console.js new file mode 100644 index 00000000..8c7877ed --- /dev/null +++ b/lib/browser-console.js @@ -0,0 +1,171 @@ + +/** + * This is the web browser implementation of `debug()`. + * + * Expose `debug()` as the module. + */ +exports = module.exports = require('./common'); +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) {} +} diff --git a/debug.js b/lib/common.js similarity index 80% rename from debug.js rename to lib/common.js index a21c0930..205fb4d7 100644 --- a/debug.js +++ b/lib/common.js @@ -1,43 +1,15 @@ - -/** - * 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.debug = 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. + * This is the common logic for all environments. */ -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; /** @@ -46,7 +18,6 @@ var prevTime; * @return {Number} * @api private */ - function selectColor() { return exports.colors[prevColor++ % exports.colors.length]; } @@ -58,9 +29,7 @@ function selectColor() { * @return {Function} * @api public */ - function debug(namespace) { - // define the `disabled` version function disabled() { } @@ -68,7 +37,6 @@ function debug(namespace) { // define the `enabled` version function enabled() { - var self = enabled; // set `diff` timestamp @@ -80,14 +48,18 @@ function debug(namespace) { 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(); + if (self.useColors === null) { + self.useColors = exports.useColors(); + } + if (self.color === null && self.useColors) { + self.color = selectColor(); + } var args = Array.prototype.slice.call(arguments); args[0] = exports.coerce(args[0]); - if ('string' !== typeof args[0]) { + if (typeof args[0] !== 'string') { // anything else let's inspect with %o args = ['%o'].concat(args); } @@ -96,10 +68,12 @@ function debug(namespace) { 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; + if (match === '%%') { + return match; + } index++; var formatter = exports.formatters[format]; - if ('function' === typeof formatter) { + if (typeof formatter !== 'function') { var val = args[index]; match = formatter.call(self, val); @@ -110,9 +84,10 @@ function debug(namespace) { return match; }); - if ('function' === typeof exports.formatArgs) { + if (typeof exports.formatArgs === 'function') { args = exports.formatArgs.apply(self, args); } + /* eslint no-console: 0 */ var logFn = enabled.log || exports.log || console.log.bind(console); logFn.apply(self, args); } @@ -125,6 +100,25 @@ function debug(namespace) { return fn; } +exports = module.exports = debug.debug = debug; +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 = {}; + + /** * Enables a debug mode by namespaces. This can include modes * separated by a colon and wildcards. @@ -133,14 +127,16 @@ function debug(namespace) { * @api public */ -function enable(namespaces) { +exports.enable = 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 + if (!split[i]) { + continue; + } // ignore empty strings namespaces = split[i].replace(/\*/g, '.*?'); if (namespaces[0] === '-') { exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); @@ -148,7 +144,7 @@ function enable(namespaces) { exports.names.push(new RegExp('^' + namespaces + '$')); } } -} +}; /** * Disable debug output. @@ -156,9 +152,9 @@ function enable(namespaces) { * @api public */ -function disable() { +exports.disable = function disable() { exports.enable(''); -} +}; /** * Returns true if the given mode name is enabled, false otherwise. @@ -168,8 +164,9 @@ function disable() { * @api public */ -function enabled(name) { - var i, len; +exports.enabled = function enabled(name) { + var i; + var len; for (i = 0, len = exports.skips.length; i < len; i++) { if (exports.skips[i].test(name)) { return false; @@ -181,7 +178,7 @@ function enabled(name) { } } return false; -} +}; /** * Coerce `val`. @@ -191,7 +188,9 @@ function enabled(name) { * @api private */ -function coerce(val) { - if (val instanceof Error) return val.stack || val.message; +exports.coerce = function coerce(val) { + if (val instanceof Error) { + return val.stack || val.message; + } return val; -} +}; diff --git a/lib/index.js b/lib/index.js new file mode 100644 index 00000000..3b0ce1b2 --- /dev/null +++ b/lib/index.js @@ -0,0 +1,12 @@ +if (process.versions.electron) { + if (process.type === 'renderer') { + module.exports = require('./browser-console'); + } else { + // TODO (imlucas) nslog etc. as we're in the main process. + module.exports = require('./stream'); + } +} else if (typeof window !== 'undefined') { + module.exports = require('./browser-console'); +} else { + module.exports = require('./stream'); +} diff --git a/lib/stream.js b/lib/stream.js new file mode 100644 index 00000000..ce9abf83 --- /dev/null +++ b/lib/stream.js @@ -0,0 +1,195 @@ +/** + * Module dependencies. + */ +var tty = require('tty'); +var util = require('util'); + +/** + * 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) { + /* eslint camelcase: 0 */ + 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; +} + + +/** + * This is the Node.js implementation of `debug()`. + * + * Expose `debug()` as the module. + */ + +exports = module.exports = require('./common'); + +/** + * 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 = fd === 1 ? process.stdout : + fd === 2 ? process.stderr : + createWritableStdioStream(fd); + +/** + * Is stdout a TTY? Colored output is enabled when `true`. + * @return {Boolean} + */ +function useColors() { + var debugColors = (process.env.DEBUG_COLORS || '').trim().toLowerCase(); + if (debugColors.length === 0) { + return tty.isatty(fd); + } + return ['0', 'no', 'false', 'disabled'].indexOf(debugColors) === -1; +} + +exports.useColors = useColors(); + +/** + * Map %o to `util.inspect()`, since Node doesn't do that out of the box. + * @return {Function} + */ +var inspect = 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 + */ + +exports.formatArgs = function formatArgs() { + var args = arguments; + var name = exports.namespace; + + if (exports.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. + */ + +exports.log = function log() { + return stream.write(util.format.apply(this, arguments) + '\n'); +}; + +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ +exports.save = function save(namespaces) { + if (namespaces === null) { + // 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 + */ +exports.load = function load() { + return process.env.DEBUG; +}; + +/** + * Enable namespaces listed in `process.env.DEBUG` initially. + */ +exports.enable(exports.load()); diff --git a/node.js b/node.js index 28d6a7f4..7ad378a1 100644 --- a/node.js +++ b/node.js @@ -1,223 +1,3 @@ // babel explicitly requires ('debug/node') // via hadron-compile-cache even in the renderer. -// So just check here as well so formatting -// is nice and consistent between console and devtools. -var isRenderer = require('is-electron-renderer'); -if (isRenderer) { - module.exports = require('./browser.js'); - return; -} - -/** - * 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; -exports.isRenderer = require('is-electron-renderer'); -var browser = require('./browser'); - -/** - * 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() { - if (exports.isRenderer) { - return console.log.apply(console, arguments); - } - 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()); +module.exports = require('./lib'); diff --git a/package.json b/package.json index c64baf1d..b5f167a1 100644 --- a/package.json +++ b/package.json @@ -21,6 +21,11 @@ "ms": "0.7.1" }, "devDependencies": { - "mocha": "*" + "eslint-config-mongodb-js": "^2.0.0", + "mocha": "*", + "mongodb-js-fmt": "0.0.3" + }, + "scripts": { + "fmt": "mongodb-js-fmt" } } From 31258561bf392f2006d035e4d27621371bee0699 Mon Sep 17 00:00:00 2001 From: Lucas Hrabovsky Date: Wed, 22 Jun 2016 14:13:48 -0400 Subject: [PATCH 2/2] More cleanup to make the renderer work. --- lib/browser-console.js | 112 +++++++++++++++++------------------------ lib/common.js | 10 ++-- 2 files changed, 50 insertions(+), 72 deletions(-) diff --git a/lib/browser-console.js b/lib/browser-console.js index 8c7877ed..c93ef5b5 100644 --- a/lib/browser-console.js +++ b/lib/browser-console.js @@ -5,15 +5,30 @@ * Expose `debug()` as the module. */ exports = module.exports = require('./common'); -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(); + +/* global chrome, window, document, navigator */ +var chromeStorage = typeof chrome !== 'undefined' && typeof chrome.storage !== 'undefined'; + +/** + * 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) { + return null; + } +} + +exports.storage = chromeStorage ? chrome.storage.local : localstorage(); /** * Colors. @@ -28,28 +43,11 @@ exports.colors = [ '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); -} +exports.useColors = true; /** * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. */ - exports.formatters.j = function(v) { return JSON.stringify(v); }; @@ -61,21 +59,16 @@ exports.formatters.j = function(v) { * @api public */ -function formatArgs() { +exports.formatArgs = function formatArgs() { var args = arguments; - var useColors = this.useColors; - args[0] = (useColors ? '%c' : '') + args[0] = '%c' + this.namespace - + (useColors ? ' %c' : ' ') + + ' %c' + args[0] - + (useColors ? '%c ' : ' ') + + '%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)); @@ -85,11 +78,11 @@ function formatArgs() { var index = 0; var lastC = 0; args[0].replace(/%[a-z%]/g, function(match) { - if ('%%' === match) { + if (match === '%%') { return; } index++; - if ('%c' === match) { + if (match === '%c') { // we only are interested in the *last* %c // (the user may have provided their own) lastC = index; @@ -107,12 +100,10 @@ function formatArgs() { * @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); +exports.log = function log() { + /* eslint no-console: 0 */ + debugger; + return Function.prototype.apply.call(console.log, console, arguments); } /** @@ -122,14 +113,16 @@ function log() { * @api private */ -function save(namespaces) { +exports.save = function save(namespaces) { try { - if (null == namespaces) { + if (namespaces === null) { exports.storage.removeItem('debug'); } else { exports.storage.debug = namespaces; } - } catch (e) {} + } catch (e) { + console.error(e); + } } /** @@ -139,11 +132,13 @@ function save(namespaces) { * @api private */ -function load() { +exports.load = function load() { var r; try { r = exports.storage.debug; - } catch (e) {} + } catch (e) { + console.error(e); + } return r; } @@ -151,21 +146,4 @@ function load() { * 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) {} -} +exports.enable(exports.load()); diff --git a/lib/common.js b/lib/common.js index 205fb4d7..b31a7b30 100644 --- a/lib/common.js +++ b/lib/common.js @@ -48,13 +48,13 @@ function debug(namespace) { prevTime = curr; // add the `color` if not set - if (self.useColors === null) { - self.useColors = exports.useColors(); + if (!self.useColors) { + self.useColors = true; } - if (self.color === null && self.useColors) { + + if (!self.color && self.useColors) { self.color = selectColor(); } - var args = Array.prototype.slice.call(arguments); args[0] = exports.coerce(args[0]); @@ -73,7 +73,7 @@ function debug(namespace) { } index++; var formatter = exports.formatters[format]; - if (typeof formatter !== 'function') { + if (typeof formatter === 'function') { var val = args[index]; match = formatter.call(self, val);