-
-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathdev.js
More file actions
270 lines (225 loc) · 7.54 KB
/
dev.js
File metadata and controls
270 lines (225 loc) · 7.54 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
#!/usr/bin/env node
/**
* Cross-platform script to run both frontend (Vite) and backend (Wrangler) in parallel
* Works on Windows, macOS, and Linux
*/
const http = require('http');
const { spawn } = require('child_process');
const fs = require('fs');
const path = require('path');
// ANSI color codes for better terminal output
const colors = {
reset: '\x1b[0m',
bright: '\x1b[1m',
cyan: '\x1b[36m',
yellow: '\x1b[33m',
green: '\x1b[32m',
red: '\x1b[31m',
};
const log = {
info: (msg) => console.log(`${colors.cyan}[INFO]${colors.reset} ${msg}`),
success: (msg) => console.log(`${colors.green}[SUCCESS]${colors.reset} ${msg}`),
error: (msg) => console.log(`${colors.red}[ERROR]${colors.reset} ${msg}`),
frontend: (msg) => console.log(`${colors.yellow}[FE]${colors.reset} ${msg}`),
backend: (msg) => console.log(`${colors.cyan}[BE]${colors.reset} ${msg}`),
};
// Determine the current platform
const isWindows = process.platform === 'win32';
// App directory
const appDir = path.join(__dirname, 'apps/otta-web');
function ensureDistDirectory() {
const distDir = path.join(appDir, 'dist');
const indexHtmlPath = path.join(distDir, 'index.html');
try {
if (!fs.existsSync(distDir)) {
fs.mkdirSync(distDir, { recursive: true });
log.info(`Created missing dist directory: ${distDir}`);
}
if (!fs.existsSync(indexHtmlPath)) {
fs.writeFileSync(
indexHtmlPath,
'<html>created by dev.js as placeholder for wrangler in development mode</html>\n',
'utf-8',
);
log.info('Created missing dist/index.html placeholder for Wrangler');
}
} catch (error) {
log.error(`Failed to prepare dist directory: ${error.message}`);
process.exit(1);
}
}
// Default ports
const PORT_FE = process.env.PORT_FE || 3003;
const PORT_BE = process.env.PORT_BE || 3004;
// Check for --noopen flag
const noOpen = process.argv.includes('--noopen');
const FRONTEND_URL = `http://127.0.0.1:${PORT_FE}`;
const BACKEND_URL = `http://127.0.0.1:${PORT_BE}`;
const BACKEND_HEALTH_URL = `${BACKEND_URL}/api/health`;
function waitForHttpReady(url, label, { timeoutMs = 90000, intervalMs = 250, acceptStatuses = [200] } = {}) {
const startedAt = Date.now();
return new Promise((resolve, reject) => {
let settled = false;
let probeTimer = null;
const settle = (callback, value) => {
if (settled) {
return;
}
settled = true;
if (probeTimer) {
clearTimeout(probeTimer);
probeTimer = null;
}
callback(value);
};
const scheduleNextCheck = () => {
if (settled) {
return;
}
probeTimer = setTimeout(check, intervalMs);
};
const check = () => {
if (settled) {
return;
}
const request = http.get(url, (response) => {
response.resume();
if (acceptStatuses.includes(response.statusCode || 0)) {
settle(resolve);
return;
}
if (Date.now() - startedAt >= timeoutMs) {
settle(
reject,
new Error(
`${label} did not become ready within ${timeoutMs}ms (last status: ${response.statusCode})`,
),
);
return;
}
scheduleNextCheck();
});
request.on('error', () => {
if (Date.now() - startedAt >= timeoutMs) {
settle(reject, new Error(`${label} did not become ready within ${timeoutMs}ms`));
return;
}
scheduleNextCheck();
});
request.setTimeout(2000, () => {
request.destroy(new Error(`${label} probe timed out`));
});
};
check();
});
}
function openBrowser(url) {
if (noOpen) {
return;
}
if (isWindows) {
const child = spawn('cmd.exe', ['/c', 'start', '', url], {
detached: true,
stdio: 'ignore',
});
child.unref();
return;
}
const command = process.platform === 'darwin' ? 'open' : 'xdg-open';
const child = spawn(command, [url], {
detached: true,
stdio: 'ignore',
});
child.unref();
}
function spawnPnpm(args) {
if (isWindows) {
return spawn('cmd.exe', ['/d', '/s', '/c', `pnpm ${args.join(' ')}`], {
cwd: appDir,
stdio: 'pipe',
env: { ...process.env, PORT_FE, PORT_BE },
});
}
return spawn('pnpm', args, {
cwd: appDir,
stdio: 'pipe',
env: { ...process.env, PORT_FE, PORT_BE },
});
}
ensureDistDirectory();
log.info('Starting Vite app in development mode...');
log.info(`Platform: ${process.platform}`);
log.info(`App directory: ${appDir}`);
log.info(`Frontend Port: ${PORT_FE}`);
log.info(`Backend Port: ${PORT_BE}`);
if (noOpen) {
log.info('Browser auto-open disabled (--noopen flag)');
}
// Start frontend (Vite)
log.info('Starting frontend (Vite)...');
const frontendArgs = ['exec', 'vite'];
const frontend = spawnPnpm(frontendArgs);
// Start backend (Wrangler)
log.info('Starting backend (Wrangler)...');
const backend = spawnPnpm(['dev:worker', '--', '--port', PORT_BE]);
// Handle frontend output
frontend.stdout.on('data', (data) => {
const lines = data.toString().trim().split('\n');
lines.forEach((line) => log.frontend(line));
});
frontend.stderr.on('data', (data) => {
const lines = data.toString().trim().split('\n');
lines.forEach((line) => log.frontend(line));
});
// Handle backend output
backend.stdout.on('data', (data) => {
const lines = data.toString().trim().split('\n');
lines.forEach((line) => log.backend(line));
});
backend.stderr.on('data', (data) => {
const lines = data.toString().trim().split('\n');
lines.forEach((line) => log.backend(line));
});
// Handle process exits
frontend.on('close', (code) => {
if (code !== 0 && code !== null) {
log.error(`Frontend exited with code ${code}`);
}
process.exit(code || 0);
});
backend.on('close', (code) => {
if (code !== 0 && code !== null) {
log.error(`Backend exited with code ${code}`);
}
process.exit(code || 0);
});
// Handle Ctrl+C gracefully
process.on('SIGINT', () => {
log.info('Shutting down...');
frontend.kill('SIGINT');
backend.kill('SIGINT');
process.exit(0);
});
process.on('SIGTERM', () => {
log.info('Shutting down...');
frontend.kill('SIGTERM');
backend.kill('SIGTERM');
process.exit(0);
});
(async () => {
try {
log.info('Waiting for frontend and backend readiness...');
await Promise.all([
waitForHttpReady(FRONTEND_URL, 'Frontend', { acceptStatuses: [200] }),
waitForHttpReady(BACKEND_HEALTH_URL, 'Backend', { acceptStatuses: [200] }),
]);
log.success('Frontend and backend are ready.');
log.info(`Frontend: ${FRONTEND_URL}`);
log.info(`Backend: ${BACKEND_URL}`);
log.info('Press Ctrl+C to stop both processes');
openBrowser(FRONTEND_URL);
} catch (error) {
log.error(error instanceof Error ? error.message : String(error));
log.info('Processes are still running. Inspect the logs above for the blocking startup issue.');
}
})();