-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuild.js
More file actions
374 lines (288 loc) · 9.22 KB
/
build.js
File metadata and controls
374 lines (288 loc) · 9.22 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
#!/usr/bin/env node
/**
* Custom build script for NodeDaemon
* Compiles TypeScript and creates single-file distributions
*/
const fs = require('fs');
const path = require('path');
const { execSync } = require('child_process');
const DIST_DIR = 'dist';
const SRC_DIR = 'src';
const BUILD_DIR = 'build';
class Builder {
constructor() {
this.startTime = Date.now();
}
log(message, ...args) {
const timestamp = new Date().toISOString();
console.log(`[${timestamp}] ${message}`, ...args);
}
error(message, ...args) {
const timestamp = new Date().toISOString();
console.error(`[${timestamp}] ERROR: ${message}`, ...args);
}
success(message, ...args) {
const timestamp = new Date().toISOString();
console.log(`[${timestamp}] ✅ ${message}`, ...args);
}
async build() {
try {
this.log('Starting NodeDaemon build...');
// Clean previous builds
await this.clean();
// Compile TypeScript
await this.compileTypeScript();
// Create single file distributions
await this.createDistributions();
// Copy additional files
await this.copyAssets();
// Set executable permissions
await this.setPermissions();
const buildTime = Date.now() - this.startTime;
this.success(`Build completed in ${buildTime}ms`);
} catch (error) {
this.error('Build failed:', error.message);
process.exit(1);
}
}
async clean() {
this.log('Cleaning previous builds...');
const dirs = [DIST_DIR, BUILD_DIR];
dirs.forEach(dir => {
if (fs.existsSync(dir)) {
fs.rmSync(dir, { recursive: true, force: true });
}
});
dirs.forEach(dir => {
fs.mkdirSync(dir, { recursive: true });
});
this.success('Clean completed');
}
async compileTypeScript() {
this.log('Compiling TypeScript...');
try {
execSync('npx tsc', { stdio: 'inherit' });
this.success('TypeScript compilation completed');
} catch (error) {
throw new Error(`TypeScript compilation failed: ${error.message}`);
}
}
async createDistributions() {
this.log('Creating distributions...');
// Create CLI distribution
await this.createCLIDistribution();
// Create daemon distribution
await this.createDaemonDistribution();
this.success('Distributions created');
}
async createCLIDistribution() {
this.log('Bundling CLI...');
const cliEntryPoint = path.join(DIST_DIR, 'cli', 'index.js');
const cliBundle = path.join(BUILD_DIR, 'nodedaemon.js');
// Simple bundling - inline all requires
const bundledCode = this.bundleFiles(cliEntryPoint, new Set());
// Add shebang
const finalCode = `#!/usr/bin/env node\n\n${bundledCode}`;
fs.writeFileSync(cliBundle, finalCode, 'utf8');
this.success('CLI bundle created');
}
async createDaemonDistribution() {
this.log('Bundling daemon...');
const daemonEntryPoint = path.join(DIST_DIR, 'daemon', 'index.js');
const daemonBundle = path.join(BUILD_DIR, 'nodedaemon-daemon.js');
// Simple bundling - inline all requires
const bundledCode = this.bundleFiles(daemonEntryPoint, new Set());
// Add shebang
const finalCode = `#!/usr/bin/env node\n\n${bundledCode}`;
fs.writeFileSync(daemonBundle, finalCode, 'utf8');
this.success('Daemon bundle created');
}
bundleFiles(entryPoint, processed) {
if (processed.has(entryPoint)) {
return '';
}
processed.add(entryPoint);
if (!fs.existsSync(entryPoint)) {
this.error(`File not found: ${entryPoint}`);
return '';
}
let content = fs.readFileSync(entryPoint, 'utf8');
// Remove source map references
content = content.replace(/\/\/# sourceMappingURL=.*$/gm, '');
// Find require statements for local files
const requireRegex = /require\(['"](\.[^'"]+)['"]\)/g;
let match;
while ((match = requireRegex.exec(content)) !== null) {
const requiredPath = match[1];
const resolvedPath = this.resolveRequire(path.dirname(entryPoint), requiredPath);
if (resolvedPath && resolvedPath.includes(DIST_DIR)) {
// This is a local file, inline it
const inlinedContent = this.bundleFiles(resolvedPath, processed);
// Replace the require with the inlined content wrapped in an IIFE
const replacement = `(function() {
const module = { exports: {} };
const exports = module.exports;
${inlinedContent}
return module.exports;
})()`;
content = content.replace(match[0], replacement);
}
}
return content;
}
resolveRequire(fromDir, requirePath) {
// Handle relative requires
if (requirePath.startsWith('./') || requirePath.startsWith('../')) {
let resolvedPath = path.resolve(fromDir, requirePath);
// Try with .js extension
if (fs.existsSync(resolvedPath + '.js')) {
return resolvedPath + '.js';
}
// Try as directory with index.js
if (fs.existsSync(path.join(resolvedPath, 'index.js'))) {
return path.join(resolvedPath, 'index.js');
}
// Try as-is
if (fs.existsSync(resolvedPath)) {
return resolvedPath;
}
}
return null;
}
async copyAssets() {
this.log('Copying assets...');
// Copy package.json for version info
const packageJson = JSON.parse(fs.readFileSync('package.json', 'utf8'));
const slimPackage = {
name: packageJson.name,
version: packageJson.version,
description: packageJson.description,
bin: packageJson.bin
};
fs.writeFileSync(
path.join(BUILD_DIR, 'package.json'),
JSON.stringify(slimPackage, null, 2),
'utf8'
);
// Copy README
if (fs.existsSync('README.md')) {
fs.copyFileSync('README.md', path.join(BUILD_DIR, 'README.md'));
}
// Copy LICENSE if exists
if (fs.existsSync('LICENSE')) {
fs.copyFileSync('LICENSE', path.join(BUILD_DIR, 'LICENSE'));
}
// Copy web directory
const webSrc = 'web';
const webDist = path.join(DIST_DIR, 'web');
if (fs.existsSync(webSrc)) {
if (!fs.existsSync(webDist)) {
fs.mkdirSync(webDist, { recursive: true });
}
const files = fs.readdirSync(webSrc);
files.forEach(file => {
fs.copyFileSync(
path.join(webSrc, file),
path.join(webDist, file)
);
});
}
this.success('Assets copied');
}
async setPermissions() {
if (process.platform !== 'win32') {
this.log('Setting executable permissions...');
const executables = [
path.join(BUILD_DIR, 'nodedaemon.js'),
path.join(BUILD_DIR, 'nodedaemon-daemon.js')
];
executables.forEach(file => {
if (fs.existsSync(file)) {
fs.chmodSync(file, 0o755);
}
});
this.success('Permissions set');
}
}
async createInstaller() {
this.log('Creating installer script...');
const installerScript = `#!/bin/bash
# NodeDaemon Installer
set -e
# Detect OS and architecture
OS="$(uname -s)"
ARCH="$(uname -m)"
echo "Installing NodeDaemon..."
echo "OS: $OS"
echo "Architecture: $ARCH"
# Create installation directory
INSTALL_DIR="/usr/local/bin"
if [[ "$OS" == "Darwin" ]]; then
INSTALL_DIR="/usr/local/bin"
elif [[ "$OS" == "Linux" ]]; then
INSTALL_DIR="/usr/local/bin"
fi
echo "Installation directory: $INSTALL_DIR"
# Check for required permissions
if [[ ! -w "$INSTALL_DIR" ]]; then
echo "Error: Cannot write to $INSTALL_DIR"
echo "Please run with sudo or choose a different installation directory"
exit 1
fi
# Copy binaries
cp nodedaemon.js "$INSTALL_DIR/nodedaemon"
cp nodedaemon-daemon.js "$INSTALL_DIR/nodedaemon-daemon"
# Set permissions
chmod +x "$INSTALL_DIR/nodedaemon"
chmod +x "$INSTALL_DIR/nodedaemon-daemon"
echo "✅ NodeDaemon installed successfully!"
echo "Run 'nodedaemon --help' to get started"
`;
fs.writeFileSync(path.join(BUILD_DIR, 'install.sh'), installerScript, 'utf8');
if (process.platform !== 'win32') {
fs.chmodSync(path.join(BUILD_DIR, 'install.sh'), 0o755);
}
this.success('Installer created');
}
async watch() {
this.log('Starting watch mode...');
const watcher = fs.watch(SRC_DIR, { recursive: true }, (eventType, filename) => {
if (filename && filename.endsWith('.ts')) {
this.log(`File changed: ${filename}, rebuilding...`);
this.build().catch(error => {
this.error('Rebuild failed:', error.message);
});
}
});
process.on('SIGINT', () => {
this.log('Stopping watch mode...');
watcher.close();
process.exit(0);
});
this.success('Watch mode started. Press Ctrl+C to stop.');
}
}
// CLI interface
async function main() {
const builder = new Builder();
const command = process.argv[2];
switch (command) {
case 'watch':
await builder.build();
await builder.watch();
break;
case 'installer':
await builder.build();
await builder.createInstaller();
break;
default:
await builder.build();
}
}
if (require.main === module) {
main().catch(error => {
console.error('Build script failed:', error);
process.exit(1);
});
}
module.exports = { Builder };