@weapp-tailwindcss/hbuilderx-runner 0.1.5 → 0.1.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +8 -0
- package/README.zh-CN.md +8 -0
- package/dist/index.cjs +196 -68
- package/dist/index.d.ts +5 -1
- package/dist/index.mjs +196 -68
- package/package.json +4 -3
package/README.md
CHANGED
|
@@ -54,3 +54,11 @@ If one CLI matches multiple hosts, the runner reports an ambiguity instead of gu
|
|
|
54
54
|
Some HBuilderX releases reject concurrent stable and Alpha processes. The runner never closes an existing instance automatically; it reports `cli-instance-mismatch` when the target edition cannot start, so close the conflicting instance before retrying.
|
|
55
55
|
|
|
56
56
|
`runPnpmCommand`, `spawnPnpmCommand`, `hbuilderxPnpmArgs`, and the synchronous `startLaunch` remain for compatibility. Use a bound runner when the stable/Alpha choice must be deterministic; the `@dcloudio/hbuilderx-cli` pnpm wrapper performs its own process discovery and cannot provide that guarantee.
|
|
57
|
+
|
|
58
|
+
## Timeouts and cleanup
|
|
59
|
+
|
|
60
|
+
After `timeoutMs`, `runCommand` cleans up its own process before waiting for the real `close` event and final logs. Cleanup has a separate budget: POSIX waits up to one second after the requested signal, then up to one second after `SIGKILL`; Windows runs `taskkill /T /F` with a five-second timeout, then waits up to one second for closure. Cleanup already in progress also waits for descendants in the default detached process group, including descendants that close their pipes before the root exits.
|
|
61
|
+
|
|
62
|
+
A graceful exit code of zero after the business deadline still has the `timeout` classification. `allowFailure` permits business failures, but never cleanup failures. `HBuilderXCommandError.cleanupError` and `cause` retain cleanup diagnostics alongside the command, cwd, observed exit and recent logs. A Windows partial tree-termination failure remains an error even if the root closes.
|
|
63
|
+
|
|
64
|
+
Call and await `stop()` before a long-running root process closes. Repeated calls share the same cleanup result. Natural closure revokes the numeric PID/group handle to avoid targeting a later process that reuses it; services that deliberately leave the group are outside this scope. With `detached: false`, only the owned root's closure is confirmed. The synchronous `killProcessTree` remains a best-effort compatibility request, not cleanup confirmation. Unreaped POSIX orphan processes or persistent permission errors that prevent confirmation cause conservative cleanup failure.
|
package/README.zh-CN.md
CHANGED
|
@@ -55,3 +55,11 @@ macOS 默认路径为 `/Applications/HBuilderX.app/Contents/MacOS/cli` 和 `/App
|
|
|
55
55
|
部分 HBuilderX 版本自身会拒绝 stable 与 Alpha 跨版本并行运行。runner 不会擅自关闭当前实例;目标版本无法启动时会抛出 `cli-instance-mismatch`,请关闭冲突实例后重试。
|
|
56
56
|
|
|
57
57
|
`runPnpmCommand`、`spawnPnpmCommand`、`hbuilderxPnpmArgs` 和同步 `startLaunch` 为兼容旧调用保留。需要固定 stable/Alpha 时应使用绑定 runner;`@dcloudio/hbuilderx-cli` 的 pnpm 包装器会重新按运行进程探测版本,无法提供同等保证。
|
|
58
|
+
|
|
59
|
+
## 超时与清理
|
|
60
|
+
|
|
61
|
+
`runCommand` 达到 `timeoutMs` 后先清理自己启动的进程,再等待真实 `close` 和最终日志。清理使用独立预算:POSIX 先发送请求信号,最多等待 1 秒,再发送 `SIGKILL` 并最多等待 1 秒;Windows 使用最多 5 秒的 `taskkill /T /F`,随后最多等待 1 秒确认关闭。默认独立进程组中的后代即使关闭管道、根进程先退出,也纳入已开始的清理。
|
|
62
|
+
|
|
63
|
+
业务超时后即使进程优雅地返回 0,结果仍是 `timeout`。`allowFailure` 只允许返回业务失败,不放行清理失败;清理失败通过 `HBuilderXCommandError.cleanupError` 和 `cause` 保留,主错误继续记录命令、cwd、退出状态和最近日志。Windows 部分终止失败不会因根进程关闭而被抹掉。
|
|
64
|
+
|
|
65
|
+
长驻命令必须在根进程 `close` 前调用并等待 `stop()`,重复调用复用同一次清理结果。自然关闭后注销数字 PID/进程组句柄,避免误终止后来复用该编号的进程;不会追踪主动脱离独立组的服务。`detached: false` 只确认所持有的根进程关闭。同步 `killProcessTree` 仅保留兼容的终止请求,不等同于清理成功。POSIX 进程组若仍含未回收的孤儿进程,或权限错误持续导致无法确认组已消失,清理会保守失败。
|
package/dist/index.cjs
CHANGED
|
@@ -51,7 +51,7 @@ function wait(ms) {
|
|
|
51
51
|
const macOSStableCli = "/Applications/HBuilderX.app/Contents/MacOS/cli";
|
|
52
52
|
const macOSAlphaCli = "/Applications/HBuilderX-Alpha.app/Contents/MacOS/cli";
|
|
53
53
|
function resolveCandidateSource(candidate, env) {
|
|
54
|
-
if (candidate === env
|
|
54
|
+
if (candidate === env["HBUILDERX_CLI_PATH"]) return "env";
|
|
55
55
|
if (candidate === "/Applications/HBuilderX.app/Contents/MacOS/cli" || candidate === "/Applications/HBuilderX-Alpha.app/Contents/MacOS/cli") return "default-path";
|
|
56
56
|
return "candidate";
|
|
57
57
|
}
|
|
@@ -68,8 +68,8 @@ async function resolveConfiguredCli(options) {
|
|
|
68
68
|
source: resolveCandidateSource(candidate, env)
|
|
69
69
|
};
|
|
70
70
|
}
|
|
71
|
-
if (env
|
|
72
|
-
path: env
|
|
71
|
+
if (env["HBUILDERX_CLI_PATH"] && await fileExists(env["HBUILDERX_CLI_PATH"])) return {
|
|
72
|
+
path: env["HBUILDERX_CLI_PATH"],
|
|
73
73
|
source: "env"
|
|
74
74
|
};
|
|
75
75
|
}
|
|
@@ -92,9 +92,9 @@ function inferHBuilderXChannel(file) {
|
|
|
92
92
|
if (/HBuilderX(?:\.app)?[\\/]/i.test(file) || /HBuilderX\.exe$/i.test(file)) return "stable";
|
|
93
93
|
return "unknown";
|
|
94
94
|
}
|
|
95
|
-
function getDefaultHBuilderXCliCandidates(env = node_process.default.env, channel = resolveHBuilderXChannel(env
|
|
95
|
+
function getDefaultHBuilderXCliCandidates(env = node_process.default.env, channel = resolveHBuilderXChannel(env["HBUILDERX_CHANNEL"]), platform = node_process.default.platform) {
|
|
96
96
|
const defaults = platform === "darwin" ? channel === "stable" ? [macOSStableCli] : channel === "alpha" ? [macOSAlphaCli] : [macOSStableCli, macOSAlphaCli] : [];
|
|
97
|
-
return unique([env
|
|
97
|
+
return unique([env["HBUILDERX_CLI_PATH"], ...defaults].filter((item) => Boolean(item)));
|
|
98
98
|
}
|
|
99
99
|
function extractHBuilderXMacOSExecutables(output) {
|
|
100
100
|
return unique(Array.from(output.matchAll(/(\/[^\r\n]*?HBuilderX(?:-Alpha|\s+Alpha)?\.app\/Contents\/MacOS\/HBuilderX)(?=\s|$)/gi), (match) => match[1]));
|
|
@@ -202,7 +202,7 @@ async function firstExisting(items) {
|
|
|
202
202
|
}
|
|
203
203
|
async function resolveHBuilderXCliInfoFromOptions(options = {}) {
|
|
204
204
|
const env = options.env ?? node_process.default.env;
|
|
205
|
-
const channel = resolveHBuilderXChannel(options.channel ?? env
|
|
205
|
+
const channel = resolveHBuilderXChannel(options.channel ?? env["HBUILDERX_CHANNEL"]);
|
|
206
206
|
const running = await findRunningHBuilderXCliCandidates();
|
|
207
207
|
const configured = await resolveConfiguredCli(options);
|
|
208
208
|
if (configured) return {
|
|
@@ -357,37 +357,138 @@ function formatRecentLogs(logs, maxLength = 6e3) {
|
|
|
357
357
|
return important.length > 0 ? `关键错误:\n${important.join("\n")}\n\n最近日志:\n${recent}` : recent;
|
|
358
358
|
}
|
|
359
359
|
//#endregion
|
|
360
|
-
//#region src/process.ts
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
360
|
+
//#region src/process/termination.ts
|
|
361
|
+
const ownedGroups = /* @__PURE__ */ new WeakMap();
|
|
362
|
+
const closedChildren = /* @__PURE__ */ new WeakSet();
|
|
363
|
+
const shutdownWaitMs = 1e3;
|
|
364
|
+
/** 只记录本次 spawn 创建的独立进程组,不从外部 PID 猜测组归属。 */
|
|
365
|
+
function registerProcessGroup(child, detached) {
|
|
366
|
+
if (node_process.default.platform !== "win32" && detached && child.pid) ownedGroups.set(child, child.pid);
|
|
367
|
+
child.once("close", () => {
|
|
368
|
+
closedChildren.add(child);
|
|
369
|
+
ownedGroups.delete(child);
|
|
370
|
+
});
|
|
371
|
+
}
|
|
372
|
+
function signalOwnedTree(child, signal, group) {
|
|
373
|
+
if (!child.pid) return;
|
|
372
374
|
if (node_process.default.platform === "win32") {
|
|
373
|
-
(
|
|
375
|
+
if (child.exitCode !== null || child.signalCode !== null || closedChildren.has(child)) return;
|
|
376
|
+
const result = (0, node_child_process.spawnSync)("taskkill", [
|
|
374
377
|
"/pid",
|
|
375
|
-
String(pid),
|
|
378
|
+
String(child.pid),
|
|
376
379
|
"/t",
|
|
377
380
|
"/f"
|
|
378
381
|
], {
|
|
379
|
-
|
|
382
|
+
timeout: 5e3,
|
|
383
|
+
killSignal: "SIGKILL",
|
|
384
|
+
maxBuffer: 65536,
|
|
385
|
+
encoding: "utf8",
|
|
386
|
+
stdio: [
|
|
387
|
+
"ignore",
|
|
388
|
+
"pipe",
|
|
389
|
+
"pipe"
|
|
390
|
+
],
|
|
380
391
|
windowsHide: true
|
|
381
392
|
});
|
|
393
|
+
if (result.error || result.status !== 0) throw new Error(`taskkill pid=${child.pid} 失败,exit=${result.status} signal=${result.signal}\n${result.error?.message ?? ""}\n${result.stderr ?? ""}\n${result.stdout ?? ""}`, { cause: result.error });
|
|
382
394
|
return;
|
|
383
395
|
}
|
|
384
|
-
try {
|
|
385
|
-
node_process.default.kill(-
|
|
386
|
-
|
|
396
|
+
if (group) try {
|
|
397
|
+
node_process.default.kill(-group, signal);
|
|
398
|
+
return;
|
|
399
|
+
} catch (error) {
|
|
400
|
+
if (error.code !== "ESRCH") throw error;
|
|
401
|
+
}
|
|
402
|
+
if (!closedChildren.has(child) && child.exitCode === null && child.signalCode === null && !child.kill(signal)) throw new Error(`未能向子进程 pid=${child.pid} 发送 ${signal}`);
|
|
403
|
+
}
|
|
404
|
+
/** 同步入口在 close 后失效,避免稍后向复用的 PID 或进程组发送信号。 */
|
|
405
|
+
function signalProcessTree(child, signal) {
|
|
406
|
+
if (!closedChildren.has(child)) signalOwnedTree(child, signal, ownedGroups.get(child));
|
|
407
|
+
}
|
|
408
|
+
function waitForCleanup(closed, isGroupGone) {
|
|
409
|
+
return new Promise((resolve, reject) => {
|
|
410
|
+
let didClose = false;
|
|
411
|
+
let finished = false;
|
|
412
|
+
let lastProbeError;
|
|
413
|
+
const finish = (done, error) => {
|
|
414
|
+
finished = true;
|
|
415
|
+
clearTimeout(deadline);
|
|
416
|
+
clearInterval(poll);
|
|
417
|
+
if (error) reject(error);
|
|
418
|
+
else resolve(done);
|
|
419
|
+
};
|
|
420
|
+
const check = () => {
|
|
421
|
+
if (finished) return;
|
|
422
|
+
try {
|
|
423
|
+
const groupGone = isGroupGone();
|
|
424
|
+
lastProbeError = void 0;
|
|
425
|
+
if (didClose && groupGone) finish(true);
|
|
426
|
+
} catch (error) {
|
|
427
|
+
lastProbeError = error;
|
|
428
|
+
}
|
|
429
|
+
};
|
|
430
|
+
const expire = () => finish(false, lastProbeError);
|
|
431
|
+
const deadline = setTimeout(expire, shutdownWaitMs);
|
|
432
|
+
const poll = setInterval(check, 25);
|
|
433
|
+
closed.then(() => {
|
|
434
|
+
didClose = true;
|
|
435
|
+
check();
|
|
436
|
+
});
|
|
437
|
+
check();
|
|
438
|
+
});
|
|
439
|
+
}
|
|
440
|
+
/** 清理预算独立于业务超时;只持有本轮开始时仍有效的组归属。 */
|
|
441
|
+
async function stopProcessTree(child, closed, signal) {
|
|
442
|
+
let group = ownedGroups.get(child);
|
|
443
|
+
const errors = [];
|
|
444
|
+
const isGroupGone = () => {
|
|
445
|
+
if (!group) return true;
|
|
446
|
+
try {
|
|
447
|
+
node_process.default.kill(-group, 0);
|
|
448
|
+
return false;
|
|
449
|
+
} catch (error) {
|
|
450
|
+
if (error.code !== "ESRCH") throw error;
|
|
451
|
+
group = void 0;
|
|
452
|
+
ownedGroups.delete(child);
|
|
453
|
+
return true;
|
|
454
|
+
}
|
|
455
|
+
};
|
|
456
|
+
const signals = node_process.default.platform === "win32" || signal === "SIGKILL" ? [signal] : [signal, "SIGKILL"];
|
|
457
|
+
for (const nextSignal of signals) {
|
|
458
|
+
try {
|
|
459
|
+
signalOwnedTree(child, nextSignal, group);
|
|
460
|
+
} catch (error) {
|
|
461
|
+
errors.push(error);
|
|
462
|
+
}
|
|
387
463
|
try {
|
|
388
|
-
|
|
389
|
-
|
|
464
|
+
if (await waitForCleanup(closed, isGroupGone)) {
|
|
465
|
+
if (!errors.length) return;
|
|
466
|
+
break;
|
|
467
|
+
}
|
|
468
|
+
} catch (error) {
|
|
469
|
+
errors.push(error);
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
const details = errors.map((error) => error instanceof Error ? error.message : String(error)).join("\n");
|
|
473
|
+
throw new AggregateError(errors, `子进程 pid=${child.pid ?? "unknown"} 的有界清理未成功:需确认 close 和本轮进程组结束\n${details}`.trim());
|
|
474
|
+
}
|
|
475
|
+
//#endregion
|
|
476
|
+
//#region src/process.ts
|
|
477
|
+
var HBuilderXCommandError = class extends Error {
|
|
478
|
+
result;
|
|
479
|
+
cleanupError;
|
|
480
|
+
constructor(message, result, cleanupError) {
|
|
481
|
+
super(message, cleanupError ? { cause: cleanupError } : void 0);
|
|
482
|
+
this.name = "HBuilderXCommandError";
|
|
483
|
+
this.result = result;
|
|
484
|
+
if (cleanupError) this.cleanupError = cleanupError;
|
|
390
485
|
}
|
|
486
|
+
};
|
|
487
|
+
/** 保留同步请求终止的兼容入口;需要确认关闭时必须等待 spawned.stop()。 */
|
|
488
|
+
function killProcessTree(child, signal = "SIGTERM") {
|
|
489
|
+
try {
|
|
490
|
+
signalProcessTree(child, signal);
|
|
491
|
+
} catch {}
|
|
391
492
|
}
|
|
392
493
|
function createCommandResult(options, exit, logs, timedOut = false) {
|
|
393
494
|
const output = formatRecentLogs(logs);
|
|
@@ -401,21 +502,27 @@ function createCommandResult(options, exit, logs, timedOut = false) {
|
|
|
401
502
|
issue: timedOut ? createTimeoutIssue() : classifyHBuilderXOutput(output)
|
|
402
503
|
};
|
|
403
504
|
}
|
|
404
|
-
function buildCommandError(prefix, options, exit, logs, timedOut = false) {
|
|
505
|
+
function buildCommandError(prefix, options, exit, logs, timedOut = false, cleanupError) {
|
|
405
506
|
const result = createCommandResult(options, exit, logs, timedOut);
|
|
507
|
+
if (cleanupError && !timedOut) result.issue = {
|
|
508
|
+
kind: "process-exit",
|
|
509
|
+
message: "子进程清理失败,未确认关闭或进程树终止。"
|
|
510
|
+
};
|
|
406
511
|
return new HBuilderXCommandError([
|
|
407
512
|
`${prefix}: ${options.command} ${options.args.join(" ")}`,
|
|
408
513
|
`cwd=${options.cwd}`,
|
|
409
514
|
`exit=${exit.signal ?? exit.code}`,
|
|
410
515
|
`issue=${result.issue.kind}: ${result.issue.message}`,
|
|
411
516
|
result.issue.hint ? `hint=${result.issue.hint}` : "",
|
|
412
|
-
result.output
|
|
413
|
-
|
|
517
|
+
result.output,
|
|
518
|
+
cleanupError ? `cleanup=${cleanupError.message}` : ""
|
|
519
|
+
].filter(Boolean).join("\n"), result, cleanupError);
|
|
414
520
|
}
|
|
415
521
|
function spawnCommand(options) {
|
|
522
|
+
const detached = options.detached ?? node_process.default.platform !== "win32";
|
|
416
523
|
const child = (0, cross_spawn.default)(options.command, options.args, {
|
|
417
524
|
cwd: options.cwd,
|
|
418
|
-
detached
|
|
525
|
+
detached,
|
|
419
526
|
stdio: options.stdio === "inherit" ? "inherit" : [
|
|
420
527
|
"ignore",
|
|
421
528
|
"pipe",
|
|
@@ -424,14 +531,16 @@ function spawnCommand(options) {
|
|
|
424
531
|
env: {
|
|
425
532
|
...node_process.default.env,
|
|
426
533
|
...options.env,
|
|
427
|
-
NODE_OPTIONS: options.env?.NODE_OPTIONS ?? node_process.default.env
|
|
534
|
+
NODE_OPTIONS: options.env?.["NODE_OPTIONS"] ?? node_process.default.env["NODE_OPTIONS"] ?? "--max-old-space-size=8192"
|
|
428
535
|
}
|
|
429
536
|
});
|
|
537
|
+
registerProcessGroup(child, detached);
|
|
430
538
|
const logs = options.stdio === "inherit" ? [] : collectProcessOutput(child);
|
|
431
539
|
child.on("error", (error) => logs.push(`${error.message}\n`));
|
|
432
540
|
let exit;
|
|
541
|
+
let stopping;
|
|
433
542
|
const closed = new Promise((resolve) => {
|
|
434
|
-
child.
|
|
543
|
+
child.once("close", (code, signal) => {
|
|
435
544
|
exit = {
|
|
436
545
|
code,
|
|
437
546
|
signal
|
|
@@ -449,9 +558,16 @@ function spawnCommand(options) {
|
|
|
449
558
|
ensureRunning() {
|
|
450
559
|
if (exit && exit.code !== 0) throw buildCommandError("命令提前退出", options, exit, logs);
|
|
451
560
|
},
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
561
|
+
stop(signal = "SIGTERM") {
|
|
562
|
+
if (stopping) return stopping;
|
|
563
|
+
if (exit) return Promise.resolve();
|
|
564
|
+
stopping = stopProcessTree(child, closed, signal).catch((error) => {
|
|
565
|
+
throw buildCommandError("命令清理失败", options, {
|
|
566
|
+
code: child.exitCode,
|
|
567
|
+
signal: child.signalCode
|
|
568
|
+
}, logs, false, error);
|
|
569
|
+
});
|
|
570
|
+
return stopping;
|
|
455
571
|
}
|
|
456
572
|
};
|
|
457
573
|
}
|
|
@@ -460,19 +576,26 @@ async function runCommand(options) {
|
|
|
460
576
|
let timer;
|
|
461
577
|
let timedOut = false;
|
|
462
578
|
try {
|
|
463
|
-
const
|
|
579
|
+
const deadline = Symbol("deadline");
|
|
580
|
+
const outcome = await (options.timeoutMs == null ? spawned.closed : Promise.race([spawned.closed, new Promise((resolve) => {
|
|
464
581
|
timer = setTimeout(() => {
|
|
465
582
|
timedOut = true;
|
|
466
|
-
|
|
467
|
-
resolve({
|
|
468
|
-
code: null,
|
|
469
|
-
signal: "SIGTERM"
|
|
470
|
-
});
|
|
583
|
+
resolve(deadline);
|
|
471
584
|
}, options.timeoutMs);
|
|
472
585
|
})]));
|
|
586
|
+
if (outcome === deadline) try {
|
|
587
|
+
await spawned.stop();
|
|
588
|
+
} catch (error) {
|
|
589
|
+
const cleanupError = error instanceof HBuilderXCommandError ? error.cleanupError ?? error : error;
|
|
590
|
+
throw buildCommandError("命令超时且清理失败", options, {
|
|
591
|
+
code: spawned.child.exitCode,
|
|
592
|
+
signal: spawned.child.signalCode
|
|
593
|
+
}, spawned.logs, true, cleanupError);
|
|
594
|
+
}
|
|
595
|
+
const exit = outcome === deadline ? await spawned.closed : outcome;
|
|
473
596
|
const result = createCommandResult(options, exit, spawned.logs, timedOut);
|
|
474
|
-
if (exit.code === 0 || options.allowFailure) return result;
|
|
475
|
-
throw buildCommandError(
|
|
597
|
+
if (!timedOut && exit.code === 0 || options.allowFailure) return result;
|
|
598
|
+
throw buildCommandError(timedOut ? "命令超时" : "命令失败", options, exit, spawned.logs, timedOut);
|
|
476
599
|
} finally {
|
|
477
600
|
if (timer) clearTimeout(timer);
|
|
478
601
|
}
|
|
@@ -507,8 +630,12 @@ const ansiRE = new RegExp(`${String.fromCharCode(27)}\\[[\\d;]*m`, "g");
|
|
|
507
630
|
function stripAnsi(value) {
|
|
508
631
|
return value.replace(ansiRE, "");
|
|
509
632
|
}
|
|
633
|
+
/** CLI 的未启动协议响应因界面语言不同而变化,不能作为 host 名称解析。 */
|
|
634
|
+
function isStoppedHostDiagnostic(line) {
|
|
635
|
+
return /^(?:HBuilderX is not detected running\. Please execute cli open.*|没有可用的命令[,,]尝试使用\s*cli open|未检测到已打开的\s*HBuilderX[,,]请先执行\s*cli open.*)$/i.test(line.trim());
|
|
636
|
+
}
|
|
510
637
|
function parseHBuilderXHosts(output) {
|
|
511
|
-
return [...new Set(stripAnsi(output).split(/\r?\n/).map((line) => line.trim()).filter((line) => line.length > 0 && !/^-?\d+:cli:|命令.+(?:不存在|错误)|not detected running/i.test(line)))];
|
|
638
|
+
return [...new Set(stripAnsi(output).split(/\r?\n/).map((line) => line.trim()).filter((line) => line.length > 0 && !isStoppedHostDiagnostic(line) && !/^-?\d+:cli:|命令.+(?:不存在|错误)|not detected running/i.test(line)))];
|
|
512
639
|
}
|
|
513
640
|
function parseHBuilderXVersion(output) {
|
|
514
641
|
return stripAnsi(output).match(/\b(\d+\.\d+(?:\.\d+)+(?:-[0-9a-z.-]+)?)\b/i)?.[1];
|
|
@@ -574,11 +701,11 @@ async function connectHBuilderXHost(options) {
|
|
|
574
701
|
};
|
|
575
702
|
const assertCommand = (result) => {
|
|
576
703
|
if (result.issue.kind === "cli-instance-mismatch" || result.issue.kind === "cli-host-ambiguous") throw createRunnerError(cliPath, cwd, result.args, result.issue.kind, result.issue.message, result.issue.hint ?? "请检查目标 HBuilderX host。", logs);
|
|
577
|
-
if (result.exit.code !== 0) throw new HBuilderXCommandError(`HBuilderX host 命令失败:${cliPath} ${result.args.join(" ")}\ncwd=${cwd}\nexit=${result.exit.signal ?? result.exit.code}\nissue=${result.issue.kind}\n${formatRecentLogs(logs)}`, result);
|
|
704
|
+
if (result.issue.kind === "timeout" || result.exit.code !== 0) throw new HBuilderXCommandError(`HBuilderX host 命令失败:${cliPath} ${result.args.join(" ")}\ncwd=${cwd}\nexit=${result.exit.signal ?? result.exit.code}\nissue=${result.issue.kind}\n${formatRecentLogs(logs)}`, result);
|
|
578
705
|
};
|
|
579
706
|
const probe = async () => {
|
|
580
707
|
const listed = await command(["listhost"]);
|
|
581
|
-
if (!(listed.issue.kind !== "timeout" &&
|
|
708
|
+
if (!(listed.issue.kind !== "timeout" && stripAnsi(listed.output).split(/\r?\n/).some(isStoppedHostDiagnostic))) assertCommand(listed);
|
|
582
709
|
const hosts = parseHBuilderXHosts(listed.output);
|
|
583
710
|
const compatible = [];
|
|
584
711
|
for (const host of explicitHost ? [explicitHost] : hosts) {
|
|
@@ -643,11 +770,12 @@ async function createHBuilderXRunner(options = {}) {
|
|
|
643
770
|
};
|
|
644
771
|
const cwd = options.cwd ?? node_process.default.cwd();
|
|
645
772
|
const timeoutMs = options.timeoutMs ?? defaultStartupTimeoutMs;
|
|
773
|
+
const candidates = options.hbuilderxCliPath ? [options.hbuilderxCliPath] : options.candidates;
|
|
646
774
|
const resolveOptions = {
|
|
647
|
-
candidates
|
|
648
|
-
channel: options.channel,
|
|
775
|
+
...candidates !== void 0 ? { candidates } : {},
|
|
776
|
+
...options.channel !== void 0 ? { channel: options.channel } : {},
|
|
649
777
|
env,
|
|
650
|
-
host: options.host
|
|
778
|
+
...options.host !== void 0 ? { host: options.host } : {}
|
|
651
779
|
};
|
|
652
780
|
const configured = await resolveConfiguredCli(resolveOptions);
|
|
653
781
|
const resolution = configured ? {
|
|
@@ -658,15 +786,15 @@ async function createHBuilderXRunner(options = {}) {
|
|
|
658
786
|
...env,
|
|
659
787
|
HBUILDERX_CLI_PATH: resolution.path
|
|
660
788
|
};
|
|
661
|
-
const requestedChannel = resolveHBuilderXChannel(options.channel ?? env
|
|
789
|
+
const requestedChannel = resolveHBuilderXChannel(options.channel ?? env["HBUILDERX_CHANNEL"]);
|
|
662
790
|
const expectedChannel = resolution.channel !== "unknown" ? resolution.channel : requestedChannel === "auto" ? inferHBuilderXChannel(resolution.path) : requestedChannel;
|
|
663
|
-
const explicitHost = options.host ?? env
|
|
791
|
+
const explicitHost = options.host ?? env["HBUILDERX_HOST"];
|
|
664
792
|
const selected = await connectHBuilderXHost({
|
|
665
793
|
cliPath: resolution.path,
|
|
666
794
|
cwd,
|
|
667
795
|
env: cliEnv,
|
|
668
796
|
expectedChannel,
|
|
669
|
-
explicitHost,
|
|
797
|
+
...explicitHost !== void 0 ? { explicitHost } : {},
|
|
670
798
|
timeoutMs
|
|
671
799
|
});
|
|
672
800
|
const boundResolution = {
|
|
@@ -755,14 +883,14 @@ async function resolveHBuilderXCliInfo(candidatesOrOptions, env = node_process.d
|
|
|
755
883
|
}
|
|
756
884
|
async function resolveHBuilderXCli(candidatesOrOptions) {
|
|
757
885
|
const options = Array.isArray(candidatesOrOptions) ? { candidates: candidatesOrOptions } : candidatesOrOptions ?? {};
|
|
758
|
-
resolveHBuilderXChannel(options.channel ?? (options.env ?? node_process.default.env)
|
|
886
|
+
resolveHBuilderXChannel(options.channel ?? (options.env ?? node_process.default.env)["HBUILDERX_CHANNEL"]);
|
|
759
887
|
return (await resolveConfiguredCli(options))?.path ?? (await resolveHBuilderXCliInfoFromOptions(options)).path;
|
|
760
888
|
}
|
|
761
889
|
function createHBuilderXEnv(options = {}) {
|
|
762
890
|
return {
|
|
763
891
|
...options.env,
|
|
764
|
-
HBUILDERX_CLI_PATH: options.hbuilderxCliPath ?? options.env?.HBUILDERX_CLI_PATH ?? node_process.default.env
|
|
765
|
-
NODE_OPTIONS: options.env?.NODE_OPTIONS ?? node_process.default.env
|
|
892
|
+
HBUILDERX_CLI_PATH: options.hbuilderxCliPath ?? options.env?.["HBUILDERX_CLI_PATH"] ?? node_process.default.env["HBUILDERX_CLI_PATH"] ?? getDefaultHBuilderXCliCandidates()[0],
|
|
893
|
+
NODE_OPTIONS: options.env?.["NODE_OPTIONS"] ?? node_process.default.env["NODE_OPTIONS"] ?? "--max-old-space-size=8192"
|
|
766
894
|
};
|
|
767
895
|
}
|
|
768
896
|
function hbuilderxPnpmArgs(args) {
|
|
@@ -777,8 +905,8 @@ async function runPnpmCommand(options) {
|
|
|
777
905
|
command: "pnpm",
|
|
778
906
|
args: options.args,
|
|
779
907
|
cwd: options.cwd,
|
|
780
|
-
timeoutMs: options.timeoutMs,
|
|
781
|
-
allowFailure: options.allowFailure,
|
|
908
|
+
...options.timeoutMs !== void 0 ? { timeoutMs: options.timeoutMs } : {},
|
|
909
|
+
...options.allowFailure !== void 0 ? { allowFailure: options.allowFailure } : {},
|
|
782
910
|
env: createHBuilderXEnv(options)
|
|
783
911
|
});
|
|
784
912
|
}
|
|
@@ -842,9 +970,9 @@ function resolveAdbCommand(env = node_process.default.env) {
|
|
|
842
970
|
env: {}
|
|
843
971
|
};
|
|
844
972
|
const candidates = [
|
|
845
|
-
env
|
|
846
|
-
env
|
|
847
|
-
env
|
|
973
|
+
env["ANDROID_HOME"],
|
|
974
|
+
env["ANDROID_SDK_ROOT"],
|
|
975
|
+
env["HOME"] ? node_path.default.join(env["HOME"], "Library/Android/sdk") : void 0,
|
|
848
976
|
"/opt/android-sdk",
|
|
849
977
|
"/usr/local/share/android-sdk"
|
|
850
978
|
].filter((item) => Boolean(item));
|
|
@@ -855,9 +983,9 @@ function resolveAdbCommand(env = node_process.default.env) {
|
|
|
855
983
|
command: adbPath,
|
|
856
984
|
output: candidate.output,
|
|
857
985
|
env: {
|
|
858
|
-
ANDROID_HOME: env
|
|
859
|
-
ANDROID_SDK_ROOT: env
|
|
860
|
-
PATH: `${node_path.default.dirname(adbPath)}${node_path.default.delimiter}${env
|
|
986
|
+
ANDROID_HOME: env["ANDROID_HOME"] ?? sdkRoot,
|
|
987
|
+
ANDROID_SDK_ROOT: env["ANDROID_SDK_ROOT"] ?? sdkRoot,
|
|
988
|
+
PATH: `${node_path.default.dirname(adbPath)}${node_path.default.delimiter}${env["PATH"] ?? ""}`
|
|
861
989
|
}
|
|
862
990
|
};
|
|
863
991
|
}
|
|
@@ -886,7 +1014,7 @@ function assertIosSimulatorToolchain(env = node_process.default.env) {
|
|
|
886
1014
|
if (!simctl.ok || !xcodebuild.ok || firstLaunchStatus?.ok === false) throw new Error([
|
|
887
1015
|
"当前机器缺少 iOS 模拟器所需的完整 Xcode 工具链,无法运行 HBuilderX app-ios E2E。",
|
|
888
1016
|
`xcode-select: ${xcodeSelect.output || "unknown"}`,
|
|
889
|
-
`DEVELOPER_DIR: ${env
|
|
1017
|
+
`DEVELOPER_DIR: ${env["DEVELOPER_DIR"] || "未设置"}`,
|
|
890
1018
|
`simctl: ${simctl.output || "not found"}`,
|
|
891
1019
|
`xcodebuild: ${xcodebuild.output || "not found"}`,
|
|
892
1020
|
`firstLaunchStatus: ${firstLaunchStatus?.output || (firstLaunchStatus?.ok === false ? "not ready" : "unknown")}`,
|
|
@@ -932,7 +1060,7 @@ function selectPreferredIosSimulatorDevice(devices) {
|
|
|
932
1060
|
})[0];
|
|
933
1061
|
}
|
|
934
1062
|
function resolveIosSimulatorDeviceId(env = node_process.default.env) {
|
|
935
|
-
const explicitDeviceId = env
|
|
1063
|
+
const explicitDeviceId = env["E2E_HBUILDERX_IOS_DEVICE_ID"];
|
|
936
1064
|
if (explicitDeviceId) return explicitDeviceId;
|
|
937
1065
|
const booted = runTool("xcrun", [
|
|
938
1066
|
"simctl",
|
|
@@ -961,9 +1089,9 @@ function resolveIosSimulatorDeviceId(env = node_process.default.env) {
|
|
|
961
1089
|
}
|
|
962
1090
|
function resolveHdcCommand(env = node_process.default.env) {
|
|
963
1091
|
const candidates = [
|
|
964
|
-
env
|
|
965
|
-
env
|
|
966
|
-
env
|
|
1092
|
+
env["DEMO_VISUAL_HARMONY_HDC_PATH"],
|
|
1093
|
+
env["E2E_HBUILDERX_HARMONY_HDC_PATH"],
|
|
1094
|
+
env["HDC_PATH"],
|
|
967
1095
|
"hdc",
|
|
968
1096
|
node_process.default.platform === "darwin" ? "/Applications/DevEco-Studio.app/Contents/sdk/default/openharmony/toolchains/hdc" : void 0
|
|
969
1097
|
].filter((item) => Boolean(item));
|
package/dist/index.d.ts
CHANGED
|
@@ -25,6 +25,7 @@ export interface HBuilderXCommandOptions {
|
|
|
25
25
|
command: string;
|
|
26
26
|
args: string[];
|
|
27
27
|
cwd: string;
|
|
28
|
+
/** 业务截止时间;超时后另有有界进程清理预算。 */
|
|
28
29
|
timeoutMs?: number;
|
|
29
30
|
env?: Record<string, string | undefined>;
|
|
30
31
|
allowFailure?: boolean;
|
|
@@ -46,6 +47,7 @@ export interface SpawnedHBuilderXCommand {
|
|
|
46
47
|
command: string;
|
|
47
48
|
args: string[];
|
|
48
49
|
cwd: string;
|
|
50
|
+
/** 在 close 前启动有界清理并确认本轮进程树结束;失败抛出诊断,多次调用复用同一结果。 */
|
|
49
51
|
stop: (signal?: NodeJS.Signals) => Promise<void>;
|
|
50
52
|
closed: Promise<CommandExit>;
|
|
51
53
|
ensureRunning: () => void;
|
|
@@ -138,8 +140,10 @@ export declare function resolveHBuilderXCliInfoFromOptions(options?: HBuilderXCl
|
|
|
138
140
|
//#region src/process.d.ts
|
|
139
141
|
export declare class HBuilderXCommandError extends Error {
|
|
140
142
|
readonly result: HBuilderXCommandResult;
|
|
141
|
-
|
|
143
|
+
readonly cleanupError?: Error;
|
|
144
|
+
constructor(message: string, result: HBuilderXCommandResult, cleanupError?: Error);
|
|
142
145
|
}
|
|
146
|
+
/** 保留同步请求终止的兼容入口;需要确认关闭时必须等待 spawned.stop()。 */
|
|
143
147
|
export declare function killProcessTree(child: ChildProcess, signal?: NodeJS.Signals): void;
|
|
144
148
|
export declare function spawnCommand(options: HBuilderXCommandOptions): SpawnedHBuilderXCommand;
|
|
145
149
|
export declare function runCommand(options: HBuilderXCommandOptions): Promise<HBuilderXCommandResult>;
|
package/dist/index.mjs
CHANGED
|
@@ -24,7 +24,7 @@ function wait(ms) {
|
|
|
24
24
|
const macOSStableCli = "/Applications/HBuilderX.app/Contents/MacOS/cli";
|
|
25
25
|
const macOSAlphaCli = "/Applications/HBuilderX-Alpha.app/Contents/MacOS/cli";
|
|
26
26
|
function resolveCandidateSource(candidate, env) {
|
|
27
|
-
if (candidate === env
|
|
27
|
+
if (candidate === env["HBUILDERX_CLI_PATH"]) return "env";
|
|
28
28
|
if (candidate === "/Applications/HBuilderX.app/Contents/MacOS/cli" || candidate === "/Applications/HBuilderX-Alpha.app/Contents/MacOS/cli") return "default-path";
|
|
29
29
|
return "candidate";
|
|
30
30
|
}
|
|
@@ -41,8 +41,8 @@ async function resolveConfiguredCli(options) {
|
|
|
41
41
|
source: resolveCandidateSource(candidate, env)
|
|
42
42
|
};
|
|
43
43
|
}
|
|
44
|
-
if (env
|
|
45
|
-
path: env
|
|
44
|
+
if (env["HBUILDERX_CLI_PATH"] && await fileExists(env["HBUILDERX_CLI_PATH"])) return {
|
|
45
|
+
path: env["HBUILDERX_CLI_PATH"],
|
|
46
46
|
source: "env"
|
|
47
47
|
};
|
|
48
48
|
}
|
|
@@ -65,9 +65,9 @@ function inferHBuilderXChannel(file) {
|
|
|
65
65
|
if (/HBuilderX(?:\.app)?[\\/]/i.test(file) || /HBuilderX\.exe$/i.test(file)) return "stable";
|
|
66
66
|
return "unknown";
|
|
67
67
|
}
|
|
68
|
-
function getDefaultHBuilderXCliCandidates(env = process.env, channel = resolveHBuilderXChannel(env
|
|
68
|
+
function getDefaultHBuilderXCliCandidates(env = process.env, channel = resolveHBuilderXChannel(env["HBUILDERX_CHANNEL"]), platform = process.platform) {
|
|
69
69
|
const defaults = platform === "darwin" ? channel === "stable" ? [macOSStableCli] : channel === "alpha" ? [macOSAlphaCli] : [macOSStableCli, macOSAlphaCli] : [];
|
|
70
|
-
return unique([env
|
|
70
|
+
return unique([env["HBUILDERX_CLI_PATH"], ...defaults].filter((item) => Boolean(item)));
|
|
71
71
|
}
|
|
72
72
|
function extractHBuilderXMacOSExecutables(output) {
|
|
73
73
|
return unique(Array.from(output.matchAll(/(\/[^\r\n]*?HBuilderX(?:-Alpha|\s+Alpha)?\.app\/Contents\/MacOS\/HBuilderX)(?=\s|$)/gi), (match) => match[1]));
|
|
@@ -175,7 +175,7 @@ async function firstExisting(items) {
|
|
|
175
175
|
}
|
|
176
176
|
async function resolveHBuilderXCliInfoFromOptions(options = {}) {
|
|
177
177
|
const env = options.env ?? process.env;
|
|
178
|
-
const channel = resolveHBuilderXChannel(options.channel ?? env
|
|
178
|
+
const channel = resolveHBuilderXChannel(options.channel ?? env["HBUILDERX_CHANNEL"]);
|
|
179
179
|
const running = await findRunningHBuilderXCliCandidates();
|
|
180
180
|
const configured = await resolveConfiguredCli(options);
|
|
181
181
|
if (configured) return {
|
|
@@ -330,37 +330,138 @@ function formatRecentLogs(logs, maxLength = 6e3) {
|
|
|
330
330
|
return important.length > 0 ? `关键错误:\n${important.join("\n")}\n\n最近日志:\n${recent}` : recent;
|
|
331
331
|
}
|
|
332
332
|
//#endregion
|
|
333
|
-
//#region src/process.ts
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
333
|
+
//#region src/process/termination.ts
|
|
334
|
+
const ownedGroups = /* @__PURE__ */ new WeakMap();
|
|
335
|
+
const closedChildren = /* @__PURE__ */ new WeakSet();
|
|
336
|
+
const shutdownWaitMs = 1e3;
|
|
337
|
+
/** 只记录本次 spawn 创建的独立进程组,不从外部 PID 猜测组归属。 */
|
|
338
|
+
function registerProcessGroup(child, detached) {
|
|
339
|
+
if (process.platform !== "win32" && detached && child.pid) ownedGroups.set(child, child.pid);
|
|
340
|
+
child.once("close", () => {
|
|
341
|
+
closedChildren.add(child);
|
|
342
|
+
ownedGroups.delete(child);
|
|
343
|
+
});
|
|
344
|
+
}
|
|
345
|
+
function signalOwnedTree(child, signal, group) {
|
|
346
|
+
if (!child.pid) return;
|
|
345
347
|
if (process.platform === "win32") {
|
|
346
|
-
|
|
348
|
+
if (child.exitCode !== null || child.signalCode !== null || closedChildren.has(child)) return;
|
|
349
|
+
const result = spawnSync("taskkill", [
|
|
347
350
|
"/pid",
|
|
348
|
-
String(pid),
|
|
351
|
+
String(child.pid),
|
|
349
352
|
"/t",
|
|
350
353
|
"/f"
|
|
351
354
|
], {
|
|
352
|
-
|
|
355
|
+
timeout: 5e3,
|
|
356
|
+
killSignal: "SIGKILL",
|
|
357
|
+
maxBuffer: 65536,
|
|
358
|
+
encoding: "utf8",
|
|
359
|
+
stdio: [
|
|
360
|
+
"ignore",
|
|
361
|
+
"pipe",
|
|
362
|
+
"pipe"
|
|
363
|
+
],
|
|
353
364
|
windowsHide: true
|
|
354
365
|
});
|
|
366
|
+
if (result.error || result.status !== 0) throw new Error(`taskkill pid=${child.pid} 失败,exit=${result.status} signal=${result.signal}\n${result.error?.message ?? ""}\n${result.stderr ?? ""}\n${result.stdout ?? ""}`, { cause: result.error });
|
|
355
367
|
return;
|
|
356
368
|
}
|
|
357
|
-
try {
|
|
358
|
-
process.kill(-
|
|
359
|
-
|
|
369
|
+
if (group) try {
|
|
370
|
+
process.kill(-group, signal);
|
|
371
|
+
return;
|
|
372
|
+
} catch (error) {
|
|
373
|
+
if (error.code !== "ESRCH") throw error;
|
|
374
|
+
}
|
|
375
|
+
if (!closedChildren.has(child) && child.exitCode === null && child.signalCode === null && !child.kill(signal)) throw new Error(`未能向子进程 pid=${child.pid} 发送 ${signal}`);
|
|
376
|
+
}
|
|
377
|
+
/** 同步入口在 close 后失效,避免稍后向复用的 PID 或进程组发送信号。 */
|
|
378
|
+
function signalProcessTree(child, signal) {
|
|
379
|
+
if (!closedChildren.has(child)) signalOwnedTree(child, signal, ownedGroups.get(child));
|
|
380
|
+
}
|
|
381
|
+
function waitForCleanup(closed, isGroupGone) {
|
|
382
|
+
return new Promise((resolve, reject) => {
|
|
383
|
+
let didClose = false;
|
|
384
|
+
let finished = false;
|
|
385
|
+
let lastProbeError;
|
|
386
|
+
const finish = (done, error) => {
|
|
387
|
+
finished = true;
|
|
388
|
+
clearTimeout(deadline);
|
|
389
|
+
clearInterval(poll);
|
|
390
|
+
if (error) reject(error);
|
|
391
|
+
else resolve(done);
|
|
392
|
+
};
|
|
393
|
+
const check = () => {
|
|
394
|
+
if (finished) return;
|
|
395
|
+
try {
|
|
396
|
+
const groupGone = isGroupGone();
|
|
397
|
+
lastProbeError = void 0;
|
|
398
|
+
if (didClose && groupGone) finish(true);
|
|
399
|
+
} catch (error) {
|
|
400
|
+
lastProbeError = error;
|
|
401
|
+
}
|
|
402
|
+
};
|
|
403
|
+
const expire = () => finish(false, lastProbeError);
|
|
404
|
+
const deadline = setTimeout(expire, shutdownWaitMs);
|
|
405
|
+
const poll = setInterval(check, 25);
|
|
406
|
+
closed.then(() => {
|
|
407
|
+
didClose = true;
|
|
408
|
+
check();
|
|
409
|
+
});
|
|
410
|
+
check();
|
|
411
|
+
});
|
|
412
|
+
}
|
|
413
|
+
/** 清理预算独立于业务超时;只持有本轮开始时仍有效的组归属。 */
|
|
414
|
+
async function stopProcessTree(child, closed, signal) {
|
|
415
|
+
let group = ownedGroups.get(child);
|
|
416
|
+
const errors = [];
|
|
417
|
+
const isGroupGone = () => {
|
|
418
|
+
if (!group) return true;
|
|
419
|
+
try {
|
|
420
|
+
process.kill(-group, 0);
|
|
421
|
+
return false;
|
|
422
|
+
} catch (error) {
|
|
423
|
+
if (error.code !== "ESRCH") throw error;
|
|
424
|
+
group = void 0;
|
|
425
|
+
ownedGroups.delete(child);
|
|
426
|
+
return true;
|
|
427
|
+
}
|
|
428
|
+
};
|
|
429
|
+
const signals = process.platform === "win32" || signal === "SIGKILL" ? [signal] : [signal, "SIGKILL"];
|
|
430
|
+
for (const nextSignal of signals) {
|
|
431
|
+
try {
|
|
432
|
+
signalOwnedTree(child, nextSignal, group);
|
|
433
|
+
} catch (error) {
|
|
434
|
+
errors.push(error);
|
|
435
|
+
}
|
|
360
436
|
try {
|
|
361
|
-
|
|
362
|
-
|
|
437
|
+
if (await waitForCleanup(closed, isGroupGone)) {
|
|
438
|
+
if (!errors.length) return;
|
|
439
|
+
break;
|
|
440
|
+
}
|
|
441
|
+
} catch (error) {
|
|
442
|
+
errors.push(error);
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
const details = errors.map((error) => error instanceof Error ? error.message : String(error)).join("\n");
|
|
446
|
+
throw new AggregateError(errors, `子进程 pid=${child.pid ?? "unknown"} 的有界清理未成功:需确认 close 和本轮进程组结束\n${details}`.trim());
|
|
447
|
+
}
|
|
448
|
+
//#endregion
|
|
449
|
+
//#region src/process.ts
|
|
450
|
+
var HBuilderXCommandError = class extends Error {
|
|
451
|
+
result;
|
|
452
|
+
cleanupError;
|
|
453
|
+
constructor(message, result, cleanupError) {
|
|
454
|
+
super(message, cleanupError ? { cause: cleanupError } : void 0);
|
|
455
|
+
this.name = "HBuilderXCommandError";
|
|
456
|
+
this.result = result;
|
|
457
|
+
if (cleanupError) this.cleanupError = cleanupError;
|
|
363
458
|
}
|
|
459
|
+
};
|
|
460
|
+
/** 保留同步请求终止的兼容入口;需要确认关闭时必须等待 spawned.stop()。 */
|
|
461
|
+
function killProcessTree(child, signal = "SIGTERM") {
|
|
462
|
+
try {
|
|
463
|
+
signalProcessTree(child, signal);
|
|
464
|
+
} catch {}
|
|
364
465
|
}
|
|
365
466
|
function createCommandResult(options, exit, logs, timedOut = false) {
|
|
366
467
|
const output = formatRecentLogs(logs);
|
|
@@ -374,21 +475,27 @@ function createCommandResult(options, exit, logs, timedOut = false) {
|
|
|
374
475
|
issue: timedOut ? createTimeoutIssue() : classifyHBuilderXOutput(output)
|
|
375
476
|
};
|
|
376
477
|
}
|
|
377
|
-
function buildCommandError(prefix, options, exit, logs, timedOut = false) {
|
|
478
|
+
function buildCommandError(prefix, options, exit, logs, timedOut = false, cleanupError) {
|
|
378
479
|
const result = createCommandResult(options, exit, logs, timedOut);
|
|
480
|
+
if (cleanupError && !timedOut) result.issue = {
|
|
481
|
+
kind: "process-exit",
|
|
482
|
+
message: "子进程清理失败,未确认关闭或进程树终止。"
|
|
483
|
+
};
|
|
379
484
|
return new HBuilderXCommandError([
|
|
380
485
|
`${prefix}: ${options.command} ${options.args.join(" ")}`,
|
|
381
486
|
`cwd=${options.cwd}`,
|
|
382
487
|
`exit=${exit.signal ?? exit.code}`,
|
|
383
488
|
`issue=${result.issue.kind}: ${result.issue.message}`,
|
|
384
489
|
result.issue.hint ? `hint=${result.issue.hint}` : "",
|
|
385
|
-
result.output
|
|
386
|
-
|
|
490
|
+
result.output,
|
|
491
|
+
cleanupError ? `cleanup=${cleanupError.message}` : ""
|
|
492
|
+
].filter(Boolean).join("\n"), result, cleanupError);
|
|
387
493
|
}
|
|
388
494
|
function spawnCommand(options) {
|
|
495
|
+
const detached = options.detached ?? process.platform !== "win32";
|
|
389
496
|
const child = spawn(options.command, options.args, {
|
|
390
497
|
cwd: options.cwd,
|
|
391
|
-
detached
|
|
498
|
+
detached,
|
|
392
499
|
stdio: options.stdio === "inherit" ? "inherit" : [
|
|
393
500
|
"ignore",
|
|
394
501
|
"pipe",
|
|
@@ -397,14 +504,16 @@ function spawnCommand(options) {
|
|
|
397
504
|
env: {
|
|
398
505
|
...process.env,
|
|
399
506
|
...options.env,
|
|
400
|
-
NODE_OPTIONS: options.env?.NODE_OPTIONS ?? process.env
|
|
507
|
+
NODE_OPTIONS: options.env?.["NODE_OPTIONS"] ?? process.env["NODE_OPTIONS"] ?? "--max-old-space-size=8192"
|
|
401
508
|
}
|
|
402
509
|
});
|
|
510
|
+
registerProcessGroup(child, detached);
|
|
403
511
|
const logs = options.stdio === "inherit" ? [] : collectProcessOutput(child);
|
|
404
512
|
child.on("error", (error) => logs.push(`${error.message}\n`));
|
|
405
513
|
let exit;
|
|
514
|
+
let stopping;
|
|
406
515
|
const closed = new Promise((resolve) => {
|
|
407
|
-
child.
|
|
516
|
+
child.once("close", (code, signal) => {
|
|
408
517
|
exit = {
|
|
409
518
|
code,
|
|
410
519
|
signal
|
|
@@ -422,9 +531,16 @@ function spawnCommand(options) {
|
|
|
422
531
|
ensureRunning() {
|
|
423
532
|
if (exit && exit.code !== 0) throw buildCommandError("命令提前退出", options, exit, logs);
|
|
424
533
|
},
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
534
|
+
stop(signal = "SIGTERM") {
|
|
535
|
+
if (stopping) return stopping;
|
|
536
|
+
if (exit) return Promise.resolve();
|
|
537
|
+
stopping = stopProcessTree(child, closed, signal).catch((error) => {
|
|
538
|
+
throw buildCommandError("命令清理失败", options, {
|
|
539
|
+
code: child.exitCode,
|
|
540
|
+
signal: child.signalCode
|
|
541
|
+
}, logs, false, error);
|
|
542
|
+
});
|
|
543
|
+
return stopping;
|
|
428
544
|
}
|
|
429
545
|
};
|
|
430
546
|
}
|
|
@@ -433,19 +549,26 @@ async function runCommand(options) {
|
|
|
433
549
|
let timer;
|
|
434
550
|
let timedOut = false;
|
|
435
551
|
try {
|
|
436
|
-
const
|
|
552
|
+
const deadline = Symbol("deadline");
|
|
553
|
+
const outcome = await (options.timeoutMs == null ? spawned.closed : Promise.race([spawned.closed, new Promise((resolve) => {
|
|
437
554
|
timer = setTimeout(() => {
|
|
438
555
|
timedOut = true;
|
|
439
|
-
|
|
440
|
-
resolve({
|
|
441
|
-
code: null,
|
|
442
|
-
signal: "SIGTERM"
|
|
443
|
-
});
|
|
556
|
+
resolve(deadline);
|
|
444
557
|
}, options.timeoutMs);
|
|
445
558
|
})]));
|
|
559
|
+
if (outcome === deadline) try {
|
|
560
|
+
await spawned.stop();
|
|
561
|
+
} catch (error) {
|
|
562
|
+
const cleanupError = error instanceof HBuilderXCommandError ? error.cleanupError ?? error : error;
|
|
563
|
+
throw buildCommandError("命令超时且清理失败", options, {
|
|
564
|
+
code: spawned.child.exitCode,
|
|
565
|
+
signal: spawned.child.signalCode
|
|
566
|
+
}, spawned.logs, true, cleanupError);
|
|
567
|
+
}
|
|
568
|
+
const exit = outcome === deadline ? await spawned.closed : outcome;
|
|
446
569
|
const result = createCommandResult(options, exit, spawned.logs, timedOut);
|
|
447
|
-
if (exit.code === 0 || options.allowFailure) return result;
|
|
448
|
-
throw buildCommandError(
|
|
570
|
+
if (!timedOut && exit.code === 0 || options.allowFailure) return result;
|
|
571
|
+
throw buildCommandError(timedOut ? "命令超时" : "命令失败", options, exit, spawned.logs, timedOut);
|
|
449
572
|
} finally {
|
|
450
573
|
if (timer) clearTimeout(timer);
|
|
451
574
|
}
|
|
@@ -480,8 +603,12 @@ const ansiRE = new RegExp(`${String.fromCharCode(27)}\\[[\\d;]*m`, "g");
|
|
|
480
603
|
function stripAnsi(value) {
|
|
481
604
|
return value.replace(ansiRE, "");
|
|
482
605
|
}
|
|
606
|
+
/** CLI 的未启动协议响应因界面语言不同而变化,不能作为 host 名称解析。 */
|
|
607
|
+
function isStoppedHostDiagnostic(line) {
|
|
608
|
+
return /^(?:HBuilderX is not detected running\. Please execute cli open.*|没有可用的命令[,,]尝试使用\s*cli open|未检测到已打开的\s*HBuilderX[,,]请先执行\s*cli open.*)$/i.test(line.trim());
|
|
609
|
+
}
|
|
483
610
|
function parseHBuilderXHosts(output) {
|
|
484
|
-
return [...new Set(stripAnsi(output).split(/\r?\n/).map((line) => line.trim()).filter((line) => line.length > 0 && !/^-?\d+:cli:|命令.+(?:不存在|错误)|not detected running/i.test(line)))];
|
|
611
|
+
return [...new Set(stripAnsi(output).split(/\r?\n/).map((line) => line.trim()).filter((line) => line.length > 0 && !isStoppedHostDiagnostic(line) && !/^-?\d+:cli:|命令.+(?:不存在|错误)|not detected running/i.test(line)))];
|
|
485
612
|
}
|
|
486
613
|
function parseHBuilderXVersion(output) {
|
|
487
614
|
return stripAnsi(output).match(/\b(\d+\.\d+(?:\.\d+)+(?:-[0-9a-z.-]+)?)\b/i)?.[1];
|
|
@@ -547,11 +674,11 @@ async function connectHBuilderXHost(options) {
|
|
|
547
674
|
};
|
|
548
675
|
const assertCommand = (result) => {
|
|
549
676
|
if (result.issue.kind === "cli-instance-mismatch" || result.issue.kind === "cli-host-ambiguous") throw createRunnerError(cliPath, cwd, result.args, result.issue.kind, result.issue.message, result.issue.hint ?? "请检查目标 HBuilderX host。", logs);
|
|
550
|
-
if (result.exit.code !== 0) throw new HBuilderXCommandError(`HBuilderX host 命令失败:${cliPath} ${result.args.join(" ")}\ncwd=${cwd}\nexit=${result.exit.signal ?? result.exit.code}\nissue=${result.issue.kind}\n${formatRecentLogs(logs)}`, result);
|
|
677
|
+
if (result.issue.kind === "timeout" || result.exit.code !== 0) throw new HBuilderXCommandError(`HBuilderX host 命令失败:${cliPath} ${result.args.join(" ")}\ncwd=${cwd}\nexit=${result.exit.signal ?? result.exit.code}\nissue=${result.issue.kind}\n${formatRecentLogs(logs)}`, result);
|
|
551
678
|
};
|
|
552
679
|
const probe = async () => {
|
|
553
680
|
const listed = await command(["listhost"]);
|
|
554
|
-
if (!(listed.issue.kind !== "timeout" &&
|
|
681
|
+
if (!(listed.issue.kind !== "timeout" && stripAnsi(listed.output).split(/\r?\n/).some(isStoppedHostDiagnostic))) assertCommand(listed);
|
|
555
682
|
const hosts = parseHBuilderXHosts(listed.output);
|
|
556
683
|
const compatible = [];
|
|
557
684
|
for (const host of explicitHost ? [explicitHost] : hosts) {
|
|
@@ -616,11 +743,12 @@ async function createHBuilderXRunner(options = {}) {
|
|
|
616
743
|
};
|
|
617
744
|
const cwd = options.cwd ?? process.cwd();
|
|
618
745
|
const timeoutMs = options.timeoutMs ?? defaultStartupTimeoutMs;
|
|
746
|
+
const candidates = options.hbuilderxCliPath ? [options.hbuilderxCliPath] : options.candidates;
|
|
619
747
|
const resolveOptions = {
|
|
620
|
-
candidates
|
|
621
|
-
channel: options.channel,
|
|
748
|
+
...candidates !== void 0 ? { candidates } : {},
|
|
749
|
+
...options.channel !== void 0 ? { channel: options.channel } : {},
|
|
622
750
|
env,
|
|
623
|
-
host: options.host
|
|
751
|
+
...options.host !== void 0 ? { host: options.host } : {}
|
|
624
752
|
};
|
|
625
753
|
const configured = await resolveConfiguredCli(resolveOptions);
|
|
626
754
|
const resolution = configured ? {
|
|
@@ -631,15 +759,15 @@ async function createHBuilderXRunner(options = {}) {
|
|
|
631
759
|
...env,
|
|
632
760
|
HBUILDERX_CLI_PATH: resolution.path
|
|
633
761
|
};
|
|
634
|
-
const requestedChannel = resolveHBuilderXChannel(options.channel ?? env
|
|
762
|
+
const requestedChannel = resolveHBuilderXChannel(options.channel ?? env["HBUILDERX_CHANNEL"]);
|
|
635
763
|
const expectedChannel = resolution.channel !== "unknown" ? resolution.channel : requestedChannel === "auto" ? inferHBuilderXChannel(resolution.path) : requestedChannel;
|
|
636
|
-
const explicitHost = options.host ?? env
|
|
764
|
+
const explicitHost = options.host ?? env["HBUILDERX_HOST"];
|
|
637
765
|
const selected = await connectHBuilderXHost({
|
|
638
766
|
cliPath: resolution.path,
|
|
639
767
|
cwd,
|
|
640
768
|
env: cliEnv,
|
|
641
769
|
expectedChannel,
|
|
642
|
-
explicitHost,
|
|
770
|
+
...explicitHost !== void 0 ? { explicitHost } : {},
|
|
643
771
|
timeoutMs
|
|
644
772
|
});
|
|
645
773
|
const boundResolution = {
|
|
@@ -728,14 +856,14 @@ async function resolveHBuilderXCliInfo(candidatesOrOptions, env = process.env) {
|
|
|
728
856
|
}
|
|
729
857
|
async function resolveHBuilderXCli(candidatesOrOptions) {
|
|
730
858
|
const options = Array.isArray(candidatesOrOptions) ? { candidates: candidatesOrOptions } : candidatesOrOptions ?? {};
|
|
731
|
-
resolveHBuilderXChannel(options.channel ?? (options.env ?? process.env)
|
|
859
|
+
resolveHBuilderXChannel(options.channel ?? (options.env ?? process.env)["HBUILDERX_CHANNEL"]);
|
|
732
860
|
return (await resolveConfiguredCli(options))?.path ?? (await resolveHBuilderXCliInfoFromOptions(options)).path;
|
|
733
861
|
}
|
|
734
862
|
function createHBuilderXEnv(options = {}) {
|
|
735
863
|
return {
|
|
736
864
|
...options.env,
|
|
737
|
-
HBUILDERX_CLI_PATH: options.hbuilderxCliPath ?? options.env?.HBUILDERX_CLI_PATH ?? process.env
|
|
738
|
-
NODE_OPTIONS: options.env?.NODE_OPTIONS ?? process.env
|
|
865
|
+
HBUILDERX_CLI_PATH: options.hbuilderxCliPath ?? options.env?.["HBUILDERX_CLI_PATH"] ?? process.env["HBUILDERX_CLI_PATH"] ?? getDefaultHBuilderXCliCandidates()[0],
|
|
866
|
+
NODE_OPTIONS: options.env?.["NODE_OPTIONS"] ?? process.env["NODE_OPTIONS"] ?? "--max-old-space-size=8192"
|
|
739
867
|
};
|
|
740
868
|
}
|
|
741
869
|
function hbuilderxPnpmArgs(args) {
|
|
@@ -750,8 +878,8 @@ async function runPnpmCommand(options) {
|
|
|
750
878
|
command: "pnpm",
|
|
751
879
|
args: options.args,
|
|
752
880
|
cwd: options.cwd,
|
|
753
|
-
timeoutMs: options.timeoutMs,
|
|
754
|
-
allowFailure: options.allowFailure,
|
|
881
|
+
...options.timeoutMs !== void 0 ? { timeoutMs: options.timeoutMs } : {},
|
|
882
|
+
...options.allowFailure !== void 0 ? { allowFailure: options.allowFailure } : {},
|
|
755
883
|
env: createHBuilderXEnv(options)
|
|
756
884
|
});
|
|
757
885
|
}
|
|
@@ -815,9 +943,9 @@ function resolveAdbCommand(env = process.env) {
|
|
|
815
943
|
env: {}
|
|
816
944
|
};
|
|
817
945
|
const candidates = [
|
|
818
|
-
env
|
|
819
|
-
env
|
|
820
|
-
env
|
|
946
|
+
env["ANDROID_HOME"],
|
|
947
|
+
env["ANDROID_SDK_ROOT"],
|
|
948
|
+
env["HOME"] ? path.join(env["HOME"], "Library/Android/sdk") : void 0,
|
|
821
949
|
"/opt/android-sdk",
|
|
822
950
|
"/usr/local/share/android-sdk"
|
|
823
951
|
].filter((item) => Boolean(item));
|
|
@@ -828,9 +956,9 @@ function resolveAdbCommand(env = process.env) {
|
|
|
828
956
|
command: adbPath,
|
|
829
957
|
output: candidate.output,
|
|
830
958
|
env: {
|
|
831
|
-
ANDROID_HOME: env
|
|
832
|
-
ANDROID_SDK_ROOT: env
|
|
833
|
-
PATH: `${path.dirname(adbPath)}${path.delimiter}${env
|
|
959
|
+
ANDROID_HOME: env["ANDROID_HOME"] ?? sdkRoot,
|
|
960
|
+
ANDROID_SDK_ROOT: env["ANDROID_SDK_ROOT"] ?? sdkRoot,
|
|
961
|
+
PATH: `${path.dirname(adbPath)}${path.delimiter}${env["PATH"] ?? ""}`
|
|
834
962
|
}
|
|
835
963
|
};
|
|
836
964
|
}
|
|
@@ -859,7 +987,7 @@ function assertIosSimulatorToolchain(env = process.env) {
|
|
|
859
987
|
if (!simctl.ok || !xcodebuild.ok || firstLaunchStatus?.ok === false) throw new Error([
|
|
860
988
|
"当前机器缺少 iOS 模拟器所需的完整 Xcode 工具链,无法运行 HBuilderX app-ios E2E。",
|
|
861
989
|
`xcode-select: ${xcodeSelect.output || "unknown"}`,
|
|
862
|
-
`DEVELOPER_DIR: ${env
|
|
990
|
+
`DEVELOPER_DIR: ${env["DEVELOPER_DIR"] || "未设置"}`,
|
|
863
991
|
`simctl: ${simctl.output || "not found"}`,
|
|
864
992
|
`xcodebuild: ${xcodebuild.output || "not found"}`,
|
|
865
993
|
`firstLaunchStatus: ${firstLaunchStatus?.output || (firstLaunchStatus?.ok === false ? "not ready" : "unknown")}`,
|
|
@@ -905,7 +1033,7 @@ function selectPreferredIosSimulatorDevice(devices) {
|
|
|
905
1033
|
})[0];
|
|
906
1034
|
}
|
|
907
1035
|
function resolveIosSimulatorDeviceId(env = process.env) {
|
|
908
|
-
const explicitDeviceId = env
|
|
1036
|
+
const explicitDeviceId = env["E2E_HBUILDERX_IOS_DEVICE_ID"];
|
|
909
1037
|
if (explicitDeviceId) return explicitDeviceId;
|
|
910
1038
|
const booted = runTool("xcrun", [
|
|
911
1039
|
"simctl",
|
|
@@ -934,9 +1062,9 @@ function resolveIosSimulatorDeviceId(env = process.env) {
|
|
|
934
1062
|
}
|
|
935
1063
|
function resolveHdcCommand(env = process.env) {
|
|
936
1064
|
const candidates = [
|
|
937
|
-
env
|
|
938
|
-
env
|
|
939
|
-
env
|
|
1065
|
+
env["DEMO_VISUAL_HARMONY_HDC_PATH"],
|
|
1066
|
+
env["E2E_HBUILDERX_HARMONY_HDC_PATH"],
|
|
1067
|
+
env["HDC_PATH"],
|
|
940
1068
|
"hdc",
|
|
941
1069
|
process.platform === "darwin" ? "/Applications/DevEco-Studio.app/Contents/sdk/default/openharmony/toolchains/hdc" : void 0
|
|
942
1070
|
].filter((item) => Boolean(item));
|
package/package.json
CHANGED
|
@@ -1,18 +1,18 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@weapp-tailwindcss/hbuilderx-runner",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "0.1.
|
|
4
|
+
"version": "0.1.7",
|
|
5
5
|
"description": "HBuilderX runner utilities for cross-platform uni-app Tailwind CSS workflows. 跨端 uni-app Tailwind CSS 工作流的 HBuilderX 运行器工具。",
|
|
6
6
|
"author": "ice breaker <1324318532@qq.com>",
|
|
7
7
|
"license": "MIT",
|
|
8
8
|
"homepage": "https://tw.weapp.dev/docs/quick-start/frameworks/hbuilderx",
|
|
9
9
|
"repository": {
|
|
10
10
|
"type": "git",
|
|
11
|
-
"url": "git+https://github.com/
|
|
11
|
+
"url": "git+https://github.com/weapp-tailwindcss/weapp-tailwindcss.git",
|
|
12
12
|
"directory": "packages/hbuilderx-runner"
|
|
13
13
|
},
|
|
14
14
|
"bugs": {
|
|
15
|
-
"url": "https://github.com/
|
|
15
|
+
"url": "https://github.com/weapp-tailwindcss/weapp-tailwindcss/issues"
|
|
16
16
|
},
|
|
17
17
|
"keywords": [
|
|
18
18
|
"hbuilderx",
|
|
@@ -52,6 +52,7 @@
|
|
|
52
52
|
"dev": "tsdown --watch --sourcemap",
|
|
53
53
|
"build": "tsdown",
|
|
54
54
|
"test": "vitest run",
|
|
55
|
+
"typecheck": "tsc -p tsconfig.json --pretty false",
|
|
55
56
|
"test:dev": "vitest",
|
|
56
57
|
"release": "pnpm publish",
|
|
57
58
|
"lint": "eslint .",
|