@xi4z/dsh-utils 0.5.0 → 0.7.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 +258 -314
- package/cordis.patch.yml +36 -37
- package/lib/index.d.ts +5 -63
- package/lib/index.js +6 -859
- package/lib/index.js.map +1 -1
- package/locale/en.json +1 -1
- package/locale/zh.json +1 -1
- package/package.json +10 -46
- package/src/index.ts +6 -927
- package/client.js +0 -2330
- package/lib/ui-host.d.ts +0 -96
- package/lib/ui-host.js +0 -970
- package/lib/ui-host.js.map +0 -1
- package/packages/approval-policy/lib/index.d.ts +0 -297
- package/packages/approval-policy/lib/index.js +0 -425
- package/packages/approval-policy/lib/index.js.map +0 -1
- package/packages/approval-policy/locale/en.json +0 -6
- package/packages/approval-policy/locale/zh.json +0 -6
- package/packages/notify/lib/index.d.ts +0 -290
- package/packages/notify/lib/index.js +0 -915
- package/packages/notify/lib/index.js.map +0 -1
- package/packages/notify/locale/en.json +0 -6
- package/packages/notify/locale/zh.json +0 -6
- package/packages/skill-panel/lib/index.d.ts +0 -49
- package/packages/skill-panel/lib/index.js +0 -420
- package/packages/skill-panel/lib/index.js.map +0 -1
- package/packages/skill-panel/locale/en.json +0 -6
- package/packages/skill-panel/locale/zh.json +0 -6
- package/packages/utils-agents/lib/git.d.ts +0 -87
- package/packages/utils-agents/lib/git.js +0 -403
- package/packages/utils-agents/lib/git.js.map +0 -1
- package/packages/utils-agents/lib/global-repo.d.ts +0 -57
- package/packages/utils-agents/lib/global-repo.js +0 -301
- package/packages/utils-agents/lib/global-repo.js.map +0 -1
- package/packages/utils-agents/lib/index.d.ts +0 -80
- package/packages/utils-agents/lib/index.js +0 -435
- package/packages/utils-agents/lib/index.js.map +0 -1
- package/packages/utils-agents/lib/legacy.d.ts +0 -30
- package/packages/utils-agents/lib/legacy.js +0 -141
- package/packages/utils-agents/lib/legacy.js.map +0 -1
- package/packages/utils-agents/lib/native.d.ts +0 -74
- package/packages/utils-agents/lib/native.js +0 -232
- package/packages/utils-agents/lib/native.js.map +0 -1
- package/packages/utils-agents/lib/presets.d.ts +0 -34
- package/packages/utils-agents/lib/presets.js +0 -312
- package/packages/utils-agents/lib/presets.js.map +0 -1
- package/packages/utils-agents/lib/shared.d.ts +0 -105
- package/packages/utils-agents/lib/shared.js +0 -507
- package/packages/utils-agents/lib/shared.js.map +0 -1
- package/packages/utils-agents/lib/update.d.ts +0 -129
- package/packages/utils-agents/lib/update.js +0 -507
- package/packages/utils-agents/lib/update.js.map +0 -1
- package/packages/utils-agents/lib/util.d.ts +0 -215
- package/packages/utils-agents/lib/util.js +0 -475
- package/packages/utils-agents/lib/util.js.map +0 -1
- package/packages/utils-agents/locale/en.json +0 -6
- package/packages/utils-agents/locale/zh.json +0 -6
- package/skills/dsh-approval-policy-config/SKILL.md +0 -96
- package/src/ui-host.ts +0 -1073
package/lib/ui-host.js
DELETED
|
@@ -1,970 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* `dsh-utils` main component (`utils-main`), repository-sync half.
|
|
3
|
-
*
|
|
4
|
-
* `src/index.ts` applies this module, so the `utils-main` row owns both halves:
|
|
5
|
-
* recursive `SKILL.md` discovery and the JSON routes behind the skill-repository
|
|
6
|
-
* panel. The browser half is this package's `client.js`, served from the same
|
|
7
|
-
* package-root row.
|
|
8
|
-
*
|
|
9
|
-
* The panel configures one Git repository (URL, branch, target directory, and an
|
|
10
|
-
* optional deploy key). A sync clones a missing target or fast-forwards an
|
|
11
|
-
* existing checkout of the same branch, then initializes submodules on a
|
|
12
|
-
* best-effort basis; the target's nested `SKILL.md` files are picked up by
|
|
13
|
-
* this component's discovery provider. Nothing is ever pushed.
|
|
14
|
-
*
|
|
15
|
-
* Routes and durable state keep the `dsh-utils-ui` names (the API paths, the
|
|
16
|
-
* panel tab, and `$DSH_HOME/storages/dsh-utils-ui.json` plus an optional
|
|
17
|
-
* `.deploy-key`) so a profile that mounted the former standalone UI host keeps
|
|
18
|
-
* its saved settings after the merge. Both files are written atomically with
|
|
19
|
-
* mode 600. The key's content never reaches a response, a log line, or a git
|
|
20
|
-
* argument vector: git only ever receives its path through `GIT_SSH_COMMAND`.
|
|
21
|
-
* Every command runs through `execFile` (never a shell) with terminal prompts
|
|
22
|
-
* disabled and a bounded timeout.
|
|
23
|
-
*
|
|
24
|
-
* @module dsh-utils/ui-host
|
|
25
|
-
*/
|
|
26
|
-
import { execFile } from 'node:child_process';
|
|
27
|
-
import { randomBytes } from 'node:crypto';
|
|
28
|
-
import { chmod, mkdir, readFile, readdir, rename, rm, stat, writeFile } from 'node:fs/promises';
|
|
29
|
-
import { homedir } from 'node:os';
|
|
30
|
-
import { dirname, isAbsolute, join, relative, resolve } from 'node:path';
|
|
31
|
-
import { fileURLToPath } from 'node:url';
|
|
32
|
-
/** Exact Connection routes owned by the sync panel. */
|
|
33
|
-
export const ROUTE_PATHS = {
|
|
34
|
-
status: '/api/dsh-utils-ui/status',
|
|
35
|
-
config: '/api/dsh-utils-ui/config',
|
|
36
|
-
key: '/api/dsh-utils-ui/key',
|
|
37
|
-
sync: '/api/dsh-utils-ui/sync',
|
|
38
|
-
};
|
|
39
|
-
/** GET: repository settings, target state, last sync. */
|
|
40
|
-
export const STATUS_PATH = ROUTE_PATHS.status;
|
|
41
|
-
/** POST: replace the repository settings. */
|
|
42
|
-
export const CONFIG_PATH = ROUTE_PATHS.config;
|
|
43
|
-
/** POST: store or clear the deploy key. */
|
|
44
|
-
export const KEY_PATH = ROUTE_PATHS.key;
|
|
45
|
-
/** POST: clone or fast-forward the target. */
|
|
46
|
-
export const SYNC_PATH = ROUTE_PATHS.sync;
|
|
47
|
-
/** Default repository: the public upstream of this machine's skill collection. */
|
|
48
|
-
export const DEFAULT_REPO_URL = 'https://github.com/xi4z/skills';
|
|
49
|
-
/** Default branch: the Agent branch of that repository. */
|
|
50
|
-
export const DEFAULT_BRANCH = 'Agent';
|
|
51
|
-
/** Reply headers shared by successful and failed route responses. */
|
|
52
|
-
const JSON_HEADERS = {
|
|
53
|
-
'content-type': 'application/json; charset=utf-8',
|
|
54
|
-
'cache-control': 'no-store',
|
|
55
|
-
};
|
|
56
|
-
/** Directory under $DSH_HOME holding the panel's durable files. */
|
|
57
|
-
const STORAGE_DIR_NAME = 'storages';
|
|
58
|
-
/** Repository settings plus the last sync outcome. */
|
|
59
|
-
const STATE_FILE_NAME = 'dsh-utils-ui.json';
|
|
60
|
-
/** Deploy key pasted into the panel; never returned to the browser. */
|
|
61
|
-
const KEY_FILE_NAME = 'dsh-utils-ui.deploy-key';
|
|
62
|
-
/** Every git command is bounded, so a hung remote cannot hold the request open. */
|
|
63
|
-
const GIT_TIMEOUT_MS = 120000;
|
|
64
|
-
/** JSON request bodies are configuration, not uploads. */
|
|
65
|
-
const BODY_LIMIT_BYTES = 64 * 1024;
|
|
66
|
-
/** Pasted deploy keys are a few kilobytes; anything larger is not a key. */
|
|
67
|
-
const KEY_LIMIT_BYTES = 64 * 1024;
|
|
68
|
-
/** stdout/stderr cap for one git command. */
|
|
69
|
-
const GIT_MAX_BUFFER = 8 * 1024 * 1024;
|
|
70
|
-
/** Skill discovery never descends deeper than this when counting SKILL.md. */
|
|
71
|
-
const MAX_SCAN_DEPTH = 12;
|
|
72
|
-
/** Error lines kept in a failed sync response. */
|
|
73
|
-
const MAX_LOG_LINES = 40;
|
|
74
|
-
/** Branch names git itself accepts here: no spaces, no leading dash, no '..'. */
|
|
75
|
-
const BRANCH_PATTERN = /^[A-Za-z0-9._/-]+$/;
|
|
76
|
-
/**
|
|
77
|
-
* HTTPS hosts whose repositories are commonly authenticated with an SSH deploy
|
|
78
|
-
* key; an HTTPS URL on one of these is rewritten to SSH when a key is present.
|
|
79
|
-
*/
|
|
80
|
-
const SSH_HOSTS = new Set(['github.com', 'gitlab.com', 'gitee.com', 'bitbucket.org', 'codeberg.org']);
|
|
81
|
-
/**
|
|
82
|
-
* The package root, used to refuse a target directory inside this plugin.
|
|
83
|
-
* The module builds to `lib/ui-host.js`, so the package root is one directory
|
|
84
|
-
* up.
|
|
85
|
-
*/
|
|
86
|
-
const PACKAGE_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..');
|
|
87
|
-
/** A route failure carrying its HTTP status and an optional sanitized git log. */
|
|
88
|
-
class UiError extends Error {
|
|
89
|
-
status;
|
|
90
|
-
log;
|
|
91
|
-
/**
|
|
92
|
-
* @param message - user-facing, sanitized message.
|
|
93
|
-
* @param status - HTTP status the route answers with.
|
|
94
|
-
* @param log - sanitized git output lines, when the failure came from git.
|
|
95
|
-
*/
|
|
96
|
-
constructor(message, status, log) {
|
|
97
|
-
super(message);
|
|
98
|
-
this.name = 'UiError';
|
|
99
|
-
this.status = status;
|
|
100
|
-
this.log = log;
|
|
101
|
-
}
|
|
102
|
-
}
|
|
103
|
-
/**
|
|
104
|
-
* Activate the host half: register the four panel routes when this deployment
|
|
105
|
-
* provides a Connection. A non-web host simply has no routes.
|
|
106
|
-
* @param ctx - host Cordis context.
|
|
107
|
-
*/
|
|
108
|
-
export function applyUiHost(ctx) {
|
|
109
|
-
ctx.inject(['connection'], (scope) => {
|
|
110
|
-
const connection = scope.connection;
|
|
111
|
-
if (!connection)
|
|
112
|
-
return;
|
|
113
|
-
registerRoute(scope, ctx, connection, ROUTE_PATHS.status, ['GET'], (request) => handleStatus(ctx, request));
|
|
114
|
-
registerRoute(scope, ctx, connection, ROUTE_PATHS.config, ['POST'], (request) => handleConfig(ctx, request));
|
|
115
|
-
registerRoute(scope, ctx, connection, ROUTE_PATHS.key, ['POST'], (request) => handleKey(ctx, request));
|
|
116
|
-
registerRoute(scope, ctx, connection, ROUTE_PATHS.sync, ['POST'], (request) => handleSync(ctx, request));
|
|
117
|
-
});
|
|
118
|
-
}
|
|
119
|
-
/**
|
|
120
|
-
* Register one exact route, logging (rather than throwing) a registration
|
|
121
|
-
* failure so a conflicting contribution cannot take the whole row down.
|
|
122
|
-
* @param scope - context owning the Connection service.
|
|
123
|
-
* @param ctx - host context for warnings.
|
|
124
|
-
* @param connection - Connection fetch registry.
|
|
125
|
-
* @param path - exact route path.
|
|
126
|
-
* @param methods - HTTP methods the route owns.
|
|
127
|
-
* @param fetch - request handler.
|
|
128
|
-
*/
|
|
129
|
-
function registerRoute(scope, ctx, connection, path, methods, fetch) {
|
|
130
|
-
scope.effect(() => {
|
|
131
|
-
try {
|
|
132
|
-
return connection.fetch.register({ path, methods, requestBody: 'buffered', fetch });
|
|
133
|
-
}
|
|
134
|
-
catch (error) {
|
|
135
|
-
ctx.logger.warn('utils-main repo-sync: cannot register ' + path + ': ' + errorMessage(error));
|
|
136
|
-
return () => Promise.resolve();
|
|
137
|
-
}
|
|
138
|
-
}, 'utils-main repo-sync: ' + path);
|
|
139
|
-
}
|
|
140
|
-
/**
|
|
141
|
-
* Serve the panel's status: configuration, key source, target checkout, and the
|
|
142
|
-
* last sync outcome.
|
|
143
|
-
* @param ctx - host context for warnings.
|
|
144
|
-
* @param request - incoming GET request.
|
|
145
|
-
* @returns JSON status response.
|
|
146
|
-
*/
|
|
147
|
-
async function handleStatus(ctx, request) {
|
|
148
|
-
void request;
|
|
149
|
-
try {
|
|
150
|
-
return json(await statusPayload(), 200);
|
|
151
|
-
}
|
|
152
|
-
catch (error) {
|
|
153
|
-
ctx.logger.warn('utils-main repo-sync: cannot read status: ' + errorMessage(error));
|
|
154
|
-
return json({ error: errorMessage(error) }, 500);
|
|
155
|
-
}
|
|
156
|
-
}
|
|
157
|
-
/**
|
|
158
|
-
* Serve the panel's configuration update.
|
|
159
|
-
* @param ctx - host context for warnings.
|
|
160
|
-
* @param request - incoming POST request with a JSON object body.
|
|
161
|
-
* @returns JSON configuration response.
|
|
162
|
-
*/
|
|
163
|
-
async function handleConfig(ctx, request) {
|
|
164
|
-
try {
|
|
165
|
-
const body = await readJsonBody(request);
|
|
166
|
-
const state = await readState();
|
|
167
|
-
const next = applyConfigPatch(state, body);
|
|
168
|
-
await writeState(next);
|
|
169
|
-
const key = await inspectKey(next);
|
|
170
|
-
return json({ ok: true, ...publicConfig(next), keySource: key.keySource, hasStoredKey: key.hasStoredKey }, 200);
|
|
171
|
-
}
|
|
172
|
-
catch (error) {
|
|
173
|
-
return failure(ctx, error, '保存配置失败');
|
|
174
|
-
}
|
|
175
|
-
}
|
|
176
|
-
/**
|
|
177
|
-
* Serve the panel's deploy-key update. An empty key clears the stored key.
|
|
178
|
-
* @param ctx - host context for warnings.
|
|
179
|
-
* @param request - incoming POST request with a key field.
|
|
180
|
-
* @returns JSON { hasStoredKey, keySource }; never the key itself.
|
|
181
|
-
*/
|
|
182
|
-
async function handleKey(ctx, request) {
|
|
183
|
-
try {
|
|
184
|
-
const body = await readJsonBody(request);
|
|
185
|
-
if (body === null || typeof body !== 'object' || Array.isArray(body)) {
|
|
186
|
-
throw new UiError('请求体必须是 JSON 对象', 400);
|
|
187
|
-
}
|
|
188
|
-
const value = body.key;
|
|
189
|
-
if (value === undefined)
|
|
190
|
-
throw new UiError('请求体缺少 key 字段', 400);
|
|
191
|
-
if (typeof value !== 'string')
|
|
192
|
-
throw new UiError('key 必须是字符串', 400);
|
|
193
|
-
const material = value.replace(/\r\n/g, '\n');
|
|
194
|
-
if (material.includes('\u0000'))
|
|
195
|
-
throw new UiError('key 不能包含 NUL 字符', 400);
|
|
196
|
-
if (Buffer.byteLength(material, 'utf8') > KEY_LIMIT_BYTES)
|
|
197
|
-
throw new UiError('key 过大', 400);
|
|
198
|
-
if (material.trim() === '') {
|
|
199
|
-
await rm(storedKeyFile(), { force: true });
|
|
200
|
-
}
|
|
201
|
-
else {
|
|
202
|
-
await writePrivateFile(storedKeyFile(), material.endsWith('\n') ? material : material + '\n');
|
|
203
|
-
}
|
|
204
|
-
const state = await readState();
|
|
205
|
-
const key = await inspectKey(state);
|
|
206
|
-
return json({ ok: true, hasStoredKey: key.hasStoredKey, keySource: key.keySource, keyPath: state.keyPath }, 200);
|
|
207
|
-
}
|
|
208
|
-
catch (error) {
|
|
209
|
-
return failure(ctx, error, '保存密钥失败');
|
|
210
|
-
}
|
|
211
|
-
}
|
|
212
|
-
/**
|
|
213
|
-
* Serve the panel's sync: clone a missing target, or fast-forward an existing
|
|
214
|
-
* checkout of the configured branch. The outcome is recorded either way.
|
|
215
|
-
* @param ctx - host context for warnings.
|
|
216
|
-
* @param request - incoming POST request; the body is ignored.
|
|
217
|
-
* @returns JSON { ok, at, commit, skills, warnings } or { error, log? }.
|
|
218
|
-
*/
|
|
219
|
-
async function handleSync(ctx, request) {
|
|
220
|
-
void request;
|
|
221
|
-
const state = await readState();
|
|
222
|
-
try {
|
|
223
|
-
const key = await inspectKey(state);
|
|
224
|
-
const result = await performSync(state, key);
|
|
225
|
-
const at = new Date().toISOString();
|
|
226
|
-
await recordSync(ctx, { at, ok: true, commit: result.commit, skills: result.skills, message: '' });
|
|
227
|
-
return json({
|
|
228
|
-
ok: true,
|
|
229
|
-
at,
|
|
230
|
-
commit: result.commit,
|
|
231
|
-
skills: result.skills,
|
|
232
|
-
skillNames: result.skillNames,
|
|
233
|
-
warnings: result.warnings,
|
|
234
|
-
branch: state.branch,
|
|
235
|
-
targetDir: state.targetDir,
|
|
236
|
-
}, 200);
|
|
237
|
-
}
|
|
238
|
-
catch (error) {
|
|
239
|
-
const at = new Date().toISOString();
|
|
240
|
-
await recordSync(ctx, { at, ok: false, commit: '', skills: 0, message: errorMessage(error) });
|
|
241
|
-
return failure(ctx, error, '同步失败', at);
|
|
242
|
-
}
|
|
243
|
-
}
|
|
244
|
-
/**
|
|
245
|
-
* Run one pull-only sync against the configured repository.
|
|
246
|
-
* @param state - configuration snapshot for this attempt.
|
|
247
|
-
* @param key - resolved key location.
|
|
248
|
-
* @returns the new commit, skill count, and non-fatal warnings.
|
|
249
|
-
* @throws {@link UiError} for validation, conflict, and git failures.
|
|
250
|
-
*/
|
|
251
|
-
async function performSync(state, key) {
|
|
252
|
-
const warnings = [];
|
|
253
|
-
const repo = parseRepoUrl(state.repoUrl);
|
|
254
|
-
const keyFile = key.keyFile;
|
|
255
|
-
if (repo.isSsh && keyFile === undefined) {
|
|
256
|
-
throw new UiError('仓库地址是 SSH 形式,需要先在面板保存 Deploy Key 或填写密钥路径后才能同步。', 400);
|
|
257
|
-
}
|
|
258
|
-
if ((repo.kind === 'file' || repo.kind === 'path') && keyFile !== undefined) {
|
|
259
|
-
warnings.push('本地仓库地址不需要 Deploy Key,已忽略密钥。');
|
|
260
|
-
}
|
|
261
|
-
const remote = cloneUrlFor(state.repoUrl, keyFile !== undefined);
|
|
262
|
-
const target = state.targetDir;
|
|
263
|
-
const kind = await pathKind(target);
|
|
264
|
-
if (!kind.exists) {
|
|
265
|
-
await mkdir(dirname(target), { recursive: true });
|
|
266
|
-
const clone = await runGit([
|
|
267
|
-
'clone',
|
|
268
|
-
'--depth', '1',
|
|
269
|
-
'--branch', state.branch,
|
|
270
|
-
'--single-branch',
|
|
271
|
-
remote,
|
|
272
|
-
target,
|
|
273
|
-
], { keyFile });
|
|
274
|
-
if (clone.code !== 0)
|
|
275
|
-
throw gitFailure('克隆仓库失败', clone);
|
|
276
|
-
}
|
|
277
|
-
else if (!kind.isDirectory) {
|
|
278
|
-
throw new UiError('目标路径已存在且不是目录,拒绝覆盖:' + target, 409);
|
|
279
|
-
}
|
|
280
|
-
else {
|
|
281
|
-
if (!await isGitRepository(target)) {
|
|
282
|
-
throw new UiError('目标目录已存在但不是 git 仓库,拒绝覆盖:' + target, 409);
|
|
283
|
-
}
|
|
284
|
-
const current = await currentBranch(target);
|
|
285
|
-
if (current !== state.branch) {
|
|
286
|
-
throw new UiError('目标仓库当前分支是 ' + (current ?? '(detached HEAD)') + ',与配置分支 ' + state.branch
|
|
287
|
-
+ ' 不一致;请手动切换分支或修改配置后再同步。', 409);
|
|
288
|
-
}
|
|
289
|
-
const origin = await originUrl(target);
|
|
290
|
-
if (origin === undefined) {
|
|
291
|
-
throw new UiError('目标仓库没有 origin 远端,拒绝同步:' + target, 409);
|
|
292
|
-
}
|
|
293
|
-
if (canonicalRepoUrl(origin) !== repo.canonical) {
|
|
294
|
-
throw new UiError('目标仓库 origin 是 ' + origin + ',与配置仓库 ' + state.repoUrl + ' 不是同一仓库,拒绝覆盖。', 409);
|
|
295
|
-
}
|
|
296
|
-
// A depth-1 fetch records the new tip without its parents, and git then
|
|
297
|
-
// refuses the ff-only merge as "unrelated histories". A shallow checkout is
|
|
298
|
-
// therefore completed first; a complete checkout fetches normally.
|
|
299
|
-
const shallow = await runGit(['rev-parse', '--is-shallow-repository'], { cwd: target });
|
|
300
|
-
const depth = shallow.code === 0 && shallow.stdout.trim() === 'true' ? ['--unshallow'] : [];
|
|
301
|
-
const fetched = await runGit(['fetch', ...depth, 'origin', state.branch], { cwd: target, keyFile });
|
|
302
|
-
if (fetched.code !== 0)
|
|
303
|
-
throw gitFailure('拉取远端分支失败', fetched);
|
|
304
|
-
const merged = await runGit(['merge', '--ff-only', 'FETCH_HEAD'], { cwd: target, keyFile });
|
|
305
|
-
if (merged.code !== 0)
|
|
306
|
-
throw gitFailure('无法快进合并(本地分支与远端已分叉)', merged);
|
|
307
|
-
}
|
|
308
|
-
if (state.recurseSubmodules) {
|
|
309
|
-
// Submodules are best effort: a private or unreachable submodule must not
|
|
310
|
-
// roll back a successful branch sync, so failures become warnings.
|
|
311
|
-
const synced = await runGit(['submodule', 'sync', '--recursive'], { cwd: target, keyFile });
|
|
312
|
-
if (synced.code !== 0) {
|
|
313
|
-
warnings.push('同步子模块地址失败:' + gitDetail(synced));
|
|
314
|
-
}
|
|
315
|
-
else {
|
|
316
|
-
const updated = await runGit(['submodule', 'update', '--init', '--recursive', '--force'], { cwd: target, keyFile });
|
|
317
|
-
if (updated.code !== 0)
|
|
318
|
-
warnings.push('初始化子模块失败:' + gitDetail(updated));
|
|
319
|
-
}
|
|
320
|
-
}
|
|
321
|
-
const commit = await revParse(target, ['--short', 'HEAD']);
|
|
322
|
-
if (commit === undefined)
|
|
323
|
-
throw new UiError('同步完成后无法读取提交号', 500);
|
|
324
|
-
const counted = await countSkills(target);
|
|
325
|
-
return { commit, skills: counted.skills, skillNames: counted.skillNames, warnings };
|
|
326
|
-
}
|
|
327
|
-
/** Build the status payload read on every panel refresh. */
|
|
328
|
-
async function statusPayload() {
|
|
329
|
-
const state = await readState();
|
|
330
|
-
const key = await inspectKey(state);
|
|
331
|
-
const target = await inspectTarget(state.targetDir);
|
|
332
|
-
return {
|
|
333
|
-
...publicConfig(state),
|
|
334
|
-
keySource: key.keySource,
|
|
335
|
-
hasStoredKey: key.hasStoredKey,
|
|
336
|
-
target,
|
|
337
|
-
};
|
|
338
|
-
}
|
|
339
|
-
/**
|
|
340
|
-
* Project the durable state into the fields the panel reads.
|
|
341
|
-
* @param state - durable state.
|
|
342
|
-
* @returns repository settings plus the last sync record.
|
|
343
|
-
*/
|
|
344
|
-
function publicConfig(state) {
|
|
345
|
-
return {
|
|
346
|
-
repoUrl: state.repoUrl,
|
|
347
|
-
branch: state.branch,
|
|
348
|
-
keyPath: state.keyPath,
|
|
349
|
-
targetDir: state.targetDir,
|
|
350
|
-
recurseSubmodules: state.recurseSubmodules,
|
|
351
|
-
lastSync: state.lastSync,
|
|
352
|
-
};
|
|
353
|
-
}
|
|
354
|
-
/** The default state, resolved against the current $DSH_HOME. */
|
|
355
|
-
function defaultState() {
|
|
356
|
-
return {
|
|
357
|
-
repoUrl: DEFAULT_REPO_URL,
|
|
358
|
-
branch: DEFAULT_BRANCH,
|
|
359
|
-
keyPath: '',
|
|
360
|
-
targetDir: join(dshHome(), 'skills', 'herskill'),
|
|
361
|
-
recurseSubmodules: true,
|
|
362
|
-
lastSync: null,
|
|
363
|
-
};
|
|
364
|
-
}
|
|
365
|
-
/**
|
|
366
|
-
* Merge a configuration body onto the current state, validating every supplied
|
|
367
|
-
* field. Omitted fields are preserved; an empty keyPath clears the path.
|
|
368
|
-
* @param state - current durable state.
|
|
369
|
-
* @param body - parsed JSON request body.
|
|
370
|
-
* @returns the next state, not yet persisted.
|
|
371
|
-
*/
|
|
372
|
-
function applyConfigPatch(state, body) {
|
|
373
|
-
if (body === null || typeof body !== 'object' || Array.isArray(body)) {
|
|
374
|
-
throw new UiError('请求体必须是 JSON 对象', 400);
|
|
375
|
-
}
|
|
376
|
-
const record = body;
|
|
377
|
-
const next = { ...state };
|
|
378
|
-
if (record.repoUrl !== undefined)
|
|
379
|
-
next.repoUrl = parseRepoUrl(requireString(record.repoUrl, 'repoUrl')).raw;
|
|
380
|
-
if (record.branch !== undefined)
|
|
381
|
-
next.branch = validateBranch(requireString(record.branch, 'branch'));
|
|
382
|
-
if (record.targetDir !== undefined)
|
|
383
|
-
next.targetDir = resolveTargetDir(requireString(record.targetDir, 'targetDir'));
|
|
384
|
-
if (record.recurseSubmodules !== undefined) {
|
|
385
|
-
if (typeof record.recurseSubmodules !== 'boolean')
|
|
386
|
-
throw new UiError('recurseSubmodules 必须是布尔值', 400);
|
|
387
|
-
next.recurseSubmodules = record.recurseSubmodules;
|
|
388
|
-
}
|
|
389
|
-
next.keyPath = normalizeKeyPath(record.keyPath, state.keyPath);
|
|
390
|
-
return next;
|
|
391
|
-
}
|
|
392
|
-
/** Read one required string field from a request body. */
|
|
393
|
-
function requireString(value, field) {
|
|
394
|
-
if (typeof value !== 'string')
|
|
395
|
-
throw new UiError(field + ' 必须是字符串', 400);
|
|
396
|
-
return value;
|
|
397
|
-
}
|
|
398
|
-
/**
|
|
399
|
-
* Normalize a configured key path without requiring it to exist yet.
|
|
400
|
-
* @param value - raw keyPath field, or undefined to keep the current one.
|
|
401
|
-
* @param current - current stored value.
|
|
402
|
-
* @returns the trimmed path, or an empty string to clear it.
|
|
403
|
-
*/
|
|
404
|
-
function normalizeKeyPath(value, current) {
|
|
405
|
-
if (value === undefined)
|
|
406
|
-
return current;
|
|
407
|
-
if (typeof value !== 'string')
|
|
408
|
-
throw new UiError('keyPath 必须是字符串', 400);
|
|
409
|
-
const raw = value.trim();
|
|
410
|
-
if (raw === '')
|
|
411
|
-
return '';
|
|
412
|
-
if (hasControlCharacters(raw))
|
|
413
|
-
throw new UiError('keyPath 不能包含换行或控制字符', 400);
|
|
414
|
-
expandPath(raw);
|
|
415
|
-
return raw;
|
|
416
|
-
}
|
|
417
|
-
/** Whether text carries a newline, NUL, or other control character. */
|
|
418
|
-
function hasControlCharacters(value) {
|
|
419
|
-
// eslint-disable-next-line no-control-regex
|
|
420
|
-
return /[\u0000-\u001f\u007f]/.test(value);
|
|
421
|
-
}
|
|
422
|
-
/**
|
|
423
|
-
* Resolve a configured target directory: tilde and environment expansion, absolute
|
|
424
|
-
* path required, and never the filesystem root or this package's own checkout.
|
|
425
|
-
* @param raw - configured path.
|
|
426
|
-
* @returns the resolved absolute path.
|
|
427
|
-
*/
|
|
428
|
-
function resolveTargetDir(raw) {
|
|
429
|
-
const value = raw.trim();
|
|
430
|
-
if (value === '')
|
|
431
|
-
throw new UiError('目标目录不能为空', 400);
|
|
432
|
-
if (hasControlCharacters(value))
|
|
433
|
-
throw new UiError('目标目录不能包含换行或控制字符', 400);
|
|
434
|
-
const expanded = expandPath(value);
|
|
435
|
-
if (!isAbsolute(expanded))
|
|
436
|
-
throw new UiError('目标目录必须是绝对路径:' + value, 400);
|
|
437
|
-
const resolved = resolve(expanded);
|
|
438
|
-
if (resolved === '/')
|
|
439
|
-
throw new UiError('目标目录不能是文件系统根目录', 400);
|
|
440
|
-
if (isInsidePackage(resolved))
|
|
441
|
-
throw new UiError('目标目录不能位于 dsh-utils 包内,避免覆盖插件自身', 400);
|
|
442
|
-
return resolved;
|
|
443
|
-
}
|
|
444
|
-
/** Whether a path is this package's root or lies inside it. */
|
|
445
|
-
function isInsidePackage(path) {
|
|
446
|
-
const rel = relative(PACKAGE_ROOT, path);
|
|
447
|
-
return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel));
|
|
448
|
-
}
|
|
449
|
-
/**
|
|
450
|
-
* Expand a leading tilde and dollar-brace environment references. A missing
|
|
451
|
-
* variable is an error rather than an empty string, so a typo cannot silently
|
|
452
|
-
* redirect a path.
|
|
453
|
-
* @param input - configured path.
|
|
454
|
-
* @returns the expanded path.
|
|
455
|
-
*/
|
|
456
|
-
function expandPath(input) {
|
|
457
|
-
let value = input;
|
|
458
|
-
if (value === '~')
|
|
459
|
-
value = homedir();
|
|
460
|
-
else if (value.startsWith('~/') || value.startsWith('~\\'))
|
|
461
|
-
value = join(homedir(), value.slice(2));
|
|
462
|
-
value = value.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)/g, (match, braced, bare) => {
|
|
463
|
-
const variable = braced ?? bare ?? '';
|
|
464
|
-
const resolved = process.env[variable];
|
|
465
|
-
if (resolved === undefined)
|
|
466
|
-
throw new UiError('环境变量 ' + variable + ' 未设置', 400);
|
|
467
|
-
return resolved;
|
|
468
|
-
});
|
|
469
|
-
return value;
|
|
470
|
-
}
|
|
471
|
-
/**
|
|
472
|
-
* Validate a branch name.
|
|
473
|
-
* @param raw - configured branch.
|
|
474
|
-
* @returns the trimmed branch name.
|
|
475
|
-
*/
|
|
476
|
-
function validateBranch(raw) {
|
|
477
|
-
const value = raw.trim();
|
|
478
|
-
if (value === '')
|
|
479
|
-
throw new UiError('分支不能为空', 400);
|
|
480
|
-
if (!BRANCH_PATTERN.test(value))
|
|
481
|
-
throw new UiError('分支名不合法:' + value, 400);
|
|
482
|
-
if (value.startsWith('-') || value.startsWith('/') || value.endsWith('/') || value.endsWith('.')
|
|
483
|
-
|| value.includes('..') || value.includes('//')) {
|
|
484
|
-
throw new UiError('分支名不合法:' + value, 400);
|
|
485
|
-
}
|
|
486
|
-
return value;
|
|
487
|
-
}
|
|
488
|
-
/**
|
|
489
|
-
* Parse and validate one repository URL.
|
|
490
|
-
* @param rawInput - configured repository URL (https, http, ssh, scp-like, file, or absolute path).
|
|
491
|
-
* @returns normalized fields plus a comparison key.
|
|
492
|
-
*/
|
|
493
|
-
function parseRepoUrl(rawInput) {
|
|
494
|
-
const raw = rawInput.trim();
|
|
495
|
-
if (raw === '')
|
|
496
|
-
throw new UiError('仓库地址不能为空', 400);
|
|
497
|
-
if (hasControlCharacters(raw))
|
|
498
|
-
throw new UiError('仓库地址不能包含换行或控制字符', 400);
|
|
499
|
-
if (/\s/.test(raw))
|
|
500
|
-
throw new UiError('仓库地址不能包含空白字符', 400);
|
|
501
|
-
if (raw.startsWith('-'))
|
|
502
|
-
throw new UiError('仓库地址不能以 - 开头', 400);
|
|
503
|
-
const httpMatch = /^(https?):\/\/([^/]+)\/(.+)$/i.exec(raw);
|
|
504
|
-
if (httpMatch !== null) {
|
|
505
|
-
const scheme = httpMatch[1].toLowerCase();
|
|
506
|
-
const host = httpMatch[2].toLowerCase();
|
|
507
|
-
const path = trimGitSuffix(httpMatch[3].replace(/^\/+/, '').replace(/\/+$/, ''));
|
|
508
|
-
if (path === '')
|
|
509
|
-
throw new UiError('仓库地址缺少仓库路径:' + raw, 400);
|
|
510
|
-
return {
|
|
511
|
-
kind: scheme === 'https' ? 'https' : 'http',
|
|
512
|
-
raw,
|
|
513
|
-
isSsh: false,
|
|
514
|
-
host,
|
|
515
|
-
path,
|
|
516
|
-
canonical: host + '/' + path.toLowerCase(),
|
|
517
|
-
};
|
|
518
|
-
}
|
|
519
|
-
const sshUrlMatch = /^ssh:\/\/(?:[^@/]+@)?([^/]+)\/(.+)$/i.exec(raw);
|
|
520
|
-
if (sshUrlMatch !== null) {
|
|
521
|
-
const host = sshUrlMatch[1].toLowerCase();
|
|
522
|
-
const path = trimGitSuffix(sshUrlMatch[2].replace(/^\/+/, '').replace(/\/+$/, ''));
|
|
523
|
-
if (path === '')
|
|
524
|
-
throw new UiError('仓库地址缺少仓库路径:' + raw, 400);
|
|
525
|
-
return { kind: 'ssh', raw, isSsh: true, host, path, canonical: host + '/' + path.toLowerCase() };
|
|
526
|
-
}
|
|
527
|
-
if (/^file:\/\//i.test(raw)) {
|
|
528
|
-
let path;
|
|
529
|
-
try {
|
|
530
|
-
path = resolve(fileURLToPath(raw));
|
|
531
|
-
}
|
|
532
|
-
catch {
|
|
533
|
-
throw new UiError('file:// 地址不合法:' + raw, 400);
|
|
534
|
-
}
|
|
535
|
-
return { kind: 'file', raw, isSsh: false, host: undefined, path, canonical: 'file:' + path };
|
|
536
|
-
}
|
|
537
|
-
if (isAbsolute(raw)) {
|
|
538
|
-
const path = resolve(raw);
|
|
539
|
-
return { kind: 'path', raw, isSsh: false, host: undefined, path, canonical: 'file:' + path };
|
|
540
|
-
}
|
|
541
|
-
const scpMatch = /^(?:([A-Za-z0-9._-]+)@)?([A-Za-z0-9._-]+\.[A-Za-z0-9._-]+):(.+)$/.exec(raw);
|
|
542
|
-
if (scpMatch !== null) {
|
|
543
|
-
const host = scpMatch[2].toLowerCase();
|
|
544
|
-
const path = trimGitSuffix(scpMatch[3].replace(/^\/+/, '').replace(/\/+$/, ''));
|
|
545
|
-
if (path === '')
|
|
546
|
-
throw new UiError('仓库地址缺少仓库路径:' + raw, 400);
|
|
547
|
-
return { kind: 'scp', raw, isSsh: true, host, path, canonical: host + '/' + path.toLowerCase() };
|
|
548
|
-
}
|
|
549
|
-
throw new UiError('无法识别的仓库地址:' + raw + '(支持 https、http、ssh、git@host:path、file:// 或绝对路径)', 400);
|
|
550
|
-
}
|
|
551
|
-
/** Strip one trailing .git suffix. */
|
|
552
|
-
function trimGitSuffix(path) {
|
|
553
|
-
return path.endsWith('.git') ? path.slice(0, -4) : path;
|
|
554
|
-
}
|
|
555
|
-
/**
|
|
556
|
-
* Pick the URL git should actually use. With a deploy key present, an HTTPS URL
|
|
557
|
-
* on a well-known host becomes its SSH form; every other URL is used verbatim.
|
|
558
|
-
* @param repoUrl - configured repository URL.
|
|
559
|
-
* @param hasKey - whether an SSH identity is available.
|
|
560
|
-
* @returns the URL passed to git.
|
|
561
|
-
*/
|
|
562
|
-
export function cloneUrlFor(repoUrl, hasKey) {
|
|
563
|
-
const repo = parseRepoUrl(repoUrl);
|
|
564
|
-
if (!hasKey || repo.kind !== 'https' || repo.host === undefined)
|
|
565
|
-
return repo.raw;
|
|
566
|
-
const host = repo.host.split(':')[0];
|
|
567
|
-
if (!SSH_HOSTS.has(host))
|
|
568
|
-
return repo.raw;
|
|
569
|
-
return 'git@' + host + ':' + repo.path + '.git';
|
|
570
|
-
}
|
|
571
|
-
/**
|
|
572
|
-
* Canonical comparison key for a repository URL, tolerant of the common .git
|
|
573
|
-
* suffix, scheme (https vs ssh), host case, and trailing slashes.
|
|
574
|
-
* @param raw - any repository URL.
|
|
575
|
-
* @returns the canonical form; unparseable input falls back to a lowercased trim.
|
|
576
|
-
*/
|
|
577
|
-
export function canonicalRepoUrl(raw) {
|
|
578
|
-
try {
|
|
579
|
-
return parseRepoUrl(raw).canonical;
|
|
580
|
-
}
|
|
581
|
-
catch {
|
|
582
|
-
return raw.trim().toLowerCase();
|
|
583
|
-
}
|
|
584
|
-
}
|
|
585
|
-
/** Resolve where the SSH identity comes from. */
|
|
586
|
-
async function inspectKey(state) {
|
|
587
|
-
const hasStoredKey = await fileExists(storedKeyFile());
|
|
588
|
-
if (state.keyPath !== '') {
|
|
589
|
-
let candidate;
|
|
590
|
-
try {
|
|
591
|
-
candidate = expandPath(state.keyPath);
|
|
592
|
-
}
|
|
593
|
-
catch {
|
|
594
|
-
candidate = undefined;
|
|
595
|
-
}
|
|
596
|
-
if (candidate !== undefined && isAbsolute(candidate) && await fileExists(candidate)) {
|
|
597
|
-
return { keySource: 'path', hasStoredKey, keyFile: resolve(candidate) };
|
|
598
|
-
}
|
|
599
|
-
}
|
|
600
|
-
if (hasStoredKey)
|
|
601
|
-
return { keySource: 'stored', hasStoredKey, keyFile: storedKeyFile() };
|
|
602
|
-
return { keySource: 'none', hasStoredKey, keyFile: undefined };
|
|
603
|
-
}
|
|
604
|
-
/** Inspect a target checkout for the status route. */
|
|
605
|
-
async function inspectTarget(target) {
|
|
606
|
-
const kind = await pathKind(target);
|
|
607
|
-
if (!kind.isDirectory) {
|
|
608
|
-
return { exists: kind.exists, isRepo: false, branch: null, commit: null, dirty: false, skills: 0, skillNames: [] };
|
|
609
|
-
}
|
|
610
|
-
const counted = await countSkills(target);
|
|
611
|
-
if (!await isGitRepository(target)) {
|
|
612
|
-
return { exists: true, isRepo: false, branch: null, commit: null, dirty: false, ...counted };
|
|
613
|
-
}
|
|
614
|
-
const branch = await revParse(target, ['--abbrev-ref', 'HEAD']);
|
|
615
|
-
const commit = await revParse(target, ['--short', 'HEAD']);
|
|
616
|
-
const status = await runGit(['status', '--porcelain', '--untracked-files=normal'], { cwd: target });
|
|
617
|
-
return {
|
|
618
|
-
exists: true,
|
|
619
|
-
isRepo: true,
|
|
620
|
-
branch: branch ?? null,
|
|
621
|
-
commit: commit ?? null,
|
|
622
|
-
dirty: status.code === 0 && status.stdout.trim() !== '',
|
|
623
|
-
...counted,
|
|
624
|
-
};
|
|
625
|
-
}
|
|
626
|
-
/**
|
|
627
|
-
* Count nested SKILL.md files and name the first-level directories that contain
|
|
628
|
-
* at least one, which is the skill set the catalog will see.
|
|
629
|
-
* @param target - target directory.
|
|
630
|
-
* @returns the recursive skill count and first-level skill names.
|
|
631
|
-
*/
|
|
632
|
-
async function countSkills(target) {
|
|
633
|
-
let skills = 0;
|
|
634
|
-
const skillNames = new Set();
|
|
635
|
-
const queue = [{ dir: target, top: undefined, depth: 0 }];
|
|
636
|
-
while (queue.length > 0) {
|
|
637
|
-
const current = queue.pop();
|
|
638
|
-
let entries;
|
|
639
|
-
try {
|
|
640
|
-
entries = await readdir(current.dir, { withFileTypes: true });
|
|
641
|
-
}
|
|
642
|
-
catch {
|
|
643
|
-
continue;
|
|
644
|
-
}
|
|
645
|
-
for (const entry of entries) {
|
|
646
|
-
if (entry.isFile() && entry.name === 'SKILL.md') {
|
|
647
|
-
skills += 1;
|
|
648
|
-
if (current.top !== undefined)
|
|
649
|
-
skillNames.add(current.top);
|
|
650
|
-
continue;
|
|
651
|
-
}
|
|
652
|
-
if (!entry.isDirectory())
|
|
653
|
-
continue;
|
|
654
|
-
if (entry.name === '.git' || entry.name === 'node_modules')
|
|
655
|
-
continue;
|
|
656
|
-
if (current.depth >= MAX_SCAN_DEPTH)
|
|
657
|
-
continue;
|
|
658
|
-
queue.push({ dir: join(current.dir, entry.name), top: current.top ?? entry.name, depth: current.depth + 1 });
|
|
659
|
-
}
|
|
660
|
-
}
|
|
661
|
-
return { skills, skillNames: [...skillNames].sort() };
|
|
662
|
-
}
|
|
663
|
-
/** Whether a directory is the root of a git work tree. */
|
|
664
|
-
async function isGitRepository(dir) {
|
|
665
|
-
const outcome = await runGit(['rev-parse', '--git-dir'], { cwd: dir });
|
|
666
|
-
return outcome.code === 0;
|
|
667
|
-
}
|
|
668
|
-
/** Read one git rev-parse value. */
|
|
669
|
-
async function revParse(dir, args) {
|
|
670
|
-
const outcome = await runGit(['rev-parse', ...args], { cwd: dir });
|
|
671
|
-
if (outcome.code !== 0)
|
|
672
|
-
return undefined;
|
|
673
|
-
const value = outcome.stdout.trim();
|
|
674
|
-
return value === '' ? undefined : value;
|
|
675
|
-
}
|
|
676
|
-
/** The current branch name, or undefined on a detached HEAD / non-repo. */
|
|
677
|
-
async function currentBranch(dir) {
|
|
678
|
-
return revParse(dir, ['--abbrev-ref', 'HEAD']);
|
|
679
|
-
}
|
|
680
|
-
/** The origin remote URL, when one is configured. */
|
|
681
|
-
async function originUrl(dir) {
|
|
682
|
-
const outcome = await runGit(['config', '--get', 'remote.origin.url'], { cwd: dir });
|
|
683
|
-
if (outcome.code !== 0)
|
|
684
|
-
return undefined;
|
|
685
|
-
const value = outcome.stdout.trim();
|
|
686
|
-
return value === '' ? undefined : value;
|
|
687
|
-
}
|
|
688
|
-
/**
|
|
689
|
-
* Run one git command without a shell, with prompts disabled and a bounded
|
|
690
|
-
* timeout. A configured key becomes GIT_SSH_COMMAND; the key's content is never
|
|
691
|
-
* part of the argument vector.
|
|
692
|
-
* @param args - git arguments.
|
|
693
|
-
* @param options - working directory and optional SSH identity path.
|
|
694
|
-
* @returns the normalized outcome; it never rejects for a non-zero exit.
|
|
695
|
-
*/
|
|
696
|
-
function runGit(args, options = {}) {
|
|
697
|
-
const env = { ...process.env, GIT_TERMINAL_PROMPT: '0' };
|
|
698
|
-
if (options.keyFile !== undefined)
|
|
699
|
-
env.GIT_SSH_COMMAND = sshCommand(options.keyFile);
|
|
700
|
-
return new Promise((resolvePromise) => {
|
|
701
|
-
execFile('git', [...args], {
|
|
702
|
-
...(options.cwd === undefined ? {} : { cwd: options.cwd }),
|
|
703
|
-
env,
|
|
704
|
-
timeout: GIT_TIMEOUT_MS,
|
|
705
|
-
killSignal: 'SIGTERM',
|
|
706
|
-
maxBuffer: GIT_MAX_BUFFER,
|
|
707
|
-
windowsHide: true,
|
|
708
|
-
encoding: 'utf8',
|
|
709
|
-
}, (error, stdout, stderr) => {
|
|
710
|
-
// execFile reports success as a null error; only a non-null error carries
|
|
711
|
-
// an exit code, a signal, or a spawn failure.
|
|
712
|
-
const failure = error;
|
|
713
|
-
const code = failure === null ? 0 : failure.code;
|
|
714
|
-
resolvePromise({
|
|
715
|
-
code: typeof code === 'number' ? code : null,
|
|
716
|
-
stdout: typeof stdout === 'string' ? stdout : '',
|
|
717
|
-
stderr: typeof stderr === 'string' ? stderr : '',
|
|
718
|
-
timedOut: failure?.killed === true,
|
|
719
|
-
spawnError: typeof code === 'string' ? (code + ': ' + (failure?.message ?? '')).trim() : undefined,
|
|
720
|
-
});
|
|
721
|
-
});
|
|
722
|
-
});
|
|
723
|
-
}
|
|
724
|
-
/** Build the SSH command that supplies one identity file, quoted for git's shell. */
|
|
725
|
-
function sshCommand(keyFile) {
|
|
726
|
-
return 'ssh -i ' + shellQuote(keyFile) + ' -o IdentitiesOnly=yes -o BatchMode=yes -o StrictHostKeyChecking=accept-new';
|
|
727
|
-
}
|
|
728
|
-
/** Single-quote one value for a POSIX shell. */
|
|
729
|
-
function shellQuote(value) {
|
|
730
|
-
return "'" + value.replace(/'/g, "'\\''") + "'";
|
|
731
|
-
}
|
|
732
|
-
/** The last useful line of a failed git command. */
|
|
733
|
-
function gitDetail(outcome) {
|
|
734
|
-
if (outcome.timedOut)
|
|
735
|
-
return '命令超过 ' + Math.round(GIT_TIMEOUT_MS / 1000) + 's 未完成';
|
|
736
|
-
return outcome.spawnError ?? logLines(outcome).at(-1) ?? '退出码 ' + (outcome.code ?? '未知');
|
|
737
|
-
}
|
|
738
|
-
/**
|
|
739
|
-
* Turn a failed git command into a sanitized route failure.
|
|
740
|
-
* @param label - what the command was doing.
|
|
741
|
-
* @param outcome - failed command outcome.
|
|
742
|
-
* @returns an error carrying the last useful line and the sanitized log.
|
|
743
|
-
*/
|
|
744
|
-
function gitFailure(label, outcome) {
|
|
745
|
-
return new UiError(label + ':' + gitDetail(outcome), 500, logLines(outcome));
|
|
746
|
-
}
|
|
747
|
-
/** Sanitized git output lines: ANSI stripped, blank lines dropped, tail kept. */
|
|
748
|
-
function logLines(outcome) {
|
|
749
|
-
const text = outcome.stderr + '\n' + outcome.stdout;
|
|
750
|
-
return text
|
|
751
|
-
// eslint-disable-next-line no-control-regex
|
|
752
|
-
.replace(/\u001b\[[0-9;]*m/g, '')
|
|
753
|
-
.split('\n')
|
|
754
|
-
.map((line) => line.trim())
|
|
755
|
-
.filter((line) => line !== '')
|
|
756
|
-
.slice(-MAX_LOG_LINES);
|
|
757
|
-
}
|
|
758
|
-
/** Build a failure response from a thrown value. */
|
|
759
|
-
function failure(ctx, error, label, at) {
|
|
760
|
-
const message = errorMessage(error);
|
|
761
|
-
ctx.logger.warn('utils-main repo-sync: ' + label + ':' + message);
|
|
762
|
-
const log = error instanceof UiError ? error.log : undefined;
|
|
763
|
-
return json({
|
|
764
|
-
error: message,
|
|
765
|
-
...(at === undefined ? {} : { at }),
|
|
766
|
-
...(log !== undefined && log.length > 0 ? { log } : {}),
|
|
767
|
-
}, errorStatus(error));
|
|
768
|
-
}
|
|
769
|
-
/** HTTP status for a thrown value. */
|
|
770
|
-
function errorStatus(error) {
|
|
771
|
-
return error instanceof UiError ? error.status : 500;
|
|
772
|
-
}
|
|
773
|
-
/** Whether a path is a regular file. */
|
|
774
|
-
async function fileExists(path) {
|
|
775
|
-
try {
|
|
776
|
-
return (await stat(path)).isFile();
|
|
777
|
-
}
|
|
778
|
-
catch {
|
|
779
|
-
return false;
|
|
780
|
-
}
|
|
781
|
-
}
|
|
782
|
-
/** Whether a path exists and, when it does, whether it is a directory. */
|
|
783
|
-
async function pathKind(path) {
|
|
784
|
-
try {
|
|
785
|
-
const info = await stat(path);
|
|
786
|
-
return { exists: true, isDirectory: info.isDirectory() };
|
|
787
|
-
}
|
|
788
|
-
catch (error) {
|
|
789
|
-
if (isAbsent(error))
|
|
790
|
-
return { exists: false, isDirectory: false };
|
|
791
|
-
throw error;
|
|
792
|
-
}
|
|
793
|
-
}
|
|
794
|
-
/** Read the durable state, falling back field by field to the defaults. */
|
|
795
|
-
async function readState() {
|
|
796
|
-
const defaults = defaultState();
|
|
797
|
-
let raw;
|
|
798
|
-
try {
|
|
799
|
-
raw = await readFile(statePath(), 'utf8');
|
|
800
|
-
}
|
|
801
|
-
catch {
|
|
802
|
-
return defaults;
|
|
803
|
-
}
|
|
804
|
-
let parsed;
|
|
805
|
-
try {
|
|
806
|
-
parsed = JSON.parse(raw);
|
|
807
|
-
}
|
|
808
|
-
catch {
|
|
809
|
-
return defaults;
|
|
810
|
-
}
|
|
811
|
-
if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed))
|
|
812
|
-
return defaults;
|
|
813
|
-
const record = parsed;
|
|
814
|
-
return {
|
|
815
|
-
repoUrl: storedRepoUrl(record.repoUrl, defaults.repoUrl),
|
|
816
|
-
branch: storedBranch(record.branch, defaults.branch),
|
|
817
|
-
keyPath: storedKeyPathValue(record.keyPath),
|
|
818
|
-
targetDir: storedTargetDir(record.targetDir, defaults.targetDir),
|
|
819
|
-
recurseSubmodules: typeof record.recurseSubmodules === 'boolean' ? record.recurseSubmodules : defaults.recurseSubmodules,
|
|
820
|
-
lastSync: storedLastSync(record.lastSync),
|
|
821
|
-
};
|
|
822
|
-
}
|
|
823
|
-
/** One stored repository URL, or the default when absent or invalid. */
|
|
824
|
-
function storedRepoUrl(value, fallback) {
|
|
825
|
-
if (typeof value !== 'string' || value.trim() === '')
|
|
826
|
-
return fallback;
|
|
827
|
-
try {
|
|
828
|
-
return parseRepoUrl(value).raw;
|
|
829
|
-
}
|
|
830
|
-
catch {
|
|
831
|
-
return fallback;
|
|
832
|
-
}
|
|
833
|
-
}
|
|
834
|
-
/** One stored branch, or the default when absent or invalid. */
|
|
835
|
-
function storedBranch(value, fallback) {
|
|
836
|
-
if (typeof value !== 'string')
|
|
837
|
-
return fallback;
|
|
838
|
-
try {
|
|
839
|
-
return validateBranch(value);
|
|
840
|
-
}
|
|
841
|
-
catch {
|
|
842
|
-
return fallback;
|
|
843
|
-
}
|
|
844
|
-
}
|
|
845
|
-
/** One stored key path; a hand-edited path that no longer validates is ignored. */
|
|
846
|
-
function storedKeyPathValue(value) {
|
|
847
|
-
if (typeof value !== 'string')
|
|
848
|
-
return '';
|
|
849
|
-
const raw = value.trim();
|
|
850
|
-
if (raw === '' || hasControlCharacters(raw))
|
|
851
|
-
return '';
|
|
852
|
-
try {
|
|
853
|
-
expandPath(raw);
|
|
854
|
-
}
|
|
855
|
-
catch {
|
|
856
|
-
return '';
|
|
857
|
-
}
|
|
858
|
-
return raw;
|
|
859
|
-
}
|
|
860
|
-
/** One stored target directory, or the default when absent or invalid. */
|
|
861
|
-
function storedTargetDir(value, fallback) {
|
|
862
|
-
if (typeof value !== 'string')
|
|
863
|
-
return fallback;
|
|
864
|
-
try {
|
|
865
|
-
return resolveTargetDir(value);
|
|
866
|
-
}
|
|
867
|
-
catch {
|
|
868
|
-
return fallback;
|
|
869
|
-
}
|
|
870
|
-
}
|
|
871
|
-
/** One stored last-sync record, or null when absent or malformed. */
|
|
872
|
-
function storedLastSync(value) {
|
|
873
|
-
if (value === null || typeof value !== 'object' || Array.isArray(value))
|
|
874
|
-
return null;
|
|
875
|
-
const record = value;
|
|
876
|
-
if (typeof record.at !== 'string' || record.at === '')
|
|
877
|
-
return null;
|
|
878
|
-
if (typeof record.ok !== 'boolean')
|
|
879
|
-
return null;
|
|
880
|
-
return {
|
|
881
|
-
at: record.at,
|
|
882
|
-
ok: record.ok,
|
|
883
|
-
commit: typeof record.commit === 'string' ? record.commit : '',
|
|
884
|
-
skills: typeof record.skills === 'number' && Number.isFinite(record.skills) ? record.skills : 0,
|
|
885
|
-
message: typeof record.message === 'string' ? record.message : '',
|
|
886
|
-
};
|
|
887
|
-
}
|
|
888
|
-
/** Persist the durable state atomically with mode 600. */
|
|
889
|
-
async function writeState(state) {
|
|
890
|
-
await writePrivateFile(statePath(), JSON.stringify(state, null, 2) + '\n');
|
|
891
|
-
}
|
|
892
|
-
/** Record one sync outcome without clobbering configuration edited meanwhile. */
|
|
893
|
-
async function recordSync(ctx, record) {
|
|
894
|
-
try {
|
|
895
|
-
const state = await readState();
|
|
896
|
-
state.lastSync = record;
|
|
897
|
-
await writeState(state);
|
|
898
|
-
}
|
|
899
|
-
catch (error) {
|
|
900
|
-
ctx.logger.warn('utils-main repo-sync: cannot record sync state: ' + errorMessage(error));
|
|
901
|
-
}
|
|
902
|
-
}
|
|
903
|
-
/**
|
|
904
|
-
* Write one private file atomically: a random-suffix sibling is created with
|
|
905
|
-
* mode 600 and renamed over the target, so a reader sees either the old or the
|
|
906
|
-
* new complete content and the replacement keeps mode 600.
|
|
907
|
-
* @param file - final path.
|
|
908
|
-
* @param content - complete next content.
|
|
909
|
-
*/
|
|
910
|
-
async function writePrivateFile(file, content) {
|
|
911
|
-
const directory = dirname(file);
|
|
912
|
-
await mkdir(directory, { recursive: true, mode: 0o700 });
|
|
913
|
-
const temp = file + '.' + randomBytes(6).toString('hex') + '.tmp';
|
|
914
|
-
try {
|
|
915
|
-
await writeFile(temp, content, { mode: 0o600, flag: 'wx' });
|
|
916
|
-
await rename(temp, file);
|
|
917
|
-
}
|
|
918
|
-
catch (error) {
|
|
919
|
-
await rm(temp, { force: true });
|
|
920
|
-
throw error;
|
|
921
|
-
}
|
|
922
|
-
await chmod(file, 0o600);
|
|
923
|
-
}
|
|
924
|
-
/** Resolve $DSH_HOME, falling back to ~/.dsh. */
|
|
925
|
-
function dshHome() {
|
|
926
|
-
const override = process.env.DSH_HOME;
|
|
927
|
-
if (typeof override === 'string' && override.trim() !== '')
|
|
928
|
-
return resolve(override.trim());
|
|
929
|
-
return join(homedir(), '.dsh');
|
|
930
|
-
}
|
|
931
|
-
/** $DSH_HOME/storages. */
|
|
932
|
-
function storageDir() {
|
|
933
|
-
return join(dshHome(), STORAGE_DIR_NAME);
|
|
934
|
-
}
|
|
935
|
-
/** The durable settings file. */
|
|
936
|
-
function statePath() {
|
|
937
|
-
return join(storageDir(), STATE_FILE_NAME);
|
|
938
|
-
}
|
|
939
|
-
/** The stored deploy key file. */
|
|
940
|
-
function storedKeyFile() {
|
|
941
|
-
return join(storageDir(), KEY_FILE_NAME);
|
|
942
|
-
}
|
|
943
|
-
/** Parse one buffered JSON request body, with a size cap. */
|
|
944
|
-
async function readJsonBody(request) {
|
|
945
|
-
const text = await request.text();
|
|
946
|
-
if (Buffer.byteLength(text, 'utf8') > BODY_LIMIT_BYTES)
|
|
947
|
-
throw new UiError('请求体过大', 413);
|
|
948
|
-
if (text.trim() === '')
|
|
949
|
-
return {};
|
|
950
|
-
try {
|
|
951
|
-
return JSON.parse(text);
|
|
952
|
-
}
|
|
953
|
-
catch {
|
|
954
|
-
throw new UiError('请求体不是合法 JSON', 400);
|
|
955
|
-
}
|
|
956
|
-
}
|
|
957
|
-
/** Build one JSON response with no-store caching. */
|
|
958
|
-
function json(value, status) {
|
|
959
|
-
return new Response(JSON.stringify(value), { status, headers: JSON_HEADERS });
|
|
960
|
-
}
|
|
961
|
-
/** Whether an fs error means the path is simply absent. */
|
|
962
|
-
function isAbsent(error) {
|
|
963
|
-
return typeof error === 'object' && error !== null && 'code' in error
|
|
964
|
-
&& (error.code === 'ENOENT' || error.code === 'ENOTDIR');
|
|
965
|
-
}
|
|
966
|
-
/** Render an unknown error for a log line or route payload. */
|
|
967
|
-
function errorMessage(error) {
|
|
968
|
-
return error instanceof Error ? error.message : String(error);
|
|
969
|
-
}
|
|
970
|
-
//# sourceMappingURL=ui-host.js.map
|