@easyv/screen-cli 0.0.0-stage → 0.1.1
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 +283 -2
- package/bin/easyv-screen.js +2 -0
- package/dist/analyzer.js +130 -0
- package/dist/client.js +168 -0
- package/dist/commands/auth.js +285 -0
- package/dist/commands/component.js +197 -0
- package/dist/commands/data.js +147 -0
- package/dist/commands/debug.js +31 -0
- package/dist/commands/screen.js +199 -0
- package/dist/commands/skills.js +53 -0
- package/dist/config.js +421 -0
- package/dist/debug-query.js +224 -0
- package/dist/index.js +25 -0
- package/dist/output.js +7 -0
- package/package.json +36 -4
- package/skills/easyv-component-dev/SKILL.md +50 -0
- package/skills/easyv-component-dev/references/component-spec.md +123 -0
- package/skills/easyv-screen-build/SKILL.md +40 -0
- package/skills/easyv-screen-data/SKILL.md +53 -0
- package/skills/easyv-screen-debug/SKILL.md +49 -0
- package/skills/easyv-screen-edit/SKILL.md +59 -0
- package/skills/easyv-screen-shared/SKILL.md +32 -0
- package/spec/openapi.v1.yaml +2850 -0
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.registerScreen = registerScreen;
|
|
4
|
+
const node_fs_1 = require("node:fs");
|
|
5
|
+
const client_1 = require("../client");
|
|
6
|
+
const output_1 = require("../output");
|
|
7
|
+
const auth_1 = require("./auth");
|
|
8
|
+
const config_1 = require("../config");
|
|
9
|
+
function registerScreen(program) {
|
|
10
|
+
const screen = program.command('screen').description('大屏');
|
|
11
|
+
screen.command('groups')
|
|
12
|
+
.description('列出当前团队的大屏分组')
|
|
13
|
+
.action(async function () {
|
|
14
|
+
await runJson(this, () => (0, client_1.createClient)().request('GET', '/groups'));
|
|
15
|
+
});
|
|
16
|
+
screen.command('list')
|
|
17
|
+
.description('列出当前团队的大屏')
|
|
18
|
+
.option('--group <groupId>', '按分组过滤')
|
|
19
|
+
.option('--keyword <keyword>', '按名称过滤')
|
|
20
|
+
.action(async function (options) {
|
|
21
|
+
try {
|
|
22
|
+
const result = await (0, client_1.createClient)().request('GET', '/screens', {
|
|
23
|
+
query: { groupId: options.group, keyword: options.keyword },
|
|
24
|
+
});
|
|
25
|
+
(0, output_1.emit)((0, auth_1.globalJson)(this), result, () => {
|
|
26
|
+
for (const item of result.screens ?? [])
|
|
27
|
+
console.log(`${item.id}\t${item.name}`);
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
catch (error) {
|
|
31
|
+
(0, client_1.exitOnError)(error);
|
|
32
|
+
}
|
|
33
|
+
});
|
|
34
|
+
screen.command('create')
|
|
35
|
+
.description('创建大屏')
|
|
36
|
+
.requiredOption('--name <name>', '大屏名称')
|
|
37
|
+
.option('--group <groupId>', '分组 id')
|
|
38
|
+
.action(async function (options) {
|
|
39
|
+
try {
|
|
40
|
+
const result = await (0, client_1.createClient)().request('POST', '/screens', {
|
|
41
|
+
body: { name: options.name, ...(options.group != null ? { groupId: Number(options.group) } : {}) },
|
|
42
|
+
});
|
|
43
|
+
(0, output_1.emit)((0, auth_1.globalJson)(this), result, () => console.log(`已创建大屏 ${result.id}:${result.name}`));
|
|
44
|
+
}
|
|
45
|
+
catch (error) {
|
|
46
|
+
(0, client_1.exitOnError)(error);
|
|
47
|
+
}
|
|
48
|
+
});
|
|
49
|
+
screen.command('get')
|
|
50
|
+
.description('查看大屏详情')
|
|
51
|
+
.argument('<screenId>', '大屏 id')
|
|
52
|
+
.action(async function (screenId) {
|
|
53
|
+
await runJson(this, () => (0, client_1.createClient)().request('GET', `/screens/${screenId}`));
|
|
54
|
+
});
|
|
55
|
+
const document = screen.command('document').description('大屏文档');
|
|
56
|
+
document.command('get')
|
|
57
|
+
.description('读取大屏文档')
|
|
58
|
+
.argument('<screenId>')
|
|
59
|
+
.option('-o, --output <file>', '写入文件')
|
|
60
|
+
.action(async function (screenId, options) {
|
|
61
|
+
try {
|
|
62
|
+
const result = await (0, client_1.createClient)().request('GET', `/screens/${screenId}/document`);
|
|
63
|
+
if (options.output != null)
|
|
64
|
+
(0, node_fs_1.writeFileSync)(options.output, JSON.stringify(result, null, 2));
|
|
65
|
+
(0, output_1.emit)((0, auth_1.globalJson)(this), result, () => {
|
|
66
|
+
console.log(options.output != null ? `已写入 ${options.output}` : JSON.stringify(result, null, 2));
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
catch (error) {
|
|
70
|
+
(0, client_1.exitOnError)(error);
|
|
71
|
+
}
|
|
72
|
+
});
|
|
73
|
+
document.command('put')
|
|
74
|
+
.description('用文档文件更新大屏')
|
|
75
|
+
.argument('<screenId>')
|
|
76
|
+
.requiredOption('-f, --file <file>', '文档 JSON 文件')
|
|
77
|
+
.option('--if-match <revision>', '期望的 revision')
|
|
78
|
+
.action(async function (screenId, options) {
|
|
79
|
+
try {
|
|
80
|
+
const documentBody = JSON.parse((0, node_fs_1.readFileSync)(options.file, 'utf8'));
|
|
81
|
+
const result = await (0, client_1.createClient)().request('PUT', `/screens/${screenId}/document`, {
|
|
82
|
+
body: documentBody,
|
|
83
|
+
ifMatch: options.ifMatch,
|
|
84
|
+
});
|
|
85
|
+
(0, output_1.emit)((0, auth_1.globalJson)(this), result, () => reportChanges(result));
|
|
86
|
+
}
|
|
87
|
+
catch (error) {
|
|
88
|
+
(0, client_1.exitOnError)(error);
|
|
89
|
+
}
|
|
90
|
+
});
|
|
91
|
+
screen.command('apply')
|
|
92
|
+
.description('执行一批原子操作')
|
|
93
|
+
.argument('<screenId>')
|
|
94
|
+
.requiredOption('-f, --file <file>', '操作 JSON 文件,形如 {"operations": [...]}')
|
|
95
|
+
.option('--if-match <revision>')
|
|
96
|
+
.action(async function (screenId, options) {
|
|
97
|
+
try {
|
|
98
|
+
const body = JSON.parse((0, node_fs_1.readFileSync)(options.file, 'utf8'));
|
|
99
|
+
const result = await (0, client_1.createClient)().request('POST', `/screens/${screenId}/operations`, {
|
|
100
|
+
body,
|
|
101
|
+
ifMatch: options.ifMatch,
|
|
102
|
+
});
|
|
103
|
+
(0, output_1.emit)((0, auth_1.globalJson)(this), result, () => reportChanges(result));
|
|
104
|
+
}
|
|
105
|
+
catch (error) {
|
|
106
|
+
(0, client_1.exitOnError)(error);
|
|
107
|
+
}
|
|
108
|
+
});
|
|
109
|
+
screen.command('validate')
|
|
110
|
+
.description('校验大屏或一份待写入的文档')
|
|
111
|
+
.argument('<screenId>')
|
|
112
|
+
.option('-f, --file <file>', '校验文件里的文档,而不是已保存内容')
|
|
113
|
+
.action(async function (screenId, options) {
|
|
114
|
+
try {
|
|
115
|
+
const body = options.file != null ? { document: JSON.parse((0, node_fs_1.readFileSync)(options.file, 'utf8')) } : {};
|
|
116
|
+
const result = await (0, client_1.createClient)().request('POST', `/screens/${screenId}/validate`, { body });
|
|
117
|
+
(0, output_1.emit)((0, auth_1.globalJson)(this), result, () => {
|
|
118
|
+
console.log(result.valid ? '校验通过' : '校验未通过');
|
|
119
|
+
for (const issue of result.issues ?? [])
|
|
120
|
+
console.log(`[${issue.severity}] ${issue.message}`);
|
|
121
|
+
});
|
|
122
|
+
if (!result.valid)
|
|
123
|
+
process.exit(1);
|
|
124
|
+
}
|
|
125
|
+
catch (error) {
|
|
126
|
+
(0, client_1.exitOnError)(error);
|
|
127
|
+
}
|
|
128
|
+
});
|
|
129
|
+
screen.command('publish')
|
|
130
|
+
.argument('<screenId>')
|
|
131
|
+
.description('发布大屏')
|
|
132
|
+
.action(async (screenId) => {
|
|
133
|
+
await runVoid('PUT', `/screens/${screenId}/publish`, `已发布大屏 ${screenId}`);
|
|
134
|
+
});
|
|
135
|
+
screen.command('unpublish')
|
|
136
|
+
.argument('<screenId>')
|
|
137
|
+
.description('取消发布')
|
|
138
|
+
.action(async (screenId) => {
|
|
139
|
+
await runVoid('DELETE', `/screens/${screenId}/publish`, `已取消发布大屏 ${screenId}`);
|
|
140
|
+
});
|
|
141
|
+
screen.command('snapshot')
|
|
142
|
+
.description('截图预览页,供搭建后自检布局')
|
|
143
|
+
.argument('<screenId>')
|
|
144
|
+
.option('-o, --output <file>', '输出图片', 'snapshot.png')
|
|
145
|
+
.action(async (screenId, options) => {
|
|
146
|
+
try {
|
|
147
|
+
await takeSnapshot(screenId, options.output);
|
|
148
|
+
}
|
|
149
|
+
catch (error) {
|
|
150
|
+
(0, client_1.exitOnError)(error);
|
|
151
|
+
}
|
|
152
|
+
});
|
|
153
|
+
}
|
|
154
|
+
async function takeSnapshot(screenId, output) {
|
|
155
|
+
const target = (0, config_1.activeTarget)();
|
|
156
|
+
if (target == null)
|
|
157
|
+
throw new Error((0, config_1.missingWorkspaceMessage)());
|
|
158
|
+
const issued = await (0, client_1.createClient)().request('POST', `/screens/${screenId}/preview-token`);
|
|
159
|
+
const url = (0, config_1.joinBase)(target.baseUrl, issued.previewPath);
|
|
160
|
+
let chromium;
|
|
161
|
+
try {
|
|
162
|
+
chromium = require('playwright').chromium;
|
|
163
|
+
}
|
|
164
|
+
catch {
|
|
165
|
+
throw new Error('没有安装 playwright。运行 npm i -g playwright && npx playwright install chromium 后重试');
|
|
166
|
+
}
|
|
167
|
+
const browser = await chromium.launch({ headless: true });
|
|
168
|
+
try {
|
|
169
|
+
const page = await browser.newPage({ viewport: { width: 1920, height: 1080 } });
|
|
170
|
+
await page.goto(url, { waitUntil: 'networkidle' });
|
|
171
|
+
await page.screenshot({ path: output, fullPage: true });
|
|
172
|
+
}
|
|
173
|
+
finally {
|
|
174
|
+
await browser.close();
|
|
175
|
+
}
|
|
176
|
+
console.log(`已截图到 ${output}`);
|
|
177
|
+
}
|
|
178
|
+
async function runJson(command, call) {
|
|
179
|
+
try {
|
|
180
|
+
const result = await call();
|
|
181
|
+
(0, output_1.emit)((0, auth_1.globalJson)(command), result, () => console.log(JSON.stringify(result, null, 2)));
|
|
182
|
+
}
|
|
183
|
+
catch (error) {
|
|
184
|
+
(0, client_1.exitOnError)(error);
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
async function runVoid(method, path, message) {
|
|
188
|
+
try {
|
|
189
|
+
await (0, client_1.createClient)().request(method, path);
|
|
190
|
+
console.log(message);
|
|
191
|
+
}
|
|
192
|
+
catch (error) {
|
|
193
|
+
(0, client_1.exitOnError)(error);
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
function reportChanges(result) {
|
|
197
|
+
const { added, updated, removed } = result.changes;
|
|
198
|
+
console.log(`已写入。新增 ${added},修改 ${updated},删除 ${removed}。revision ${result.revision}`);
|
|
199
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.registerSkills = registerSkills;
|
|
4
|
+
const node_fs_1 = require("node:fs");
|
|
5
|
+
const node_os_1 = require("node:os");
|
|
6
|
+
const node_path_1 = require("node:path");
|
|
7
|
+
/** 技能随 CLI 发布,安装到各 AI 工具的技能目录 */
|
|
8
|
+
const SKILL_TARGETS = [
|
|
9
|
+
(0, node_path_1.join)((0, node_os_1.homedir)(), '.agents', 'skills'),
|
|
10
|
+
(0, node_path_1.join)((0, node_os_1.homedir)(), '.claude', 'skills'),
|
|
11
|
+
(0, node_path_1.join)((0, node_os_1.homedir)(), '.cursor', 'skills'),
|
|
12
|
+
(0, node_path_1.join)((0, node_os_1.homedir)(), '.codex', 'skills'),
|
|
13
|
+
];
|
|
14
|
+
function registerSkills(program) {
|
|
15
|
+
program.command('skills')
|
|
16
|
+
.description('安装随 CLI 附带的技能')
|
|
17
|
+
.command('install')
|
|
18
|
+
.description('安装到 Claude、Cursor、Codex 的技能目录')
|
|
19
|
+
.action(() => {
|
|
20
|
+
const source = (0, node_path_1.join)(__dirname, '..', '..', 'skills');
|
|
21
|
+
if (!(0, node_fs_1.existsSync)(source)) {
|
|
22
|
+
console.error('没有找到技能目录,确认 CLI 安装完整');
|
|
23
|
+
process.exit(1);
|
|
24
|
+
}
|
|
25
|
+
const names = (0, node_fs_1.readdirSync)(source).filter(name => (0, node_fs_1.existsSync)((0, node_path_1.join)(source, name, 'SKILL.md')));
|
|
26
|
+
const canonical = SKILL_TARGETS[0];
|
|
27
|
+
(0, node_fs_1.mkdirSync)(canonical, { recursive: true });
|
|
28
|
+
for (const name of names) {
|
|
29
|
+
const target = (0, node_path_1.join)(canonical, name);
|
|
30
|
+
(0, node_fs_1.rmSync)(target, { recursive: true, force: true });
|
|
31
|
+
(0, node_fs_1.cpSync)((0, node_path_1.join)(source, name), target, { recursive: true });
|
|
32
|
+
}
|
|
33
|
+
for (const linkRoot of SKILL_TARGETS.slice(1)) {
|
|
34
|
+
(0, node_fs_1.mkdirSync)(linkRoot, { recursive: true });
|
|
35
|
+
for (const name of names)
|
|
36
|
+
linkSkill((0, node_path_1.join)(canonical, name), (0, node_path_1.join)(linkRoot, name));
|
|
37
|
+
}
|
|
38
|
+
console.log(`已安装 ${names.length} 个技能:${names.join('、')}`);
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
function linkSkill(from, to) {
|
|
42
|
+
if ((0, node_fs_1.existsSync)(to)) {
|
|
43
|
+
if ((0, node_fs_1.lstatSync)(to).isSymbolicLink())
|
|
44
|
+
return;
|
|
45
|
+
return;
|
|
46
|
+
}
|
|
47
|
+
try {
|
|
48
|
+
(0, node_fs_1.symlinkSync)(from, to);
|
|
49
|
+
}
|
|
50
|
+
catch {
|
|
51
|
+
(0, node_fs_1.cpSync)(from, to, { recursive: true });
|
|
52
|
+
}
|
|
53
|
+
}
|
package/dist/config.js
ADDED
|
@@ -0,0 +1,421 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.MISSING_WORKSPACE = void 0;
|
|
4
|
+
exports.isSession = isSession;
|
|
5
|
+
exports.listEnvironments = listEnvironments;
|
|
6
|
+
exports.hasMultipleWorkspaces = hasMultipleWorkspaces;
|
|
7
|
+
exports.describeWorkspace = describeWorkspace;
|
|
8
|
+
exports.missingWorkspaceMessage = missingWorkspaceMessage;
|
|
9
|
+
exports.activeTarget = activeTarget;
|
|
10
|
+
exports.joinBase = joinBase;
|
|
11
|
+
exports.apiEndpoint = apiEndpoint;
|
|
12
|
+
exports.setBaseUrl = setBaseUrl;
|
|
13
|
+
exports.addEnvironment = addEnvironment;
|
|
14
|
+
exports.useEnvironment = useEnvironment;
|
|
15
|
+
exports.removeEnvironment = removeEnvironment;
|
|
16
|
+
exports.addSession = addSession;
|
|
17
|
+
exports.saveCurrentSession = saveCurrentSession;
|
|
18
|
+
exports.useKey = useKey;
|
|
19
|
+
exports.removeKey = removeKey;
|
|
20
|
+
exports.listKeys = listKeys;
|
|
21
|
+
const node_child_process_1 = require("node:child_process");
|
|
22
|
+
const node_fs_1 = require("node:fs");
|
|
23
|
+
const node_os_1 = require("node:os");
|
|
24
|
+
const node_path_1 = require("node:path");
|
|
25
|
+
const HOME = process.env['EASYV_SCREEN_HOME'] ?? (0, node_path_1.join)((0, node_os_1.homedir)(), '.easyv-screen');
|
|
26
|
+
const CONFIG_FILE = (0, node_path_1.join)(HOME, 'config.json');
|
|
27
|
+
const SECRET_FILE = (0, node_path_1.join)(HOME, 'credentials.json');
|
|
28
|
+
const KEYCHAIN_SERVICE = 'easyv-screen';
|
|
29
|
+
const USE_KEYCHAIN = (0, node_os_1.platform)() === 'darwin' && process.env['EASYV_SCREEN_HOME'] == null;
|
|
30
|
+
const OPEN_API_PATH = '/api/easyv/open/v1';
|
|
31
|
+
function isSession(value) {
|
|
32
|
+
return value != null && typeof value === 'object' && typeof value.accessToken === 'string' && typeof value.refreshToken === 'string';
|
|
33
|
+
}
|
|
34
|
+
/** 只有一个工作台时对外不出现这个名字,多个工作台时才用来切换 */
|
|
35
|
+
const DEFAULT_ENVIRONMENT = 'default';
|
|
36
|
+
exports.MISSING_WORKSPACE = '还没有配置工作台。先运行 easyv-screen config set --base-url <地址>';
|
|
37
|
+
function listEnvironments() {
|
|
38
|
+
const config = loadConfig();
|
|
39
|
+
return config.environments.map(env => ({
|
|
40
|
+
name: env.name,
|
|
41
|
+
baseUrl: env.baseUrl,
|
|
42
|
+
current: env.name === config.current,
|
|
43
|
+
keys: [...env.keys],
|
|
44
|
+
currentKey: env.currentKey ?? null,
|
|
45
|
+
}));
|
|
46
|
+
}
|
|
47
|
+
function hasMultipleWorkspaces() {
|
|
48
|
+
return loadConfig().environments.length > 1;
|
|
49
|
+
}
|
|
50
|
+
function describeWorkspace() {
|
|
51
|
+
const environments = listEnvironments();
|
|
52
|
+
const current = environments.find(env => env.current);
|
|
53
|
+
if (environments.length <= 1) {
|
|
54
|
+
const only = current ?? environments[0];
|
|
55
|
+
return {
|
|
56
|
+
baseUrl: only?.baseUrl ?? null,
|
|
57
|
+
currentKey: only?.currentKey ?? null,
|
|
58
|
+
keys: only?.keys ?? [],
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
return {
|
|
62
|
+
baseUrl: current?.baseUrl ?? null,
|
|
63
|
+
currentKey: current?.currentKey ?? null,
|
|
64
|
+
keys: current?.keys ?? [],
|
|
65
|
+
current: current?.name ?? null,
|
|
66
|
+
environments,
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
/** 还没配地址,或有多个工作台但没选定当前项时,告诉调用方下一步该运行什么 */
|
|
70
|
+
function missingWorkspaceMessage() {
|
|
71
|
+
const config = loadConfig();
|
|
72
|
+
if (config.environments.length > 1)
|
|
73
|
+
return '还没有选择工作台。运行 easyv-screen config use <名称>';
|
|
74
|
+
return exports.MISSING_WORKSPACE;
|
|
75
|
+
}
|
|
76
|
+
function activeTarget() {
|
|
77
|
+
const config = loadConfig();
|
|
78
|
+
const env = config.environments.find(item => item.name === config.current);
|
|
79
|
+
if (env == null)
|
|
80
|
+
return undefined;
|
|
81
|
+
const credential = env.currentKey == null ? undefined : readSecrets()[env.name]?.[env.currentKey];
|
|
82
|
+
const token = isSession(credential) ? credential.accessToken : undefined;
|
|
83
|
+
return { name: env.name, baseUrl: env.baseUrl, keyName: env.currentKey, token, credential };
|
|
84
|
+
}
|
|
85
|
+
/** 把路径接到工作台地址后面 */
|
|
86
|
+
function joinBase(baseUrl, path) {
|
|
87
|
+
const base = trimSlash(baseUrl);
|
|
88
|
+
return path.startsWith('/') ? `${base}${path}` : `${base}/${path}`;
|
|
89
|
+
}
|
|
90
|
+
/** 接口根路径。配置里只存工作台地址,请求时补上固定前缀 */
|
|
91
|
+
function apiEndpoint(baseUrl) {
|
|
92
|
+
return joinBase(baseUrl, OPEN_API_PATH);
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* 设置唯一的工作台地址。没有地址时记入名为 default 的一项;已有一项时改这一项的地址。
|
|
96
|
+
* 地址变了就清掉原来的 Key,因为它们属于旧工作台。已有多项时拒绝,改由 add / use 指定名称。
|
|
97
|
+
*/
|
|
98
|
+
function setBaseUrl(url) {
|
|
99
|
+
const baseUrl = normalizeBaseUrl(url);
|
|
100
|
+
const config = loadConfig();
|
|
101
|
+
if (config.environments.length > 1)
|
|
102
|
+
throw new Error('已有多个工作台。添加用 easyv-screen config add --name <名称> --base-url <地址>,切换用 easyv-screen config use <名称>');
|
|
103
|
+
if (config.environments.length === 0) {
|
|
104
|
+
config.environments.push({ name: DEFAULT_ENVIRONMENT, baseUrl, keys: [] });
|
|
105
|
+
config.current = DEFAULT_ENVIRONMENT;
|
|
106
|
+
saveConfig(config);
|
|
107
|
+
return { baseUrl, created: true, changed: true, clearedKeys: false };
|
|
108
|
+
}
|
|
109
|
+
const env = config.environments[0];
|
|
110
|
+
if (env.baseUrl === baseUrl) {
|
|
111
|
+
if (config.current !== env.name) {
|
|
112
|
+
config.current = env.name;
|
|
113
|
+
saveConfig(config);
|
|
114
|
+
}
|
|
115
|
+
return { baseUrl, created: false, changed: false, clearedKeys: false };
|
|
116
|
+
}
|
|
117
|
+
const hadKeys = env.keys.length > 0;
|
|
118
|
+
env.baseUrl = baseUrl;
|
|
119
|
+
env.keys = [];
|
|
120
|
+
delete env.currentKey;
|
|
121
|
+
config.current = env.name;
|
|
122
|
+
saveConfig(config);
|
|
123
|
+
const clearedSecrets = clearEnvironmentSecrets(env.name);
|
|
124
|
+
return { baseUrl, created: false, changed: true, clearedKeys: hadKeys || clearedSecrets };
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* 新增一个工作台地址。同名或同一个地址已存在时拒绝,避免把 Key 拆到两处。
|
|
128
|
+
* `select` 为 true 时立刻切过去。
|
|
129
|
+
*/
|
|
130
|
+
function addEnvironment(input) {
|
|
131
|
+
const name = normalizeName(input.name);
|
|
132
|
+
const baseUrl = normalizeBaseUrl(input.baseUrl);
|
|
133
|
+
const config = loadConfig();
|
|
134
|
+
const sameName = config.environments.find(item => item.name === name);
|
|
135
|
+
if (sameName != null)
|
|
136
|
+
throw new Error(`环境「${name}」已存在。切换用 easyv-screen config use ${name}`);
|
|
137
|
+
const sameUrl = config.environments.find(item => item.baseUrl === baseUrl);
|
|
138
|
+
if (sameUrl != null) {
|
|
139
|
+
if (config.environments.length === 1)
|
|
140
|
+
throw new Error('这个地址已经是当前工作台。要添加另一个工作台,请换一个地址');
|
|
141
|
+
throw new Error(`这个地址已经在环境「${sameUrl.name}」里。切换用 easyv-screen config use ${sameUrl.name}`);
|
|
142
|
+
}
|
|
143
|
+
const created = { name, baseUrl, keys: [] };
|
|
144
|
+
config.environments.push(created);
|
|
145
|
+
if (input.select === true || config.current == null)
|
|
146
|
+
config.current = name;
|
|
147
|
+
saveConfig(config);
|
|
148
|
+
return created;
|
|
149
|
+
}
|
|
150
|
+
function useEnvironment(name) {
|
|
151
|
+
const config = loadConfig();
|
|
152
|
+
const env = requireEnvironment(config, normalizeName(name));
|
|
153
|
+
config.current = env.name;
|
|
154
|
+
saveConfig(config);
|
|
155
|
+
return env;
|
|
156
|
+
}
|
|
157
|
+
/** 删除工作台。只有一个时可以不写名称;有多个时必须带上环境名 */
|
|
158
|
+
function removeEnvironment(name) {
|
|
159
|
+
const config = loadConfig();
|
|
160
|
+
const target = resolveRemoveTarget(config, name);
|
|
161
|
+
if (!config.environments.some(item => item.name === target)) {
|
|
162
|
+
if (config.environments.length > 1) {
|
|
163
|
+
const names = config.environments.map(item => item.name).join('、');
|
|
164
|
+
throw new Error(`没有环境「${target}」。现有环境:${names}`);
|
|
165
|
+
}
|
|
166
|
+
throw new Error(config.environments.length === 0 ? exports.MISSING_WORKSPACE : `没有名为「${target}」的工作台`);
|
|
167
|
+
}
|
|
168
|
+
config.environments = config.environments.filter(item => item.name !== target);
|
|
169
|
+
if (config.current === target)
|
|
170
|
+
config.current = config.environments.length === 1 ? config.environments[0].name : undefined;
|
|
171
|
+
saveConfig(config);
|
|
172
|
+
clearEnvironmentSecrets(target);
|
|
173
|
+
return target;
|
|
174
|
+
}
|
|
175
|
+
/** 设备码登录成功后保存。之后访问令牌过期会就地换成新的 */
|
|
176
|
+
function addSession(name, session) {
|
|
177
|
+
writeCredential(name, session);
|
|
178
|
+
}
|
|
179
|
+
function saveCurrentSession(session) {
|
|
180
|
+
const config = loadConfig();
|
|
181
|
+
const env = requireCurrent(config);
|
|
182
|
+
if (env.currentKey == null)
|
|
183
|
+
throw new Error('还没有选中的登录状态');
|
|
184
|
+
const secrets = readSecrets();
|
|
185
|
+
secrets[env.name] = { ...secrets[env.name], [env.currentKey]: session };
|
|
186
|
+
writeSecrets(secrets);
|
|
187
|
+
}
|
|
188
|
+
function useKey(name) {
|
|
189
|
+
const keyName = normalizeName(name);
|
|
190
|
+
const config = loadConfig();
|
|
191
|
+
const env = requireCurrent(config);
|
|
192
|
+
if (!env.keys.includes(keyName))
|
|
193
|
+
throw new Error(missingKeyMessage(env, keyName));
|
|
194
|
+
env.currentKey = keyName;
|
|
195
|
+
saveConfig(config);
|
|
196
|
+
}
|
|
197
|
+
function removeKey(name) {
|
|
198
|
+
const keyName = normalizeName(name);
|
|
199
|
+
const config = loadConfig();
|
|
200
|
+
const env = requireCurrent(config);
|
|
201
|
+
if (!env.keys.includes(keyName))
|
|
202
|
+
throw new Error(missingKeyMessage(env, keyName));
|
|
203
|
+
env.keys = env.keys.filter(item => item !== keyName);
|
|
204
|
+
if (env.currentKey === keyName)
|
|
205
|
+
env.currentKey = undefined;
|
|
206
|
+
saveConfig(config);
|
|
207
|
+
const secrets = readSecrets();
|
|
208
|
+
if (secrets[env.name] != null)
|
|
209
|
+
delete secrets[env.name][keyName];
|
|
210
|
+
writeSecrets(secrets);
|
|
211
|
+
}
|
|
212
|
+
function listKeys() {
|
|
213
|
+
const config = loadConfig();
|
|
214
|
+
const env = config.environments.find(item => item.name === config.current);
|
|
215
|
+
if (env == null)
|
|
216
|
+
return [];
|
|
217
|
+
const secrets = readSecrets()[env.name] ?? {};
|
|
218
|
+
return env.keys.map(name => ({
|
|
219
|
+
name,
|
|
220
|
+
appId: labelOf(secrets[name]),
|
|
221
|
+
current: name === env.currentKey,
|
|
222
|
+
}));
|
|
223
|
+
}
|
|
224
|
+
function writeCredential(name, credential) {
|
|
225
|
+
const keyName = normalizeName(name);
|
|
226
|
+
const config = loadConfig();
|
|
227
|
+
const env = requireCurrent(config);
|
|
228
|
+
if (!env.keys.includes(keyName))
|
|
229
|
+
env.keys.push(keyName);
|
|
230
|
+
env.currentKey = keyName;
|
|
231
|
+
saveConfig(config);
|
|
232
|
+
const secrets = readSecrets();
|
|
233
|
+
secrets[env.name] = { ...secrets[env.name], [keyName]: credential };
|
|
234
|
+
writeSecrets(secrets);
|
|
235
|
+
}
|
|
236
|
+
function requireCurrent(config) {
|
|
237
|
+
const env = config.environments.find(item => item.name === config.current);
|
|
238
|
+
if (env == null)
|
|
239
|
+
throw new Error(missingWorkspaceMessage());
|
|
240
|
+
return env;
|
|
241
|
+
}
|
|
242
|
+
function resolveRemoveTarget(config, name) {
|
|
243
|
+
const given = name?.trim() ?? '';
|
|
244
|
+
if (given.length > 0)
|
|
245
|
+
return normalizeName(given);
|
|
246
|
+
if (config.environments.length === 1)
|
|
247
|
+
return config.environments[0].name;
|
|
248
|
+
if (config.environments.length === 0)
|
|
249
|
+
throw new Error(exports.MISSING_WORKSPACE);
|
|
250
|
+
throw new Error('有多个工作台。请指定要删除的环境:easyv-screen config remove <名称>');
|
|
251
|
+
}
|
|
252
|
+
function clearEnvironmentSecrets(name) {
|
|
253
|
+
const secrets = readSecrets();
|
|
254
|
+
if (secrets[name] == null)
|
|
255
|
+
return false;
|
|
256
|
+
delete secrets[name];
|
|
257
|
+
writeSecrets(secrets);
|
|
258
|
+
return true;
|
|
259
|
+
}
|
|
260
|
+
function requireEnvironment(config, name) {
|
|
261
|
+
const env = config.environments.find(item => item.name === name);
|
|
262
|
+
if (env == null) {
|
|
263
|
+
if (config.environments.length <= 1)
|
|
264
|
+
throw new Error(config.environments.length === 0 ? exports.MISSING_WORKSPACE : '当前只有一个工作台。要再添加一个才需要按名称切换:easyv-screen config add --name <名称> --base-url <地址>');
|
|
265
|
+
const names = config.environments.map(item => item.name).join('、');
|
|
266
|
+
throw new Error(`没有环境「${name}」。现有环境:${names}`);
|
|
267
|
+
}
|
|
268
|
+
return env;
|
|
269
|
+
}
|
|
270
|
+
function missingKeyMessage(env, keyName) {
|
|
271
|
+
const available = env.keys.length > 0 ? env.keys.join('、') : '(空)';
|
|
272
|
+
if (loadConfig().environments.length <= 1)
|
|
273
|
+
return `没有登录「${keyName}」。已有登录:${available}`;
|
|
274
|
+
return `环境「${env.name}」下没有登录「${keyName}」。这个地址下已有登录:${available}`;
|
|
275
|
+
}
|
|
276
|
+
function loadConfig() {
|
|
277
|
+
return selectOnlyEnvironment(parseConfig());
|
|
278
|
+
}
|
|
279
|
+
function parseConfig() {
|
|
280
|
+
const parsed = readJson(CONFIG_FILE);
|
|
281
|
+
if (parsed == null)
|
|
282
|
+
return { environments: [] };
|
|
283
|
+
if (Array.isArray(parsed.environments))
|
|
284
|
+
return withoutWeb(parsed.current, parsed.environments);
|
|
285
|
+
// 旧版本只存了一个地址,读到时收成一个环境。web 字段不再使用
|
|
286
|
+
if (typeof parsed.endpoint === 'string' && parsed.endpoint.length > 0)
|
|
287
|
+
return migrateLegacy(parsed.endpoint);
|
|
288
|
+
return { environments: [] };
|
|
289
|
+
}
|
|
290
|
+
/** 只剩一个工作台时,它就是当前项,调用方不用再选一次 */
|
|
291
|
+
function selectOnlyEnvironment(config) {
|
|
292
|
+
if (config.environments.length !== 1)
|
|
293
|
+
return config;
|
|
294
|
+
const only = config.environments[0];
|
|
295
|
+
if (config.current === only.name)
|
|
296
|
+
return config;
|
|
297
|
+
config.current = only.name;
|
|
298
|
+
saveConfig(config);
|
|
299
|
+
return config;
|
|
300
|
+
}
|
|
301
|
+
/** 丢掉已废弃的 web 字段,baseURL 保持原样 */
|
|
302
|
+
function withoutWeb(current, environments) {
|
|
303
|
+
const hasWeb = environments.some(env => env.web != null);
|
|
304
|
+
const next = environments.map(env => ({
|
|
305
|
+
name: env.name,
|
|
306
|
+
baseUrl: env.baseUrl,
|
|
307
|
+
keys: env.keys ?? [],
|
|
308
|
+
...(env.currentKey != null ? { currentKey: env.currentKey } : {}),
|
|
309
|
+
}));
|
|
310
|
+
const config = { current, environments: next };
|
|
311
|
+
if (hasWeb)
|
|
312
|
+
saveConfig(config);
|
|
313
|
+
return config;
|
|
314
|
+
}
|
|
315
|
+
function migrateLegacy(endpoint) {
|
|
316
|
+
const name = 'default';
|
|
317
|
+
const config = {
|
|
318
|
+
current: name,
|
|
319
|
+
environments: [{
|
|
320
|
+
name,
|
|
321
|
+
baseUrl: normalizeBaseUrl(endpoint),
|
|
322
|
+
keys: [],
|
|
323
|
+
}],
|
|
324
|
+
};
|
|
325
|
+
saveConfig(config);
|
|
326
|
+
return config;
|
|
327
|
+
}
|
|
328
|
+
function saveConfig(config) {
|
|
329
|
+
(0, node_fs_1.mkdirSync)(HOME, { recursive: true });
|
|
330
|
+
(0, node_fs_1.writeFileSync)(CONFIG_FILE, JSON.stringify(config, null, 2));
|
|
331
|
+
}
|
|
332
|
+
function readSecrets() {
|
|
333
|
+
if (USE_KEYCHAIN) {
|
|
334
|
+
const raw = keychainGet();
|
|
335
|
+
const parsed = parseSecret(raw);
|
|
336
|
+
if (parsed != null)
|
|
337
|
+
return parsed;
|
|
338
|
+
}
|
|
339
|
+
return parseSecret(readText(SECRET_FILE)) ?? {};
|
|
340
|
+
}
|
|
341
|
+
function writeSecrets(secrets) {
|
|
342
|
+
const text = JSON.stringify(secrets);
|
|
343
|
+
if (USE_KEYCHAIN && keychainSet(text))
|
|
344
|
+
return;
|
|
345
|
+
(0, node_fs_1.mkdirSync)(HOME, { recursive: true });
|
|
346
|
+
(0, node_fs_1.writeFileSync)(SECRET_FILE, text);
|
|
347
|
+
(0, node_fs_1.chmodSync)(SECRET_FILE, 0o600);
|
|
348
|
+
}
|
|
349
|
+
function parseSecret(raw) {
|
|
350
|
+
if (raw == null || !raw.startsWith('{'))
|
|
351
|
+
return undefined;
|
|
352
|
+
try {
|
|
353
|
+
return JSON.parse(raw);
|
|
354
|
+
}
|
|
355
|
+
catch {
|
|
356
|
+
return undefined;
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
function readJson(file) {
|
|
360
|
+
const text = readText(file);
|
|
361
|
+
if (text == null)
|
|
362
|
+
return undefined;
|
|
363
|
+
try {
|
|
364
|
+
return JSON.parse(text);
|
|
365
|
+
}
|
|
366
|
+
catch {
|
|
367
|
+
return undefined;
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
function readText(file) {
|
|
371
|
+
try {
|
|
372
|
+
const text = (0, node_fs_1.readFileSync)(file, 'utf8');
|
|
373
|
+
return text.length > 0 ? text : undefined;
|
|
374
|
+
}
|
|
375
|
+
catch {
|
|
376
|
+
return undefined;
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
function normalizeName(name) {
|
|
380
|
+
const trimmed = name.trim();
|
|
381
|
+
if (trimmed.length === 0)
|
|
382
|
+
throw new Error('名称不能为空');
|
|
383
|
+
return trimmed;
|
|
384
|
+
}
|
|
385
|
+
function normalizeBaseUrl(url) {
|
|
386
|
+
const trimmed = trimSlash(url.trim());
|
|
387
|
+
if (!/^https?:\/\//.test(trimmed))
|
|
388
|
+
throw new Error('baseURL 需要以 http:// 或 https:// 开头,例如 https://workspace.example.com');
|
|
389
|
+
return trimmed;
|
|
390
|
+
}
|
|
391
|
+
function trimSlash(url) {
|
|
392
|
+
return url.replace(/\/+$/, '');
|
|
393
|
+
}
|
|
394
|
+
function labelOf(credential) {
|
|
395
|
+
if (credential == null)
|
|
396
|
+
return '';
|
|
397
|
+
if (isSession(credential))
|
|
398
|
+
return '已登录';
|
|
399
|
+
return '需重新登录';
|
|
400
|
+
}
|
|
401
|
+
function keychainGet() {
|
|
402
|
+
try {
|
|
403
|
+
return (0, node_child_process_1.execFileSync)('security', ['find-generic-password', '-a', KEYCHAIN_SERVICE, '-s', KEYCHAIN_SERVICE, '-w'], {
|
|
404
|
+
stdio: ['ignore', 'pipe', 'ignore'],
|
|
405
|
+
}).toString().trim() || undefined;
|
|
406
|
+
}
|
|
407
|
+
catch {
|
|
408
|
+
return undefined;
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
function keychainSet(secret) {
|
|
412
|
+
try {
|
|
413
|
+
(0, node_child_process_1.execFileSync)('security', ['add-generic-password', '-U', '-a', KEYCHAIN_SERVICE, '-s', KEYCHAIN_SERVICE, '-w', secret], {
|
|
414
|
+
stdio: 'ignore',
|
|
415
|
+
});
|
|
416
|
+
return true;
|
|
417
|
+
}
|
|
418
|
+
catch {
|
|
419
|
+
return false;
|
|
420
|
+
}
|
|
421
|
+
}
|