create-fleetbo-project 1.0.27 → 1.0.29

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.
@@ -4,13 +4,14 @@ const { execSync } = require('child_process');
4
4
  const fs = require('fs');
5
5
  const path = require('path');
6
6
  const https = require('https');
7
+ const unzipper = require('unzipper');
7
8
 
8
9
  // --- Configuration ---
9
- const repoOwner = 'FleetFleetbo'; // Assurez-vous que c'est le bon nom d'utilisateur GitHub
10
- const repoName = 'dev.fleetbo.io'; // Assurez-vous que c'est le bon nom de dépôt
11
- const branchName = 'master'; // Le nom de la branche est maintenant configurable
10
+ const repoOwner = 'FleetFleetbo';
11
+ const repoName = 'dev.fleetbo.io';
12
+ const branchName = 'master';
12
13
 
13
- // URL de votre Cloud Function.
14
+ const repoUrl = `https://github.com/${repoOwner}/${repoName}/archive/refs/heads/${branchName}.zip`;
14
15
  const bootstrapUrl = 'https://us-central1-myapp-259bf.cloudfunctions.net/bootstrapProject';
15
16
 
16
17
  // --- Analyse des Arguments ---
@@ -34,13 +35,42 @@ if (!bootstrapToken) {
34
35
 
35
36
  const projectName = projectNameArg;
36
37
 
38
+ /**
39
+ * Fonction pour copier récursivement un dossier
40
+ */
41
+ function copyRecursiveSync(src, dest) {
42
+ const exists = fs.existsSync(src);
43
+ const stats = exists && fs.statSync(src);
44
+ const isDirectory = exists && stats.isDirectory();
45
+
46
+ if (isDirectory) {
47
+ if (!fs.existsSync(dest)) {
48
+ fs.mkdirSync(dest, { recursive: true });
49
+ }
50
+ fs.readdirSync(src).forEach(childItemName => {
51
+ copyRecursiveSync(
52
+ path.join(src, childItemName),
53
+ path.join(dest, childItemName)
54
+ );
55
+ });
56
+ } else {
57
+ fs.copyFileSync(src, dest);
58
+ }
59
+ }
60
+
37
61
  /**
38
62
  * Fonction pour appeler la Cloud Function et récupérer les clés.
39
63
  */
40
64
  function fetchProjectKeys(token) {
41
65
  return new Promise((resolve, reject) => {
42
66
  const postData = JSON.stringify({ token });
43
- const options = { method: 'POST', headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(postData) } };
67
+ const options = {
68
+ method: 'POST',
69
+ headers: {
70
+ 'Content-Type': 'application/json',
71
+ 'Content-Length': Buffer.byteLength(postData)
72
+ }
73
+ };
44
74
  const req = https.request(bootstrapUrl, options, (res) => {
45
75
  let data = '';
46
76
  res.on('data', (chunk) => { data += chunk; });
@@ -60,40 +90,92 @@ function fetchProjectKeys(token) {
60
90
  }
61
91
 
62
92
  /**
63
- * Fonction Principale Asynchrone (Version utilisant degit pour un clonage fiable)
93
+ * Fonction Principale Asynchrone
64
94
  */
65
95
  async function setupProject() {
66
96
  console.log(`\nCréation de votre projet Fleetbo "${projectName}"...`);
67
97
  const projectDir = path.join(process.cwd(), projectName);
98
+ const tempDir = path.join(process.cwd(), `fleetbo-temp-${Date.now()}`);
68
99
 
69
100
  try {
70
- // *** DÉBUT DE LA NOUVELLE LOGIQUE DE CLONAGE AVEC DEGIT ***
71
- console.log(` [1/5] 📥 Clonage du template via degit (cela peut prendre un moment)...`);
72
- const degitRepo = `${repoOwner}/${repoName}#${branchName}`;
73
- // Utilise npx pour s'assurer que degit est disponible sans installation globale
74
- execSync(`npx degit ${degitRepo} ${projectName}`, { stdio: 'inherit' });
75
- console.log(' [2/5] Template cloné avec succès.');
76
- // *** FIN DE LA NOUVELLE LOGIQUE ***
77
-
78
- process.chdir(projectDir);
79
- console.log(' [3/5] 🔑 Récupération des clés de projet...');
101
+ // Étape 1 : Téléchargement et décompression
102
+ console.log(` [1/5] 📥 Téléchargement du template...`);
103
+ await new Promise((resolve, reject) => {
104
+ https.get(repoUrl, (response) => {
105
+ if (response.statusCode === 301 || response.statusCode === 302) {
106
+ return https.get(response.headers.location, (redirectResponse) => {
107
+ redirectResponse.pipe(unzipper.Extract({ path: tempDir }))
108
+ .on('finish', resolve)
109
+ .on('error', (err) => reject(new Error(`Erreur de décompression: ${err.message}`)));
110
+ }).on('error', (err) => reject(new Error(`Erreur réseau après redirection: ${err.message}`)));
111
+ }
112
+ response.pipe(unzipper.Extract({ path: tempDir }))
113
+ .on('finish', resolve)
114
+ .on('error', (err) => reject(new Error(`Erreur de décompression: ${err.message}`)));
115
+ }).on('error', (err) => reject(new Error(`Erreur réseau: ${err.message}`)));
116
+ });
117
+
118
+ console.log(' [2/5] ✅ Template téléchargé. Organisation des fichiers...');
119
+
120
+ // Étape 2 : Localiser intelligemment la racine du projet
121
+ const unzippedBaseFolder = fs.readdirSync(tempDir)[0];
122
+ let sourceDir = path.join(tempDir, unzippedBaseFolder);
123
+
124
+ if (!fs.existsSync(path.join(sourceDir, 'package.json'))) {
125
+ const nestedProjectDir = fs.readdirSync(sourceDir).find(file => {
126
+ const fullPath = path.join(sourceDir, file);
127
+ return fs.statSync(fullPath).isDirectory() && fs.existsSync(path.join(fullPath, 'package.json'));
128
+ });
129
+ if (!nestedProjectDir) throw new Error('Impossible de trouver package.json dans le template.');
130
+ sourceDir = path.join(sourceDir, nestedProjectDir);
131
+ }
132
+
133
+ // Étape 3 : Copier RÉCURSIVEMENT tous les fichiers et dossiers
134
+ console.log(` [3/5] 📂 Copie de tous les fichiers du template...`);
135
+
136
+ // Vérifier que le répertoire source existe et contient des fichiers
137
+ if (!fs.existsSync(sourceDir)) {
138
+ throw new Error(`Le répertoire source n'existe pas: ${sourceDir}`);
139
+ }
140
+
141
+ const sourceFiles = fs.readdirSync(sourceDir);
142
+ console.log(` → ${sourceFiles.length} éléments détectés à la racine du template`);
143
+
144
+ // Copier récursivement tout le contenu
145
+ copyRecursiveSync(sourceDir, projectDir);
146
+
147
+ // Vérifier que la copie a réussi
148
+ const copiedFiles = fs.readdirSync(projectDir);
149
+ console.log(` → ${copiedFiles.length} éléments copiés dans le nouveau projet`);
150
+
151
+ if (!fs.existsSync(path.join(projectDir, 'package.json'))) {
152
+ throw new Error('Erreur: package.json n\'a pas été copié correctement');
153
+ }
154
+
155
+ // Étape 4 : Récupération des clés
156
+ console.log(' [4/5] 🔑 Récupération des clés de projet...');
80
157
  const keys = await fetchProjectKeys(bootstrapToken);
158
+
81
159
  if (!keys.enterpriseId || !keys.fleetboDBKey) {
82
160
  throw new Error("Les clés reçues du serveur sont invalides.");
83
161
  }
84
162
 
85
- console.log(' [4/5] Fichier .env configuré avec succès.');
163
+ // Configuration du fichier .env
86
164
  const envContent = `REACT_APP_FLEETBO_DB_KEY=${keys.fleetboDBKey}\nREACT_APP_ENTERPRISE_ID=${keys.enterpriseId}\n`;
87
165
  fs.writeFileSync(path.join(projectDir, '.env'), envContent, 'utf8');
166
+ console.log(' ✅ Fichier .env configuré avec succès.');
88
167
 
89
- console.log(' [5/5] 📦 Installation des dépendances (cela peut prendre quelques minutes)...');
90
- execSync('npm install', { stdio: 'inherit' });
91
-
168
+ // Mise à jour du package.json avec le nom du projet
92
169
  const packageJsonPath = path.join(projectDir, 'package.json');
93
170
  const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
94
171
  packageJson.name = projectName;
95
172
  fs.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2), 'utf8');
96
173
 
174
+ // Étape 5 : Installation des dépendances
175
+ console.log(' [5/5] 📦 Installation des dépendances...');
176
+ process.chdir(projectDir);
177
+ execSync('npm install', { stdio: 'inherit' });
178
+
97
179
  console.log('\n🚀 Votre projet Fleetbo est prêt !');
98
180
  console.log(`\nPour commencer, exécutez les commandes suivantes :`);
99
181
  console.log(` cd ${projectName}`);
@@ -101,13 +183,17 @@ async function setupProject() {
101
183
 
102
184
  } catch (error) {
103
185
  console.error('\n❌ Une erreur est survenue lors de la création du projet :', error.message);
186
+ console.error(' Détails:', error);
104
187
  if (fs.existsSync(projectDir)) {
105
- console.log(' Nettoyage du répertoire du projet...');
188
+ console.log(' 🧹 Nettoyage du projet incomplet...');
106
189
  fs.rmSync(projectDir, { recursive: true, force: true });
107
190
  }
108
191
  process.exit(1);
192
+ } finally {
193
+ if (fs.existsSync(tempDir)) {
194
+ fs.rmSync(tempDir, { recursive: true, force: true });
195
+ }
109
196
  }
110
197
  }
111
198
 
112
- setupProject();
113
-
199
+ setupProject();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-fleetbo-project",
3
- "version": "1.0.27",
3
+ "version": "1.0.29",
4
4
  "description": "Creates a new Fleetbo project.",
5
5
  "main": "install-react-template.js",
6
6
  "bin": {