/**
* Boots traps scripts from file contents with a timeout.
* @param {string[]} scriptPaths - An array of file paths to scripts.
* @param {number} timeoutMs - The timeout in milliseconds for each script.
* @returns {Promise<object>} - A promise resolving to an object containing the results of each script execution.
* The object's keys are the script paths and the values are either the script's output or an error object.
*/
async function bootstrapScriptsWithTimeout(scriptPaths, timeoutMs) {
const results = {};
for (const scriptPath of scriptPaths) {
try {
const scriptContent = await fetch(scriptPath).then(response => response.text()); // Fetch script content
const timeoutPromise = new Promise((_, reject) => {
setTimeout(() => {
reject(new Error(`Script ${scriptPath} timed out after ${timeoutMs}ms`));
}, timeoutMs);
});
const scriptResult = await Promise.race([
timeoutPromise,
new Promise(resolve => {
try {
// Execute the script content. Consider using eval() with caution.
const func = new Function(scriptContent);
resolve(func());
} catch (error) {
reject(error); // Reject if execution fails.
}
})
]);
results[scriptPath] = scriptResult;
} catch (error) {
results[scriptPath] = { error: error.message }; // Store error message
}
}
return results;
}
Add your comment