slicejs-cli 2.8.5 → 2.9.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,175 +1,175 @@
1
- import fs from 'fs';
2
- import path from 'path';
3
- import { fileURLToPath } from 'url';
4
- import Table from 'cli-table3';
5
- import chalk from 'chalk';
6
- import Print from '../Print.js';
7
- import { getSrcPath, getComponentsJsPath, getConfigPath } from '../utils/PathHelper.js';
8
-
9
- const __dirname = path.dirname(fileURLToPath(import.meta.url));
10
-
11
- /**
12
- * Carga la configuración desde sliceConfig.json
13
- * @returns {object} - Objeto de configuración
14
- */
15
- const loadConfig = () => {
16
- try {
17
- const configPath = getConfigPath(import.meta.url);
18
- if (!fs.existsSync(configPath)) {
19
- Print.error('sliceConfig.json not found');
20
- Print.info('Run "slice init" to initialize your project');
21
- return null;
22
- }
23
- const rawData = fs.readFileSync(configPath, 'utf-8');
24
- return JSON.parse(rawData);
25
- } catch (error) {
26
- Print.error(`Failed to load configuration: ${error.message}`);
27
- Print.info('Check that sliceConfig.json is valid JSON');
28
- return null;
29
- }
30
- };
31
-
32
- /**
33
- * Lista los archivos en una carpeta dada, filtrando solo los archivos .js
34
- * @param {string} folderPath - Ruta de la carpeta a leer
35
- * @returns {string[]} - Lista de archivos encontrados
36
- */
37
- const listComponents = (folderPath) => {
38
- try {
39
- if (!fs.existsSync(folderPath)) {
40
- return [];
41
- }
42
- const result = fs.readdirSync(folderPath);
43
- return result;
44
- } catch (error) {
45
- Print.error(`Failed to read directory ${folderPath}: ${error.message}`);
46
- return [];
47
- }
48
- };
49
-
50
- /**
51
- * Cuenta archivos en un directorio de componente
52
- */
53
- const countComponentFiles = (componentPath) => {
54
- try {
55
- if (!fs.existsSync(componentPath)) return 0;
56
- const files = fs.readdirSync(componentPath);
57
- return files.filter(f => fs.statSync(path.join(componentPath, f)).isFile()).length;
58
- } catch {
59
- return 0;
60
- }
61
- };
62
-
63
- /**
64
- * Obtiene los componentes dinámicamente desde sliceConfig.json
65
- * @returns {object} - Mapeo de componentes con su categoría
66
- */
67
- const getComponents = () => {
68
- const config = loadConfig();
69
- if (!config) return {};
70
-
71
- const folderSuffix = 'src'; // Siempre usar 'src' para desarrollo
72
- const componentPaths = config.paths?.components || {};
73
- let allComponents = new Map();
74
-
75
- Object.entries(componentPaths).forEach(([category, { path: folderPath }]) => {
76
- const cleanFolderPath = folderPath ? folderPath.replace(/^[/\\]+/, '') : '';
77
- const fullPath = getSrcPath(import.meta.url, cleanFolderPath);
78
- const files = listComponents(fullPath);
79
-
80
- files.forEach(file => {
81
- const componentPath = path.join(fullPath, file);
82
- if (fs.statSync(componentPath).isDirectory()) {
83
- const fileCount = countComponentFiles(componentPath);
84
- allComponents.set(file, { category, files: fileCount });
85
- }
86
- });
87
- });
88
-
89
- return Object.fromEntries(allComponents);
90
- };
91
-
92
- function listComponentsReal() {
93
- try {
94
- // Obtener componentes dinámicamente
95
- const components = getComponents();
96
-
97
- if (Object.keys(components).length === 0) {
98
- Print.warning('No components found in your project');
99
- Print.info('Create your first component with "slice component create"');
100
- return;
101
- }
102
-
103
- // Crear tabla con cli-table3
104
- const table = new Table({
105
- head: [
106
- chalk.cyan.bold('Component'),
107
- chalk.cyan.bold('Category'),
108
- chalk.cyan.bold('Files')
109
- ],
110
- colWidths: [30, 20, 10],
111
- style: {
112
- head: [],
113
- border: ['gray']
114
- }
115
- });
116
-
117
- // Agrupar por categoría para mejor visualización
118
- const byCategory = {};
119
- Object.entries(components).forEach(([name, data]) => {
120
- if (!byCategory[data.category]) {
121
- byCategory[data.category] = [];
122
- }
123
- byCategory[data.category].push({ name, files: data.files });
124
- });
125
-
126
- // Agregar filas a la tabla
127
- Object.entries(byCategory).forEach(([category, comps]) => {
128
- comps.forEach((comp, index) => {
129
- if (index === 0) {
130
- // Primera fila de la categoría
131
- table.push([
132
- chalk.bold(comp.name),
133
- chalk.yellow(category),
134
- comp.files.toString()
135
- ]);
136
- } else {
137
- // Resto de componentes en la categoría
138
- table.push([
139
- chalk.bold(comp.name),
140
- chalk.gray('″'), // Ditto mark
141
- comp.files.toString()
142
- ]);
143
- }
144
- });
145
- });
146
-
147
- Print.newLine();
148
- Print.title('📦 Local Components');
149
- Print.newLine();
150
- console.log(table.toString());
151
- Print.newLine();
152
- Print.info(`Total: ${Object.keys(components).length} component${Object.keys(components).length !== 1 ? 's' : ''} found`);
153
-
154
- // Ruta donde se generará components.js
155
- const outputPath = getComponentsJsPath(import.meta.url);
156
-
157
- // Asegurar que el directorio existe
158
- const outputDir = path.dirname(outputPath);
159
- if (!fs.existsSync(outputDir)) {
160
- fs.mkdirSync(outputDir, { recursive: true });
161
- }
162
-
163
- // Generar archivo components.js con los componentes detectados
164
- const componentsForExport = Object.fromEntries(
165
- Object.entries(components).map(([name, data]) => [name, data.category])
166
- );
167
- fs.writeFileSync(outputPath, `const components = ${JSON.stringify(componentsForExport, null, 2)};\n\nexport default components;\n`);
168
-
169
- } catch (error) {
170
- Print.error(`Failed to list components: ${error.message}`);
171
- Print.info('Make sure your project structure is correct');
172
- }
173
- }
174
-
175
- export default listComponentsReal;
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import { fileURLToPath } from 'url';
4
+ import Table from 'cli-table3';
5
+ import chalk from 'chalk';
6
+ import Print from '../Print.js';
7
+ import { getSrcPath, getComponentsJsPath, getConfigPath } from '../utils/PathHelper.js';
8
+
9
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
10
+
11
+ /**
12
+ * Carga la configuración desde sliceConfig.json
13
+ * @returns {object} - Objeto de configuración
14
+ */
15
+ const loadConfig = () => {
16
+ try {
17
+ const configPath = getConfigPath(import.meta.url);
18
+ if (!fs.existsSync(configPath)) {
19
+ Print.error('sliceConfig.json not found');
20
+ Print.info('Run "slice init" to initialize your project');
21
+ return null;
22
+ }
23
+ const rawData = fs.readFileSync(configPath, 'utf-8');
24
+ return JSON.parse(rawData);
25
+ } catch (error) {
26
+ Print.error(`Failed to load configuration: ${error.message}`);
27
+ Print.info('Check that sliceConfig.json is valid JSON');
28
+ return null;
29
+ }
30
+ };
31
+
32
+ /**
33
+ * Lista los archivos en una carpeta dada, filtrando solo los archivos .js
34
+ * @param {string} folderPath - Ruta de la carpeta a leer
35
+ * @returns {string[]} - Lista de archivos encontrados
36
+ */
37
+ const listComponents = (folderPath) => {
38
+ try {
39
+ if (!fs.existsSync(folderPath)) {
40
+ return [];
41
+ }
42
+ const result = fs.readdirSync(folderPath);
43
+ return result;
44
+ } catch (error) {
45
+ Print.error(`Failed to read directory ${folderPath}: ${error.message}`);
46
+ return [];
47
+ }
48
+ };
49
+
50
+ /**
51
+ * Cuenta archivos en un directorio de componente
52
+ */
53
+ const countComponentFiles = (componentPath) => {
54
+ try {
55
+ if (!fs.existsSync(componentPath)) return 0;
56
+ const files = fs.readdirSync(componentPath);
57
+ return files.filter(f => fs.statSync(path.join(componentPath, f)).isFile()).length;
58
+ } catch {
59
+ return 0;
60
+ }
61
+ };
62
+
63
+ /**
64
+ * Obtiene los componentes dinámicamente desde sliceConfig.json
65
+ * @returns {object} - Mapeo de componentes con su categoría
66
+ */
67
+ const getComponents = () => {
68
+ const config = loadConfig();
69
+ if (!config) return {};
70
+
71
+ const folderSuffix = 'src'; // Siempre usar 'src' para desarrollo
72
+ const componentPaths = config.paths?.components || {};
73
+ let allComponents = new Map();
74
+
75
+ Object.entries(componentPaths).forEach(([category, { path: folderPath }]) => {
76
+ const cleanFolderPath = folderPath ? folderPath.replace(/^[/\\]+/, '') : '';
77
+ const fullPath = getSrcPath(import.meta.url, cleanFolderPath);
78
+ const files = listComponents(fullPath);
79
+
80
+ files.forEach(file => {
81
+ const componentPath = path.join(fullPath, file);
82
+ if (fs.statSync(componentPath).isDirectory()) {
83
+ const fileCount = countComponentFiles(componentPath);
84
+ allComponents.set(file, { category, files: fileCount });
85
+ }
86
+ });
87
+ });
88
+
89
+ return Object.fromEntries(allComponents);
90
+ };
91
+
92
+ function listComponentsReal() {
93
+ try {
94
+ // Obtener componentes dinámicamente
95
+ const components = getComponents();
96
+
97
+ if (Object.keys(components).length === 0) {
98
+ Print.warning('No components found in your project');
99
+ Print.info('Create your first component with "slice component create"');
100
+ return;
101
+ }
102
+
103
+ // Crear tabla con cli-table3
104
+ const table = new Table({
105
+ head: [
106
+ chalk.cyan.bold('Component'),
107
+ chalk.cyan.bold('Category'),
108
+ chalk.cyan.bold('Files')
109
+ ],
110
+ colWidths: [30, 20, 10],
111
+ style: {
112
+ head: [],
113
+ border: ['gray']
114
+ }
115
+ });
116
+
117
+ // Agrupar por categoría para mejor visualización
118
+ const byCategory = {};
119
+ Object.entries(components).forEach(([name, data]) => {
120
+ if (!byCategory[data.category]) {
121
+ byCategory[data.category] = [];
122
+ }
123
+ byCategory[data.category].push({ name, files: data.files });
124
+ });
125
+
126
+ // Agregar filas a la tabla
127
+ Object.entries(byCategory).forEach(([category, comps]) => {
128
+ comps.forEach((comp, index) => {
129
+ if (index === 0) {
130
+ // Primera fila de la categoría
131
+ table.push([
132
+ chalk.bold(comp.name),
133
+ chalk.yellow(category),
134
+ comp.files.toString()
135
+ ]);
136
+ } else {
137
+ // Resto de componentes en la categoría
138
+ table.push([
139
+ chalk.bold(comp.name),
140
+ chalk.gray('″'), // Ditto mark
141
+ comp.files.toString()
142
+ ]);
143
+ }
144
+ });
145
+ });
146
+
147
+ Print.newLine();
148
+ Print.title('📦 Local Components');
149
+ Print.newLine();
150
+ console.log(table.toString());
151
+ Print.newLine();
152
+ Print.info(`Total: ${Object.keys(components).length} component${Object.keys(components).length !== 1 ? 's' : ''} found`);
153
+
154
+ // Ruta donde se generará components.js
155
+ const outputPath = getComponentsJsPath(import.meta.url);
156
+
157
+ // Asegurar que el directorio existe
158
+ const outputDir = path.dirname(outputPath);
159
+ if (!fs.existsSync(outputDir)) {
160
+ fs.mkdirSync(outputDir, { recursive: true });
161
+ }
162
+
163
+ // Generar archivo components.js con los componentes detectados
164
+ const componentsForExport = Object.fromEntries(
165
+ Object.entries(components).map(([name, data]) => [name, data.category])
166
+ );
167
+ fs.writeFileSync(outputPath, `const components = ${JSON.stringify(componentsForExport, null, 2)};\n\nexport default components;\n`);
168
+
169
+ } catch (error) {
170
+ Print.error(`Failed to list components: ${error.message}`);
171
+ Print.info('Make sure your project structure is correct');
172
+ }
173
+ }
174
+
175
+ export default listComponentsReal;