-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
423 lines (360 loc) · 13.9 KB
/
server.js
File metadata and controls
423 lines (360 loc) · 13.9 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
// Simple server to handle generate_controls_list.js execution
import express from 'express';
import { exec, spawn } from 'child_process';
import path from 'path';
import fs from 'fs';
import archiver from 'archiver';
import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const app = express();
const PORT = 3002;
function writeFilePayload(filePath, payload) {
if (payload && typeof payload === 'object' && payload.encoding === 'base64') {
const base64Data = payload.data || '';
const buffer = Buffer.from(base64Data, 'base64');
fs.writeFileSync(filePath, buffer);
} else {
fs.writeFileSync(filePath, payload || '');
}
}
// Middleware
const BODY_LIMIT = '50mb'; // Allow larger payloads for uploaded assets
app.use(express.json({ limit: BODY_LIMIT }));
app.use(express.urlencoded({ limit: BODY_LIMIT, extended: true }));
app.use(express.static('.'));
// Endpoint to run generate_controls_list.js
app.post('/api/generate-controls', (req, res) => {
console.log('Running generate_controls_list.js...');
exec('node scripts/generate_controls_list.js', { cwd: __dirname }, (error, stdout, stderr) => {
if (error) {
console.error('Error running script:', error);
return res.status(500).json({
success: false,
error: error.message,
stdout: stdout,
stderr: stderr
});
}
console.log('Script output:', stdout);
if (stderr) console.log('Script stderr:', stderr);
// Check if index.json was updated
const indexPath = path.join(__dirname, 'Controls', 'index.json');
if (fs.existsSync(indexPath)) {
const content = fs.readFileSync(indexPath, 'utf8');
console.log('Updated index.json:', content);
}
res.json({
success: true,
message: 'Controls list generated successfully',
stdout: stdout,
stderr: stderr
});
});
});
// Endpoint to get current controls
app.get('/api/controls', (req, res) => {
const indexPath = path.join(__dirname, 'Controls', 'index.json');
if (fs.existsSync(indexPath)) {
const content = fs.readFileSync(indexPath, 'utf8');
res.json(JSON.parse(content));
} else {
res.json([]);
}
});
// Endpoint to generate a new control from wizard
app.post('/api/generate-control', (req, res) => {
const { files, controlName } = req.body;
if (!files || !controlName) {
return res.status(400).json({
success: false,
error: 'Files and control name are required'
});
}
// Create a temporary directory for the new control
const tempDir = path.join(__dirname, 'temp', controlName);
const zipPath = path.join(__dirname, 'temp', `${controlName}.zip`);
// Ensure temp directory exists
if (!fs.existsSync(path.join(__dirname, 'temp'))) {
fs.mkdirSync(path.join(__dirname, 'temp'));
}
// Create control directory
if (fs.existsSync(tempDir)) {
fs.rmSync(tempDir, { recursive: true });
}
fs.mkdirSync(tempDir);
// Write files
Object.entries(files).forEach(([fileName, fileContent]) => {
const filePath = path.join(tempDir, fileName);
writeFilePayload(filePath, fileContent);
});
// Create ZIP
const output = fs.createWriteStream(zipPath);
const archive = archiver('zip', { zlib: { level: 9 } });
output.on('close', () => {
console.log(`Control generated: ${zipPath} (${archive.pointer()} bytes)`);
// Send the ZIP file
res.setHeader('Content-Type', 'application/zip');
res.setHeader('Content-Disposition', `attachment; filename="${controlName}.zip"`);
const zipStream = fs.createReadStream(zipPath);
zipStream.pipe(res);
// Clean up after sending
zipStream.on('end', () => {
fs.rmSync(tempDir, { recursive: true });
fs.unlinkSync(zipPath);
});
});
archive.on('error', (err) => {
console.error('Archive error:', err);
res.status(500).json({
success: false,
error: 'Failed to create ZIP: ' + err.message
});
});
archive.pipe(output);
archive.directory(tempDir, false);
archive.finalize();
});
// Endpoint to create ZIP of a control folder
app.post('/api/zip-control', async (req, res) => {
console.log('Received ZIP request:', req.body);
const { folderName, controlPath: customPath } = req.body;
if (!folderName) {
return res.status(400).json({
success: false,
error: 'Folder name is required'
});
}
// Use custom path if provided, otherwise assume it's in Controls folder
const controlPath = customPath || path.join(__dirname, 'Controls', folderName);
let zipPath = path.join(__dirname, 'Controls', `${folderName}.zip`);
// Check if control folder exists
if (!fs.existsSync(controlPath)) {
return res.status(404).json({
success: false,
error: `Control folder '${folderName}' not found at ${controlPath}`
});
}
// Ensure Controls directory exists
const controlsDir = path.join(__dirname, 'Controls');
if (!fs.existsSync(controlsDir)) {
try {
fs.mkdirSync(controlsDir, { recursive: true });
} catch (e) {
return res.status(500).json({
success: false,
error: 'Failed to create Controls directory: ' + e.message
});
}
}
// Delete existing ZIP if it exists
if (fs.existsSync(zipPath)) {
try {
fs.unlinkSync(zipPath);
console.log(`Deleted existing ZIP: ${zipPath}`);
// Add a small delay to ensure the file is fully deleted
await new Promise(resolve => setTimeout(resolve, 100));
} catch (e) {
console.error('Error deleting existing ZIP:', e);
// If we can't delete the existing file, try to create with a timestamp
const timestamp = Date.now();
const newZipPath = path.join(__dirname, 'Controls', `${folderName}_${timestamp}.zip`);
console.log(`Creating new ZIP with timestamp: ${newZipPath}`);
zipPath = newZipPath;
}
}
// Create new ZIP
const output = fs.createWriteStream(zipPath);
const archive = archiver('zip', { zlib: { level: 9 } });
// Handle output stream errors
output.on('error', (err) => {
console.error('Output stream error:', err);
if (!res.headersSent) {
res.status(500).json({
success: false,
error: 'Failed to create ZIP file: ' + err.message
});
}
});
output.on('close', () => {
clearTimeout(timeout);
console.log(`ZIP created: ${zipPath} (${archive.pointer()} bytes)`);
// Open the directory where the ZIP was created
const controlsDir = path.join(__dirname, 'Controls');
console.log(`Attempting to open directory: ${controlsDir}`);
// Use spawn for better control on Windows
let child;
if (process.platform === 'win32') {
child = spawn('explorer', [controlsDir], {
detached: true,
stdio: 'ignore'
});
} else if (process.platform === 'darwin') {
child = spawn('open', [controlsDir], {
detached: true,
stdio: 'ignore'
});
} else {
child = spawn('xdg-open', [controlsDir], {
detached: true,
stdio: 'ignore'
});
}
child.on('error', (error) => {
console.log('Could not open directory:', error.message);
});
child.on('spawn', () => {
console.log(`Successfully opened directory: ${controlsDir}`);
child.unref(); // Allow the parent process to exit
});
// Send JSON response
if (!res.headersSent) {
res.json({
success: true,
message: `ZIP created successfully: ${folderName}.zip`,
zipPath: `${folderName}.zip`,
size: archive.pointer(),
directoryOpened: controlsDir
});
}
});
archive.on('error', (err) => {
console.error('Archive error:', err);
if (!res.headersSent) {
res.status(500).json({
success: false,
error: 'Failed to create ZIP: ' + err.message
});
}
});
// Set a timeout to prevent hanging requests
const timeout = setTimeout(() => {
if (!res.headersSent) {
console.error('ZIP creation timeout');
res.status(500).json({
success: false,
error: 'ZIP creation timed out'
});
}
}, 30000); // 30 second timeout
archive.pipe(output);
archive.directory(controlPath, false);
archive.finalize();
});
// Documentation API endpoints
app.get('/api/docs', (req, res) => {
const docsDir = path.join(__dirname, 'docs');
if (!fs.existsSync(docsDir)) {
return res.json([]);
}
try {
// Define logical order for documentation
const docOrder = [
'Overview.md',
'Getting Started.md',
'Manifest Configuration.md',
'Standard Properties.md',
'Script References.md',
'Data Binding.md',
'Form View Validation.md',
'Control Methods.md',
'Responsive Controls.md',
'Style Integration.md',
'Localization.md',
'Accessibility.md'
];
const allFiles = fs.readdirSync(docsDir)
.filter(file => file.endsWith('.md'))
.map(file => ({
filename: file,
title: file.replace('.md', '').replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase()),
order: docOrder.indexOf(file) !== -1 ? docOrder.indexOf(file) : 999
}))
.sort((a, b) => {
// Sort by order first, then alphabetically for any files not in the order list
if (a.order !== b.order) {
return a.order - b.order;
}
return a.filename.localeCompare(b.filename);
})
.map(({ filename, title }) => ({ filename, title }));
res.json(allFiles);
} catch (error) {
console.error('Error reading docs directory:', error);
res.status(500).json({ error: 'Failed to read documentation files' });
}
});
app.get('/api/docs/:filename', (req, res) => {
const { filename } = req.params;
const filePath = path.join(__dirname, 'docs', filename);
// Security check - ensure the file is in the docs directory
if (!filePath.startsWith(path.join(__dirname, 'docs'))) {
return res.status(403).json({ error: 'Access denied' });
}
if (!fs.existsSync(filePath)) {
return res.status(404).json({ error: 'Document not found' });
}
try {
const content = fs.readFileSync(filePath, 'utf8');
res.setHeader('Content-Type', 'text/plain; charset=utf-8');
res.send(content);
} catch (error) {
console.error('Error reading document:', error);
res.status(500).json({ error: 'Failed to read document' });
}
});
// Load control into workbench endpoint
app.post('/api/load-to-workbench', (req, res) => {
const { files, controlName, displayName } = req.body;
if (!files || !controlName) {
return res.status(400).json({
success: false,
error: 'Files and control name are required'
});
}
try {
// Create control directory in Controls folder
const controlsDir = path.join(__dirname, 'Controls');
const controlDir = path.join(controlsDir, controlName);
// Ensure Controls directory exists
if (!fs.existsSync(controlsDir)) {
fs.mkdirSync(controlsDir, { recursive: true });
}
// Remove existing control directory if it exists
if (fs.existsSync(controlDir)) {
fs.rmSync(controlDir, { recursive: true });
}
// Create new control directory
fs.mkdirSync(controlDir);
// Write files to control directory
Object.entries(files).forEach(([fileName, fileContent]) => {
const filePath = path.join(controlDir, fileName);
writeFilePayload(filePath, fileContent);
});
// Regenerate controls index
exec('node scripts/generate_controls_list.js', { cwd: __dirname }, (error, stdout, stderr) => {
if (error) {
console.error('Error regenerating controls index:', error);
// Don't fail the request, just log the error
} else {
console.log('Controls index regenerated successfully');
}
});
console.log(`Control loaded into workbench: ${controlName}`);
res.json({
success: true,
message: `Control '${displayName || controlName}' loaded successfully into workbench`,
controlPath: controlDir,
filesCreated: Object.keys(files)
});
} catch (error) {
console.error('Error loading control into workbench:', error);
res.status(500).json({
success: false,
error: 'Failed to load control into workbench: ' + error.message
});
}
});
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});