chromalogger 1.1.2 → 1.3.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.
@@ -1,131 +0,0 @@
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
- * @param {Set} [refs] - Set to track circular references
13
- * @returns {string} Formatted object string
14
- */
15
- export const formatObject = (obj, depth = 0, refs = new WeakSet()) => {
16
- const indent = ' '.repeat(depth);
17
- const nextIndent = ' '.repeat(depth + 1);
18
-
19
- try {
20
- if (obj === null) return 'null';
21
- if (obj === undefined) return 'undefined';
22
- if (!isObject(obj)) return String(obj);
23
-
24
- // Vérifier les références circulaires
25
- if (refs.has(obj)) {
26
- return '[Circular]';
27
- }
28
-
29
- // Marquer cet objet comme visité
30
- refs.add(obj);
31
-
32
- const entries = Object.entries(obj);
33
- if (entries.length === 0) return '{}';
34
-
35
- // For small objects, keep on one line
36
- if (entries.every(([_, value]) => !isObject(value) || value === null)) {
37
- const content = entries
38
- .map(([key, value]) => `${key}: ${formatValue(value, depth + 1, refs)}`)
39
- .join(', ');
40
- return `{ ${content} }`;
41
- }
42
-
43
- // For larger or complex objects, use multiple lines
44
- const content = entries
45
- .map(([key, value]) => `${nextIndent}${key}: ${formatValue(value, depth + 1, refs)}`)
46
- .join(',\n');
47
-
48
- const result = `{\n${content}\n${indent}}`;
49
-
50
- // Nettoyer les références après le formatage
51
- refs.delete(obj);
52
- return result;
53
- } catch (error) {
54
- // En cas d'erreur, nettoyer les références
55
- if (isObject(obj)) {
56
- refs.delete(obj);
57
- }
58
- return '[Object]';
59
- }
60
- };
61
-
62
- /**
63
- * Format a value for display
64
- * @param {*} value - Value to format
65
- * @param {number} [depth=0] - Current depth for indentation
66
- * @param {Set} [refs] - Set to track circular references
67
- * @returns {string} Formatted value
68
- */
69
- const formatValue = (value, depth = 0, refs = new WeakSet()) => {
70
- if (value === null) return 'null';
71
- if (value === undefined) return 'undefined';
72
-
73
- switch (typeof value) {
74
- case 'string':
75
- return `"${value}"`;
76
- case 'object':
77
- if (Array.isArray(value)) {
78
- return formatArray(value, depth, refs);
79
- }
80
- return formatObject(value, depth, refs);
81
- case 'function':
82
- return '[Function]';
83
- case 'symbol':
84
- return value.toString();
85
- default:
86
- return String(value);
87
- }
88
- };
89
-
90
- /**
91
- * Format an array for display
92
- * @param {Array} arr - Array to format
93
- * @param {number} [depth=0] - Current depth for indentation
94
- * @param {Set} [refs] - Set to track circular references
95
- * @returns {string} Formatted array string
96
- */
97
- const formatArray = (arr, depth = 0, refs = new WeakSet()) => {
98
- if (!Array.isArray(arr)) return '[]';
99
- if (arr.length === 0) return '[]';
100
-
101
- // Vérifier les références circulaires pour les tableaux
102
- if (refs.has(arr)) {
103
- return '[Circular]';
104
- }
105
-
106
- // Marquer ce tableau comme visité
107
- refs.add(arr);
108
-
109
- const indent = ' '.repeat(depth);
110
- const nextIndent = ' '.repeat(depth + 1);
111
-
112
- // For small arrays, keep on one line
113
- if (arr.length <= 3 && arr.every((item) => !isObject(item) || item === null)) {
114
- return `[ ${arr.map((item) => formatValue(item, depth + 1, refs)).join(', ')} ]`;
115
- }
116
-
117
- // For larger or complex arrays, use multiple lines
118
- const items = arr.map((item) => `${nextIndent}${formatValue(item, depth + 1, refs)}`).join(',\n');
119
-
120
- const result = `[\n${items}\n${indent}]`;
121
-
122
- // Nettoyer les références après le formatage
123
- refs.delete(arr);
124
- return result;
125
- };
126
-
127
- export default {
128
- formatObject,
129
- formatArray,
130
- formatValue,
131
- };
@@ -1,218 +0,0 @@
1
- /**
2
- * Console logger implementation
3
- * @module core/loggers/consoleLogger
4
- */
5
-
6
- import { validateInput } from '../utils/validate.js';
7
- import styles from '../styles.js';
8
- import util from 'util';
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
- console.log('\n=== DEBUG: Début de la fonction logger ===');
48
- console.log('Arguments reçus:', args);
49
-
50
- // Vérifier le niveau de log
51
- let logLevel = LOG_LEVELS.INFO;
52
- if (styleNames.includes('dim')) {
53
- logLevel = LOG_LEVELS.DEBUG;
54
- } else if (styleNames.includes('yellow')) {
55
- logLevel = LOG_LEVELS.WARN;
56
- } else if (styleNames.includes('red')) {
57
- logLevel = LOG_LEVELS.ERROR;
58
- }
59
-
60
- console.log('Niveau de log actuel:', currentLogLevel, 'Niveau requis:', logLevel);
61
-
62
- if (logLevel < currentLogLevel) return;
63
-
64
- // Si pas d'arguments, afficher une ligne vide
65
- if (args.length === 0) {
66
- console.log();
67
- return;
68
- }
69
-
70
- // Préparer le message final
71
- let output = '';
72
-
73
- // Si le premier argument est une chaîne et qu'il y a plus d'un argument,
74
- // traiter comme un template string
75
- if (typeof args[0] === 'string' && args.length > 1) {
76
- const message = args[0];
77
- const values = args.slice(1);
78
- output = formatMessage(message, values);
79
- } else {
80
- // Sinon, formater chaque argument individuellement
81
- const formattedArgs = args.map((arg) => {
82
- try {
83
- if (arg === null) return 'null';
84
- if (arg === undefined) return 'undefined';
85
- if (typeof arg === 'object' || Array.isArray(arg)) {
86
- return util.inspect(arg, {
87
- showHidden: false,
88
- depth: 6,
89
- colors: false,
90
- maxArrayLength: 10,
91
- breakLength: 80,
92
- compact: 3,
93
- sorted: false,
94
- getters: false,
95
- showProxy: false,
96
- customInspect: true,
97
- });
98
- }
99
- return String(arg);
100
- } catch (e) {
101
- return `[Error: ${e.message}]`;
102
- }
103
- });
104
- output = formattedArgs.join(' ');
105
- }
106
-
107
- // Afficher le message formaté avec les styles
108
- const finalOutput = stylePrefix + output + styles.reset;
109
- console.log('=== DEBUG: Sortie finale ===\n', finalOutput, '\n======================');
110
- console.log(finalOutput);
111
- } catch (error) {
112
- console.error(`${styles.red}LogColor: Logging error - ${error.message}${styles.reset}`);
113
- }
114
- };
115
-
116
- // Add style methods for method chaining
117
- Object.keys(styles).forEach((styleName) => {
118
- Object.defineProperty(logger, styleName, {
119
- get: () => createLogger(...styleNames, styleName),
120
- });
121
- });
122
-
123
- return logger;
124
- };
125
-
126
- /**
127
- * Format a message with placeholders
128
- * @param {string} message - Message with {0}, {1}, etc. placeholders
129
- * @param {Array} values - Values to replace placeholders
130
- * @returns {string} Formatted message
131
- */
132
- const formatMessage = (message, values = []) => {
133
- if (typeof message !== 'string') {
134
- return '';
135
- }
136
-
137
- if (!Array.isArray(values) || values.length === 0) {
138
- // Remplacer les doubles accolades échappées par des marqueurs temporaires
139
- return message.replace(/\{\{/g, '\uE000').replace(/\}\}/g, '\uE001')
140
- .replace(/\{\d+\}/g, match => match) // Laisser les placeholders tels quels
141
- .replace(/\uE000/g, '{').replace(/\uE001/g, '}');
142
- }
143
-
144
- // Si le message ne contient pas de placeholders, ajouter les valeurs à la suite
145
- if (!/\{\d+\}/.test(message)) {
146
- return `${message} ${values
147
- .map((v) => (typeof v === 'object' ? JSON.stringify(v) : String(v)))
148
- .join(' ')}`.trim();
149
- }
150
-
151
- // Remplacer d'abord les doubles accolades échappées par des marqueurs temporaires
152
- const tempMessage = message.replace(/\{\{/g, '\uE000').replace(/\}\}/g, '\uE001');
153
-
154
- // Remplacer les placeholders
155
- const formatted = tempMessage.replace(/\{(\d+)\}/g, (match, index) => {
156
- const value = values[parseInt(index, 10)];
157
- if (value === undefined || value === null) {
158
- return match;
159
- }
160
-
161
- // Utiliser util.inspect pour les objets et tableaux
162
- if (typeof value === 'object' || Array.isArray(value)) {
163
- return util.inspect(value, {
164
- showHidden: false,
165
- depth: 6,
166
- colors: false,
167
- maxArrayLength: 10,
168
- breakLength: 80,
169
- compact: 3,
170
- sorted: false,
171
- getters: false,
172
- showProxy: false,
173
- customInspect: true,
174
- });
175
- }
176
-
177
- return String(value);
178
- });
179
-
180
- // Remplacer les marqueurs temporaires par des accolades simples
181
- return formatted.replace(/\uE000/g, '{').replace(/\uE001/g, '}');
182
- };
183
-
184
- /**
185
- * Set the current log level
186
- * @param {string} level - Log level (DEBUG, INFO, WARN, ERROR, NONE)
187
- */
188
- const setLogLevel = (level) => {
189
- const upperLevel = level.toUpperCase();
190
- if (LOG_LEVELS[upperLevel] !== undefined) {
191
- currentLogLevel = LOG_LEVELS[upperLevel];
192
- } else {
193
- console.warn(`LogColor: Unknown log level "${level}". Using INFO.`);
194
- currentLogLevel = LOG_LEVELS.INFO;
195
- }
196
- };
197
-
198
- // Create default loggers
199
- const log = createLogger();
200
- const debug = createLogger('dim');
201
- const info = createLogger('cyan');
202
- const warn = createLogger('yellow');
203
- const error = createLogger('red');
204
-
205
- // Export everything
206
- export { createLogger, formatMessage, setLogLevel, log, debug, info, warn, error, LOG_LEVELS };
207
-
208
- export default {
209
- createLogger,
210
- formatMessage,
211
- setLogLevel,
212
- log,
213
- debug,
214
- info,
215
- warn,
216
- error,
217
- LOG_LEVELS,
218
- };
package/core/styles.js DELETED
@@ -1,75 +0,0 @@
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;
@@ -1,45 +0,0 @@
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 || args.length === 0) {
14
- return [];
15
- }
16
-
17
- // Convertir les arguments en tableau s'ils ne le sont pas déjà
18
- const argsArray = Array.isArray(args) ? args : Array.from(args);
19
-
20
- return argsArray;
21
- };
22
-
23
- /**
24
- * Check if a value is an object (and not null/array)
25
- * @param {*} value - Value to check
26
- * @returns {boolean} True if the value is a non-null object and not an array
27
- */
28
- export const isObject = (value) => {
29
- return value !== null && typeof value === 'object' && !Array.isArray(value);
30
- };
31
-
32
- /**
33
- * Check if a value is a plain object
34
- * @param {*} value - Value to check
35
- * @returns {boolean} True if the value is a plain object
36
- */
37
- export const isPlainObject = (value) => {
38
- return isObject(value) && Object.prototype.toString.call(value) === '[object Object]';
39
- };
40
-
41
- export default {
42
- validateInput,
43
- isObject,
44
- isPlainObject,
45
- };
package/test.js DELETED
@@ -1,159 +0,0 @@
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 { createLogger, setLogLevel, log, debug, info, warn, error } from './index.js';
8
-
9
- // ========================================
10
- // 1. Test des styles de base
11
- // ========================================
12
- const title = createLogger('bright');
13
- const redText = createLogger('red');
14
- const greenText = createLogger('green');
15
- const blueText = createLogger('blue');
16
- const highlightText = createLogger('black', 'bgYellow');
17
- const bold = createLogger('bright');
18
- const underlineText = createLogger('underline');
19
-
20
- console.log();
21
- title('=== 1. Test des styles de base ===');
22
- redText('Texte en rouge');
23
- greenText('Texte en vert');
24
- blueText('Texte en bleu');
25
- highlightText('Texte noir sur fond jaune');
26
- bold('Texte en gras');
27
- underlineText('Texte souligné');
28
-
29
- // ========================================
30
- // 2. Test des loggers prédéfinis
31
- // ========================================
32
- console.log('\n=== 2. Test des loggers prédéfinis ===');
33
- log('Message de log standard');
34
- debug('Message de débogage');
35
- info("Message d'information");
36
- warn("Message d'avertissement");
37
- error("Message d'erreur");
38
-
39
- // ========================================
40
- // 3. Test du formatage d'objets
41
- // ========================================
42
- console.log("\n=== 3. Test du formatage d'objets ===");
43
- const utilisateur = {
44
- id: 1,
45
- nom: 'Dupont',
46
- prenom: 'Jean',
47
- email: 'jean.dupont@example.com',
48
- actif: true,
49
- roles: ['admin', 'utilisateur'],
50
- preferences: {
51
- theme: 'sombre',
52
- notifications: true,
53
- langue: 'fr',
54
- },
55
- };
56
-
57
- info('Utilisateur:', utilisateur);
58
-
59
- // ========================================
60
- // 4. Test des templates
61
- // ========================================
62
- console.log('\n=== 4. Test des templates ===');
63
- const nom = 'Alice';
64
- const age = 31;
65
- info('Bonjour {0}, vous avez {1} ans de {{nom et age}}', nom, age);
66
-
67
- // ========================================
68
- // 5. Test des niveaux de log
69
- // ========================================
70
- console.log('\n=== 5. Test des niveaux de log ===');
71
- console.log('Niveau de log actuel: DEBUG');
72
- setLogLevel('DEBUG');
73
- debug("Ce message de débogage devrait s'afficher");
74
-
75
- console.log('\nChangement du niveau de log à WARN');
76
- setLogLevel('WARN');
77
- debug("Ce message de débogage ne devrait PAS s'afficher");
78
- info("Ce message d'information ne devrait PAS s'afficher");
79
- warn("Ce message d'avertissement devrait s'afficher");
80
- error("Ce message d'erreur devrait s'afficher");
81
-
82
- // ========================================
83
- // 6. Test des styles personnalisés
84
- // ========================================
85
- const customTitle = createLogger('bright');
86
- const success = createLogger('green', 'bright');
87
- const important = createLogger('yellow', 'bgRed', 'bright');
88
- const highlight = createLogger('black', 'bgYellow', 'bright');
89
-
90
- console.log();
91
- customTitle('=== 6. Test des styles personnalisés ===');
92
- success('Opération réussie !');
93
- important('Ceci est un message important !');
94
-
95
- // ========================================
96
- // 7. Test des chaînages de styles
97
- // ========================================
98
- const styledText = createLogger('red', 'bright', 'underline');
99
- styledText('Ce texte est en rouge, en gras et souligné');
100
-
101
- // ========================================
102
- // 8. Test avec des tableaux
103
- // ========================================
104
- const sectionTitle = createLogger('bright');
105
- const cyanText = createLogger('cyan');
106
-
107
- console.log();
108
- sectionTitle('=== 8. Test avec des tableaux ===');
109
- console.log();
110
- cyanText('Tableau de nombres:');
111
- console.log(JSON.stringify([1, 2, 3, 4, 5], null, 2));
112
-
113
- console.log();
114
- cyanText('Liste des utilisateurs:');
115
- console.log(
116
- JSON.stringify(
117
- [
118
- { id: 1, nom: 'Alice' },
119
- { id: 2, nom: 'Bob' },
120
- { id: 3, nom: 'Charlie' },
121
- ],
122
- null,
123
- 2
124
- )
125
- );
126
-
127
- // Références circulaires
128
- console.log('\n=== 6. Test des références circulaires ===');
129
- const obj1 = { name: 'Objet 1' };
130
- const obj2 = { name: 'Objet 2', ref: obj1 };
131
- obj1.ref = obj2;
132
-
133
- // Afficher directement l'objet pour le débogage
134
- console.log('Obj1:', obj1);
135
- console.log('Obj2:', obj2);
136
-
137
- // Afficher avec le logger personnalisé
138
- console.log('\n=== Test du logger personnalisé ===');
139
- console.log('Type de log:', typeof log);
140
- console.log('log est une fonction ?:', typeof log === 'function');
141
-
142
- // Définir le niveau de log sur DEBUG pour voir tous les messages
143
- setLogLevel('DEBUG');
144
- console.log('Niveau de log défini sur DEBUG');
145
-
146
- // Tester avec un simple message
147
- console.log('\nTest avec un message simple:');
148
- log('Ceci est un test simple');
149
-
150
- // Tester avec un objet simple
151
- console.log('\nTest avec un objet simple:');
152
- log({ test: 'objet simple' });
153
-
154
- // Tester avec les objets circulaires
155
- log('\nTest avec les objets circulaires:');
156
- log('obj1:', obj1);
157
- log('obj2:', obj2);
158
-
159
- console.log('\n=== Fin des tests ===');
package/utils/chroma.js DELETED
@@ -1,42 +0,0 @@
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;