-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalidate.js
More file actions
445 lines (363 loc) · 14 KB
/
validate.js
File metadata and controls
445 lines (363 loc) · 14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
#!/usr/bin/env node
/**
* Script de validation du thème Obsidian Monokai Night
* Vérifie la validité du CSS, des couleurs et de la configuration
*/
const fs = require('fs-extra');
const path = require('path');
const chalk = require('chalk');
class ThemeValidator {
constructor() {
this.errors = [];
this.warnings = [];
this.info = [];
this.stats = {
cssSize: 0,
variableCount: 0,
ruleCount: 0,
colorCount: 0
};
}
async run() {
console.log(chalk.bold.magenta('🔍 === VALIDATION DU THÈME ===\n'));
try {
await this.validateFiles();
await this.validateCSS();
await this.validateColors();
await this.validateConfiguration();
this.analyzeStats();
this.displayReport();
} catch (error) {
console.log(chalk.bold.red('\n💥 Erreur lors de la validation:'));
console.log(chalk.red(error.message));
process.exit(1);
}
// Code de sortie basé sur les erreurs
process.exit(this.errors.length > 0 ? 1 : 0);
}
async validateFiles() {
console.log(chalk.blue('📁 Validation des fichiers...'));
const requiredFiles = [
'theme.css',
'manifest.json',
'package.json',
'scripts/color-mapping.json',
'README.md'
];
for (const file of requiredFiles) {
const filepath = path.resolve(file);
if (await fs.pathExists(filepath)) {
this.info.push(`✅ ${file} existe`);
// Vérifier la taille du fichier CSS
if (file === 'theme.css') {
const stats = await fs.stat(filepath);
this.stats.cssSize = stats.size;
if (stats.size === 0) {
this.errors.push(`❌ ${file} est vide`);
} else if (stats.size > 500 * 1024) { // 500KB
this.warnings.push(`⚠️ ${file} est très volumineux (${Math.round(stats.size / 1024)}KB)`);
}
}
} else {
this.errors.push(`❌ ${file} manquant`);
}
}
console.log(chalk.green('✅ Validation des fichiers terminée'));
}
async validateCSS() {
console.log(chalk.blue('🎨 Validation du CSS...'));
const cssPath = path.resolve('theme.css');
if (!await fs.pathExists(cssPath)) {
this.errors.push('❌ theme.css non trouvé');
return;
}
const css = await fs.readFile(cssPath, 'utf8');
// Validation de base de la syntaxe CSS
this.validateCSSStructure(css);
this.validateCSSVariables(css);
this.validateCSSRules(css);
this.checkCSSBestPractices(css);
console.log(chalk.green('✅ Validation CSS terminée'));
}
validateCSSStructure(css) {
// Vérifier les accolades équilibrées
const openBraces = (css.match(/{/g) || []).length;
const closeBraces = (css.match(/}/g) || []).length;
if (openBraces !== closeBraces) {
this.errors.push(`❌ Accolades déséquilibrées: ${openBraces} ouvertes, ${closeBraces} fermées`);
}
// Vérifier la présence de variables CSS
const hasRootVariables = css.includes(':root');
if (!hasRootVariables) {
this.errors.push('❌ Aucune variable CSS :root trouvée');
}
// Compter les règles CSS
this.stats.ruleCount = (css.match(/[^}]*{[^{]*}/g) || []).length;
this.info.push(`📊 ${this.stats.ruleCount} règles CSS trouvées`);
}
validateCSSVariables(css) {
// Extraire toutes les variables CSS
const variableMatches = css.match(/--[\w-]+:\s*[^;]+;/g) || [];
this.stats.variableCount = variableMatches.length;
// Variables obligatoires pour Obsidian
const requiredVariables = [
'--background-primary',
'--background-secondary',
'--text-normal',
'--text-muted',
'--interactive-accent'
];
for (const variable of requiredVariables) {
if (!css.includes(variable)) {
this.errors.push(`❌ Variable obligatoire manquante: ${variable}`);
}
}
// Vérifier les couleurs valides
const colorVariables = variableMatches.filter(match =>
/#[0-9a-fA-F]{3,8}|rgb|rgba|hsl|hsla/.test(match)
);
this.stats.colorCount = colorVariables.length;
this.info.push(`🎨 ${this.stats.variableCount} variables CSS trouvées`);
this.info.push(`🌈 ${this.stats.colorCount} variables de couleur trouvées`);
}
validateCSSRules(css) {
// Vérifier la présence de sélecteurs Obsidian importants
const importantSelectors = [
'.app-container',
'.workspace',
'.cm-editor',
'.nav-file-title',
'.modal'
];
for (const selector of importantSelectors) {
if (!css.includes(selector)) {
this.warnings.push(`⚠️ Sélecteur recommandé manquant: ${selector}`);
}
}
// Vérifier les propriétés dangereuses
const dangerousProperties = [
'position: fixed',
'z-index: 9999',
'!important'
];
for (const prop of dangerousProperties) {
if (css.includes(prop)) {
this.warnings.push(`⚠️ Propriété potentiellement problématique: ${prop}`);
}
}
}
checkCSSBestPractices(css) {
// Vérifier l'utilisation excessive d'!important
const importantCount = (css.match(/!important/g) || []).length;
if (importantCount > 10) {
this.warnings.push(`⚠️ Utilisation excessive d'!important (${importantCount} occurrences)`);
}
// Vérifier la cohérence des commentaires
const hasComments = css.includes('/*') && css.includes('*/');
if (!hasComments) {
this.warnings.push('⚠️ Aucun commentaire CSS trouvé');
}
// Vérifier la présence d'informations d'en-tête
if (!css.includes('Obsidian') && !css.includes('Monokai')) {
this.warnings.push('⚠️ En-tête de thème manquant ou incomplet');
}
}
async validateColors() {
console.log(chalk.blue('🌈 Validation des couleurs...'));
try {
const mappingPath = path.resolve('scripts/color-mapping.json');
const mapping = await fs.readJson(mappingPath);
// Vérifier la structure du mapping
const requiredSections = ['baseColors', 'syntaxColors', 'uiColors', 'mappingRules'];
for (const section of requiredSections) {
if (!mapping[section]) {
this.errors.push(`❌ Section manquante dans color-mapping.json: ${section}`);
}
}
// Vérifier les couleurs hexadécimales
this.validateHexColors(mapping);
// Vérifier la cohérence des mappings
this.validateMappingRules(mapping);
} catch (error) {
this.errors.push('❌ Erreur lors de la validation des couleurs: ' + error.message);
}
console.log(chalk.green('✅ Validation des couleurs terminée'));
}
validateHexColors(mapping) {
const hexColorRegex = /^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3}|[A-Fa-f0-9]{8})$/;
// Parcourir toutes les couleurs
const allColors = {
...mapping.baseColors?.vscode,
...mapping.baseColors?.obsidian,
...mapping.syntaxColors?.vscode,
...mapping.syntaxColors?.obsidian,
...mapping.uiColors?.vscode,
...mapping.uiColors?.obsidian,
...mapping.customVariables
};
for (const [key, value] of Object.entries(allColors)) {
if (typeof value === 'string' && value.startsWith('#')) {
if (!hexColorRegex.test(value)) {
this.errors.push(`❌ Couleur hexadécimale invalide: ${key} = ${value}`);
}
}
}
}
validateMappingRules(mapping) {
if (!mapping.mappingRules || !Array.isArray(mapping.mappingRules)) {
this.errors.push('❌ mappingRules doit être un tableau');
return;
}
for (const rule of mapping.mappingRules) {
if (!rule.source || !rule.target) {
this.errors.push('❌ Règle de mapping incomplète (source/target manquant)');
}
// Vérifier que la source existe dans les couleurs VSCode
const vscodeColors = {
...mapping.baseColors?.vscode,
...mapping.syntaxColors?.vscode,
...mapping.uiColors?.vscode
};
if (!vscodeColors[rule.source]) {
this.warnings.push(`⚠️ Source de mapping non trouvée: ${rule.source}`);
}
}
}
async validateConfiguration() {
console.log(chalk.blue('⚙️ Validation de la configuration...'));
// Valider manifest.json
await this.validateManifest();
// Valider package.json
await this.validatePackageJson();
console.log(chalk.green('✅ Validation de la configuration terminée'));
}
async validateManifest() {
try {
const manifestPath = path.resolve('manifest.json');
const manifest = await fs.readJson(manifestPath);
const requiredFields = ['name', 'version', 'minAppVersion', 'description', 'author'];
for (const field of requiredFields) {
if (!manifest[field]) {
this.errors.push(`❌ Champ manquant dans manifest.json: ${field}`);
}
}
// Vérifier le format de version
const versionRegex = /^\d+\.\d+\.\d+$/;
if (manifest.version && !versionRegex.test(manifest.version)) {
this.errors.push(`❌ Format de version invalide dans manifest.json: ${manifest.version}`);
}
if (manifest.minAppVersion && !versionRegex.test(manifest.minAppVersion)) {
this.errors.push(`❌ Format minAppVersion invalide: ${manifest.minAppVersion}`);
}
this.info.push(`📋 Manifest: ${manifest.name} v${manifest.version}`);
} catch (error) {
this.errors.push('❌ Erreur lors de la validation du manifest: ' + error.message);
}
}
async validatePackageJson() {
try {
const packagePath = path.resolve('package.json');
const pkg = await fs.readJson(packagePath);
const requiredFields = ['name', 'version', 'description', 'author', 'license'];
for (const field of requiredFields) {
if (!pkg[field]) {
this.warnings.push(`⚠️ Champ recommandé manquant dans package.json: ${field}`);
}
}
// Vérifier les scripts
const requiredScripts = ['build', 'check-updates', 'sync'];
for (const script of requiredScripts) {
if (!pkg.scripts || !pkg.scripts[script]) {
this.warnings.push(`⚠️ Script manquant dans package.json: ${script}`);
}
}
// Vérifier les dépendances de développement
const requiredDevDeps = ['axios', 'fs-extra', 'chalk'];
for (const dep of requiredDevDeps) {
if (!pkg.devDependencies || !pkg.devDependencies[dep]) {
this.warnings.push(`⚠️ Dépendance manquante: ${dep}`);
}
}
this.info.push(`📦 Package: ${pkg.name} v${pkg.version}`);
} catch (error) {
this.errors.push('❌ Erreur lors de la validation du package.json: ' + error.message);
}
}
analyzeStats() {
console.log(chalk.blue('📊 Analyse des statistiques...'));
// Analyser la taille du CSS
if (this.stats.cssSize > 0) {
const sizeKB = Math.round(this.stats.cssSize / 1024);
this.info.push(`📏 Taille du CSS: ${sizeKB}KB`);
if (sizeKB < 10) {
this.warnings.push('⚠️ Le fichier CSS semble très petit');
} else if (sizeKB > 200) {
this.warnings.push('⚠️ Le fichier CSS est très volumineux');
}
}
// Analyser le ratio variables/règles
if (this.stats.variableCount > 0 && this.stats.ruleCount > 0) {
const ratio = this.stats.variableCount / this.stats.ruleCount;
if (ratio < 0.1) {
this.warnings.push('⚠️ Peu de variables CSS utilisées par rapport au nombre de règles');
}
}
// Analyser la couverture des couleurs
if (this.stats.colorCount < 10) {
this.warnings.push('⚠️ Peu de variables de couleur définies');
}
console.log(chalk.green('✅ Analyse des statistiques terminée'));
}
displayReport() {
console.log(chalk.bold.magenta('\n📋 === RAPPORT DE VALIDATION ===\n'));
// Résumé
console.log(chalk.bold.white('📊 RÉSUMÉ:'));
console.log(` Erreurs: ${chalk.red(this.errors.length)}`);
console.log(` Avertissements: ${chalk.yellow(this.warnings.length)}`);
console.log(` Informations: ${chalk.cyan(this.info.length)}`);
console.log('');
// Statistiques
console.log(chalk.bold.white('📈 STATISTIQUES:'));
console.log(` Taille CSS: ${chalk.cyan(Math.round(this.stats.cssSize / 1024))}KB`);
console.log(` Variables CSS: ${chalk.cyan(this.stats.variableCount)}`);
console.log(` Règles CSS: ${chalk.cyan(this.stats.ruleCount)}`);
console.log(` Variables couleur: ${chalk.cyan(this.stats.colorCount)}`);
console.log('');
// Erreurs
if (this.errors.length > 0) {
console.log(chalk.bold.red('❌ ERREURS:'));
this.errors.forEach(error => console.log(` ${error}`));
console.log('');
}
// Avertissements
if (this.warnings.length > 0) {
console.log(chalk.bold.yellow('⚠️ AVERTISSEMENTS:'));
this.warnings.forEach(warning => console.log(` ${warning}`));
console.log('');
}
// Informations (en mode verbose seulement)
if (process.env.VERBOSE === '1' && this.info.length > 0) {
console.log(chalk.bold.cyan('ℹ️ INFORMATIONS:'));
this.info.forEach(info => console.log(` ${info}`));
console.log('');
}
// Résultat final
if (this.errors.length === 0) {
console.log(chalk.bold.green('✅ VALIDATION RÉUSSIE !'));
if (this.warnings.length > 0) {
console.log(chalk.yellow(` ${this.warnings.length} avertissement(s) à considérer`));
}
} else {
console.log(chalk.bold.red('❌ VALIDATION ÉCHOUÉE !'));
console.log(chalk.red(` ${this.errors.length} erreur(s) à corriger`));
}
console.log('');
console.log(chalk.gray('💡 Utilisez VERBOSE=1 pour plus de détails'));
}
}
// Exécution du script
if (require.main === module) {
const validator = new ThemeValidator();
validator.run();
}
module.exports = ThemeValidator;