MCPcopy Create free account
hub / github.com/TraderAlice/OpenAlice / runScript

Function runScript

src/workspaces/workspace-creator.ts:334–415  ·  view source on GitHub ↗
(
  script: string,
  args: readonly string[],
  extraEnv: { [key: string]: string },
  timeoutMs: number,
)

Source from the content-addressed store, hash-verified

332 * doesn't depend on which OS the tests happen to run on.
333 */
334export function runScript(
335 script: string,
336 args: readonly string[],
337 extraEnv: { [key: string]: string },
338 timeoutMs: number,
339): Promise<RunResult> {
340 const isMjs = script.endsWith('.mjs');
341 const isWindows = process.platform === 'win32';
342
343 // `.mjs` (built-in templates): run on the Electron-bundled Node. In the
344 // packaged app `process.execPath` is the Electron binary; ELECTRON_RUN_AS_NODE
345 // flips it to pure-Node mode (a harmless no-op for a plain `node` execPath in
346 // dev). No bash, no shebang reliance → works on a bare Windows/Mac box.
347 // `.sh` (third-party fallback): unix reads the `#!/usr/bin/env bash` shebang;
348 // Windows has no native bash, so we invoke `bash <script>` explicitly, which
349 // requires bash on PATH (Git for Windows / WSL).
350 const cmd = isMjs ? process.execPath : isWindows ? 'bash' : script;
351 const cmdArgs = isMjs || isWindows ? [script, ...args] : args;
352 const env = isMjs
353 ? { ...process.env, ...extraEnv, ELECTRON_RUN_AS_NODE: '1' }
354 : { ...process.env, ...extraEnv };
355
356 return new Promise((resolve) => {
357 const child = spawn(cmd, cmdArgs, {
358 env,
359 stdio: ['ignore', 'pipe', 'pipe'],
360 });
361
362 const stdoutChunks: Buffer[] = [];
363 const stderrChunks: Buffer[] = [];
364 let timedOut = false;
365
366 child.stdout.on('data', (c: Buffer) => stdoutChunks.push(c));
367 child.stderr.on('data', (c: Buffer) => stderrChunks.push(c));
368
369 const timer = setTimeout(() => {
370 timedOut = true;
371 child.kill('SIGTERM');
372 setTimeout(() => {
373 if (child.exitCode === null) child.kill('SIGKILL');
374 }, 2000);
375 }, timeoutMs);
376 timer.unref();
377
378 child.on('error', (err) => {
379 clearTimeout(timer);
380 const errMsg = (err as Error).message;
381 // ENOENT on Windows when we tried `bash` (a `.sh` third-party template)
382 // means Git Bash / WSL bash isn't on PATH — surface the install hint.
383 // Built-in `.mjs` templates run on the bundled Node and never hit this.
384 const hinted =
385 !isMjs && isWindows && /ENOENT/i.test(errMsg) ? `${errMsg}\n${WINDOWS_BASH_HINT}` : errMsg;
386 resolve({
387 ok: false,
388 stdout: Buffer.concat(stdoutChunks).toString('utf8'),
389 stderr: `${hinted}\n${Buffer.concat(stderrChunks).toString('utf8')}`,
390 exitCode: null,
391 });

Callers 2

createMethod · 0.70

Calls 2

pushMethod · 0.65
toStringMethod · 0.45

Tested by

no test coverage detected