@fecommunity/reactpress-server 1.0.0-beta.13 → 1.0.0-beta.14

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,626 +1,203 @@
1
1
  #!/usr/bin/env node
2
2
 
3
- const express = require('express');
4
- const mysql = require('mysql2/promise');
5
- const chalk = require('chalk');
6
- const open = require('open');
7
- const fs = require('fs');
3
+ /**
4
+ * ReactPress Server CLI Entry Point
5
+ * This script allows starting the ReactPress server via npx
6
+ * Supports both regular and PM2 startup modes
7
+ */
8
+
8
9
  const path = require('path');
9
- const { spawn } = require('child_process');
10
+ const fs = require('fs');
11
+ const { spawn, spawnSync } = require('child_process');
10
12
 
11
- const PORT = 3003;
12
- const SERVER_PORT = 3002;
13
+ // Capture the original working directory where npx was executed
14
+ // BUT prioritize the REACTPRESS_ORIGINAL_CWD environment variable if it exists
15
+ // This ensures consistency when running via pnpm dev from root directory
16
+ const originalCwd = process.env.REACTPRESS_ORIGINAL_CWD || process.cwd();
13
17
 
14
- // Main entry point with auto-detection
15
- async function main() {
16
- const args = process.argv.slice(2);
17
-
18
- // Check if .env exists in current directory
19
- const envPath = path.join(process.cwd(), '.env');
20
- const hasEnv = fs.existsSync(envPath);
21
-
22
- console.log(chalk.blue('🚀 ReactPress Server'));
23
-
24
- if (!hasEnv) {
25
- console.log(chalk.yellow('⚠️ No configuration found. Starting installation wizard...'));
26
- await runInstallationWizard();
27
- } else {
28
- console.log(chalk.green('✅ Configuration found. Starting server...'));
29
- startServer();
18
+ // Get command line arguments
19
+ const args = process.argv.slice(2);
20
+ const usePM2 = args.includes('--pm2');
21
+ const showHelp = args.includes('--help') || args.includes('-h');
22
+
23
+ // Show help if requested
24
+ if (showHelp) {
25
+ console.log(`
26
+ ReactPress Server - NestJS-based backend API for ReactPress CMS
27
+
28
+ Usage:
29
+ npx @fecommunity/reactpress-server [options]
30
+
31
+ Options:
32
+ --pm2 Start server with PM2 process manager
33
+ --help, -h Show this help message
34
+
35
+ Examples:
36
+ npx @fecommunity/reactpress-server # Start server normally
37
+ npx @fecommunity/reactpress-server --pm2 # Start server with PM2
38
+ npx @fecommunity/reactpress-server --help # Show this help message
39
+ `);
40
+ process.exit(0);
41
+ }
42
+
43
+ // Get the directory where this script is located
44
+ const binDir = __dirname;
45
+ const serverDir = path.join(binDir, '..');
46
+ const distPath = path.join(serverDir, 'dist', 'main.js');
47
+ const ecosystemPath = path.join(serverDir, 'ecosystem.config.js');
48
+
49
+ // Function to check if PM2 is installed
50
+ function isPM2Installed() {
51
+ try {
52
+ require.resolve('pm2');
53
+ return true;
54
+ } catch (e) {
55
+ // Check if PM2 is installed globally
56
+ try {
57
+ spawnSync('pm2', ['--version'], { stdio: 'ignore' });
58
+ return true;
59
+ } catch (e) {
60
+ return false;
61
+ }
30
62
  }
31
63
  }
32
64
 
33
- // Installation wizard
34
- async function runInstallationWizard() {
35
- console.log(chalk.cyan('🌍 Starting installation wizard...'));
65
+ // Function to install PM2
66
+ function installPM2() {
67
+ console.log('[ReactPress Server] Installing PM2...');
68
+ const installResult = spawnSync('npm', ['install', 'pm2', '--no-save'], {
69
+ stdio: 'inherit',
70
+ cwd: serverDir
71
+ });
36
72
 
37
- const app = express();
38
- app.use(express.json());
39
- app.use(express.urlencoded({ extended: true }));
40
- app.get('/', (req, res) => res.send(getWordPressHTML()));
73
+ if (installResult.status !== 0) {
74
+ console.error('[ReactPress Server] Failed to install PM2');
75
+ return false;
76
+ }
41
77
 
42
- // Test database connection
43
- app.post('/test-db', async (req, res) => {
44
- const { host, port, user, password, database } = req.body;
45
-
46
- if (!host || !port || !user || !database) {
47
- return res.json({
48
- success: false,
49
- message: 'All database fields are required.'
50
- });
78
+ return true;
79
+ }
80
+
81
+ // Function to start with PM2
82
+ function startWithPM2() {
83
+ // Check if PM2 is installed
84
+ if (!isPM2Installed()) {
85
+ // Try to install PM2
86
+ if (!installPM2()) {
87
+ console.error('[ReactPress Server] Cannot start with PM2');
88
+ process.exit(1);
51
89
  }
90
+ }
91
+
92
+ // Check if the server is built
93
+ if (!fs.existsSync(distPath)) {
94
+ console.log('[ReactPress Server] Server not built yet. Building...');
52
95
 
53
- try {
54
- console.log(chalk.cyan(`Testing connection to ${user}@${host}:${port}/${database}...`));
55
-
56
- const conn = await mysql.createConnection({
57
- host: host.trim(),
58
- port: parseInt(port),
59
- user: user.trim(),
60
- password: password,
61
- connectTimeout: 5000,
62
- acquireTimeout: 5000,
63
- timeout: 5000
64
- });
65
-
66
- try {
67
- await conn.query(`USE \`${database.trim()}\``);
68
- console.log(chalk.green(`Database '${database}' exists and accessible`));
69
- } catch (dbError) {
70
- if (dbError.code === 'ER_BAD_DB_ERROR') {
71
- await conn.query(`CREATE DATABASE \`${database.trim()}\` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci`);
72
- console.log(chalk.green(`Database '${database}' created successfully`));
73
- } else {
74
- throw dbError;
75
- }
76
- }
77
-
78
- await conn.end();
79
- console.log(chalk.green('✅ Database connection test passed'));
80
-
81
- res.json({
82
- success: true,
83
- message: `Successfully connected to database '${database}' on ${host}:${port}`
84
- });
85
-
86
- } catch (error) {
87
- console.log(chalk.red('❌ Database connection failed:'), error.message);
88
-
89
- let errorMessage = 'Database connection failed: ';
90
-
91
- switch (error.code) {
92
- case 'ECONNREFUSED':
93
- errorMessage += `Cannot connect to MySQL server at ${host}:${port}. Please ensure MySQL is running.`;
94
- break;
95
- case 'ER_ACCESS_DENIED_ERROR':
96
- errorMessage += `Access denied for user '${user}'. Please check your username and password.`;
97
- break;
98
- case 'ENOTFOUND':
99
- errorMessage += `Host '${host}' not found. Please check the hostname.`;
100
- break;
101
- case 'ETIMEDOUT':
102
- errorMessage += `Connection timeout to ${host}:${port}. Please check your network and firewall settings.`;
103
- break;
104
- case 'ER_BAD_DB_ERROR':
105
- errorMessage += `Database '${database}' does not exist and cannot be created. Please check your permissions.`;
106
- break;
107
- default:
108
- errorMessage += error.message;
109
- }
110
-
111
- res.json({ success: false, message: errorMessage });
96
+ // Try to build the server
97
+ const buildResult = spawnSync('npm', ['run', 'build'], {
98
+ stdio: 'inherit',
99
+ cwd: serverDir
100
+ });
101
+
102
+ if (buildResult.status !== 0) {
103
+ console.error('[ReactPress Server] Failed to build server');
104
+ process.exit(1);
112
105
  }
113
- });
106
+ }
114
107
 
115
- // Install and start server
116
- app.post('/install', async (req, res) => {
117
- const { db, site } = req.body;
118
-
119
- // Final validation
120
- try {
121
- const testConn = await mysql.createConnection({
122
- host: db.host.trim(),
123
- port: parseInt(db.port),
124
- user: db.user.trim(),
125
- password: db.password,
126
- database: db.database.trim()
127
- });
128
- await testConn.end();
129
- } catch (error) {
130
- return res.json({
131
- success: false,
132
- message: 'Final database validation failed. Please test your connection again.'
133
- });
108
+ console.log('[ReactPress Server] Starting with PM2...');
109
+
110
+ // Use ecosystem.config.js if it exists, otherwise use direct command
111
+ let pm2Command = 'pm2';
112
+ try {
113
+ // Try to resolve PM2 path
114
+ pm2Command = path.join(serverDir, 'node_modules', '.bin', 'pm2');
115
+ if (!fs.existsSync(pm2Command)) {
116
+ pm2Command = 'pm2';
134
117
  }
118
+ } catch (e) {
119
+ pm2Command = 'pm2';
120
+ }
121
+
122
+ // Check if ecosystem.config.js exists
123
+ if (fs.existsSync(ecosystemPath)) {
124
+ const pm2 = spawn(pm2Command, ['start', ecosystemPath], {
125
+ stdio: 'inherit',
126
+ cwd: serverDir
127
+ });
135
128
 
136
- const env = `# ReactPress Configuration
137
- # Generated on ${new Date().toISOString()}
138
-
139
- DB_HOST=${db.host}
140
- DB_PORT=${db.port}
141
- DB_USER=${db.user}
142
- DB_PASSWD=${db.password}
143
- DB_DATABASE=${db.database}
144
- CLIENT_SITE_URL=${site.clientUrl}
145
- SERVER_SITE_URL=${site.serverUrl}
146
- `;
129
+ pm2.on('close', (code) => {
130
+ console.log(`[ReactPress Server] PM2 process exited with code ${code}`);
131
+ process.exit(code);
132
+ });
147
133
 
148
- const envPath = path.join(process.cwd(), '.env');
149
- fs.writeFileSync(envPath, env);
150
- console.log(chalk.green('✅ Configuration saved to .env file'));
134
+ pm2.on('error', (error) => {
135
+ console.error('[ReactPress Server] Failed to start with PM2:', error);
136
+ process.exit(1);
137
+ });
138
+ } else {
139
+ // Fallback to direct start
140
+ const pm2 = spawn(pm2Command, ['start', distPath, '--name', 'reactpress-server'], {
141
+ stdio: 'inherit',
142
+ cwd: serverDir
143
+ });
151
144
 
152
- res.json({
153
- success: true,
154
- message: 'ReactPress installed successfully! Starting server...',
155
- serverUrl: site.serverUrl
145
+ pm2.on('close', (code) => {
146
+ console.log(`[ReactPress Server] PM2 process exited with code ${code}`);
147
+ process.exit(code);
156
148
  });
157
149
 
158
- // Close installation server and start ReactPress server
159
- setTimeout(() => {
160
- console.log(chalk.green('\n🎉 Installation completed!'));
161
- console.log(chalk.cyan('🚀 Starting ReactPress Server...'));
162
- server.close();
163
- startServer();
164
- }, 2000);
165
- });
166
-
167
- const server = app.listen(PORT, () => {
168
- const url = `http://localhost:${PORT}`;
169
- console.log(chalk.green(`✅ Installation wizard: ${url}`));
170
- open(url);
171
- console.log(chalk.gray('Press Ctrl+C to cancel\n'));
172
- });
173
-
174
- process.on('SIGINT', () => {
175
- console.log(chalk.yellow('\n⚠️ Installation cancelled'));
176
- server.close();
177
- process.exit(0);
178
- });
179
- }
180
-
181
- // Start ReactPress server
182
- function startServer() {
183
- const envPath = path.join(process.cwd(), '.env');
184
-
185
- if (!fs.existsSync(envPath)) {
186
- console.log(chalk.red('❌ No configuration found!'));
187
- console.log(chalk.yellow('Please run the installation first.'));
188
- return;
150
+ pm2.on('error', (error) => {
151
+ console.error('[ReactPress Server] Failed to start with PM2:', error);
152
+ process.exit(1);
153
+ });
189
154
  }
190
-
191
- console.log(chalk.blue('🚀 Starting ReactPress Server...'));
192
- console.log(chalk.cyan(`🌍 Server will be available at: http://localhost:${SERVER_PORT}/api`));
193
-
194
- // Start the NestJS server
195
- const serverDir = path.dirname(__dirname); // server directory
196
- const server = spawn('npm', ['run', 'dev'], {
197
- cwd: serverDir,
198
- stdio: 'inherit',
199
- env: { ...process.env, NODE_ENV: 'development' }
200
- });
201
-
202
- server.on('error', (error) => {
203
- console.log(chalk.red('❌ Failed to start server:'), error.message);
204
- });
205
-
206
- // Open browser after server starts
207
- setTimeout(() => {
208
- open(`http://localhost:${SERVER_PORT}/api`);
209
- }, 5000);
210
155
  }
211
156
 
212
- // WordPress-style HTML
213
- function getWordPressHTML() {
214
- return `<!DOCTYPE html>
215
- <html lang="en">
216
- <head>
217
- <meta charset="UTF-8">
218
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
219
- <title>ReactPress › Installation</title>
220
- <style>
221
- * { margin: 0; padding: 0; box-sizing: border-box; }
222
- body {
223
- font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
224
- background: #f1f1f1;
225
- color: #444;
226
- line-height: 1.4;
227
- }
228
- .wp-container {
229
- max-width: 600px;
230
- margin: 40px auto;
231
- background: #fff;
232
- border: 1px solid #ccd0d4;
233
- box-shadow: 0 1px 3px rgba(0,0,0,0.04);
234
- }
235
- .wp-header {
236
- background: #0073aa;
237
- color: #fff;
238
- padding: 24px;
239
- text-align: center;
240
- border-bottom: 1px solid #005a87;
241
- }
242
- .wp-header h1 { font-size: 24px; font-weight: 400; margin-bottom: 8px; }
243
- .wp-header p { font-size: 16px; opacity: 0.9; }
244
- .wp-content { padding: 24px; }
245
- .wp-step { display: none; }
246
- .wp-step.active { display: block; }
247
- .wp-step h2 { font-size: 22px; font-weight: 600; margin-bottom: 20px; color: #1d2327; }
248
- .wp-description {
249
- background: #f0f6fc;
250
- border: 1px solid #c3e4f0;
251
- border-left: 4px solid #0073aa;
252
- padding: 12px 16px;
253
- margin-bottom: 20px;
254
- font-size: 14px;
255
- color: #0c4a6e;
256
- }
257
- .wp-form-table { width: 100%; margin-bottom: 20px; }
258
- .wp-form-table th {
259
- text-align: left;
260
- padding: 10px 0;
261
- width: 140px;
262
- vertical-align: top;
263
- font-weight: 600;
264
- color: #1d2327;
265
- }
266
- .wp-form-table td { padding: 10px 0; }
267
- .wp-form-table input[type="text"],
268
- .wp-form-table input[type="password"],
269
- .wp-form-table input[type="number"],
270
- .wp-form-table input[type="url"] {
271
- width: 100%;
272
- max-width: 320px;
273
- padding: 8px 12px;
274
- border: 1px solid #8c8f94;
275
- border-radius: 4px;
276
- font-size: 14px;
277
- line-height: 1.4;
278
- transition: border-color 0.15s ease-in-out;
279
- }
280
- .wp-form-table input:focus {
281
- border-color: #0073aa;
282
- outline: 0;
283
- box-shadow: 0 0 0 1px #0073aa;
284
- }
285
- .wp-form-table .description {
286
- font-size: 13px;
287
- color: #646970;
288
- margin-top: 4px;
289
- }
290
- .wp-button {
291
- background: #0073aa;
292
- color: #fff;
293
- border: 1px solid #0073aa;
294
- padding: 8px 16px;
295
- font-size: 14px;
296
- font-weight: 600;
297
- border-radius: 3px;
298
- cursor: pointer;
299
- transition: all 0.15s ease-in-out;
300
- text-decoration: none;
301
- display: inline-block;
302
- }
303
- .wp-button:hover { background: #005a87; border-color: #005a87; }
304
- .wp-button:disabled {
305
- background: #f0f0f1;
306
- border-color: #dcdcde;
307
- color: #a7aaad;
308
- cursor: not-allowed;
309
- }
310
- .wp-button.button-large { padding: 12px 24px; font-size: 16px; }
311
- .wp-notice {
312
- border: 1px solid #c3c4c7;
313
- border-left-width: 4px;
314
- padding: 12px;
315
- margin: 16px 0;
316
- background: #fff;
317
- }
318
- .wp-notice.notice-success { border-left-color: #00a32a; background: #f7fcf7; }
319
- .wp-notice.notice-error { border-left-color: #d63638; background: #fcf2f2; }
320
- .wp-notice p { margin: 0; font-size: 14px; }
321
- .wp-progress { background: #f0f0f1; height: 4px; margin-bottom: 20px; }
322
- .wp-progress-bar { background: #0073aa; height: 100%; transition: width 0.3s ease; }
323
- .wp-loader {
324
- display: inline-block;
325
- width: 16px;
326
- height: 16px;
327
- border: 2px solid #f3f3f3;
328
- border-top: 2px solid #0073aa;
329
- border-radius: 50%;
330
- animation: wp-spin 1s linear infinite;
331
- margin-right: 8px;
332
- }
333
- @keyframes wp-spin {
334
- 0% { transform: rotate(0deg); }
335
- 100% { transform: rotate(360deg); }
336
- }
337
- .wp-footer {
338
- background: #f6f7f7;
339
- border-top: 1px solid #c3c4c7;
340
- padding: 16px 24px;
341
- text-align: center;
342
- font-size: 13px;
343
- color: #646970;
344
- }
345
- .text-center { text-align: center; }
346
- </style>
347
- </head>
348
- <body>
349
- <div class="wp-container">
350
- <div class="wp-header">
351
- <h1>ReactPress</h1>
352
- <p>5-Minute Installation</p>
353
- </div>
354
-
355
- <div class="wp-progress">
356
- <div class="wp-progress-bar" id="progressBar" style="width: 33%;"></div>
357
- </div>
358
-
359
- <div class="wp-content">
360
- <!-- Step 1: Database Configuration -->
361
- <div class="wp-step active" id="step1">
362
- <h2>Database Connection Information</h2>
363
-
364
- <div class="wp-description">
365
- You should have this information available from your web hosting provider. If you don't have it, contact them before continuing.
366
- </div>
367
-
368
- <table class="wp-form-table">
369
- <tr>
370
- <th><label for="dbHost">Database Host</label></th>
371
- <td>
372
- <input type="text" id="dbHost" value="127.0.0.1" />
373
- <p class="description">Usually "localhost" or "127.0.0.1"</p>
374
- </td>
375
- </tr>
376
- <tr>
377
- <th><label for="dbPort">Database Port</label></th>
378
- <td>
379
- <input type="number" id="dbPort" value="3306" />
380
- <p class="description">Default MySQL port is 3306</p>
381
- </td>
382
- </tr>
383
- <tr>
384
- <th><label for="dbUser">Username</label></th>
385
- <td>
386
- <input type="text" id="dbUser" value="" placeholder="Database username" />
387
- <p class="description">Your MySQL username</p>
388
- </td>
389
- </tr>
390
- <tr>
391
- <th><label for="dbPassword">Password</label></th>
392
- <td>
393
- <input type="password" id="dbPassword" value="" placeholder="Database password" />
394
- <p class="description">Your MySQL password</p>
395
- </td>
396
- </tr>
397
- <tr>
398
- <th><label for="dbName">Database Name</label></th>
399
- <td>
400
- <input type="text" id="dbName" value="reactpress" />
401
- <p class="description">The name of the database you want to use with ReactPress</p>
402
- </td>
403
- </tr>
404
- </table>
405
-
406
- <div id="dbResult"></div>
407
-
408
- <p class="text-center">
409
- <button class="wp-button button-large" onclick="testDatabase()" id="testBtn">
410
- Test Database Connection
411
- </button>
412
- </p>
413
- </div>
414
-
415
- <!-- Step 2: Site Configuration -->
416
- <div class="wp-step" id="step2">
417
- <h2>Site Information</h2>
418
-
419
- <div class="wp-description">
420
- Please provide the following information. Don't worry, you can always change these settings later.
421
- </div>
422
-
423
- <table class="wp-form-table">
424
- <tr>
425
- <th><label for="clientUrl">Client Site URL</label></th>
426
- <td>
427
- <input type="url" id="clientUrl" value="http://localhost:3001" />
428
- <p class="description">The URL where your ReactPress frontend will be accessible</p>
429
- </td>
430
- </tr>
431
- <tr>
432
- <th><label for="serverUrl">API Server URL</label></th>
433
- <td>
434
- <input type="url" id="serverUrl" value="http://localhost:3002" />
435
- <p class="description">The URL where your ReactPress API server will run</p>
436
- </td>
437
- </tr>
438
- </table>
439
-
440
- <div id="installResult"></div>
441
-
442
- <p class="text-center">
443
- <button class="wp-button button-large" onclick="installReactPress()" id="installBtn">
444
- Install & Start ReactPress
445
- </button>
446
- </p>
447
- </div>
448
-
449
- <!-- Step 3: Success -->
450
- <div class="wp-step" id="step3">
451
- <h2>🎉 Installation Complete!</h2>
452
-
453
- <div class="wp-notice notice-success">
454
- <p><strong>ReactPress has been installed and is starting...</strong></p>
455
- </div>
456
-
457
- <p>Your ReactPress server is now starting up. You can:</p>
458
-
459
- <ul style="margin: 16px 0 16px 20px;">
460
- <li>Close this browser window</li>
461
- <li>The server API will open automatically at <strong>http://localhost:3002/api</strong></li>
462
- <li>Access your admin panel at <strong>http://localhost:3001/admin</strong> (when client is running)</li>
463
- </ul>
464
-
465
- <div class="wp-description">
466
- <strong>Note:</strong> To restart the server in the future, simply run <code>npx @fecommunity/reactpress-server</code> again.
467
- </div>
468
- </div>
469
- </div>
470
-
471
- <div class="wp-footer">
472
- <p>Need help? <a href="https://github.com/fecommunity/reactpress/issues" target="_blank">ReactPress Documentation</a></p>
473
- </div>
474
- </div>
157
+ // Function to start with regular Node.js
158
+ function startWithNode() {
159
+ // Check if the server is built
160
+ if (!fs.existsSync(distPath)) {
161
+ console.log('[ReactPress Server] Server not built yet. Building...');
475
162
 
476
- <script>
477
- let currentStep = 1;
478
- const totalSteps = 3;
479
- let isTestingConnection = false;
480
-
481
- function updateProgress() {
482
- const progress = (currentStep / totalSteps) * 100;
483
- document.getElementById('progressBar').style.width = progress + '%';
484
- }
485
-
486
- function showStep(step) {
487
- document.querySelectorAll('.wp-step').forEach(s => s.classList.remove('active'));
488
- document.getElementById('step' + step).classList.add('active');
489
- currentStep = step;
490
- updateProgress();
491
- }
492
-
493
- function showNotice(message, type = 'error', containerId = 'dbResult') {
494
- const container = document.getElementById(containerId);
495
- container.innerHTML = \`
496
- <div class="wp-notice notice-\${type}">
497
- <p>\${message}</p>
498
- </div>
499
- \`;
500
- }
501
-
502
- function validateDatabaseInputs() {
503
- const host = document.getElementById('dbHost').value.trim();
504
- const port = document.getElementById('dbPort').value.trim();
505
- const user = document.getElementById('dbUser').value.trim();
506
- const password = document.getElementById('dbPassword').value;
507
- const database = document.getElementById('dbName').value.trim();
508
-
509
- if (!host || !port || !user || !database) {
510
- showNotice('Please fill in all required fields.', 'error');
511
- return false;
512
- }
513
-
514
- if (isNaN(port) || port < 1 || port > 65535) {
515
- showNotice('Please enter a valid port number (1-65535).', 'error');
516
- return false;
517
- }
518
-
519
- return { host, port, user, password, database };
520
- }
521
-
522
- async function testDatabase() {
523
- if (isTestingConnection) return;
524
-
525
- const dbData = validateDatabaseInputs();
526
- if (!dbData) return;
527
-
528
- isTestingConnection = true;
529
- const testBtn = document.getElementById('testBtn');
530
- const originalText = testBtn.innerHTML;
531
-
532
- testBtn.disabled = true;
533
- testBtn.innerHTML = '<span class="wp-loader"></span>Testing connection...';
534
-
535
- try {
536
- const response = await fetch('/test-db', {
537
- method: 'POST',
538
- headers: { 'Content-Type': 'application/json' },
539
- body: JSON.stringify(dbData)
540
- });
541
-
542
- const result = await response.json();
543
-
544
- if (result.success) {
545
- showNotice(result.message, 'success');
546
- setTimeout(() => {
547
- showStep(2);
548
- }, 1500);
549
- } else {
550
- showNotice(result.message, 'error');
551
- }
552
- } catch (error) {
553
- showNotice('Failed to connect to server. Please try again.', 'error');
554
- } finally {
555
- isTestingConnection = false;
556
- testBtn.disabled = false;
557
- testBtn.innerHTML = originalText;
558
- }
559
- }
560
-
561
- async function installReactPress() {
562
- const dbData = validateDatabaseInputs();
563
- if (!dbData) {
564
- showStep(1);
565
- return;
566
- }
567
-
568
- const clientUrl = document.getElementById('clientUrl').value.trim();
569
- const serverUrl = document.getElementById('serverUrl').value.trim();
570
-
571
- if (!clientUrl || !serverUrl) {
572
- showNotice('Please fill in all site URLs.', 'error', 'installResult');
573
- return;
574
- }
575
-
576
- const installBtn = document.getElementById('installBtn');
577
- const originalText = installBtn.innerHTML;
578
-
579
- installBtn.disabled = true;
580
- installBtn.innerHTML = '<span class="wp-loader"></span>Installing & Starting...';
581
-
582
- try {
583
- const response = await fetch('/install', {
584
- method: 'POST',
585
- headers: { 'Content-Type': 'application/json' },
586
- body: JSON.stringify({
587
- db: dbData,
588
- site: { clientUrl, serverUrl }
589
- })
590
- });
591
-
592
- const result = await response.json();
593
-
594
- if (result.success) {
595
- showStep(3);
596
- // Auto-close and redirect to server after a delay
597
- setTimeout(() => {
598
- if (result.serverUrl) {
599
- window.open(result.serverUrl + '/api', '_blank');
600
- }
601
- }, 3000);
602
- } else {
603
- showNotice(result.message, 'error', 'installResult');
604
- }
605
- } catch (error) {
606
- showNotice('Installation failed. Please try again.', 'error', 'installResult');
607
- } finally {
608
- installBtn.disabled = false;
609
- installBtn.innerHTML = originalText;
610
- }
611
- }
612
-
613
- // Initialize
614
- updateProgress();
615
- document.getElementById('dbHost').focus();
616
- </script>
617
- </body>
618
- </html>`;
619
- }
163
+ // Try to build the server
164
+ const buildResult = spawnSync('npm', ['run', 'build'], {
165
+ stdio: 'inherit',
166
+ cwd: serverDir
167
+ });
168
+
169
+ if (buildResult.status !== 0) {
170
+ console.error('[ReactPress Server] Failed to build server');
171
+ process.exit(1);
172
+ }
173
+ }
174
+
175
+ // ONLY set the environment variable if it's not already set
176
+ // This preserves the value set by set-env.js when running pnpm dev from root
177
+ if (!process.env.REACTPRESS_ORIGINAL_CWD) {
178
+ process.env.REACTPRESS_ORIGINAL_CWD = originalCwd;
179
+ } else {
180
+ console.log(`[ReactPress Server] Using existing REACTPRESS_ORIGINAL_CWD: ${process.env.REACTPRESS_ORIGINAL_CWD}`);
181
+ }
620
182
 
621
- // Run the main function
622
- if (require.main === module) {
623
- main().catch(console.error);
183
+ // Change to the server directory
184
+ process.chdir(serverDir);
185
+
186
+ // Set environment variables
187
+ process.env.NODE_ENV = process.env.NODE_ENV || 'production';
188
+
189
+ // Import and run the server
190
+ try {
191
+ require(distPath);
192
+ } catch (error) {
193
+ console.error('[ReactPress Server] Failed to start server:', error);
194
+ process.exit(1);
195
+ }
624
196
  }
625
197
 
626
- module.exports = { main, startServer };
198
+ // Main execution
199
+ if (usePM2) {
200
+ startWithPM2();
201
+ } else {
202
+ startWithNode();
203
+ }