praxo-cli 0.0.0-stage → 0.1.0
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/LICENSE +21 -0
- package/README.md +159 -2
- package/dist/app.js +75 -0
- package/dist/bin.js +21 -0
- package/dist/cli/commands/ai.command.js +189 -0
- package/dist/cli/commands/cmd.command.js +265 -0
- package/dist/cli/commands/completion.command.js +334 -0
- package/dist/cli/commands/config.command.js +27 -0
- package/dist/cli/commands/decision.command.js +287 -0
- package/dist/cli/commands/doctor.command.js +45 -0
- package/dist/cli/commands/project.command.js +24 -0
- package/dist/cli/commands/search.command.js +59 -0
- package/dist/cli/commands/sync.command.js +122 -0
- package/dist/cli/commands/transfer.command.js +148 -0
- package/dist/cli/index.js +156 -0
- package/dist/cli/output.js +133 -0
- package/dist/cli/prompts.js +68 -0
- package/dist/features/ai/client.js +238 -0
- package/dist/features/ai/output.js +7 -0
- package/dist/features/ai/providers.js +52 -0
- package/dist/features/ai/schemas.js +43 -0
- package/dist/features/ai/service.js +183 -0
- package/dist/features/commands/executor.js +54 -0
- package/dist/features/commands/repository.js +61 -0
- package/dist/features/commands/safety.js +154 -0
- package/dist/features/commands/service.js +254 -0
- package/dist/features/commands/template.js +153 -0
- package/dist/features/decisions/repository.js +53 -0
- package/dist/features/decisions/service.js +209 -0
- package/dist/features/decisions/stats.js +84 -0
- package/dist/features/decisions/status.js +7 -0
- package/dist/features/projects/repository.js +51 -0
- package/dist/features/projects/service.js +74 -0
- package/dist/features/sync/git.js +207 -0
- package/dist/features/sync/merge.js +194 -0
- package/dist/features/sync/repository.js +151 -0
- package/dist/features/sync/sanitizer.js +21 -0
- package/dist/features/sync/service.js +199 -0
- package/dist/features/sync/snapshot.js +230 -0
- package/dist/infrastructure/credentials/store.js +105 -0
- package/dist/infrastructure/database/client.js +41 -0
- package/dist/infrastructure/database/migrate.js +102 -0
- package/dist/infrastructure/database/schema.js +138 -0
- package/dist/infrastructure/git/detector.js +48 -0
- package/dist/shared/clipboard.js +19 -0
- package/dist/shared/config.js +163 -0
- package/dist/shared/doctor.js +47 -0
- package/dist/shared/errors.js +19 -0
- package/dist/shared/global-search.js +51 -0
- package/dist/shared/input.js +37 -0
- package/dist/shared/links.js +48 -0
- package/dist/shared/paths.js +14 -0
- package/dist/shared/query.js +10 -0
- package/dist/shared/redaction.js +54 -0
- package/dist/shared/search.js +39 -0
- package/dist/shared/sync-metadata.js +7 -0
- package/dist/shared/tags.js +91 -0
- package/dist/shared/transfer/archive.js +197 -0
- package/dist/shared/transfer/markdown.js +53 -0
- package/dist/shared/transfer/service.js +278 -0
- package/dist/tui/Workspace.js +121 -0
- package/dist/tui/components/AiPanel.js +200 -0
- package/dist/tui/components/Catalog.js +47 -0
- package/dist/tui/components/Confirm.js +28 -0
- package/dist/tui/components/Form.js +113 -0
- package/dist/tui/components/HelpModal.js +44 -0
- package/dist/tui/components/Inspection.js +28 -0
- package/dist/tui/components/KeyHints.js +7 -0
- package/dist/tui/components/SearchInput.js +31 -0
- package/dist/tui/components/SyncPanel.js +93 -0
- package/dist/tui/index.js +18 -0
- package/dist/tui/screens/Commands.js +383 -0
- package/dist/tui/screens/DecisionForms.js +117 -0
- package/dist/tui/screens/Decisions.js +260 -0
- package/dist/tui/screens/Lookup.js +96 -0
- package/dist/tui/theme.js +47 -0
- package/drizzle/0000_initial.sql +105 -0
- package/drizzle/0001_v11_sync.sql +117 -0
- package/drizzle/meta/0000_snapshot.json +735 -0
- package/drizzle/meta/0001_snapshot.json +867 -0
- package/drizzle/meta/_journal.json +20 -0
- package/package.json +77 -4
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
import { closeSync, openSync, readFileSync, unlinkSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { Option } from 'commander';
|
|
3
|
+
import { AppError, messageOf } from '../../shared/errors.js';
|
|
4
|
+
import { validateArchive } from '../../shared/transfer/archive.js';
|
|
5
|
+
import { markdown } from '../../shared/transfer/markdown.js';
|
|
6
|
+
import { canPrompt, output } from '../output.js';
|
|
7
|
+
import { prompt } from '../prompts.js';
|
|
8
|
+
/** 从文件路径或标准输入(`-`)读取并校验归档 JSON。 */
|
|
9
|
+
function readArchive(file) {
|
|
10
|
+
let text;
|
|
11
|
+
if (file === '-') {
|
|
12
|
+
if (process.stdin.isTTY) {
|
|
13
|
+
throw new AppError(2, 'Pipe archive JSON to standard input when using "-".');
|
|
14
|
+
}
|
|
15
|
+
try {
|
|
16
|
+
text = readFileSync(0, 'utf8');
|
|
17
|
+
}
|
|
18
|
+
catch (error) {
|
|
19
|
+
throw new AppError(5, 'Cannot read JSON from standard input: ' + messageOf(error), {
|
|
20
|
+
cause: error,
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
else {
|
|
25
|
+
try {
|
|
26
|
+
text = readFileSync(file, 'utf8');
|
|
27
|
+
}
|
|
28
|
+
catch (error) {
|
|
29
|
+
throw new AppError(5, 'Cannot read JSON from ' + file + ': ' + messageOf(error), {
|
|
30
|
+
cause: error,
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
let raw;
|
|
35
|
+
try {
|
|
36
|
+
raw = JSON.parse(text.replace(/^\uFEFF/u, ''));
|
|
37
|
+
}
|
|
38
|
+
catch (error) {
|
|
39
|
+
const source = file === '-' ? 'standard input' : file;
|
|
40
|
+
throw new AppError(5, 'Cannot parse JSON from ' + source + ': ' + messageOf(error), {
|
|
41
|
+
cause: error,
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
return validateArchive(raw);
|
|
45
|
+
}
|
|
46
|
+
function emit(text, path) {
|
|
47
|
+
if (!path || path === '-') {
|
|
48
|
+
process.stdout.write(text);
|
|
49
|
+
return;
|
|
50
|
+
}
|
|
51
|
+
let descriptor;
|
|
52
|
+
try {
|
|
53
|
+
descriptor = openSync(path, 'wx', 0o600);
|
|
54
|
+
writeFileSync(descriptor, text, 'utf8');
|
|
55
|
+
}
|
|
56
|
+
catch (error) {
|
|
57
|
+
if (descriptor !== undefined) {
|
|
58
|
+
closeSync(descriptor);
|
|
59
|
+
descriptor = undefined;
|
|
60
|
+
try {
|
|
61
|
+
unlinkSync(path);
|
|
62
|
+
}
|
|
63
|
+
catch {
|
|
64
|
+
/* 保留原始写入错误。 */
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
throw new AppError(5, 'Could not export to ' + path + ': ' + messageOf(error), {
|
|
68
|
+
cause: error,
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
finally {
|
|
72
|
+
if (descriptor !== undefined)
|
|
73
|
+
closeSync(descriptor);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
function summarize(label, counts) {
|
|
77
|
+
return (label +
|
|
78
|
+
': ' +
|
|
79
|
+
Object.entries(counts)
|
|
80
|
+
.map(([key, value]) => key + ' ' + value)
|
|
81
|
+
.join(', '));
|
|
82
|
+
}
|
|
83
|
+
/** 注册 `pxo export` 与 `pxo import` 数据迁移命令。 */
|
|
84
|
+
export function registerTransfer(program, withApp) {
|
|
85
|
+
const exportCmd = program
|
|
86
|
+
.command('export')
|
|
87
|
+
.description('Export a JSON archive or Markdown')
|
|
88
|
+
.addOption(new Option('-f, --format <format>', 'Output format').choices(['json', 'md']).default('json'))
|
|
89
|
+
.addOption(new Option('--only <kind>', 'Subset of records to export').choices([
|
|
90
|
+
'all',
|
|
91
|
+
'commands',
|
|
92
|
+
'decisions',
|
|
93
|
+
]))
|
|
94
|
+
.option('-o, --output <file>', 'Write to a new file; use - for stdout')
|
|
95
|
+
.action((options) => withApp((app) => {
|
|
96
|
+
const snapshot = app.transfer.snapshot(options.only);
|
|
97
|
+
const text = options.format === 'md' ? markdown(snapshot) : JSON.stringify(snapshot, null, 2) + '\n';
|
|
98
|
+
emit(text, options.output);
|
|
99
|
+
}, 'preview'));
|
|
100
|
+
const importCmd = program
|
|
101
|
+
.command('import <file>')
|
|
102
|
+
.description('Import a Praxo JSON archive (use - for stdin)')
|
|
103
|
+
.option('--dry-run', 'Show changes without writing data')
|
|
104
|
+
.addOption(new Option('--merge', 'Merge by stable IDs (default)').conflicts('replace'))
|
|
105
|
+
.option('--replace', 'Replace all local data; requires a terminal and creates a backup')
|
|
106
|
+
.option('--json', 'Output JSON')
|
|
107
|
+
.action(async (file, options) => {
|
|
108
|
+
const mode = options.replace ? 'replace' : 'merge';
|
|
109
|
+
if (mode === 'replace' && !options.dryRun && !canPrompt()) {
|
|
110
|
+
throw new AppError(4, 'Replacement requires interactive confirmation. Use --dry-run to preview.');
|
|
111
|
+
}
|
|
112
|
+
const archive = readArchive(file);
|
|
113
|
+
if (options.dryRun || mode === 'replace') {
|
|
114
|
+
const result = await withApp((app) => app.transfer.preview(archive, mode), 'preview');
|
|
115
|
+
if (options.dryRun) {
|
|
116
|
+
output({ mode, dryRun: true, ...result }, options.json, () => {
|
|
117
|
+
const lines = [summarize('Would add', result.added)];
|
|
118
|
+
if (result.removed)
|
|
119
|
+
lines.push(summarize('Would remove', result.removed));
|
|
120
|
+
if (result.skipped)
|
|
121
|
+
lines.push(summarize('Would skip', result.skipped));
|
|
122
|
+
return lines.join('\n');
|
|
123
|
+
});
|
|
124
|
+
return;
|
|
125
|
+
}
|
|
126
|
+
const lines = [summarize('Would add', result.added)];
|
|
127
|
+
if (result.removed)
|
|
128
|
+
lines.push(summarize('Would remove', result.removed));
|
|
129
|
+
if (result.skipped)
|
|
130
|
+
lines.push(summarize('Would skip', result.skipped));
|
|
131
|
+
process.stderr.write(lines.join('\n') + '\n');
|
|
132
|
+
await prompt(async (ask) => {
|
|
133
|
+
if (!/^y(?:es)?$/iu.test((await ask('Replace all local Praxo data after creating a backup? [y/N] ')).trim()) ||
|
|
134
|
+
(await ask('Type REPLACE to confirm: ')) !== 'REPLACE') {
|
|
135
|
+
throw new AppError(4, 'Replacement cancelled.');
|
|
136
|
+
}
|
|
137
|
+
});
|
|
138
|
+
}
|
|
139
|
+
await withApp(async (app) => {
|
|
140
|
+
const result = await app.transfer.import(archive, mode, mode === 'replace');
|
|
141
|
+
if ('backupPath' in result && !options.json) {
|
|
142
|
+
process.stderr.write('Backup saved to ' + result.backupPath + '\n');
|
|
143
|
+
}
|
|
144
|
+
output({ mode, ...result }, options.json, () => summarize('Imported', result.added));
|
|
145
|
+
});
|
|
146
|
+
});
|
|
147
|
+
return [exportCmd, importCmd];
|
|
148
|
+
}
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
import { Argument, Command, CommanderError, Option } from 'commander';
|
|
2
|
+
import { readFileSync } from 'node:fs';
|
|
3
|
+
import { AppError } from '../shared/errors.js';
|
|
4
|
+
import { canPrompt, setNoInput } from './output.js';
|
|
5
|
+
import { registerAi } from './commands/ai.command.js';
|
|
6
|
+
import { registerCommandAddShortcut, registerCommands, registerTag, } from './commands/cmd.command.js';
|
|
7
|
+
import { registerCompletion } from './commands/completion.command.js';
|
|
8
|
+
import { registerConfig } from './commands/config.command.js';
|
|
9
|
+
import { registerDecideShortcut, registerDecisions, registerStats, } from './commands/decision.command.js';
|
|
10
|
+
import { registerDoctor } from './commands/doctor.command.js';
|
|
11
|
+
import { registerProjects } from './commands/project.command.js';
|
|
12
|
+
import { registerLinks, registerSearch } from './commands/search.command.js';
|
|
13
|
+
import { registerSync } from './commands/sync.command.js';
|
|
14
|
+
import { registerTransfer } from './commands/transfer.command.js';
|
|
15
|
+
const withApp = async (handler, mode) => {
|
|
16
|
+
const { createApp } = await import('../app.js');
|
|
17
|
+
const app = createApp({ mode });
|
|
18
|
+
try {
|
|
19
|
+
return await handler(app);
|
|
20
|
+
}
|
|
21
|
+
finally {
|
|
22
|
+
app.close();
|
|
23
|
+
}
|
|
24
|
+
};
|
|
25
|
+
/** 递归为所有可执行叶子子命令挂载隐藏的 --no-input 选项,支持在任意参数位置禁用交互。 */
|
|
26
|
+
function attachGlobalNoInput(command) {
|
|
27
|
+
for (const sub of command.commands) {
|
|
28
|
+
if (sub.name() === 'help')
|
|
29
|
+
continue;
|
|
30
|
+
const isLeaf = sub.commands.length === 0 || sub.name() === 'sync';
|
|
31
|
+
if (isLeaf && !sub.options.some((opt) => opt.long === '--no-input')) {
|
|
32
|
+
sub.addOption(new Option('--no-input', 'Disable interactive prompts').hideHelp());
|
|
33
|
+
}
|
|
34
|
+
attachGlobalNoInput(sub);
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
/** 沿参数序列匹配最深的有效子命令路径,用于生成精确的 --help 错误指引。 */
|
|
38
|
+
function matchedCommandPath(program, args) {
|
|
39
|
+
const path = [program.name()];
|
|
40
|
+
let current = program;
|
|
41
|
+
for (const token of args) {
|
|
42
|
+
if (token === '--')
|
|
43
|
+
break;
|
|
44
|
+
if (token.startsWith('-'))
|
|
45
|
+
continue;
|
|
46
|
+
const next = current.commands.find((cmd) => cmd.name() === token || cmd.aliases().includes(token));
|
|
47
|
+
if (!next)
|
|
48
|
+
break;
|
|
49
|
+
path.push(next.name());
|
|
50
|
+
current = next;
|
|
51
|
+
}
|
|
52
|
+
return path;
|
|
53
|
+
}
|
|
54
|
+
/** 启动交互式终端工作台(TUI)。 */
|
|
55
|
+
async function openTui(section) {
|
|
56
|
+
if (!canPrompt()) {
|
|
57
|
+
throw new AppError(2, 'The TUI requires an interactive terminal. Run pxo --help to see direct subcommands.');
|
|
58
|
+
}
|
|
59
|
+
const { launchTui } = await import('../tui/index.js');
|
|
60
|
+
await withApp((app) => launchTui(app, section));
|
|
61
|
+
}
|
|
62
|
+
/** 装配并执行 pxo CLI 根程序。 */
|
|
63
|
+
export async function cli(args) {
|
|
64
|
+
setNoInput(false);
|
|
65
|
+
const { version } = JSON.parse(readFileSync(new URL('../../package.json', import.meta.url), 'utf8'));
|
|
66
|
+
const program = new Command()
|
|
67
|
+
.name('pxo')
|
|
68
|
+
.description('Local-first terminal workspace for commands and decisions')
|
|
69
|
+
.version(version)
|
|
70
|
+
.option('--no-input', 'Disable interactive prompts (also respects CI and PRAXO_NO_PROMPT)')
|
|
71
|
+
.enablePositionalOptions()
|
|
72
|
+
.showSuggestionAfterError(true)
|
|
73
|
+
.exitOverride()
|
|
74
|
+
.configureOutput({ writeErr: () => undefined })
|
|
75
|
+
.hook('preAction', (_thisCommand, actionCommand) => {
|
|
76
|
+
let cursor = actionCommand;
|
|
77
|
+
while (cursor) {
|
|
78
|
+
const opts = cursor.opts();
|
|
79
|
+
if (opts.input === false || opts.prompt === false) {
|
|
80
|
+
setNoInput(true);
|
|
81
|
+
break;
|
|
82
|
+
}
|
|
83
|
+
cursor = cursor.parent;
|
|
84
|
+
}
|
|
85
|
+
})
|
|
86
|
+
.addHelpText('after', [
|
|
87
|
+
'',
|
|
88
|
+
'Examples:',
|
|
89
|
+
' pxo Open interactive TUI (Commands)',
|
|
90
|
+
' pxo ui decisions Open interactive TUI (Decisions)',
|
|
91
|
+
' pxo add "lsof -i :{{port:3000}}" -n "Check port" --tier hot',
|
|
92
|
+
' pxo command run "port" --var port=8080 --dry-run',
|
|
93
|
+
' pxo decide "Use SQLite" --reason "Single-file backup" --confidence 85 --in 90d',
|
|
94
|
+
' pxo decision review add <id> --result "Verified" --rating accurate --lesson "Test recovery"',
|
|
95
|
+
' pxo export -o - | pxo import - --dry-run',
|
|
96
|
+
'',
|
|
97
|
+
'Environment Variables:',
|
|
98
|
+
' PRAXO_DATA_DIR Override local SQLite data directory',
|
|
99
|
+
' PRAXO_NO_PROMPT Disable interactive prompts when set to 1/true',
|
|
100
|
+
' PRAXO_DEEPSEEK_API_KEY API key for DeepSeek (or PRAXO_GEMINI_API_KEY for Gemini)',
|
|
101
|
+
' NO_COLOR / FORCE_COLOR Control ANSI color output',
|
|
102
|
+
' CI Automatically disables interactive prompts',
|
|
103
|
+
].join('\n'));
|
|
104
|
+
// Core Commands
|
|
105
|
+
const commands = registerCommands(program, withApp).helpGroup('Core Commands:');
|
|
106
|
+
const decisions = registerDecisions(program, withApp).helpGroup('Core Commands:');
|
|
107
|
+
registerLinks(commands, 'command', withApp);
|
|
108
|
+
registerLinks(decisions, 'decision', withApp);
|
|
109
|
+
registerSearch(program, withApp).helpGroup('Core Commands:');
|
|
110
|
+
registerStats(program, withApp).helpGroup('Core Commands:');
|
|
111
|
+
// Shortcuts
|
|
112
|
+
registerCommandAddShortcut(program, withApp).helpGroup('Shortcuts:');
|
|
113
|
+
registerDecideShortcut(program, withApp).helpGroup('Shortcuts:');
|
|
114
|
+
// Sync & AI
|
|
115
|
+
registerSync(program, withApp).helpGroup('Sync & AI:');
|
|
116
|
+
registerAi(program, withApp).helpGroup('Sync & AI:');
|
|
117
|
+
// Workspace & Utilities
|
|
118
|
+
program
|
|
119
|
+
.command('ui')
|
|
120
|
+
.description('Open the interactive TUI workspace')
|
|
121
|
+
.addArgument(new Argument('[section]', 'Workspace section to open')
|
|
122
|
+
.choices(['commands', 'decisions'])
|
|
123
|
+
.default('commands'))
|
|
124
|
+
.helpGroup('Workspace & Utilities:')
|
|
125
|
+
.action((section) => openTui(section));
|
|
126
|
+
registerProjects(program, withApp).helpGroup('Workspace & Utilities:');
|
|
127
|
+
registerTag(program, withApp).helpGroup('Workspace & Utilities:');
|
|
128
|
+
registerConfig(program).helpGroup('Workspace & Utilities:');
|
|
129
|
+
for (const transfer of registerTransfer(program, withApp)) {
|
|
130
|
+
transfer.helpGroup('Workspace & Utilities:');
|
|
131
|
+
}
|
|
132
|
+
registerDoctor(program).helpGroup('Workspace & Utilities:');
|
|
133
|
+
registerCompletion(program).helpGroup('Workspace & Utilities:');
|
|
134
|
+
attachGlobalNoInput(program);
|
|
135
|
+
if (args.every((arg) => arg === '--no-input')) {
|
|
136
|
+
if (args.includes('--no-input'))
|
|
137
|
+
setNoInput(true);
|
|
138
|
+
await openTui('commands');
|
|
139
|
+
return 0;
|
|
140
|
+
}
|
|
141
|
+
try {
|
|
142
|
+
await program.parseAsync(args, { from: 'user' });
|
|
143
|
+
return 0;
|
|
144
|
+
}
|
|
145
|
+
catch (error) {
|
|
146
|
+
if (!(error instanceof CommanderError))
|
|
147
|
+
throw error;
|
|
148
|
+
if (error.exitCode === 0)
|
|
149
|
+
return 0;
|
|
150
|
+
const matched = matchedCommandPath(program, args);
|
|
151
|
+
const hint = matched.length > 1
|
|
152
|
+
? `Run ${matched.join(' ')} --help for usage.`
|
|
153
|
+
: 'Run pxo --help for available commands.';
|
|
154
|
+
throw new AppError(2, error.message.replace(/^error: /u, '') + '\n' + hint);
|
|
155
|
+
}
|
|
156
|
+
}
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
import { stripVTControlCharacters } from 'node:util';
|
|
2
|
+
import { AppError } from '../shared/errors.js';
|
|
3
|
+
import { defaultLimit } from '../shared/input.js';
|
|
4
|
+
let noInputFlag = false;
|
|
5
|
+
/** 设置全局非交互状态(由根命令 --no-input / --no-prompt 控制)。 */
|
|
6
|
+
export function setNoInput(disabled) {
|
|
7
|
+
noInputFlag = disabled;
|
|
8
|
+
}
|
|
9
|
+
/** 判断环境变量是否指示当前处于非交互环境(CI 或 PRAXO_NO_PROMPT)。 */
|
|
10
|
+
function isNonInteractiveEnv() {
|
|
11
|
+
const ci = process.env.CI;
|
|
12
|
+
if (ci && ci !== '0' && ci.toLowerCase() !== 'false')
|
|
13
|
+
return true;
|
|
14
|
+
const noPrompt = process.env.PRAXO_NO_PROMPT;
|
|
15
|
+
return Boolean(noPrompt && noPrompt !== '0' && noPrompt.toLowerCase() !== 'false');
|
|
16
|
+
}
|
|
17
|
+
/** 判断是否应在指定输出流启用 ANSI 颜色(尊重 NO_COLOR、FORCE_COLOR、TERM=dumb 与 TTY)。 */
|
|
18
|
+
export function useColor(stream = process.stdout) {
|
|
19
|
+
if (process.env.NO_COLOR)
|
|
20
|
+
return false;
|
|
21
|
+
const force = process.env.FORCE_COLOR;
|
|
22
|
+
if (force !== undefined && force !== '') {
|
|
23
|
+
return force !== '0' && force.toLowerCase() !== 'false';
|
|
24
|
+
}
|
|
25
|
+
if (process.env.TERM === 'dumb')
|
|
26
|
+
return false;
|
|
27
|
+
return Boolean(stream.isTTY);
|
|
28
|
+
}
|
|
29
|
+
/** 计算文本在等宽终端中的显示列宽,正确处理中文等东亚全角字符。 */
|
|
30
|
+
export function displayWidth(text) {
|
|
31
|
+
const plain = stripVTControlCharacters(text);
|
|
32
|
+
let width = 0;
|
|
33
|
+
for (const char of plain) {
|
|
34
|
+
const code = char.codePointAt(0) ?? 0;
|
|
35
|
+
const wide = code >= 0x1100 &&
|
|
36
|
+
(code <= 0x115f ||
|
|
37
|
+
code === 0x2329 ||
|
|
38
|
+
code === 0x232a ||
|
|
39
|
+
(code >= 0x2e80 && code <= 0xa4cf && code !== 0x303f) ||
|
|
40
|
+
(code >= 0xac00 && code <= 0xd7a3) ||
|
|
41
|
+
(code >= 0xf900 && code <= 0xfaff) ||
|
|
42
|
+
(code >= 0xfe10 && code <= 0xfe19) ||
|
|
43
|
+
(code >= 0xfe30 && code <= 0xfe6f) ||
|
|
44
|
+
(code >= 0xff00 && code <= 0xff60) ||
|
|
45
|
+
(code >= 0xffe0 && code <= 0xffe6) ||
|
|
46
|
+
(code >= 0x1f300 && code <= 0x1faff) ||
|
|
47
|
+
(code >= 0x20000 && code <= 0x3fffd));
|
|
48
|
+
width += wide ? 2 : 1;
|
|
49
|
+
}
|
|
50
|
+
return width;
|
|
51
|
+
}
|
|
52
|
+
/** 按终端显示宽度右侧补齐空格。 */
|
|
53
|
+
function padEndWidth(text, target) {
|
|
54
|
+
const gap = target - displayWidth(text);
|
|
55
|
+
return gap > 0 ? text + ' '.repeat(gap) : text;
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* 格式化 CLI 表格输出:
|
|
59
|
+
* - 交互终端(TTY):按中英文列宽对齐并带表头分隔线;
|
|
60
|
+
* - 管道/非交互环境:退化为纯净 Tab 分隔文本,便于脚本解析。
|
|
61
|
+
*/
|
|
62
|
+
export function formatTable(headers, rows, options = {}) {
|
|
63
|
+
const tty = options.tty ?? Boolean(process.stdout.isTTY);
|
|
64
|
+
if (!tty) {
|
|
65
|
+
return rows.map((row) => row.join('\t')).join('\n');
|
|
66
|
+
}
|
|
67
|
+
const color = options.color ?? useColor(process.stdout);
|
|
68
|
+
const widths = headers.map((header, col) => Math.max(displayWidth(header), ...rows.map((row) => displayWidth(row[col] ?? ''))));
|
|
69
|
+
const renderLine = (cells) => cells
|
|
70
|
+
.map((cell, col) => (col === cells.length - 1 ? cell : padEndWidth(cell, widths[col])))
|
|
71
|
+
.join(' ');
|
|
72
|
+
const headerLine = renderLine(headers);
|
|
73
|
+
const divider = widths.map((w) => '─'.repeat(w)).join('──');
|
|
74
|
+
const body = rows.map(renderLine);
|
|
75
|
+
const head = color
|
|
76
|
+
? `\x1b[1m${headerLine}\x1b[0m\n\x1b[2m${divider}\x1b[0m`
|
|
77
|
+
: `${headerLine}\n${divider}`;
|
|
78
|
+
return [head, ...body].join('\n');
|
|
79
|
+
}
|
|
80
|
+
/** 输出单条结果或结构化 JSON。 */
|
|
81
|
+
export function output(value, json, format) {
|
|
82
|
+
if (json) {
|
|
83
|
+
process.stdout.write(`${JSON.stringify(value)}\n`);
|
|
84
|
+
return;
|
|
85
|
+
}
|
|
86
|
+
const text = format();
|
|
87
|
+
if (text !== '')
|
|
88
|
+
process.stdout.write(`${text}\n`);
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* 输出列表结果:
|
|
92
|
+
* - `--json`:始终输出 JSON 数组;
|
|
93
|
+
* - 有数据时输出表格(TTY)或 TSV(非 TTY);
|
|
94
|
+
* - 空列表时仅在交互终端输出提示语,管道模式下保持 stdout 为 0 行以避免污染下游命令。
|
|
95
|
+
*/
|
|
96
|
+
export function outputList(rows, json, formatRows, emptyMessage) {
|
|
97
|
+
if (json) {
|
|
98
|
+
process.stdout.write(`${JSON.stringify(rows)}\n`);
|
|
99
|
+
return;
|
|
100
|
+
}
|
|
101
|
+
if (rows.length > 0) {
|
|
102
|
+
process.stdout.write(`${formatRows()}\n`);
|
|
103
|
+
return;
|
|
104
|
+
}
|
|
105
|
+
if (process.stdout.isTTY) {
|
|
106
|
+
process.stdout.write(`${emptyMessage}\n`);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
/** 判断当前终端与运行模式是否允许交互提示。 */
|
|
110
|
+
export function canPrompt(noPrompt = false) {
|
|
111
|
+
return (!noPrompt &&
|
|
112
|
+
!noInputFlag &&
|
|
113
|
+
!isNonInteractiveEnv() &&
|
|
114
|
+
Boolean(process.stdin.isTTY && process.stdout.isTTY && process.stderr.isTTY));
|
|
115
|
+
}
|
|
116
|
+
/** 校验正整数选项参数(如 --limit、--timeout-ms)。 */
|
|
117
|
+
export function positiveInt(value, optionName) {
|
|
118
|
+
const count = Number(value);
|
|
119
|
+
if (!/^\d+$/u.test(value) || !Number.isSafeInteger(count) || count < 1) {
|
|
120
|
+
throw new AppError(2, `${optionName} must be a positive integer.`);
|
|
121
|
+
}
|
|
122
|
+
return count;
|
|
123
|
+
}
|
|
124
|
+
/** 解析列表条数上限(默认 50)。 */
|
|
125
|
+
export function limit(value) {
|
|
126
|
+
if (value === undefined)
|
|
127
|
+
return defaultLimit;
|
|
128
|
+
return positiveInt(value, '--limit');
|
|
129
|
+
}
|
|
130
|
+
/** 收集可重复选项的值。 */
|
|
131
|
+
export function collect(value, previous) {
|
|
132
|
+
return [...previous, value];
|
|
133
|
+
}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { createInterface } from 'node:readline/promises';
|
|
2
|
+
import { AppError } from '../shared/errors.js';
|
|
3
|
+
import { canPrompt } from './output.js';
|
|
4
|
+
export async function pipedInput(label) {
|
|
5
|
+
if (process.stdin.isTTY)
|
|
6
|
+
throw new AppError(2, 'Pipe ' + label + ' to standard input.');
|
|
7
|
+
process.stdin.setEncoding('utf8');
|
|
8
|
+
let text = '';
|
|
9
|
+
for await (const chunk of process.stdin) {
|
|
10
|
+
text += String(chunk);
|
|
11
|
+
if (text.length > 32_000)
|
|
12
|
+
throw new AppError(2, 'Standard input is too large.');
|
|
13
|
+
}
|
|
14
|
+
if (!text.trim())
|
|
15
|
+
throw new AppError(2, 'Standard input is empty.');
|
|
16
|
+
return text.trim();
|
|
17
|
+
}
|
|
18
|
+
export async function prompt(action) {
|
|
19
|
+
const controller = new AbortController();
|
|
20
|
+
const interface_ = createInterface({
|
|
21
|
+
input: process.stdin,
|
|
22
|
+
output: process.stderr,
|
|
23
|
+
terminal: true,
|
|
24
|
+
});
|
|
25
|
+
const interrupt = () => controller.abort();
|
|
26
|
+
interface_.on('SIGINT', interrupt);
|
|
27
|
+
interface_.on('close', interrupt);
|
|
28
|
+
try {
|
|
29
|
+
return await action((message) => interface_.question(message, { signal: controller.signal }));
|
|
30
|
+
}
|
|
31
|
+
catch (error) {
|
|
32
|
+
if (controller.signal.aborted)
|
|
33
|
+
throw new AppError(130, 'Interactive input cancelled.');
|
|
34
|
+
throw error;
|
|
35
|
+
}
|
|
36
|
+
finally {
|
|
37
|
+
interface_.close();
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
export function requirePrompt(hint) {
|
|
41
|
+
if (!canPrompt())
|
|
42
|
+
throw new AppError(2, hint);
|
|
43
|
+
}
|
|
44
|
+
export async function confirmRemoval(label, yes) {
|
|
45
|
+
if (yes)
|
|
46
|
+
return;
|
|
47
|
+
requirePrompt('Use --yes to confirm deletion in non-interactive mode.');
|
|
48
|
+
await prompt(async (ask) => {
|
|
49
|
+
if (!/^y(?:es)?$/iu.test((await ask('Delete ' + label + '? [y/N] ')).trim())) {
|
|
50
|
+
throw new AppError(4, 'Deletion cancelled.');
|
|
51
|
+
}
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
export async function confirmRun(ask, high, reason) {
|
|
55
|
+
const accepted = /^y(?:es)?$/iu.test((await ask(reason + ' Run this command? [y/N] ')).trim());
|
|
56
|
+
if (!accepted)
|
|
57
|
+
throw new AppError(4, 'Execution cancelled.');
|
|
58
|
+
if (!high)
|
|
59
|
+
return 'interactive';
|
|
60
|
+
if ((await ask('Type RUN to confirm this high-risk command: ')) !== 'RUN') {
|
|
61
|
+
throw new AppError(4, 'High-risk confirmation did not match RUN.');
|
|
62
|
+
}
|
|
63
|
+
return 'typed';
|
|
64
|
+
}
|
|
65
|
+
export async function field(ask, label, old) {
|
|
66
|
+
const value = await ask(label + (old ? ' [' + old + ']' : '') + ': ');
|
|
67
|
+
return value === '' ? undefined : value;
|
|
68
|
+
}
|