chromalogger 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/.eslintrc.json ADDED
@@ -0,0 +1,18 @@
1
+ {
2
+ "env": {
3
+ "node": true,
4
+ "es2021": true,
5
+ "browser": true
6
+ },
7
+ "extends": ["eslint:recommended", "prettier"],
8
+ "parserOptions": {
9
+ "ecmaVersion": 2021,
10
+ "sourceType": "module"
11
+ },
12
+ "rules": {
13
+ "no-console": "off",
14
+ "no-unused-vars": ["warn", { "argsIgnorePattern": "^_" }],
15
+ "prettier/prettier": "error"
16
+ },
17
+ "plugins": ["prettier"]
18
+ }
package/.prettierrc ADDED
@@ -0,0 +1,9 @@
1
+ {
2
+ "semi": true,
3
+ "singleQuote": true,
4
+ "trailingComma": "es5",
5
+ "printWidth": 100,
6
+ "tabWidth": 2,
7
+ "bracketSpacing": true,
8
+ "arrowParens": "always"
9
+ }
@@ -0,0 +1,43 @@
1
+ # Comment contribuer
2
+
3
+ Merci de votre intérêt pour `logcolor-js` ! Voici comment vous pouvez contribuer au projet.
4
+
5
+ ## Signaler un bug
6
+
7
+ Si vous trouvez un bug, merci de créer une issue en suivant ces étapes :
8
+
9
+ 1. Vérifiez que le bug n'a pas déjà été signalé
10
+ 2. Décrivez le bug de manière claire et concise
11
+ 3. Incluez des étapes pour reproduire le bug
12
+ 4. Précisez le comportement attendu
13
+ 5. Incluez la version de Node.js et du module
14
+
15
+ ## Proposer une amélioration
16
+
17
+ 1. Créez une issue pour discuter de votre idée
18
+ 2. Si l'idée est acceptée, créez une branche pour votre fonctionnalité
19
+ 3. Assurez-vous que les tests passent (`npm test`)
20
+ 4. Soumettez une pull request
21
+
22
+ ## Processus de développement
23
+
24
+ 1. Forkez le dépôt
25
+ 2. Installez les dépendances : `npm install`
26
+ 3. Créez une branche pour votre fonctionnalité : `git checkout -b ma-nouvelle-fonctionnalite`
27
+ 4. Faites vos modifications
28
+ 5. Lancez les tests : `npm test`
29
+ 6. Formatez votre code : `npm run format`
30
+ 7. Vérifiez les erreurs de style : `npm run lint`
31
+ 8. Poussez vos modifications : `git push origin ma-nouvelle-fonctionnalite`
32
+ 9. Créez une Pull Request
33
+
34
+ ## Directives de codage
35
+
36
+ - Suivez le style de code existant
37
+ - Écrivez des tests pour les nouvelles fonctionnalités
38
+ - Documentez votre code avec des commentaires clairs
39
+ - Gardez les commits atomiques et bien décrits
40
+
41
+ ## Licence
42
+
43
+ En contribuant à ce projet, vous acceptez que vos contributions soient sous la même licence que le projet (MIT).
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Votre Nom
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,148 @@
1
+ # LogColor
2
+
3
+ Une bibliothèque JavaScript simple pour ajouter des couleurs et des styles aux messages de la console en Node.js.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install logcolor-js
9
+ ```
10
+
11
+ ## Utilisation
12
+
13
+ ### Avec ES Modules (recommandé)
14
+
15
+ ```javascript
16
+ import logger from 'logcolor-js';
17
+
18
+ // Couleurs de base
19
+ logger.red('Ceci est en rouge');
20
+ logger.green('Ceci est en vert');
21
+ logger.blue('Ceci est en bleu');
22
+ logger.yellow('Ceci est en jaune');
23
+ ```
24
+
25
+ ### Avec CommonJS
26
+
27
+ ```javascript
28
+ const logger = require('logcolor-js');
29
+
30
+ // Arrière-plans colorés
31
+ logger.bgRed(' Fond rouge ');
32
+ logger.bgGreen(' Fond vert ');
33
+ logger.bgBlue(' Fond bleu ');
34
+ ```
35
+
36
+ ## Fonctionnalités
37
+
38
+ ### Couleurs de texte
39
+
40
+ - `red(text)` - Texte rouge
41
+ - `green(text)` - Texte vert
42
+ - `blue(text)` - Texte bleu
43
+ - `yellow(text)` - Texte jaune
44
+ - `white(text)` - Texte blanc
45
+ - `black(text)` - Texte noir
46
+ - `magenta(text)` - Texte magenta
47
+ - `cyan(text)` - Texte cyan
48
+
49
+ ### Arrière-plans
50
+
51
+ - `bgRed(text)` - Fond rouge
52
+ - `bgGreen(text)` - Fond vert
53
+ - `bgBlue(text)` - Fond bleu
54
+ - `bgYellow(text)` - Fond jaune
55
+ - `bgWhite(text)` - Fond blanc
56
+ - `bgBlack(text)` - Fond noir
57
+ - `bgMagenta(text)` - Fond magenta
58
+ - `bgCyan(text)` - Fond cyan
59
+
60
+ ### Styles de texte
61
+
62
+ - `bold(text)` - Texte en gras
63
+ - `underline(text)` - Texte souligné
64
+ - `italic(text)` - Texte en italique
65
+ - `inverse(text)` - Inverse les couleurs
66
+ - `strikethrough(text)` - Texte barré
67
+
68
+ ### Niveaux de log
69
+
70
+ - `setLogLevel(level)` - Définit le niveau de log ('DEBUG', 'INFO', 'WARN', 'ERROR')
71
+ - `debug(...args)` - Message de débogage
72
+ - `info(...args)` - Information
73
+ - `warn(...args)` - Avertissement
74
+ - `error(...args)` - Erreur
75
+ - `success(...args)` - Succès (alias pour info avec icône de succès)
76
+ - `warning(...args)` - Avertissement (alias pour warn avec icône d'avertissement)
77
+
78
+ ## Exemples avancés
79
+
80
+ ### Combinaison de styles
81
+
82
+ ```javascript
83
+ // Combinaison de styles
84
+ logger.bold(logger.red('Texte en gras et rouge'));
85
+ logger.bgBlue(logger.white('Texte blanc sur fond bleu'));
86
+ ```
87
+
88
+ ### Niveaux de log
89
+
90
+ ```javascript
91
+ // Définir le niveau de log (par défaut: 'INFO')
92
+ logger.setLogLevel('DEBUG');
93
+
94
+ // Messages de log
95
+ logger.debug('Message de débogage');
96
+ logger.info('Information');
97
+ logger.warn('Avertissement');
98
+ logger.error('Erreur');
99
+ ```
100
+
101
+ ### Avec des objets et tableaux
102
+
103
+ ```javascript
104
+ // Objets
105
+ const user = {
106
+ name: 'John',
107
+ age: 30,
108
+ roles: ['admin', 'user'],
109
+ };
110
+ logger.info('Utilisateur:', user);
111
+
112
+ // Tableaux
113
+ const numbers = [1, 2, 3, 4, 5];
114
+ logger.info('Nombres:', numbers);
115
+
116
+ // Références circulaires
117
+ const obj1 = { name: 'Objet 1' };
118
+ const obj2 = { name: 'Objet 2', ref: obj1 };
119
+ obj1.ref = obj2;
120
+ logger.info('Objet avec référence circulaire:', obj1);
121
+ ```
122
+
123
+ ## Personnalisation
124
+
125
+ ### Styles personnalisés
126
+
127
+ ```javascript
128
+ // Accès direct aux codes ANSI
129
+ console.log(
130
+ `${logger.styles.bold}${logger.styles.red}Texte en gras et rouge${logger.styles.reset}`
131
+ );
132
+ ```
133
+
134
+ ### Templates
135
+
136
+ ```javascript
137
+ const name = 'Alice';
138
+ const age = 30;
139
+ logger.info('Nom: {0}, Âge: {1}', name, age);
140
+ ```
141
+
142
+ ## Contribution
143
+
144
+ Les contributions sont les bienvenues ! N'hésitez pas à ouvrir une issue ou une pull request.
145
+
146
+ ## Licence
147
+
148
+ MIT
package/chromalog.js ADDED
@@ -0,0 +1,77 @@
1
+ /**
2
+ * Chromalog - A colorful console logger with formatting and styling
3
+ * @module chromalog
4
+ */
5
+
6
+ // Import core modules
7
+ import * as styles from './core/styles.js';
8
+
9
+ // Import logger functions
10
+ import {
11
+ createLogger,
12
+ formatMessage,
13
+ setLogLevel,
14
+ LOG_LEVELS,
15
+ } from './core/loggers/consoleLogger.js';
16
+
17
+ // Import formatters
18
+ import { formatObject } from './core/formatters/objectFormatter.js';
19
+
20
+ // Import chroma utility
21
+ import chroma from './utils/chroma.js';
22
+
23
+ // Create default logger instances
24
+ const log = createLogger();
25
+ const debug = createLogger('dim');
26
+ const info = createLogger('blue');
27
+ const warn = createLogger('yellow');
28
+ const error = createLogger('red');
29
+
30
+ // Main chromalog object
31
+ const chromalog = {
32
+ // Core
33
+ styles,
34
+ chroma,
35
+
36
+ // Main logger methods
37
+ createLogger,
38
+ formatMessage,
39
+ formatObject,
40
+ setLogLevel,
41
+
42
+ // Log levels
43
+ LOG_LEVELS,
44
+
45
+ // Pre-configured loggers
46
+ log,
47
+ debug,
48
+ info,
49
+ warn,
50
+ error,
51
+ };
52
+
53
+ // Export everything
54
+ export {
55
+ // Core
56
+ styles,
57
+ chroma,
58
+
59
+ // Main logger methods
60
+ createLogger,
61
+ formatMessage,
62
+ formatObject,
63
+ setLogLevel,
64
+
65
+ // Log levels
66
+ LOG_LEVELS,
67
+
68
+ // Pre-configured loggers
69
+ log,
70
+ debug,
71
+ info,
72
+ warn,
73
+ error,
74
+
75
+ // Default export
76
+ chromalog as default,
77
+ };
package/cli.js ADDED
@@ -0,0 +1,87 @@
1
+ #!/usr/bin/env node
2
+
3
+ console.log('Démarrage du CLI...'); // Debug
4
+
5
+ import { createLogger } from './chromalog.js';
6
+ import fs from 'fs';
7
+ import { fileURLToPath } from 'url';
8
+ import path from 'path';
9
+
10
+ console.log('Chargement des modules terminé'); // Debug
11
+
12
+ function showHelp() {
13
+ const helpText = `
14
+ Utilisation : clog [options] <message>
15
+
16
+ Options :
17
+ --color <couleur> Couleur du texte (red, green, blue, etc.)
18
+ --style <styles> Styles (séparés par des virgules)
19
+ -v, --version Affiche la version
20
+ -h, --help Affiche cette aide
21
+
22
+ Exemples :
23
+ $ npx clog --color red --style bright "Attention !"
24
+ $ npx clog --color green "Opération réussie"
25
+ `;
26
+ console.log(helpText);
27
+ }
28
+
29
+ function main() {
30
+ console.log('Début de la fonction main'); // Debug
31
+ const args = process.argv.slice(2);
32
+ console.log('Arguments:', args); // Debug
33
+
34
+ // Afficher l'aide
35
+ if (args.length === 0 || args.includes('--help') || args.includes('-h') || args.includes('-V')) {
36
+ return showHelp();
37
+ }
38
+
39
+ // Afficher la version
40
+ if (args.includes('--version') || args.includes('-v')) {
41
+ const __filename = fileURLToPath(import.meta.url);
42
+ const __dirname = path.dirname(__filename);
43
+ const pkg = JSON.parse(fs.readFileSync(path.join(__dirname, 'package.json'), 'utf8'));
44
+ return console.log(pkg.version);
45
+ }
46
+
47
+ // Traitement des arguments de couleur et de style
48
+ let messageParts = [];
49
+ let color = 'white';
50
+ let styles = [];
51
+
52
+ for (let i = 0; i < args.length; i++) {
53
+ const arg = args[i];
54
+
55
+ if (arg === '--color' && args[i + 1]) {
56
+ color = args[++i];
57
+ } else if (arg === '--style' && args[i + 1]) {
58
+ styles = args[++i].split(',').map((s) => s.trim());
59
+ } else if (!arg.startsWith('--')) {
60
+ messageParts.push(arg);
61
+ }
62
+ }
63
+
64
+ const message = messageParts.join(' ');
65
+
66
+ if (!message) {
67
+ console.error('Erreur: Aucun message fourni');
68
+ return showHelp();
69
+ }
70
+
71
+ try {
72
+ // Créer et utiliser le logger
73
+ const logger = createLogger(color, ...styles);
74
+ logger(message);
75
+ } catch (error) {
76
+ console.error('Erreur:', error.message);
77
+ console.log('\nCouleurs disponibles: red, green, blue, yellow, magenta, cyan, white');
78
+ console.log(
79
+ 'Styles disponibles: bright, dim, italic, underline, blink, reverse, hidden, strikethrough'
80
+ );
81
+ }
82
+ }
83
+
84
+ // Exécuter le CLI
85
+ if (process.argv[1] && process.argv[1].endsWith('cli.js')) {
86
+ main();
87
+ }
@@ -0,0 +1,100 @@
1
+ /**
2
+ * Object formatting utilities
3
+ * @module core/formatters/objectFormatter
4
+ */
5
+
6
+ import { isObject } from '../utils/validate.js';
7
+
8
+ /**
9
+ * Format an object for display
10
+ * @param {Object} obj - Object to format
11
+ * @param {number} [depth=0] - Current depth for indentation
12
+ * @returns {string} Formatted object string
13
+ */
14
+ export const formatObject = (obj, depth = 0) => {
15
+ const indent = ' '.repeat(depth);
16
+ const nextIndent = ' '.repeat(depth + 1);
17
+
18
+ try {
19
+ if (obj === null) return 'null';
20
+ if (obj === undefined) return 'undefined';
21
+ if (!isObject(obj)) return String(obj);
22
+
23
+ const entries = Object.entries(obj);
24
+ if (entries.length === 0) return '{}';
25
+
26
+ // For small objects, keep on one line
27
+ if (entries.every(([_, value]) => !isObject(value) || value === null)) {
28
+ const content = entries
29
+ .map(([key, value]) => `${key}: ${formatValue(value, depth + 1)}`)
30
+ .join(', ');
31
+ return `{ ${content} }`;
32
+ }
33
+
34
+ // For larger or complex objects, use multiple lines
35
+ const content = entries
36
+ .map(([key, value]) => `${nextIndent}${key}: ${formatValue(value, depth + 1)}`)
37
+ .join(',\n');
38
+
39
+ return `{\n${content}\n${indent}}`;
40
+ } catch (error) {
41
+ return '[Object]';
42
+ }
43
+ };
44
+
45
+ /**
46
+ * Format a value for display
47
+ * @param {*} value - Value to format
48
+ * @param {number} [depth=0] - Current depth for indentation
49
+ * @returns {string} Formatted value
50
+ */
51
+ const formatValue = (value, depth = 0) => {
52
+ if (value === null) return 'null';
53
+ if (value === undefined) return 'undefined';
54
+
55
+ switch (typeof value) {
56
+ case 'string':
57
+ return `"${value}"`;
58
+ case 'object':
59
+ if (Array.isArray(value)) {
60
+ return formatArray(value, depth);
61
+ }
62
+ return formatObject(value, depth);
63
+ case 'function':
64
+ return '[Function]';
65
+ case 'symbol':
66
+ return value.toString();
67
+ default:
68
+ return String(value);
69
+ }
70
+ };
71
+
72
+ /**
73
+ * Format an array for display
74
+ * @param {Array} arr - Array to format
75
+ * @param {number} [depth=0] - Current depth for indentation
76
+ * @returns {string} Formatted array string
77
+ */
78
+ const formatArray = (arr, depth = 0) => {
79
+ if (!Array.isArray(arr)) return '[]';
80
+ if (arr.length === 0) return '[]';
81
+
82
+ const indent = ' '.repeat(depth);
83
+ const nextIndent = ' '.repeat(depth + 1);
84
+
85
+ // For small arrays, keep on one line
86
+ if (arr.length <= 3 && arr.every((item) => !isObject(item) || item === null)) {
87
+ return `[ ${arr.map((item) => formatValue(item, depth + 1)).join(', ')} ]`;
88
+ }
89
+
90
+ // For larger or complex arrays, use multiple lines
91
+ const items = arr.map((item) => `${nextIndent}${formatValue(item, depth + 1)}`).join(',\n');
92
+
93
+ return `[\n${items}\n${indent}]`;
94
+ };
95
+
96
+ export default {
97
+ formatObject,
98
+ formatArray,
99
+ formatValue,
100
+ };
@@ -0,0 +1,153 @@
1
+ /**
2
+ * Console logger implementation
3
+ * @module core/loggers/consoleLogger
4
+ */
5
+
6
+ import { formatObject } from '../formatters/objectFormatter.js';
7
+ import { validateInput } from '../utils/validate.js';
8
+ import styles from '../styles.js';
9
+
10
+ /**
11
+ * Log levels and their priorities
12
+ * @type {Object}
13
+ */
14
+ const LOG_LEVELS = {
15
+ DEBUG: 0,
16
+ INFO: 1,
17
+ WARN: 2,
18
+ ERROR: 3,
19
+ NONE: 4,
20
+ };
21
+
22
+ let currentLogLevel = LOG_LEVELS.INFO;
23
+
24
+ /**
25
+ * Create a logger with the specified styles
26
+ * @param {...string} styleNames - Names of styles to apply
27
+ * @returns {Function} Logger function
28
+ */
29
+ const createLogger = (...styleNames) => {
30
+ // Get style codes
31
+ const styleCodes = styleNames.map((name) => {
32
+ if (!styles[name]) {
33
+ console.warn(`LogColor: Unknown style "${name}"`);
34
+ return '';
35
+ }
36
+ return styles[name];
37
+ });
38
+
39
+ const stylePrefix = styleCodes.join('');
40
+
41
+ /**
42
+ * Logger function
43
+ * @param {...*} args - Arguments to log
44
+ */
45
+ const logger = (...args) => {
46
+ try {
47
+ // Vérifier le niveau de log
48
+ let logLevel = LOG_LEVELS.INFO;
49
+ if (styleNames.includes('dim')) {
50
+ logLevel = LOG_LEVELS.DEBUG;
51
+ } else if (styleNames.includes('yellow')) {
52
+ logLevel = LOG_LEVELS.WARN;
53
+ } else if (styleNames.includes('red')) {
54
+ logLevel = LOG_LEVELS.ERROR;
55
+ }
56
+
57
+ if (logLevel < currentLogLevel) return;
58
+
59
+ const validArgs = validateInput(args);
60
+
61
+ // Handle template strings
62
+ if (typeof validArgs[0] === 'string' && validArgs.length > 1) {
63
+ const message = formatMessage(validArgs[0], validArgs.slice(1));
64
+ console.log(`${stylePrefix}${message}${styles.reset}`);
65
+ } else {
66
+ // Format each argument
67
+ const formattedArgs = validArgs.map((arg) => {
68
+ if (arg === null) return 'null';
69
+ if (arg === undefined) return 'undefined';
70
+ if (typeof arg === 'object' || Array.isArray(arg)) {
71
+ return formatObject(arg);
72
+ }
73
+ if (typeof arg === 'string') return arg;
74
+ return String(arg);
75
+ });
76
+
77
+ // Handle multi-line output
78
+ const output = formattedArgs.join(' ').split('\n').join('\n ');
79
+ console.log(`${stylePrefix}${output}${styles.reset}`);
80
+ }
81
+ } catch (error) {
82
+ console.error(`${styles.red}LogColor: Logging error - ${error.message}${styles.reset}`);
83
+ }
84
+ };
85
+
86
+ // Add style methods for method chaining
87
+ Object.keys(styles).forEach((styleName) => {
88
+ Object.defineProperty(logger, styleName, {
89
+ get: () => createLogger(...styleNames, styleName),
90
+ });
91
+ });
92
+
93
+ return logger;
94
+ };
95
+
96
+ /**
97
+ * Format a message with placeholders
98
+ * @param {string} message - Message with {0}, {1}, etc. placeholders
99
+ * @param {Array} values - Values to replace placeholders
100
+ * @returns {string} Formatted message
101
+ */
102
+ const formatMessage = (message, values = []) => {
103
+ if (typeof message !== 'string' || !Array.isArray(values)) {
104
+ return String(message);
105
+ }
106
+
107
+ return message.replace(/\{(\d+)\}/g, (match, index) => {
108
+ const value = values[parseInt(index, 10)];
109
+ if (value === undefined) return match;
110
+
111
+ if (typeof value === 'object' || Array.isArray(value)) {
112
+ return formatObject(value);
113
+ }
114
+
115
+ return String(value);
116
+ });
117
+ };
118
+
119
+ /**
120
+ * Set the current log level
121
+ * @param {string} level - Log level (DEBUG, INFO, WARN, ERROR, NONE)
122
+ */
123
+ const setLogLevel = (level) => {
124
+ const upperLevel = level.toUpperCase();
125
+ if (LOG_LEVELS[upperLevel] !== undefined) {
126
+ currentLogLevel = LOG_LEVELS[upperLevel];
127
+ } else {
128
+ console.warn(`LogColor: Unknown log level "${level}". Using INFO.`);
129
+ currentLogLevel = LOG_LEVELS.INFO;
130
+ }
131
+ };
132
+
133
+ // Create default loggers
134
+ const log = createLogger();
135
+ const debug = createLogger('dim');
136
+ const info = createLogger('cyan');
137
+ const warn = createLogger('yellow');
138
+ const error = createLogger('red');
139
+
140
+ // Export everything
141
+ export { createLogger, formatMessage, setLogLevel, log, debug, info, warn, error, LOG_LEVELS };
142
+
143
+ export default {
144
+ createLogger,
145
+ formatMessage,
146
+ setLogLevel,
147
+ log,
148
+ debug,
149
+ info,
150
+ warn,
151
+ error,
152
+ LOG_LEVELS,
153
+ };
package/core/styles.js ADDED
@@ -0,0 +1,75 @@
1
+ /**
2
+ * ANSI escape codes for colors and styles
3
+ * @module core/styles
4
+ */
5
+
6
+ export const styles = {
7
+ // Text colors
8
+ black: '\x1b[30m',
9
+ red: '\x1b[31m',
10
+ green: '\x1b[32m',
11
+ yellow: '\x1b[33m',
12
+ blue: '\x1b[34m',
13
+ magenta: '\x1b[35m',
14
+ cyan: '\x1b[36m',
15
+ white: '\x1b[37m',
16
+ gray: '\x1b[90m',
17
+
18
+ // Background colors
19
+ bgBlack: '\x1b[40m',
20
+ bgRed: '\x1b[41m',
21
+ bgGreen: '\x1b[42m',
22
+ bgYellow: '\x1b[43m',
23
+ bgBlue: '\x1b[44m',
24
+ bgMagenta: '\x1b[45m',
25
+ bgCyan: '\x1b[46m',
26
+ bgWhite: '\x1b[47m',
27
+
28
+ // Text styles
29
+ reset: '\x1b[0m',
30
+ bright: '\x1b[1m',
31
+ dim: '\x1b[2m',
32
+ italic: '\x1b[3m',
33
+ underline: '\x1b[4m',
34
+ blink: '\x1b[5m',
35
+ reverse: '\x1b[7m',
36
+ hidden: '\x1b[8m',
37
+ strikethrough: '\x1b[9m',
38
+ };
39
+
40
+ // Aliases for common styles
41
+ export const colors = {
42
+ // Text colors
43
+ black: styles.black,
44
+ red: styles.red,
45
+ green: styles.green,
46
+ yellow: styles.yellow,
47
+ blue: styles.blue,
48
+ magenta: styles.magenta,
49
+ cyan: styles.cyan,
50
+ white: styles.white,
51
+ gray: styles.gray,
52
+
53
+ // Background colors
54
+ bgBlack: styles.bgBlack,
55
+ bgRed: styles.bgRed,
56
+ bgGreen: styles.bgGreen,
57
+ bgYellow: styles.bgYellow,
58
+ bgBlue: styles.bgBlue,
59
+ bgMagenta: styles.bgMagenta,
60
+ bgCyan: styles.bgCyan,
61
+ bgWhite: styles.bgWhite,
62
+
63
+ // Styles
64
+ reset: styles.reset,
65
+ bold: styles.bright,
66
+ dim: styles.dim,
67
+ italic: styles.italic,
68
+ underline: styles.underline,
69
+ blink: styles.blink,
70
+ inverse: styles.reverse,
71
+ hidden: styles.hidden,
72
+ strikethrough: styles.strikethrough,
73
+ };
74
+
75
+ export default styles;
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Input validation utilities
3
+ * @module core/utils/validate
4
+ */
5
+
6
+ /**
7
+ * Validate input arguments
8
+ * @param {Array} args - Arguments to validate
9
+ * @returns {Array} Validated arguments
10
+ * @throws {Error} If no arguments are provided
11
+ */
12
+ export const validateInput = (args) => {
13
+ if (args.length === 0) {
14
+ throw new Error('No arguments provided');
15
+ }
16
+
17
+ return args;
18
+ };
19
+
20
+ /**
21
+ * Check if a value is an object (and not null/array)
22
+ * @param {*} value - Value to check
23
+ * @returns {boolean} True if the value is a non-null object and not an array
24
+ */
25
+ export const isObject = (value) => {
26
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
27
+ };
28
+
29
+ /**
30
+ * Check if a value is a plain object
31
+ * @param {*} value - Value to check
32
+ * @returns {boolean} True if the value is a plain object
33
+ */
34
+ export const isPlainObject = (value) => {
35
+ return isObject(value) && Object.prototype.toString.call(value) === '[object Object]';
36
+ };
37
+
38
+ export default {
39
+ validateInput,
40
+ isObject,
41
+ isPlainObject,
42
+ };
package/index.js ADDED
@@ -0,0 +1,101 @@
1
+ /**
2
+ * ChromaLog - A powerful console logger with rich formatting and styling
3
+ * @module chromalog
4
+ * @example
5
+ * // Importation de base
6
+ * import chromalog from './index.js';
7
+ *
8
+ * // Utilisation des loggers prédéfinis
9
+ * chromalog.info('Message informatif');
10
+ * chromalog.error('Erreur critique!');
11
+ *
12
+ * // Création d'un logger personnalisé
13
+ * const myLogger = chromalog.createLogger('green', 'underline');
14
+ * myLogger('Message personnalisé');
15
+ */
16
+
17
+ // Import core modules
18
+ import * as styles from './core/styles.js';
19
+ import {
20
+ createLogger,
21
+ formatMessage,
22
+ setLogLevel,
23
+ LOG_LEVELS,
24
+ } from './core/loggers/consoleLogger.js';
25
+ import { formatObject } from './core/formatters/objectFormatter.js';
26
+
27
+ /**
28
+ * Logger de base sans style particulier
29
+ * @type {Function}
30
+ */
31
+ const log = createLogger();
32
+
33
+ /**
34
+ * Logger pour les messages de débogage (style atténué)
35
+ * @type {Function}
36
+ */
37
+ const debug = createLogger('dim');
38
+
39
+ /**
40
+ * Logger pour les messages informatifs (style cyan)
41
+ * @type {Function}
42
+ */
43
+ const info = createLogger('cyan');
44
+
45
+ /**
46
+ * Logger pour les avertissements (style jaune)
47
+ * @type {Function}
48
+ */
49
+ const warn = createLogger('yellow');
50
+
51
+ /**
52
+ * Logger pour les erreurs (style rouge)
53
+ * @type {Function}
54
+ */
55
+ const error = createLogger('red');
56
+
57
+ // Export par défaut avec toutes les fonctionnalités
58
+ const ChromaLog = {
59
+ // Core
60
+ styles,
61
+
62
+ // Main logger methods
63
+ createLogger,
64
+ formatMessage,
65
+ formatObject,
66
+ setLogLevel,
67
+
68
+ // Log levels
69
+ LOG_LEVELS,
70
+
71
+ // Pre-configured loggers
72
+ log,
73
+ debug,
74
+ info,
75
+ warn,
76
+ error,
77
+ };
78
+
79
+ export default ChromaLog;
80
+
81
+ // Export nommé pour l'import déstructuré
82
+ export {
83
+ // Core
84
+ styles,
85
+
86
+ // Main logger methods
87
+ createLogger,
88
+ formatMessage,
89
+ formatObject,
90
+ setLogLevel,
91
+
92
+ // Log levels
93
+ LOG_LEVELS,
94
+
95
+ // Pre-configured loggers
96
+ log,
97
+ debug,
98
+ info,
99
+ warn,
100
+ error,
101
+ };
package/package.json ADDED
@@ -0,0 +1,60 @@
1
+ {
2
+ "name": "chromalogger",
3
+ "version": "1.0.0",
4
+ "description": "A colorful and flexible console logger for Node.js with CLI support",
5
+ "main": "chromalog.js",
6
+ "type": "module",
7
+ "bin": {
8
+ "clog": "./cli.js"
9
+ },
10
+ "scripts": {
11
+ "test": "node test.js",
12
+ "test:watch": "nodemon --watch chromalog.js --watch test.js --exec \"npm test\"",
13
+ "lint": "eslint .",
14
+ "test:chroma": "node chromatest.js",
15
+ "test:cli": "node clitest.js",
16
+ "test:all": "npm run test && npm run test:chroma && npm run test:cli",
17
+ "format": "prettier --write .",
18
+ "fix": "eslint --fix .",
19
+ "coverage": "c8 npm test"
20
+ },
21
+ "keywords": [
22
+ "log",
23
+ "color",
24
+ "console",
25
+ "logger",
26
+ "chroma",
27
+ "clog",
28
+ "nodejs",
29
+ "browser",
30
+ "ansi",
31
+ "terminal",
32
+ "styling",
33
+ "formatting"
34
+ ],
35
+ "author": {
36
+ "name": "Orssi Mp",
37
+ "email": "votre@email.com",
38
+ "url": "https://github.com/votrepseudo"
39
+ },
40
+ "license": "MIT",
41
+ "homepage": "https://github.com/votre-utilisateur/logcolor-js#readme",
42
+ "repository": {
43
+ "type": "git",
44
+ "url": "git+https://github.com/votre-utilisateur/logcolor-js.git"
45
+ },
46
+ "bugs": {
47
+ "url": "https://github.com/votre-utilisateur/logcolor-js/issues"
48
+ },
49
+ "engines": {
50
+ "node": ">=12.0.0"
51
+ },
52
+ "devDependencies": {
53
+ "c8": "^10.1.3",
54
+ "eslint": "^8.0.0",
55
+ "eslint-config-prettier": "^10.1.8",
56
+ "eslint-plugin-prettier": "^5.5.4",
57
+ "nodemon": "^3.1.11",
58
+ "prettier": "^3.7.3"
59
+ }
60
+ }
package/test.js ADDED
@@ -0,0 +1,130 @@
1
+ /**
2
+ * Test de la bibliothèque LogColor
3
+ * Ce fichier démontre les différentes fonctionnalités de LogColor
4
+ */
5
+
6
+ // Import du module principal Chromalog
7
+ import chromalog from './index.js';
8
+
9
+ // Alias pour les propriétés
10
+ const { createLogger, setLogLevel, log, debug, info, warn, error } = chromalog;
11
+
12
+ // ========================================
13
+ // 1. Test des styles de base
14
+ // ========================================
15
+ const title = createLogger('bright');
16
+ const redText = createLogger('red');
17
+ const greenText = createLogger('green');
18
+ const blueText = createLogger('blue');
19
+ const highlightText = createLogger('black', 'bgYellow');
20
+ const bold = createLogger('bright');
21
+ const underlineText = createLogger('underline');
22
+
23
+ console.log();
24
+ title('=== 1. Test des styles de base ===');
25
+ redText('Texte en rouge');
26
+ greenText('Texte en vert');
27
+ blueText('Texte en bleu');
28
+ highlightText('Texte noir sur fond jaune');
29
+ bold('Texte en gras');
30
+ underlineText('Texte souligné');
31
+
32
+ // ========================================
33
+ // 2. Test des loggers prédéfinis
34
+ // ========================================
35
+ console.log('\n=== 2. Test des loggers prédéfinis ===');
36
+ log('Message de log standard');
37
+ debug('Message de débogage');
38
+ info("Message d'information");
39
+ warn("Message d'avertissement");
40
+ error("Message d'erreur");
41
+
42
+ // ========================================
43
+ // 3. Test du formatage d'objets
44
+ // ========================================
45
+ console.log("\n=== 3. Test du formatage d'objets ===");
46
+ const utilisateur = {
47
+ id: 1,
48
+ nom: 'Dupont',
49
+ prenom: 'Jean',
50
+ email: 'jean.dupont@example.com',
51
+ actif: true,
52
+ roles: ['admin', 'utilisateur'],
53
+ preferences: {
54
+ theme: 'sombre',
55
+ notifications: true,
56
+ langue: 'fr',
57
+ },
58
+ };
59
+
60
+ info('Utilisateur:', utilisateur);
61
+
62
+ // ========================================
63
+ // 4. Test des templates
64
+ // ========================================
65
+ console.log('\n=== 4. Test des templates ===');
66
+ const nom = 'Alice';
67
+ const age = 31;
68
+ info('Bonjour {0}, vous avez {1} ans', nom, age);
69
+
70
+ // ========================================
71
+ // 5. Test des niveaux de log
72
+ // ========================================
73
+ console.log('\n=== 5. Test des niveaux de log ===');
74
+ console.log('Niveau de log actuel: DEBUG');
75
+ setLogLevel('DEBUG');
76
+ debug("Ce message de débogage devrait s'afficher");
77
+
78
+ console.log('\nChangement du niveau de log à WARN');
79
+ setLogLevel('WARN');
80
+ debug("Ce message de débogage ne devrait PAS s'afficher");
81
+ info("Ce message d'information ne devrait PAS s'afficher");
82
+ warn("Ce message d'avertissement devrait s'afficher");
83
+ error("Ce message d'erreur devrait s'afficher");
84
+
85
+ // ========================================
86
+ // 6. Test des styles personnalisés
87
+ // ========================================
88
+ const customTitle = createLogger('bright');
89
+ const success = createLogger('green', 'bright');
90
+ const important = createLogger('yellow', 'bgRed', 'bright');
91
+ const highlight = createLogger('black', 'bgYellow', 'bright');
92
+
93
+ console.log();
94
+ customTitle('=== 6. Test des styles personnalisés ===');
95
+ success('Opération réussie !');
96
+ important('Ceci est un message important !');
97
+
98
+ // ========================================
99
+ // 7. Test des chaînages de styles
100
+ // ========================================
101
+ const styledText = createLogger('red', 'bright', 'underline');
102
+ styledText('Ce texte est en rouge, en gras et souligné');
103
+
104
+ // ========================================
105
+ // 8. Test avec des tableaux
106
+ // ========================================
107
+ const sectionTitle = createLogger('bright');
108
+ const cyanText = createLogger('cyan');
109
+
110
+ console.log();
111
+ sectionTitle('=== 8. Test avec des tableaux ===');
112
+ console.log();
113
+ cyanText('Tableau de nombres:');
114
+ console.log(JSON.stringify([1, 2, 3, 4, 5], null, 2));
115
+
116
+ console.log();
117
+ cyanText('Liste des utilisateurs:');
118
+ console.log(
119
+ JSON.stringify(
120
+ [
121
+ { id: 1, nom: 'Alice' },
122
+ { id: 2, nom: 'Bob' },
123
+ { id: 3, nom: 'Charlie' },
124
+ ],
125
+ null,
126
+ 2
127
+ )
128
+ );
129
+
130
+ console.log('\n=== Fin des tests ===');
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Fonction utilitaire pour afficher du texte avec style
3
+ * @module utils/chroma
4
+ * @example
5
+ * import chroma from './utils/chroma.js';
6
+ * chroma('Texte en rouge et gras', 'red', 'bright');
7
+ */
8
+
9
+ import { styles } from '../core/styles.js';
10
+
11
+ /**
12
+ * Affiche du texte formaté dans la console avec des styles
13
+ * @param {string} text - Le texte à afficher
14
+ * @param {...string} styleNames - Noms des styles à appliquer
15
+ * @returns {void}
16
+ */
17
+ const chroma = (text, ...styleNames) => {
18
+ const styleCodes = styleNames
19
+ .flatMap((style) => style.split(','))
20
+ .map((style) => style.trim())
21
+ .filter(Boolean)
22
+ .map((name) => {
23
+ // Vérifier si le style existe directement
24
+ if (styles[name] !== undefined) {
25
+ return styles[name];
26
+ }
27
+
28
+ // Gestion des couleurs de fond (ex: 'bgRed')
29
+ if (name.startsWith('bg')) {
30
+ const bgColor = name.substring(2);
31
+ const bgKey = `bg${bgColor.charAt(0).toUpperCase() + bgColor.slice(1)}`;
32
+ return styles[bgKey] || '';
33
+ }
34
+
35
+ return '';
36
+ })
37
+ .join('');
38
+
39
+ process.stdout.write(`${styleCodes}${text}${styles.reset}\n`);
40
+ };
41
+
42
+ export default chroma;