feat(cli): cover OpenAPI with a remote npm CLI and internal panel tools (#3074)

* feat(cli): add unified Commander CLI for QingLong 2.x

* fix(cli): publish via npm and address security review feedback

* ci(cli): package npm artifacts and remove evaluation collateral

* test(cli): use a fixed shell fixture for log retention

* refactor(cli): separate remote npm client from panel tools

* feat(cli): cover active panel OpenAPI resources

* docs(cli): unify authentication and skill guidance

* refactor(cli): isolate internal commands and generate Commander help

* refactor(cli): organize remote and internal modules by responsibility

* ci(cli): publish verified npm archives from master

* fix(cli): publish under the whyour npm scope

* ci: use npm trusted publishing for both packages

* docs: introduce the published CLI on the project homepage

* fix(cli): preserve server log truncation and correct login hints

* fix(cli): accept dashboard record request bodies

* fix(cli): preserve stdin for local task execution

* fix(cli): resolve task executables after changing directory

* fix(cli): preserve shell function tasks and sanitize test failures

* fix(cli): preserve shell hook state and resolve workdir after hooks

* fix(cli): preserve cleanup across shared shell task timeouts

* fix(cli): isolate shell control descriptors and reap timed-out descendants
This commit is contained in:
whyour
2026-09-25 23:24:41 +08:00
committed by GitHub
parent f051135fc4
commit 801a71d740
185 changed files with 22412 additions and 6 deletions
+43
View File
@@ -0,0 +1,43 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { parse } = require('../helpers/commands.cjs');
const { parseExecution } = require('../../dist/runner');
const fs = require('node:fs');
const path = require('node:path');
test('Commander adapter preserves literal values, option polarity, duplicate errors and IDs', () => {
assert.equal(parse(['task','list','--search','00123']).values.search, '00123');
assert.equal(parse(['local','start','--no-startup'], 'local').values['no-startup'], true);
assert.equal(parse(['local','start'], 'local').values['no-startup'], undefined);
assert.equal(parse(['auth','login','--url=--json']).values.url, '--json');
assert.deepEqual(parse(['local','resetpwd','--','-literal'], 'local').positionals, ['-literal']);
for (const args of [
['task','list','--search','--json'], ['auth','login','--url','--json'],
['task','list','-p','2','--page','3'], ['task','list','--json','--json'],
['--json','task','list','--json'], ['task','list','unexpected'],
['task','run','0'], ['task','run','script.js'], ['task','list','--size','201'],
['task','list','--json=false'],
]) assert.throws(() => parse(args), { exitCode:2 }, JSON.stringify(args));
assert.ok(parse(['auth','login','--help']).help);
assert.ok(parse(['--help']).help);
});
test('Commander task parsing stops at the script and preserves the execution separator', () => {
const args = ['--root','/isolated','--json','script.sh','now','--','--json','--root','-literal'];
const parsed = parseExecution(args);
assert.equal(parsed.values.root, '/isolated');
assert.equal(parsed.values.json, true);
assert.deepEqual(parsed.execution.scriptArgs, ['--json','--root','-literal']);
assert.deepEqual(parseExecution(['script.sh','--json']).execution.argv, ['script.sh','--json']);
assert.deepEqual(parseExecution(['--','-script','--','-x']).execution.scriptArgs, ['-x']);
assert.throws(() => parseExecution(['--root','--json','script.sh']), { exitCode:2 });
});
test('Commander is bundled once with its license and has no external runtime resolution', () => {
const manifest = require('../../package.json');
assert.equal(manifest.devDependencies.commander, '15.0.0');
assert.equal(Object.keys(manifest.dependencies || {}).length, 0);
const bundled = fs.readFileSync(path.join(__dirname,'../../dist/shared/cli/commander.js'), 'utf8');
assert.doesNotMatch(bundled, /require\(["']commander["']\)/);
assert.match(fs.readFileSync(path.join(__dirname,'../../dist/licenses/commander-LICENSE'), 'utf8'), /MIT/);
});
+259
View File
@@ -0,0 +1,259 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { spawnSync } = require('node:child_process');
const path = require('node:path');
const fs = require('node:fs/promises');
const os = require('node:os');
test('legacy and worker entrypoints localize invalid input before accessing an installation', () => {
const cases = [
['compat', ['absent'], '', /未知旧命令/, /Unknown legacy command/],
[
'compat',
['update', 'invalid'],
'',
/用法:ql-compat update/,
/Usage: ql-compat update/,
],
[
'compat',
['reload', 'invalid'],
'',
/用法:ql-compat reload/,
/Usage: ql-compat reload/,
],
[
'subscription-worker',
['absent'],
'',
/用法:ql-subscription-worker/,
/Usage: ql-subscription-worker/,
],
[
'subscription-worker',
['raw', 'https://example.invalid/job.js', '', 'yes'],
'',
/订阅布尔参数无效/,
/Invalid subscription boolean/,
],
[
'compat',
['raw', 'https://example.invalid/job.js', '', 'yes'],
'',
/订阅布尔参数无效/,
/Invalid subscription boolean/,
],
[
'subscription-worker',
['raw', 'https://example.invalid/job.js', '', '', '', 'extra'],
'',
/订阅参数过多/,
/Too many subscription arguments/,
],
[
'subscription-worker',
['raw', 'https://example.invalid/job.js'],
'-1',
/SUB_ID 无效/,
/Invalid SUB_ID/,
],
];
for (const [entry, args, subscriptionId, chinese, english] of cases) {
for (const language of ['zh', 'en', 'unsupported']) {
const result = spawnSync(
process.execPath,
[path.resolve(__dirname, `../../dist/${entry}.js`), ...args],
{
env: {
...process.env,
QL_LANG: language,
QL_DIR: '',
QL_DATA_DIR: '',
SUB_ID: subscriptionId,
},
encoding: 'utf8',
timeout: 5000,
},
);
assert.equal(result.status, 2, result.stderr);
assert.equal(result.stdout, '');
const error = JSON.parse(result.stderr);
assert.equal(error.code, 2);
assert.match(error.message, language === 'en' ? english : chinese);
assert.doesNotMatch(error.message, /example\.invalid/);
}
}
});
function invoke(entry, args, language) {
return spawnSync(
process.execPath,
[path.resolve(__dirname, `../../dist/${entry}.js`), ...args, '--json'],
{
env: { ...process.env, QL_LANG: language, QL_DIR: '', QL_DATA_DIR: '' },
encoding: 'utf8',
timeout: 5000,
},
);
}
test('runner JSON error handling respects the script and option-terminator boundaries', () => {
const entry = path.resolve(__dirname, '../../dist/runner.js');
for (const args of [
['sample.js', '--json'],
['--unknown-option', '--', '--json'],
]) {
const result = spawnSync(process.execPath, [entry, ...args], {
env: { ...process.env, QL_DIR: '', QL_DATA_DIR: '' },
encoding: 'utf8',
timeout: 5000,
});
assert.equal(result.status, 2);
assert.equal(result.stdout, '');
assert.throws(
() => JSON.parse(result.stderr),
SyntaxError,
'child --json must not select CLI JSON output',
);
}
const result = invoke('runner', ['--json', '--unknown-option'], 'en');
assert.equal(result.status, 2);
assert.equal(JSON.parse(result.stderr).code, 2);
});
test('actual argument failures honor locale, preserve usage status, and keep stdout empty', () => {
const cases = [
[
'runner',
['--unknown-option'],
/任务执行器选项无效/,
/Invalid runner options/,
],
['index', ['absent'], /未知命令/, /Unknown command/],
[
'index',
['task', 'list', '--absent'],
/选项未知/,
/Unknown or missing option/,
],
[
'index',
['task', 'list', '--page', '1', '-p', '2'],
/选项重复/,
/Duplicate option/,
],
['index', ['task', 'get'], /缺少必要参数/, /missing required argument/],
['index', ['login'], /缺少 --url/, /Missing --url/],
[
'index',
['auth', 'status', '--scope', 'all'],
/--scope 无效/,
/Invalid --scope/,
],
['index', ['task', 'get', '0'], /支持范围内的整数/, /supported range/],
['admin', ['absent'], /ql --help/, /ql --help/],
];
for (const [entry, args, chinese, english] of cases) {
for (const language of ['zh', 'en', 'unsupported']) {
const result = invoke(entry, args, language);
assert.equal(result.status, 2, result.stderr);
assert.equal(result.stdout, '');
const error = JSON.parse(result.stderr);
assert.equal(error.code, 2);
assert.match(error.message, language === 'en' ? english : chinese);
}
}
});
test('unexpected local configuration failures use localized generic diagnostics without exposing config output', async (t) => {
const root = await fs.mkdtemp(path.join(os.tmpdir(), 'ql-diagnostic-'));
t.after(() => fs.rm(root, { recursive: true, force: true }));
await fs.mkdir(path.join(root, 'data/config'), { recursive: true });
await fs.writeFile(path.join(root, 'data/config/config.sh'), 'exit 7\n');
for (const language of ['zh', 'en']) {
const result = invoke('admin', ['extra', '--root', root], language);
assert.equal(result.status, 1);
assert.equal(result.stdout, '');
const error = JSON.parse(result.stderr);
assert.equal(error.code, 1);
assert.match(
error.message,
language === 'en' ? /Check local configuration/ : /检查本机配置和权限/,
);
}
});
test('legacy and worker failures preserve stderr diagnostics and localize the final JSON', async (t) => {
const root = await fs.mkdtemp(
path.join(os.tmpdir(), 'ql-worker-diagnostic-'),
);
t.after(() => fs.rm(root, { recursive: true, force: true }));
await fs.mkdir(path.join(root, 'data/config'), { recursive: true });
await fs.writeFile(
path.join(root, 'data/config/config.sh'),
'echo private-config-marker >&2\nexit 7\n',
);
for (const [entry, args, chinese, english] of [
[
'compat',
['extra'],
/旧命令适配器执行失败/,
/Legacy command adapter failed/,
],
[
'subscription-worker',
['raw', 'https://example.invalid/job.js'],
/订阅执行器失败/,
/Subscription worker failed/,
],
]) {
for (const language of ['zh', 'en']) {
const result = spawnSync(
process.execPath,
[path.resolve(__dirname, `../../dist/${entry}.js`), ...args],
{
env: {
...process.env,
QL_LANG: language,
QL_DIR: root,
QL_DATA_DIR: path.join(root, 'data'),
SUB_ID: '',
},
encoding: 'utf8',
timeout: 5000,
},
);
assert.equal(result.status, 1, result.stderr);
assert.equal(result.stdout, '');
const lines = result.stderr.trim().split('\n');
assert.equal(lines[0], 'private-config-marker');
const error = JSON.parse(lines.at(-1));
assert.equal(error.code, 1);
assert.match(error.message, language === 'en' ? english : chinese);
assert.doesNotMatch(
error.message,
/private-config-marker|example\.invalid/,
);
}
}
});
test('container entry rejects positional configuration in the selected language before startup', () => {
for (const language of ['zh', 'en', 'unsupported']) {
const result = spawnSync(
process.execPath,
[path.resolve(__dirname, '../../dist/container.js'), 'invalid'],
{ env: { QL_LANG: language }, encoding: 'utf8' },
);
assert.equal(result.status, 1);
assert.equal(result.stdout, '');
const error = JSON.parse(result.stderr);
assert.equal(error.event, 'error');
assert.match(
error.message,
language === 'en'
? /environment variables only/
: /仅接受通过环境变量配置/,
);
}
});
+62
View File
@@ -0,0 +1,62 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { parse } = require('../helpers/commands.cjs');
const {
commands,
globalOptions,
localOptions,
} = require('../helpers/commands.cjs');
const { runnerOptions } = require('../../dist/internal/execution/definition');
const { standaloneHelp } = require('../../dist/internal/help/standalone');
const { spawnSync } = require('node:child_process');
const path = require('node:path');
test('every registered command and option is discoverable in both help languages', () => {
const previous = process.env.QL_LANG;
try {
for (const language of ['zh', 'en']) {
process.env.QL_LANG = language;
for (const surface of ['public', 'local']) {
const root = parse(['--help'], surface).help;
for (const spec of commands.filter((spec) =>
surface === 'local' ? spec.local : !spec.local,
)) {
assert.ok(
root.includes(surface === 'local' ? spec.name.slice(6) : spec.name),
spec.name,
);
const help = parse([...spec.name.split(' '), '--help'], surface).help;
for (const name of Object.keys({
...globalOptions,
...(spec.local ? localOptions : {}),
...spec.options,
}))
assert.ok(help.includes(`--${name}`), `${spec.name}: ${name}`);
}
}
const runner = standaloneHelp('runner', { QL_LANG: language });
for (const name of Object.keys(runnerOptions))
assert.ok(runner.includes(`--${name}`), name);
const internal = spawnSync(
process.execPath,
[path.resolve(__dirname, '../../dist/ql.js'), '--help', '--json'],
{
env: { PATH: process.env.PATH, QL_LANG: language },
encoding: 'utf8',
timeout: 10000,
},
);
assert.equal(internal.status, 0, internal.stderr);
const help = JSON.parse(internal.stdout).data.help;
for (const spec of commands.filter((spec) => spec.local))
assert.ok(help.includes(spec.name.slice(6)), spec.name);
assert.doesNotMatch(
help,
/auth login|task run|subscription list|app list/,
);
}
} finally {
if (previous === undefined) delete process.env.QL_LANG;
else process.env.QL_LANG = previous;
}
});
+215
View File
@@ -0,0 +1,215 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { spawnSync } = require('node:child_process');
const path = require('node:path');
const fs = require('node:fs/promises');
const os = require('node:os');
const {
commands,
globalOptions,
localOptions,
} = require('../helpers/commands.cjs');
const { helpText } = require('../../dist/shared/i18n/help');
const { loggedOperation } = require('../../dist/internal/runtime/commandLog');
const { createContext } = require('../../dist/internal/runtime/context');
test('every registered help description has a Chinese translation and preserves English', () => {
const text = [
...commands.map((c) => c.summary),
...Object.values({ ...globalOptions, ...localOptions }).map(
(o) => o.description,
),
...commands.flatMap((c) =>
Object.values(c.options || {}).map((o) => o.description),
),
];
for (const value of text) {
assert.notEqual(
helpText(value, {}),
value,
`Missing translation: ${value}`,
);
assert.equal(helpText(value, { QL_LANG: 'en' }), value);
}
});
test('public and local JSON help honors QL_LANG without reading panel configuration', () => {
for (const entry of ['index', 'admin'])
for (const language of ['zh', 'en']) {
const result = spawnSync(
process.execPath,
[path.resolve(__dirname, `../../dist/${entry}.js`), '--help', '--json'],
{
encoding: 'utf8',
env: {
PATH: process.env.PATH,
QL_LANG: language,
QL_DIR: '/nonexistent',
},
},
);
assert.equal(result.status, 0, result.stderr);
const help = JSON.parse(result.stdout).data.help;
assert.match(help, language === 'en' ? /Usage:/ : /用法:/);
assert.match(help, language === 'en' ? /Options:/ : /选项:/);
assert.match(help, /--json/);
}
});
test('maintenance log banners honor Chinese fallback and English selection', async (t) => {
for (const language of ['zh', 'en']) {
const root = await fs.mkdtemp(path.join(os.tmpdir(), 'ql-i18n-'));
t.after(() => fs.rm(root, { recursive: true, force: true }));
const context = createContext(
{ root },
{ QL_LANG: language, no_tee: 'true' },
);
const { logPath } = await loggedOperation(
context,
'extra',
async () => true,
);
const log = await fs.readFile(
path.join(context.paths.dir_log, logPath),
'utf8',
);
assert.match(log, language === 'en' ? /Starting/ : /开始执行/);
assert.match(
log,
language === 'en' ? /Finished.*exit code 0/ : /执行结束.*退出码 0/,
);
}
});
test('standalone entry help supports both languages without panel or repository setup', () => {
for (const entry of [
'runner',
'compat',
'subscription-worker',
]) {
for (const language of ['en', 'zh']) {
const result = spawnSync(
process.execPath,
[path.resolve(__dirname, `../../dist/${entry}.js`), '--help'],
{
encoding: 'utf8',
cwd: os.tmpdir(),
env: {
PATH: process.env.PATH,
QL_LANG: language,
QL_DIR: '/missing-panel',
QL_CLI_CONFIG: '/missing-credentials',
},
},
);
assert.equal(result.status, 0, result.stderr);
assert.equal(result.stderr, '');
assert.match(result.stdout, language === 'en' ? /Usage:/ : /用法:/);
assert.match(result.stdout, /ql(?: |-)/);
}
}
});
test('task, maintenance and subscription failure warnings honor locale without failing completed work', async (t) => {
const { LocalApi } = require('../../dist/internal/runtime/api');
const { executeTask } = require('../../dist/internal/execution/taskRunner');
const { syncRepository } = require('../../dist/internal/subscription/subscriptionRunner');
const { withOperationOutput } = require('../../dist/internal/runtime/output');
const { execFileSync } = require('node:child_process');
const git = process.platform === 'darwin' ? '/usr/bin/git' : 'git';
const root = await fs.mkdtemp(path.join(os.tmpdir(), 'ql-warning-locale-'));
t.after(() => fs.rm(root, { recursive: true, force: true }));
const source = path.join(root, 'owner/source');
await fs.mkdir(source, { recursive: true });
await fs.writeFile(path.join(source, 'job.js'), '// cron: 0 9 * * *\n');
for (const args of [
['init'],
['add', '.'],
[
'-c',
'user.name=Fixture',
'-c',
'user.email=fixture@example.invalid',
'commit',
'-m',
'fixture',
],
])
execFileSync(git, args, { cwd: source, stdio: 'ignore' });
let created = 0,
notifications = 0;
t.mock.method(LocalApi.prototype, 'call', async (endpoint, method) => {
if (endpoint === 'crons' && method === 'POST') {
created++;
return { data: { id: created } };
}
if (endpoint === 'crons') return { data: { data: [] } };
if (endpoint === 'system/notify') notifications++;
throw new Error('Fixture unavailable');
});
for (const language of ['zh', 'en']) {
const panel = path.join(root, language);
await fs.mkdir(path.join(panel, 'data/scripts'), { recursive: true });
await fs.writeFile(path.join(panel, 'data/scripts/job.sh'), 'exit 0');
const context = createContext(
{ root: panel },
{
PATH: `/usr/bin:/bin:${process.env.PATH}`,
ID: '12',
QL_LANG: language,
QL_CLI_LIFECYCLE: 'extended',
no_tee: 'true',
},
);
const task = await executeTask(context, { argv: ['job.sh'], mode: 'now' });
assert.equal(task.exitCode, 0);
const taskLog = await fs.readFile(
path.join(context.paths.dir_log, task.logPath),
'utf8',
);
assert.match(
taskLog,
language === 'en'
? /Task lifecycle reporting failed/
: /任务状态上报失败/,
);
assert.match(
taskLog,
language === 'en'
? /Task statistics reporting failed/
: /任务统计上报失败/,
);
const command = await loggedOperation(context, 'extra', async () => true);
const commandLog = await fs.readFile(
path.join(context.paths.dir_log, command.logPath),
'utf8',
);
assert.match(
commandLog,
language === 'en'
? /Command lifecycle reporting failed/
: /命令状态上报失败/,
);
let warning = '';
const subscription = await withOperationOutput(
(chunk) => {
warning += chunk.toString();
},
() =>
syncRepository(context, {
url: source,
autoAdd: true,
autoDelete: false,
}),
);
assert.equal(subscription.added, 1);
assert.match(
warning,
language === 'en'
? /Subscription synchronized, but notification delivery failed/
: /订阅同步已完成,但通知发送失败/,
);
}
assert.equal(created, 2);
assert.equal(notifications, 2);
});