-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathbun-runtime.ts
More file actions
322 lines (278 loc) · 8.84 KB
/
bun-runtime.ts
File metadata and controls
322 lines (278 loc) · 8.84 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
/**
* Bun Runtime Adapter
*
* Uses Bun's JavaScriptCore engine for fast execution with full ES2024+ support
*/
import {
BaseRuntime,
RuntimeType,
type RuntimeCapabilities,
type RuntimeMetrics,
type RuntimeConfig
} from './base-runtime.js';
import type { ExecutionOptions, ExecutionResult } from '../types/core.js';
import { ErrorType } from '../types/core.js';
import { spawn } from 'child_process';
import { writeFile, unlink } from 'fs/promises';
import { tmpdir } from 'os';
import { join } from 'path';
interface BunWorker {
id: string;
lastUsed: number;
isActive: boolean;
executionCount: number;
}
export class BunRuntime extends BaseRuntime {
private workers: Map<string, BunWorker> = new Map();
private workerQueue: string[] = [];
private totalExecutions: number = 0;
private totalExecutionTime: number = 0;
private initTime: number = 0;
private bunPath: string;
constructor(config: RuntimeConfig) {
super(config);
// Try ~/.bun/bin/bun first, fallback to 'bun' in PATH
const homeDir = process.env.HOME || process.env.USERPROFILE || '';
const bunInHome = homeDir ? `${homeDir}/.bun/bin/bun` : '';
this.bunPath = config.bun?.bunPath || bunInHome || 'bun';
}
async initialize(): Promise<void> {
const startTime = Date.now();
// Verify Bun is available
try {
await this.execBun(['--version']);
} catch (error) {
throw new Error(`Bun not found at ${this.bunPath}. Install from https://bun.sh`);
}
this.initTime = Date.now() - startTime;
this.initialized = true;
}
async execute(
code: string,
options?: ExecutionOptions
): Promise<ExecutionResult> {
if (!this.initialized) {
throw new Error('Bun runtime not initialized');
}
const startTime = Date.now();
const requestId = this.generateRequestId();
const tmpFile = join(tmpdir(), `bun-exec-${requestId}.ts`);
try {
// Wrap code with logging and error capture
const wrappedCode = this.wrapCode(code, options);
await writeFile(tmpFile, wrappedCode);
// Execute with Bun
const result = await this.execBun(['run', tmpFile], {
timeout: options?.timeout || 30000
});
const executionTime = Date.now() - startTime;
this.totalExecutions++;
this.totalExecutionTime += executionTime;
// Parse result from JSON output
const output = this.parseOutput(result.stdout);
return {
success: true,
result: output.result,
metrics: {
executionTime,
memoryUsed: 0,
cpuTime: 0,
apiCalls: 0,
startTime,
endTime: Date.now()
},
logs: output.logs,
requestId
};
} catch (error) {
return {
success: false,
error: {
type: ErrorType.RUNTIME,
message: error instanceof Error ? error.message : String(error),
stack: error instanceof Error ? error.stack : undefined,
code: 'BUN_EXEC_FAILED',
timestamp: new Date()
},
metrics: {
executionTime: Date.now() - startTime,
memoryUsed: 0,
cpuTime: 0,
apiCalls: 0,
startTime,
endTime: Date.now()
},
logs: [],
requestId
};
} finally {
// Cleanup temp file
try {
await unlink(tmpFile);
} catch {}
}
}
async shutdown(): Promise<void> {
this.workers.clear();
this.initialized = false;
}
getCapabilities(): RuntimeCapabilities {
return {
// Language features - Full ES2024+
supportsAsync: true,
supportsConst: true,
supportsLet: true,
supportsTopLevelReturn: false,
supportsTopLevelAwait: true,
supportsESModules: true,
supportsCommonJS: true,
supportsTypeScript: true,
// Execution characteristics
isInProcess: false, // Subprocess execution
isCloudBased: false,
supportsConcurrency: true,
// Performance
typicalStartupMs: 10,
typicalMemoryMB: 90,
// Security
hasNativeIsolation: true, // Process isolation
supportsFinegrainedPermissions: false
};
}
getMetrics(): RuntimeMetrics {
return {
initializationTime: this.initTime,
workerCount: this.workers.size,
totalExecutions: this.totalExecutions,
averageExecutionTime: this.totalExecutions > 0
? this.totalExecutionTime / this.totalExecutions
: 0,
memoryUsage: process.memoryUsage().heapUsed
};
}
async health(): Promise<{ healthy: boolean; message?: string }> {
try {
const result = await this.execute('console.log(1 + 1)', { timeout: 1000 });
return {
healthy: result.success,
message: result.success ? 'Bun runtime healthy' : 'Health check failed'
};
} catch (error) {
return {
healthy: false,
message: error instanceof Error ? error.message : 'Unknown error'
};
}
}
getRuntimeType(): RuntimeType {
return RuntimeType.BUN;
}
// Private helper methods
private generateRequestId(): string {
return `req_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
}
private wrapCode(code: string, options?: ExecutionOptions): string {
// Trim the code
const trimmedCode = code.trim();
// Check if code is a simple expression (doesn't contain statements)
const isExpression = !trimmedCode.includes(';') &&
!trimmedCode.startsWith('var ') &&
!trimmedCode.startsWith('let ') &&
!trimmedCode.startsWith('const ') &&
!trimmedCode.startsWith('function ');
let wrappedCode: string;
if (isExpression) {
// Simple expression - just return it
wrappedCode = `return ${trimmedCode};`;
} else {
// Complex code - check if it already has a return statement or needs one
const lines = trimmedCode.split('\n');
const lastLine = lines[lines.length - 1].trim();
// Check if code already contains a return statement
// (avoid wrapping multi-line returns like: return { ... };)
const hasReturnStatement = trimmedCode.includes('return ');
// If code already has a return statement, don't modify it
if (hasReturnStatement) {
wrappedCode = trimmedCode;
} else {
// Check if last line is a bare expression that should become a return
const isLastLineExpression = !lastLine.startsWith('var ') &&
!lastLine.startsWith('let ') &&
!lastLine.startsWith('const ') &&
!lastLine.startsWith('function ') &&
!lastLine.startsWith('if ') &&
!lastLine.startsWith('for ') &&
!lastLine.startsWith('while ') &&
lastLine.length > 0;
if (isLastLineExpression) {
// Replace last line with return statement
lines[lines.length - 1] = `return ${lastLine}`;
wrappedCode = lines.join('\n');
} else {
wrappedCode = trimmedCode;
}
}
}
return `
const __logs = [];
const __originalConsole = console.log;
console.log = (...args) => {
__logs.push(args.join(' '));
__originalConsole(...args);
};
let __result;
try {
__result = await (async function() {
${wrappedCode}
})();
} catch (error) {
console.error('EXECUTION_ERROR:', error.message);
console.error(error.stack);
process.exit(1);
}
console.log('__RESULT__', JSON.stringify({
result: __result,
logs: __logs
}));
`;
}
private parseOutput(stdout: string): { result: any; logs: string[] } {
const lines = stdout.split('\n');
const resultLine = lines.find(line => line.startsWith('__RESULT__'));
if (resultLine) {
const json = resultLine.replace('__RESULT__ ', '');
return JSON.parse(json);
}
return {
result: undefined,
logs: lines.filter(line => !line.startsWith('__RESULT__'))
};
}
private execBun(args: string[], options?: { timeout?: number }): Promise<{ stdout: string; stderr: string }> {
return new Promise((resolve, reject) => {
const proc = spawn(this.bunPath, args);
let stdout = '';
let stderr = '';
proc.stdout.on('data', (data) => {
stdout += data.toString();
});
proc.stderr.on('data', (data) => {
stderr += data.toString();
});
proc.on('close', (code) => {
if (code === 0) {
resolve({ stdout, stderr });
} else {
reject(new Error(`Bun exited with code ${code}: ${stderr}`));
}
});
proc.on('error', reject);
if (options?.timeout) {
setTimeout(() => {
proc.kill();
reject(new Error('Bun execution timeout'));
}, options.timeout);
}
});
}
}