How debug-js/debug works
Project Type and Purpose
• This is a JavaScript library (an npm package) that provides a minimalist debugging utility for both Node.js and web browsers. It is _not_ a full-stack application but an open-source tool intended to be incorporated into other projects.
High-Level Architecture Analysis
• Entry Point: src/index.js
• Environment-specific implementations:
• src/browser.js – Browser behavior (uses localStorage.debug, console.error/%c styling)
• Public API: the debug(...) function factory that returns a namespaced logger instance
• Tests: test.js, test.node.js (verify behavior in each environment)
• Build & CI: package.json, karma.conf.js (browser tests), .travis.yml
Main Components
A. Public API Layer
• Component: debug factory (index.js)
• Inputs: namespace string, options overrides
• Outputs: debug function instance (bound log method)
B. Environment Detector
• Component: common logic that decides “Node” vs. “Browser” path
• Decision based on availability of process object & presence of window
C. Node.js Implementation
• Reads process.env.DEBUG
• Uses util.format, util.inspect, console.error writing to stderr
• Adds millisecond diff using internal timestamp state
D. Browser Implementation
• Reads/writes localStorage.debug
• Persists enabled namespaces across page reloads
E. Common Utilities
• Namespace parsing & wildcard matching
• Formatter definitions (%o, %O, %s, %d, %j, custom formatters)
F. Consumer Code
• Your application modules that require('debug')('namespace')
• Interact with your own Node servers or browser UIs
Relationships & Data Flows
• Consumer calls debug('app:module') → enters Public API
• API consults Environment Detector → routes to either Node or Browser implementation
• Implementation reads configuration (DEBUG env or localStorage.debug) → determines if enabled
• Formatted messages flow out to stderr or browser console
• Tests exercise this end-to-end chain
Architectural Patterns & Principles
• Strategy Pattern: separate Node vs. Browser “strategies” behind a common interface
• Factory Pattern: debug(namespace) produces a bound logger instance
• Single Responsibility: each module (common.js, node.js, browser.js) has a focused role
• Dependency Injection (optional): override debug.log on a per-namespace basis
• Clear component labels: e.g., “Debug Factory (index.js)”, “Node Strategy (node.js)”, “Browser Strategy (browser.js)”, “Common Utils”
• From Consumer → Debug Factory → Environment Detector → [Node Strategy] or [Browser Strategy]
• From Strategies → External Dependencies (env vars or localStorage)
• From Strategies → Console / stderr
• Blue for public API & detection
• Green for implementations
• Orange for utilities
• Gray for external systems