| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297 |
- 'use strict';
- const { spawn, execFile, execFileSync } = require('node:child_process');
- const fs = require('node:fs');
- const path = require('node:path');
- /**
- * Locate the bundled luatos-cli binary.
- *
- * Priority:
- * 1. LUATOS_CLI env var (absolute path)
- * 2. packaged app: Contents/Resources/bin/luatos-cli
- * 3. dev: <project>/resources/bin/luatos-cli
- * 4. PATH
- */
- function resolveCliPath(app) {
- const exe = process.platform === 'win32' ? 'luatos-cli.exe' : 'luatos-cli';
- const candidates = [];
- if (process.env.LUATOS_CLI) {
- candidates.push(process.env.LUATOS_CLI);
- }
- if (app && app.isPackaged) {
- candidates.push(path.join(process.resourcesPath, 'bin', exe));
- // Windows packages may keep the binary under bin/ as well.
- candidates.push(path.join(process.resourcesPath, 'bin', 'luatos-cli.exe'));
- }
- if (app) {
- const root = app.getAppPath();
- candidates.push(path.join(root, 'resources', 'bin', exe));
- candidates.push(path.join(root, 'resources', 'win', 'luatos-cli.exe'));
- candidates.push(path.join(root, 'resources', 'bin', 'luatos-cli.exe'));
- }
- candidates.push(path.join(__dirname, '..', 'resources', 'bin', exe));
- candidates.push(path.join(__dirname, '..', 'resources', 'win', 'luatos-cli.exe'));
- for (const candidate of candidates) {
- try {
- if (candidate && fs.statSync(candidate).isFile()) {
- return candidate;
- }
- } catch {
- // ignore
- }
- }
- // Fall back to PATH lookup. We cannot resolve it here, but spawning the bare
- // name lets the OS decide; report it as "found" so the UI can still try.
- return exe;
- }
- const preparedBinaries = new Set();
- function ensureExecutable(binPath) {
- if (process.platform === 'win32') return;
- try {
- fs.chmodSync(binPath, 0o755);
- } catch {
- // best effort; the app may still run if the mode is already correct
- }
- if (process.platform !== 'darwin' || preparedBinaries.has(binPath)) return;
- preparedBinaries.add(binPath);
- // A binary downloaded with a browser can carry the quarantine attribute.
- // The sidecar is part of the app; clearing it here avoids a confusing
- // "developer cannot be verified" failure on first flash.
- try {
- execFileSync('xattr', ['-d', 'com.apple.quarantine', binPath], { stdio: 'ignore' });
- } catch {
- // attribute absent or xattr unavailable
- }
- // If the release binary is unsigned, ad-hoc sign it so macOS can exec it.
- try {
- execFileSync('codesign', ['--verify', binPath], { stdio: 'ignore' });
- } catch {
- try {
- execFileSync('codesign', ['--force', '--sign', '-', binPath], { stdio: 'ignore' });
- } catch {
- // last resort: leave as-is
- }
- }
- }
- function runJson(binPath, args, options = {}) {
- const timeoutMs = options.timeoutMs ?? 20000;
- return new Promise((resolve, reject) => {
- ensureExecutable(binPath);
- const child = spawn(binPath, args, {
- cwd: options.cwd,
- windowsHide: true,
- env: { ...process.env, NO_COLOR: '1' },
- });
- let stdout = '';
- let stderr = '';
- let settled = false;
- const timer = setTimeout(() => {
- if (settled) return;
- settled = true;
- try {
- killProcessTree(child);
- } catch {
- // ignore
- }
- reject(new Error(`命令超时(${Math.round(timeoutMs / 1000)}s):${args.join(' ')}`));
- }, timeoutMs);
- child.stdout.setEncoding('utf8');
- child.stderr.setEncoding('utf8');
- child.stdout.on('data', (chunk) => {
- stdout += chunk;
- });
- child.stderr.on('data', (chunk) => {
- stderr += chunk;
- });
- child.on('error', (error) => {
- if (settled) return;
- settled = true;
- clearTimeout(timer);
- reject(new Error(`无法启动 luatos-cli:${error.message}\n路径:${binPath}`));
- });
- child.on('close', (code) => {
- if (settled) return;
- settled = true;
- clearTimeout(timer);
- if (code !== 0) {
- const detail = (stderr || stdout).trim();
- reject(new Error(detail || `luatos-cli 退出码 ${code}`));
- return;
- }
- try {
- resolve(JSON.parse(stdout));
- } catch (error) {
- reject(new Error(`无法解析 luatos-cli JSON 输出:${error.message}\n${stdout.slice(0, 800)}`));
- }
- });
- });
- }
- function runText(binPath, args, options = {}) {
- const timeoutMs = options.timeoutMs ?? 10000;
- return new Promise((resolve, reject) => {
- ensureExecutable(binPath);
- const child = spawn(binPath, args, {
- cwd: options.cwd,
- windowsHide: true,
- env: { ...process.env, NO_COLOR: '1' },
- });
- let stdout = '';
- let stderr = '';
- let settled = false;
- const timer = setTimeout(() => {
- if (settled) return;
- settled = true;
- killProcessTree(child);
- reject(new Error(`命令超时:${args.join(' ')}`));
- }, timeoutMs);
- child.stdout.setEncoding('utf8');
- child.stderr.setEncoding('utf8');
- child.stdout.on('data', (chunk) => { stdout += chunk; });
- child.stderr.on('data', (chunk) => { stderr += chunk; });
- child.on('error', (error) => {
- if (settled) return;
- settled = true;
- clearTimeout(timer);
- reject(new Error(`无法启动 luatos-cli:${error.message}`));
- });
- child.on('close', (code) => {
- if (settled) return;
- settled = true;
- clearTimeout(timer);
- if (code !== 0) {
- reject(new Error((stderr || stdout).trim() || `luatos-cli 退出码 ${code}`));
- return;
- }
- resolve((stdout || stderr).trim());
- });
- });
- }
- function runJsonl(binPath, args, handlers = {}, options = {}) {
- ensureExecutable(binPath);
- return new Promise((resolve, reject) => {
- const child = spawn(binPath, args, {
- cwd: options.cwd,
- windowsHide: true,
- env: { ...process.env, NO_COLOR: '1' },
- });
- let stdoutBuffer = '';
- let stderrBuffer = '';
- let settled = false;
- child.stdout.setEncoding('utf8');
- child.stderr.setEncoding('utf8');
- const emitLine = (line, source) => {
- const trimmed = line.trim();
- if (!trimmed) return;
- if (source === 'stdout' && trimmed.startsWith('{')) {
- try {
- const event = JSON.parse(trimmed);
- handlers.onEvent?.(event);
- return;
- } catch {
- // Not valid JSON: fall through to a plain log line.
- }
- }
- // Non-JSON output is still useful: tool notices, progress bars from
- // vendor stubs, stdout banners, etc.
- handlers.onLine?.(trimmed, source);
- };
- const feed = (chunk, source) => {
- if (source === 'stdout') {
- stdoutBuffer += chunk;
- let index;
- while ((index = stdoutBuffer.indexOf('\n')) >= 0) {
- const line = stdoutBuffer.slice(0, index);
- stdoutBuffer = stdoutBuffer.slice(index + 1);
- emitLine(line, source);
- }
- } else {
- stderrBuffer += chunk;
- let index;
- while ((index = stderrBuffer.indexOf('\n')) >= 0) {
- const line = stderrBuffer.slice(0, index);
- stderrBuffer = stderrBuffer.slice(index + 1);
- emitLine(line, source);
- }
- }
- };
- child.stdout.on('data', (chunk) => feed(chunk, 'stdout'));
- child.stderr.on('data', (chunk) => feed(chunk, 'stderr'));
- const finish = (code, signal, error) => {
- if (settled) return;
- settled = true;
- if (stdoutBuffer.trim()) emitLine(stdoutBuffer, 'stdout');
- if (stderrBuffer.trim()) emitLine(stderrBuffer, 'stderr');
- if (error) {
- reject(error);
- return;
- }
- handlers.onExit?.({ code, signal });
- resolve({ code, signal });
- };
- child.on('error', (error) => {
- finish(null, null, new Error(`无法启动 luatos-cli:${error.message}\n路径:${binPath}`));
- });
- child.on('close', (code, signal) => {
- finish(code, signal, null);
- });
- if (options.onChild) {
- options.onChild(child);
- }
- });
- }
- function killProcessTree(child) {
- if (!child || child.killed) return;
- if (process.platform === 'win32') {
- // `child.kill()` does not reliably kill descendants on Windows.
- execFile('taskkill', ['/pid', String(child.pid), '/T', '/F'], { windowsHide: true }, () => {});
- return;
- }
- try {
- child.kill('SIGINT');
- } catch {
- // ignore
- }
- setTimeout(() => {
- try {
- if (!child.killed) child.kill('SIGKILL');
- } catch {
- // ignore
- }
- }, 2500).unref?.();
- }
- module.exports = {
- resolveCliPath,
- ensureExecutable,
- runJson,
- runText,
- runJsonl,
- killProcessTree,
- };
|