@xi4z/dsh-utils 0.0.0-stage → 0.5.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 +576 -2
- package/client.js +2330 -0
- package/cordis.patch.yml +101 -0
- package/icon.svg +21 -0
- package/lib/index.d.ts +69 -0
- package/lib/index.js +865 -0
- package/lib/index.js.map +1 -0
- package/lib/ui-host.d.ts +96 -0
- package/lib/ui-host.js +970 -0
- package/lib/ui-host.js.map +1 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +124 -3
- package/packages/approval-policy/lib/index.d.ts +297 -0
- package/packages/approval-policy/lib/index.js +425 -0
- package/packages/approval-policy/lib/index.js.map +1 -0
- package/packages/approval-policy/locale/en.json +6 -0
- package/packages/approval-policy/locale/zh.json +6 -0
- package/packages/notify/lib/index.d.ts +290 -0
- package/packages/notify/lib/index.js +915 -0
- package/packages/notify/lib/index.js.map +1 -0
- package/packages/notify/locale/en.json +6 -0
- package/packages/notify/locale/zh.json +6 -0
- package/packages/skill-panel/lib/index.d.ts +49 -0
- package/packages/skill-panel/lib/index.js +420 -0
- package/packages/skill-panel/lib/index.js.map +1 -0
- package/packages/skill-panel/locale/en.json +6 -0
- package/packages/skill-panel/locale/zh.json +6 -0
- package/packages/utils-agents/lib/git.d.ts +87 -0
- package/packages/utils-agents/lib/git.js +403 -0
- package/packages/utils-agents/lib/git.js.map +1 -0
- package/packages/utils-agents/lib/global-repo.d.ts +57 -0
- package/packages/utils-agents/lib/global-repo.js +301 -0
- package/packages/utils-agents/lib/global-repo.js.map +1 -0
- package/packages/utils-agents/lib/index.d.ts +80 -0
- package/packages/utils-agents/lib/index.js +435 -0
- package/packages/utils-agents/lib/index.js.map +1 -0
- package/packages/utils-agents/lib/legacy.d.ts +30 -0
- package/packages/utils-agents/lib/legacy.js +141 -0
- package/packages/utils-agents/lib/legacy.js.map +1 -0
- package/packages/utils-agents/lib/native.d.ts +74 -0
- package/packages/utils-agents/lib/native.js +232 -0
- package/packages/utils-agents/lib/native.js.map +1 -0
- package/packages/utils-agents/lib/presets.d.ts +34 -0
- package/packages/utils-agents/lib/presets.js +312 -0
- package/packages/utils-agents/lib/presets.js.map +1 -0
- package/packages/utils-agents/lib/shared.d.ts +105 -0
- package/packages/utils-agents/lib/shared.js +507 -0
- package/packages/utils-agents/lib/shared.js.map +1 -0
- package/packages/utils-agents/lib/update.d.ts +129 -0
- package/packages/utils-agents/lib/update.js +507 -0
- package/packages/utils-agents/lib/update.js.map +1 -0
- package/packages/utils-agents/lib/util.d.ts +215 -0
- package/packages/utils-agents/lib/util.js +475 -0
- package/packages/utils-agents/lib/util.js.map +1 -0
- package/packages/utils-agents/locale/en.json +6 -0
- package/packages/utils-agents/locale/zh.json +6 -0
- package/skills/dsh-approval-policy-config/SKILL.md +96 -0
- package/src/index.ts +933 -0
- package/src/ui-host.ts +1073 -0
package/lib/index.js
ADDED
|
@@ -0,0 +1,865 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `dsh-utils` main component (`utils-main`): the package root half of the
|
|
3
|
+
* bundle, mounted as a normal row by `cordis.patch.yml`.
|
|
4
|
+
*
|
|
5
|
+
* It adds nested `SKILL.md` bundles (depth >= `minDepth`) to the skill catalog,
|
|
6
|
+
* leaving depth-1 discovery to the built-in filesystem provider, and owns the
|
|
7
|
+
* skill-repository sync routes imported from `./ui-host.js`. The browser half
|
|
8
|
+
* (`client.js`) is published by this same package: `utils-main` is a
|
|
9
|
+
* package-root row, so the client-module scanner serves it from this row.
|
|
10
|
+
*
|
|
11
|
+
* @module dsh-utils
|
|
12
|
+
*/
|
|
13
|
+
import { watch } from 'node:fs';
|
|
14
|
+
import { readdir, readFile, realpath, stat } from 'node:fs/promises';
|
|
15
|
+
import { homedir } from 'node:os';
|
|
16
|
+
import { dirname, join, resolve } from 'node:path';
|
|
17
|
+
import z from '@deepseek-ai/schemastery';
|
|
18
|
+
import { applyUiHost } from './ui-host.js';
|
|
19
|
+
export const name = 'utils-main';
|
|
20
|
+
export const inject = ['skills'];
|
|
21
|
+
/** Ranks sit one step below the shipped filesystem provider, so flat skills win collisions. */
|
|
22
|
+
const RANKS = {
|
|
23
|
+
'project-dsh': 110,
|
|
24
|
+
'project-agents': 210,
|
|
25
|
+
custom: 310,
|
|
26
|
+
'user-dsh': 410,
|
|
27
|
+
'user-agents': 510,
|
|
28
|
+
};
|
|
29
|
+
const SKILL_FILE = 'SKILL.md';
|
|
30
|
+
const SKILL_NAME = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
|
|
31
|
+
const DEFAULTS = {
|
|
32
|
+
minDepth: 2,
|
|
33
|
+
maxDepth: 8,
|
|
34
|
+
watch: true,
|
|
35
|
+
debounceMs: 200,
|
|
36
|
+
pollIntervalMs: 2000,
|
|
37
|
+
includeProjectRoots: true,
|
|
38
|
+
includeUserRoots: true,
|
|
39
|
+
followSymlinks: false,
|
|
40
|
+
extraRoots: [],
|
|
41
|
+
ignoreDirs: ['.system', 'node_modules', '.git'],
|
|
42
|
+
};
|
|
43
|
+
/**
|
|
44
|
+
* Settings schema. Volatile fields are the only ones DSH exposes in the
|
|
45
|
+
* Settings form and the ones the Loader can refresh in place.
|
|
46
|
+
*/
|
|
47
|
+
export const Config = z.object({
|
|
48
|
+
minDepth: z.natural().min(1).default(DEFAULTS.minDepth).description('First folder level that may contain a skill.').volatile(),
|
|
49
|
+
maxDepth: z.natural().min(1).default(DEFAULTS.maxDepth).description('Deepest folder level that is scanned.').volatile(),
|
|
50
|
+
watch: z.boolean().default(DEFAULTS.watch).description('Refresh the catalog when skill files change.').volatile(),
|
|
51
|
+
debounceMs: z.natural().default(DEFAULTS.debounceMs).description('Debounce for watcher invalidations.').volatile(),
|
|
52
|
+
pollIntervalMs: z.natural().min(250).default(DEFAULTS.pollIntervalMs).description('Fallback polling interval.').volatile(),
|
|
53
|
+
includeProjectRoots: z.boolean().default(DEFAULTS.includeProjectRoots).description('Scan project .dsh/skills and .agents/skills.').volatile(),
|
|
54
|
+
includeUserRoots: z.boolean().default(DEFAULTS.includeUserRoots).description('Scan user-level skill roots.').volatile(),
|
|
55
|
+
followSymlinks: z.boolean().default(DEFAULTS.followSymlinks).description('Follow symlinked folders.').volatile(),
|
|
56
|
+
extraRoots: z.array(z.string().min(1)).default([...DEFAULTS.extraRoots]).description('Additional skill roots.').volatile(),
|
|
57
|
+
ignoreDirs: z.array(z.string().min(1)).default([...DEFAULTS.ignoreDirs]).description('Folder names never scanned.').volatile(),
|
|
58
|
+
});
|
|
59
|
+
/**
|
|
60
|
+
* Register the recursive skill provider on the host `skills` registry.
|
|
61
|
+
* @param ctx - plugin context carrying the `skills` service.
|
|
62
|
+
* @param config - optional row config; see {@link normalizeConfig}.
|
|
63
|
+
*/
|
|
64
|
+
export function apply(ctx, config) {
|
|
65
|
+
let provider;
|
|
66
|
+
ctx.skills.registerProvider((control) => {
|
|
67
|
+
provider = new RecursiveSkillProvider(ctx, control, config);
|
|
68
|
+
return provider;
|
|
69
|
+
});
|
|
70
|
+
ctx.on('settings/document-updated', () => provider?.syncOptions());
|
|
71
|
+
ctx.effect(function* () {
|
|
72
|
+
yield async () => {
|
|
73
|
+
await provider?.dispose();
|
|
74
|
+
};
|
|
75
|
+
}, 'utils-main watcher');
|
|
76
|
+
applyUiHost(ctx);
|
|
77
|
+
}
|
|
78
|
+
/** Provider that adds nested `SKILL.md` bundles to the skill catalog. */
|
|
79
|
+
class RecursiveSkillProvider {
|
|
80
|
+
name = name;
|
|
81
|
+
ctx;
|
|
82
|
+
control;
|
|
83
|
+
config;
|
|
84
|
+
options;
|
|
85
|
+
watchers = new Map();
|
|
86
|
+
pendingInvalidation;
|
|
87
|
+
disposed = false;
|
|
88
|
+
/**
|
|
89
|
+
* @param ctx - plugin context.
|
|
90
|
+
* @param control - registry registration control.
|
|
91
|
+
* @param config - raw row config, including Loader volatile references.
|
|
92
|
+
*/
|
|
93
|
+
constructor(ctx, control, config) {
|
|
94
|
+
this.ctx = ctx;
|
|
95
|
+
this.control = control;
|
|
96
|
+
this.config = config;
|
|
97
|
+
this.options = normalizeConfig(ctx, config);
|
|
98
|
+
control.signal.addEventListener('abort', () => {
|
|
99
|
+
void this.dispose();
|
|
100
|
+
}, { once: true });
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* Discover nested skill candidates for one workspace.
|
|
104
|
+
* @param options - lookup options; `cwd` selects the project roots.
|
|
105
|
+
* @returns candidates, or an incomplete observation when a scan failed.
|
|
106
|
+
*/
|
|
107
|
+
async list(options = {}) {
|
|
108
|
+
this.syncOptions();
|
|
109
|
+
const roots = await this.roots(options.cwd);
|
|
110
|
+
this.observeRoots(roots);
|
|
111
|
+
const candidates = [];
|
|
112
|
+
let complete = true;
|
|
113
|
+
for (const root of roots) {
|
|
114
|
+
const scan = await scanRoot(root, this.options, this.ctx, this.name);
|
|
115
|
+
if (!scan.complete)
|
|
116
|
+
complete = false;
|
|
117
|
+
for (const candidate of scan.candidates)
|
|
118
|
+
candidates.push(candidate);
|
|
119
|
+
}
|
|
120
|
+
return complete ? candidates : { candidates, complete };
|
|
121
|
+
}
|
|
122
|
+
/** Pick up Settings changes; the Loader updates volatile refs in place. */
|
|
123
|
+
syncOptions() {
|
|
124
|
+
if (this.disposed)
|
|
125
|
+
return;
|
|
126
|
+
let next;
|
|
127
|
+
try {
|
|
128
|
+
next = normalizeConfig(this.ctx, this.config);
|
|
129
|
+
}
|
|
130
|
+
catch (error) {
|
|
131
|
+
this.ctx.logger.warn(`utils-main: ignoring invalid settings: ${errorMessage(error)}`);
|
|
132
|
+
return;
|
|
133
|
+
}
|
|
134
|
+
if (sameOptions(next, this.options))
|
|
135
|
+
return;
|
|
136
|
+
this.options = next;
|
|
137
|
+
if (this.pendingInvalidation !== undefined) {
|
|
138
|
+
clearTimeout(this.pendingInvalidation);
|
|
139
|
+
this.pendingInvalidation = undefined;
|
|
140
|
+
}
|
|
141
|
+
this.closeWatchers();
|
|
142
|
+
this.control.invalidate();
|
|
143
|
+
}
|
|
144
|
+
/**
|
|
145
|
+
* Load one nested skill body from its candidate.
|
|
146
|
+
* @param candidate - winning candidate returned by {@link list}.
|
|
147
|
+
* @param options - lookup options whose signal cancels reads.
|
|
148
|
+
* @returns the full definition, or undefined when the file vanished.
|
|
149
|
+
*/
|
|
150
|
+
async get(candidate, options = {}) {
|
|
151
|
+
const path = candidate.path;
|
|
152
|
+
if (path === undefined)
|
|
153
|
+
throw new TypeError(`utils-main: candidate "${candidate.name}" carries no path`);
|
|
154
|
+
const parsed = await readSkill(path, options.signal);
|
|
155
|
+
if (parsed === undefined)
|
|
156
|
+
return undefined;
|
|
157
|
+
if (parsed.name !== candidate.name) {
|
|
158
|
+
throw new Error(`skill file ${candidate.path} now declares "${parsed.name}" but was discovered as "${candidate.name}"`);
|
|
159
|
+
}
|
|
160
|
+
return {
|
|
161
|
+
name: parsed.name,
|
|
162
|
+
description: parsed.description,
|
|
163
|
+
...(parsed.whenToUse !== undefined ? { whenToUse: parsed.whenToUse } : {}),
|
|
164
|
+
invocation: parsed.invocation,
|
|
165
|
+
source: candidate.source,
|
|
166
|
+
provider: this.name,
|
|
167
|
+
resourceBase: { kind: 'directory', path: dirname(path) },
|
|
168
|
+
path: parsed.path,
|
|
169
|
+
content: parsed.content,
|
|
170
|
+
...(parsed.metadata !== undefined ? { metadata: parsed.metadata } : {}),
|
|
171
|
+
};
|
|
172
|
+
}
|
|
173
|
+
/**
|
|
174
|
+
* Resolve the standard skill roots for a workspace.
|
|
175
|
+
* @param cwd - session working directory.
|
|
176
|
+
* @returns de-duplicated roots in precedence order.
|
|
177
|
+
*/
|
|
178
|
+
async roots(cwd) {
|
|
179
|
+
const roots = [];
|
|
180
|
+
if (this.options.includeProjectRoots && typeof cwd === 'string' && cwd.length > 0) {
|
|
181
|
+
const projectRoot = await findProjectRoot(resolve(cwd), this.ctx);
|
|
182
|
+
roots.push({ path: join(projectRoot, '.dsh', 'skills'), source: 'project-dsh', rank: RANKS['project-dsh'] });
|
|
183
|
+
roots.push({ path: join(projectRoot, '.agents', 'skills'), source: 'project-agents', rank: RANKS['project-agents'] });
|
|
184
|
+
}
|
|
185
|
+
for (const path of this.options.extraRoots) {
|
|
186
|
+
roots.push({ path, source: 'custom', rank: RANKS.custom });
|
|
187
|
+
}
|
|
188
|
+
if (this.options.includeUserRoots) {
|
|
189
|
+
roots.push({ path: join(agentHome('DSH_HOME', '.dsh'), 'skills'), source: 'user-dsh', rank: RANKS['user-dsh'] });
|
|
190
|
+
roots.push({ path: join(agentHome('DSH_AGENTS_HOME', '.agents'), 'skills'), source: 'user-agents', rank: RANKS['user-agents'] });
|
|
191
|
+
}
|
|
192
|
+
const seen = new Set();
|
|
193
|
+
const unique = [];
|
|
194
|
+
for (const root of roots) {
|
|
195
|
+
if (seen.has(root.path))
|
|
196
|
+
continue;
|
|
197
|
+
seen.add(root.path);
|
|
198
|
+
unique.push(root);
|
|
199
|
+
}
|
|
200
|
+
return unique;
|
|
201
|
+
}
|
|
202
|
+
/**
|
|
203
|
+
* Start a watcher per known root so a new nested skill invalidates the cache.
|
|
204
|
+
* @param roots - resolved roots from {@link roots}.
|
|
205
|
+
*/
|
|
206
|
+
observeRoots(roots) {
|
|
207
|
+
if (!this.options.watch || this.disposed)
|
|
208
|
+
return;
|
|
209
|
+
for (const root of roots) {
|
|
210
|
+
if (this.watchers.has(root.path))
|
|
211
|
+
continue;
|
|
212
|
+
const watcher = { root, handle: undefined, polling: undefined, lastSignature: undefined, closed: false };
|
|
213
|
+
this.watchers.set(root.path, watcher);
|
|
214
|
+
void this.openWatcher(watcher);
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
/**
|
|
218
|
+
* Open a recursive filesystem watcher, falling back to polling where the
|
|
219
|
+
* platform does not support recursive watches.
|
|
220
|
+
* @param watcher - per-root watcher state.
|
|
221
|
+
*/
|
|
222
|
+
async openWatcher(watcher) {
|
|
223
|
+
try {
|
|
224
|
+
const info = await stat(watcher.root.path);
|
|
225
|
+
if (!info.isDirectory()) {
|
|
226
|
+
this.watchers.delete(watcher.root.path);
|
|
227
|
+
return;
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
catch {
|
|
231
|
+
// Retry on a later listing; the root may be created after first discovery.
|
|
232
|
+
this.watchers.delete(watcher.root.path);
|
|
233
|
+
return;
|
|
234
|
+
}
|
|
235
|
+
if (this.disposed || watcher.closed)
|
|
236
|
+
return;
|
|
237
|
+
try {
|
|
238
|
+
const handle = watch(watcher.root.path, { recursive: true, persistent: false }, () => this.scheduleInvalidation());
|
|
239
|
+
handle.on('error', () => {
|
|
240
|
+
handle.close();
|
|
241
|
+
watcher.handle = undefined;
|
|
242
|
+
this.startPolling(watcher);
|
|
243
|
+
});
|
|
244
|
+
watcher.handle = handle;
|
|
245
|
+
}
|
|
246
|
+
catch {
|
|
247
|
+
this.startPolling(watcher);
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
/**
|
|
251
|
+
* Poll a root's nested skill signature when recursive watching is unavailable.
|
|
252
|
+
* @param watcher - per-root watcher state.
|
|
253
|
+
*/
|
|
254
|
+
startPolling(watcher) {
|
|
255
|
+
if (this.disposed || watcher.closed || watcher.polling !== undefined)
|
|
256
|
+
return;
|
|
257
|
+
const tick = async () => {
|
|
258
|
+
const signature = await scanRootSignature(watcher.root, this.options, this.ctx);
|
|
259
|
+
if (watcher.lastSignature === undefined) {
|
|
260
|
+
watcher.lastSignature = signature;
|
|
261
|
+
return;
|
|
262
|
+
}
|
|
263
|
+
if (signature !== watcher.lastSignature) {
|
|
264
|
+
watcher.lastSignature = signature;
|
|
265
|
+
this.scheduleInvalidation();
|
|
266
|
+
}
|
|
267
|
+
};
|
|
268
|
+
void tick();
|
|
269
|
+
watcher.polling = setInterval(() => void tick(), this.options.pollIntervalMs);
|
|
270
|
+
watcher.polling.unref();
|
|
271
|
+
}
|
|
272
|
+
/** Debounce a catalog invalidation burst into one refresh. */
|
|
273
|
+
scheduleInvalidation() {
|
|
274
|
+
if (this.disposed || this.pendingInvalidation !== undefined)
|
|
275
|
+
return;
|
|
276
|
+
this.pendingInvalidation = setTimeout(() => {
|
|
277
|
+
this.pendingInvalidation = undefined;
|
|
278
|
+
this.control.invalidate();
|
|
279
|
+
}, this.options.debounceMs);
|
|
280
|
+
this.pendingInvalidation.unref();
|
|
281
|
+
}
|
|
282
|
+
/** Stop every watcher and timer owned by this registration. */
|
|
283
|
+
async dispose() {
|
|
284
|
+
if (this.disposed)
|
|
285
|
+
return;
|
|
286
|
+
this.disposed = true;
|
|
287
|
+
if (this.pendingInvalidation !== undefined) {
|
|
288
|
+
clearTimeout(this.pendingInvalidation);
|
|
289
|
+
this.pendingInvalidation = undefined;
|
|
290
|
+
}
|
|
291
|
+
this.closeWatchers();
|
|
292
|
+
}
|
|
293
|
+
/** Close watcher handles and polling timers; the next listing opens fresh ones. */
|
|
294
|
+
closeWatchers() {
|
|
295
|
+
for (const watcher of this.watchers.values()) {
|
|
296
|
+
watcher.closed = true;
|
|
297
|
+
watcher.handle?.close();
|
|
298
|
+
watcher.handle = undefined;
|
|
299
|
+
if (watcher.polling !== undefined) {
|
|
300
|
+
clearInterval(watcher.polling);
|
|
301
|
+
watcher.polling = undefined;
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
this.watchers.clear();
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
/**
|
|
308
|
+
* Depth-limited recursive scan of one skill root for nested `SKILL.md` files.
|
|
309
|
+
* @param root - resolved root descriptor.
|
|
310
|
+
* @param options - normalized plugin options.
|
|
311
|
+
* @param ctx - plugin context for warnings.
|
|
312
|
+
* @returns candidates plus whether the scan was complete.
|
|
313
|
+
*/
|
|
314
|
+
async function scanRoot(root, options, ctx, providerName) {
|
|
315
|
+
const candidates = [];
|
|
316
|
+
let complete = true;
|
|
317
|
+
const stack = [{ dir: root.path, depth: 0 }];
|
|
318
|
+
const visited = new Set();
|
|
319
|
+
while (stack.length > 0) {
|
|
320
|
+
const current = stack.pop();
|
|
321
|
+
let entries;
|
|
322
|
+
try {
|
|
323
|
+
entries = await readdir(current.dir, { withFileTypes: true });
|
|
324
|
+
}
|
|
325
|
+
catch (error) {
|
|
326
|
+
if (!isAbsent(error)) {
|
|
327
|
+
complete = false;
|
|
328
|
+
ctx.logger.warn(`utils-main: cannot read ${current.dir}: ${errorMessage(error)}`);
|
|
329
|
+
}
|
|
330
|
+
continue;
|
|
331
|
+
}
|
|
332
|
+
if (current.depth >= options.minDepth && entries.some((entry) => entry.name === SKILL_FILE)) {
|
|
333
|
+
const file = join(current.dir, SKILL_FILE);
|
|
334
|
+
const parsed = await readSkillCandidate(file, root, ctx, providerName);
|
|
335
|
+
if (parsed !== undefined)
|
|
336
|
+
candidates.push(parsed);
|
|
337
|
+
}
|
|
338
|
+
if (current.depth >= options.maxDepth)
|
|
339
|
+
continue;
|
|
340
|
+
for (const entry of entries) {
|
|
341
|
+
const child = join(current.dir, entry.name);
|
|
342
|
+
if (entry.isDirectory()) {
|
|
343
|
+
if (isIgnored(entry.name, options))
|
|
344
|
+
continue;
|
|
345
|
+
stack.push({ dir: child, depth: current.depth + 1 });
|
|
346
|
+
continue;
|
|
347
|
+
}
|
|
348
|
+
if (!entry.isSymbolicLink() || !options.followSymlinks)
|
|
349
|
+
continue;
|
|
350
|
+
try {
|
|
351
|
+
const info = await stat(child);
|
|
352
|
+
if (!info.isDirectory())
|
|
353
|
+
continue;
|
|
354
|
+
const real = await realpath(child);
|
|
355
|
+
if (visited.has(real))
|
|
356
|
+
continue;
|
|
357
|
+
visited.add(real);
|
|
358
|
+
stack.push({ dir: child, depth: current.depth + 1 });
|
|
359
|
+
}
|
|
360
|
+
catch (error) {
|
|
361
|
+
ctx.logger.warn(`utils-main: cannot follow ${child}: ${errorMessage(error)}`);
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
return { candidates, complete };
|
|
366
|
+
}
|
|
367
|
+
/**
|
|
368
|
+
* Read and validate one nested skill file into a provider candidate.
|
|
369
|
+
* @param path - absolute `SKILL.md` path.
|
|
370
|
+
* @param root - root descriptor supplying source and rank.
|
|
371
|
+
* @param ctx - plugin context for warnings.
|
|
372
|
+
* @returns candidate, or undefined when the file is not a valid skill.
|
|
373
|
+
*/
|
|
374
|
+
async function readSkillCandidate(path, root, ctx, providerName) {
|
|
375
|
+
let info;
|
|
376
|
+
try {
|
|
377
|
+
info = await stat(path);
|
|
378
|
+
}
|
|
379
|
+
catch (error) {
|
|
380
|
+
if (isAbsent(error))
|
|
381
|
+
return undefined;
|
|
382
|
+
ctx.logger.warn(`utils-main: cannot stat ${path}: ${errorMessage(error)}`);
|
|
383
|
+
return undefined;
|
|
384
|
+
}
|
|
385
|
+
if (!info.isFile())
|
|
386
|
+
return undefined;
|
|
387
|
+
let parsed;
|
|
388
|
+
try {
|
|
389
|
+
parsed = await readSkill(path);
|
|
390
|
+
}
|
|
391
|
+
catch (error) {
|
|
392
|
+
ctx.logger.warn(`skill file ${path} ignored: ${errorMessage(error)}`);
|
|
393
|
+
return undefined;
|
|
394
|
+
}
|
|
395
|
+
if (parsed === undefined)
|
|
396
|
+
return undefined;
|
|
397
|
+
return {
|
|
398
|
+
name: parsed.name,
|
|
399
|
+
description: parsed.description,
|
|
400
|
+
...(parsed.whenToUse !== undefined ? { whenToUse: parsed.whenToUse } : {}),
|
|
401
|
+
invocation: parsed.invocation,
|
|
402
|
+
provider: providerName,
|
|
403
|
+
source: root.source,
|
|
404
|
+
rank: root.rank,
|
|
405
|
+
locator: { path, directory: dirname(path) },
|
|
406
|
+
resourceBase: { kind: 'directory', path: dirname(path) },
|
|
407
|
+
path,
|
|
408
|
+
...(parsed.metadata !== undefined ? { metadata: parsed.metadata } : {}),
|
|
409
|
+
};
|
|
410
|
+
}
|
|
411
|
+
/**
|
|
412
|
+
* Read and parse one skill file.
|
|
413
|
+
* @param path - absolute `SKILL.md` path.
|
|
414
|
+
* @param signal - optional abort signal.
|
|
415
|
+
* @returns parsed summary, or undefined when the file is missing or invalid.
|
|
416
|
+
*/
|
|
417
|
+
async function readSkill(path, signal) {
|
|
418
|
+
signal?.throwIfAborted();
|
|
419
|
+
let resolvedPath;
|
|
420
|
+
let raw;
|
|
421
|
+
try {
|
|
422
|
+
resolvedPath = await realpath(path);
|
|
423
|
+
raw = await readFile(resolvedPath, { encoding: 'utf8', signal });
|
|
424
|
+
}
|
|
425
|
+
catch (error) {
|
|
426
|
+
signal?.throwIfAborted();
|
|
427
|
+
if (isAbsent(error))
|
|
428
|
+
return undefined;
|
|
429
|
+
throw error;
|
|
430
|
+
}
|
|
431
|
+
signal?.throwIfAborted();
|
|
432
|
+
const frontmatter = parseFrontmatter(raw);
|
|
433
|
+
if (frontmatter === undefined)
|
|
434
|
+
return undefined;
|
|
435
|
+
const data = frontmatter.data;
|
|
436
|
+
const skillName = stringField(data, 'name');
|
|
437
|
+
const description = stringField(data, 'description');
|
|
438
|
+
if (skillName === undefined || description === undefined)
|
|
439
|
+
return undefined;
|
|
440
|
+
if (!SKILL_NAME.test(skillName)) {
|
|
441
|
+
throw new Error(`invalid skill name "${skillName}"`);
|
|
442
|
+
}
|
|
443
|
+
const whenToUse = stringField(data, 'whenToUse');
|
|
444
|
+
const metadata = data.metadata;
|
|
445
|
+
return {
|
|
446
|
+
name: skillName,
|
|
447
|
+
description,
|
|
448
|
+
...(whenToUse !== undefined ? { whenToUse } : {}),
|
|
449
|
+
invocation: parseInvocationPolicy(data),
|
|
450
|
+
...(typeof metadata === 'object' && metadata !== null && !Array.isArray(metadata) ? { metadata: metadata } : {}),
|
|
451
|
+
path: resolvedPath,
|
|
452
|
+
content: frontmatter.body.trim(),
|
|
453
|
+
};
|
|
454
|
+
}
|
|
455
|
+
/**
|
|
456
|
+
* Extract the YAML frontmatter block and Markdown body.
|
|
457
|
+
* @param raw - whole file text.
|
|
458
|
+
* @returns parsed data and body, or undefined when no frontmatter exists.
|
|
459
|
+
*/
|
|
460
|
+
function parseFrontmatter(raw) {
|
|
461
|
+
const firstLineEnd = raw.indexOf('\n');
|
|
462
|
+
if (firstLineEnd < 0)
|
|
463
|
+
return undefined;
|
|
464
|
+
if (raw.slice(0, firstLineEnd).replace(/\r$/, '') !== '---')
|
|
465
|
+
return undefined;
|
|
466
|
+
const start = firstLineEnd + 1;
|
|
467
|
+
const closing = findClosingFrontmatter(raw, start);
|
|
468
|
+
if (closing === undefined)
|
|
469
|
+
return undefined;
|
|
470
|
+
const data = parseFrontmatterData(raw.slice(start, closing.start));
|
|
471
|
+
return { data, body: raw.slice(closing.bodyStart) };
|
|
472
|
+
}
|
|
473
|
+
/**
|
|
474
|
+
* Locate the closing `---` line.
|
|
475
|
+
* @param raw - whole file text.
|
|
476
|
+
* @param start - offset just after the opening delimiter.
|
|
477
|
+
* @returns closing offsets, or undefined when unterminated.
|
|
478
|
+
*/
|
|
479
|
+
function findClosingFrontmatter(raw, start) {
|
|
480
|
+
let lineStart = start;
|
|
481
|
+
while (lineStart <= raw.length) {
|
|
482
|
+
const nextNewline = raw.indexOf('\n', lineStart);
|
|
483
|
+
const lineEnd = nextNewline < 0 ? raw.length : nextNewline;
|
|
484
|
+
if (raw.slice(lineStart, lineEnd).replace(/\r$/, '') === '---') {
|
|
485
|
+
return { start: lineStart, bodyStart: nextNewline < 0 ? raw.length : nextNewline + 1 };
|
|
486
|
+
}
|
|
487
|
+
if (nextNewline < 0)
|
|
488
|
+
return undefined;
|
|
489
|
+
lineStart = nextNewline + 1;
|
|
490
|
+
}
|
|
491
|
+
return undefined;
|
|
492
|
+
}
|
|
493
|
+
/**
|
|
494
|
+
* Parse the small YAML subset skill frontmatter uses: plain and quoted scalars,
|
|
495
|
+
* block scalars, and booleans. Nested mappings and sequences are ignored.
|
|
496
|
+
* @param block - frontmatter text without delimiters.
|
|
497
|
+
* @returns parsed top-level fields.
|
|
498
|
+
*/
|
|
499
|
+
function parseFrontmatterData(block) {
|
|
500
|
+
const data = Object.create(null);
|
|
501
|
+
const lines = block.split(/\r?\n/);
|
|
502
|
+
for (let index = 0; index < lines.length; index += 1) {
|
|
503
|
+
const line = lines[index];
|
|
504
|
+
if (line.trim() === '' || line.trimStart().startsWith('#'))
|
|
505
|
+
continue;
|
|
506
|
+
if (/^\s/.test(line))
|
|
507
|
+
continue;
|
|
508
|
+
const colon = line.indexOf(':');
|
|
509
|
+
if (colon <= 0)
|
|
510
|
+
continue;
|
|
511
|
+
const key = line.slice(0, colon).trim();
|
|
512
|
+
if (!/^[A-Za-z0-9_.-]+$/.test(key))
|
|
513
|
+
continue;
|
|
514
|
+
const rest = line.slice(colon + 1).trim();
|
|
515
|
+
if (/^[|>][+-]?$/.test(rest)) {
|
|
516
|
+
const style = rest[0];
|
|
517
|
+
const collected = [];
|
|
518
|
+
let cursor = index + 1;
|
|
519
|
+
for (; cursor < lines.length; cursor += 1) {
|
|
520
|
+
const next = lines[cursor];
|
|
521
|
+
if (next.trim() === '') {
|
|
522
|
+
collected.push('');
|
|
523
|
+
continue;
|
|
524
|
+
}
|
|
525
|
+
if (!/^\s/.test(next))
|
|
526
|
+
break;
|
|
527
|
+
collected.push(next);
|
|
528
|
+
}
|
|
529
|
+
index = cursor - 1;
|
|
530
|
+
const dedented = dedent(collected);
|
|
531
|
+
data[key] = style === '|' ? dedented.trim() : fold(dedented).trim();
|
|
532
|
+
continue;
|
|
533
|
+
}
|
|
534
|
+
if (rest === '')
|
|
535
|
+
continue;
|
|
536
|
+
data[key] = parseScalar(rest);
|
|
537
|
+
}
|
|
538
|
+
return data;
|
|
539
|
+
}
|
|
540
|
+
/**
|
|
541
|
+
* Remove the common indentation from block-scalar lines.
|
|
542
|
+
* @param lines - raw block lines.
|
|
543
|
+
* @returns de-indented text lines joined with newlines.
|
|
544
|
+
*/
|
|
545
|
+
function dedent(lines) {
|
|
546
|
+
const indents = lines.filter((line) => line.length > 0).map((line) => line.match(/^\s*/)[0].length);
|
|
547
|
+
const minimum = indents.length > 0 ? Math.min(...indents) : 0;
|
|
548
|
+
return lines.map((line) => line.slice(Math.min(minimum, line.length))).join('\n');
|
|
549
|
+
}
|
|
550
|
+
/**
|
|
551
|
+
* Fold block-scalar lines into prose.
|
|
552
|
+
* @param text - de-indented block text.
|
|
553
|
+
* @returns folded text.
|
|
554
|
+
*/
|
|
555
|
+
function fold(text) {
|
|
556
|
+
return text
|
|
557
|
+
.split('\n')
|
|
558
|
+
.map((line) => line.trim())
|
|
559
|
+
.filter((line) => line.length > 0)
|
|
560
|
+
.join(' ');
|
|
561
|
+
}
|
|
562
|
+
/**
|
|
563
|
+
* Parse one inline scalar value.
|
|
564
|
+
* @param raw - raw scalar text.
|
|
565
|
+
* @returns string, boolean, or null.
|
|
566
|
+
*/
|
|
567
|
+
function parseScalar(raw) {
|
|
568
|
+
const value = raw.trim();
|
|
569
|
+
if (value === '' || value === '~' || value === 'null')
|
|
570
|
+
return null;
|
|
571
|
+
if (value.length >= 2 && value.startsWith('"') && value.endsWith('"')) {
|
|
572
|
+
return value.slice(1, -1).replace(/\\n/g, '\n').replace(/\\"/g, '"').replace(/\\\\/g, '\\');
|
|
573
|
+
}
|
|
574
|
+
if (value.length >= 2 && value.startsWith("'") && value.endsWith("'")) {
|
|
575
|
+
return value.slice(1, -1).replace(/''/g, "'");
|
|
576
|
+
}
|
|
577
|
+
const lower = value.toLowerCase();
|
|
578
|
+
if (lower === 'true' || lower === 'yes' || lower === 'on')
|
|
579
|
+
return true;
|
|
580
|
+
if (lower === 'false' || lower === 'no' || lower === 'off')
|
|
581
|
+
return false;
|
|
582
|
+
return value;
|
|
583
|
+
}
|
|
584
|
+
/**
|
|
585
|
+
* Resolve model/user invocation controls from frontmatter.
|
|
586
|
+
* @param data - parsed frontmatter fields.
|
|
587
|
+
* @returns invocation policy.
|
|
588
|
+
*/
|
|
589
|
+
function parseInvocationPolicy(data) {
|
|
590
|
+
for (const [legacy, canonical] of [
|
|
591
|
+
['disableModelInvocation', 'disable-model-invocation'],
|
|
592
|
+
['modelInvocable', 'disable-model-invocation'],
|
|
593
|
+
['userInvocable', 'user-invocable'],
|
|
594
|
+
]) {
|
|
595
|
+
if (Object.hasOwn(data, legacy))
|
|
596
|
+
throw new Error(`frontmatter field "${legacy}" is unsupported; use "${canonical}"`);
|
|
597
|
+
}
|
|
598
|
+
const disableModelInvocation = booleanField(data, 'disable-model-invocation');
|
|
599
|
+
const userInvocable = booleanField(data, 'user-invocable');
|
|
600
|
+
return {
|
|
601
|
+
modelInvocable: disableModelInvocation !== true,
|
|
602
|
+
userInvocable: userInvocable !== false,
|
|
603
|
+
};
|
|
604
|
+
}
|
|
605
|
+
/**
|
|
606
|
+
* Read an optional boolean field with YAML-compatible coercions.
|
|
607
|
+
* @param data - parsed frontmatter fields.
|
|
608
|
+
* @param key - field name.
|
|
609
|
+
* @returns boolean when present and understood.
|
|
610
|
+
*/
|
|
611
|
+
function booleanField(data, key) {
|
|
612
|
+
if (!Object.hasOwn(data, key))
|
|
613
|
+
return undefined;
|
|
614
|
+
const value = data[key];
|
|
615
|
+
if (typeof value === 'boolean')
|
|
616
|
+
return value;
|
|
617
|
+
if (value === 1 || value === '1')
|
|
618
|
+
return true;
|
|
619
|
+
if (value === 0 || value === '0')
|
|
620
|
+
return false;
|
|
621
|
+
if (typeof value === 'string') {
|
|
622
|
+
switch (value.toLowerCase()) {
|
|
623
|
+
case 'true':
|
|
624
|
+
case 'yes':
|
|
625
|
+
case 'on':
|
|
626
|
+
return true;
|
|
627
|
+
case 'false':
|
|
628
|
+
case 'no':
|
|
629
|
+
case 'off':
|
|
630
|
+
return false;
|
|
631
|
+
}
|
|
632
|
+
}
|
|
633
|
+
throw new TypeError(`frontmatter field "${key}" must be a boolean`);
|
|
634
|
+
}
|
|
635
|
+
/**
|
|
636
|
+
* Read a non-empty string field.
|
|
637
|
+
* @param data - parsed frontmatter fields.
|
|
638
|
+
* @param key - field name.
|
|
639
|
+
* @returns the string, or undefined when absent or empty.
|
|
640
|
+
*/
|
|
641
|
+
function stringField(data, key) {
|
|
642
|
+
const value = data[key];
|
|
643
|
+
return typeof value === 'string' && value.length > 0 ? value : undefined;
|
|
644
|
+
}
|
|
645
|
+
/**
|
|
646
|
+
* Walk up from `cwd` to the nearest directory containing `.git`.
|
|
647
|
+
* @param cwd - absolute session directory.
|
|
648
|
+
* @param ctx - plugin context for warnings.
|
|
649
|
+
* @returns project root, or `cwd` when no repository marker exists.
|
|
650
|
+
*/
|
|
651
|
+
async function findProjectRoot(cwd, ctx) {
|
|
652
|
+
let current = cwd;
|
|
653
|
+
while (true) {
|
|
654
|
+
try {
|
|
655
|
+
await stat(join(current, '.git'));
|
|
656
|
+
return current;
|
|
657
|
+
}
|
|
658
|
+
catch (error) {
|
|
659
|
+
if (!isAbsent(error))
|
|
660
|
+
ctx.logger.warn(`utils-main: cannot inspect ${join(current, '.git')}: ${errorMessage(error)}`);
|
|
661
|
+
}
|
|
662
|
+
const parent = dirname(current);
|
|
663
|
+
if (parent === current)
|
|
664
|
+
return cwd;
|
|
665
|
+
current = parent;
|
|
666
|
+
}
|
|
667
|
+
}
|
|
668
|
+
/**
|
|
669
|
+
* Resolve a home-based directory from an environment override.
|
|
670
|
+
* @param variable - environment variable name.
|
|
671
|
+
* @param fallback - directory name under the home directory.
|
|
672
|
+
* @returns absolute directory path.
|
|
673
|
+
*/
|
|
674
|
+
function agentHome(variable, fallback) {
|
|
675
|
+
const override = process.env[variable];
|
|
676
|
+
if (typeof override === 'string' && override.length > 0)
|
|
677
|
+
return resolve(override);
|
|
678
|
+
return join(homedir(), fallback);
|
|
679
|
+
}
|
|
680
|
+
/**
|
|
681
|
+
* Build a change signature for polling fallback.
|
|
682
|
+
* @param root - root descriptor.
|
|
683
|
+
* @param options - normalized plugin options.
|
|
684
|
+
* @param ctx - plugin context for warnings.
|
|
685
|
+
* @returns stable signature string.
|
|
686
|
+
*/
|
|
687
|
+
async function scanRootSignature(root, options, ctx) {
|
|
688
|
+
const parts = [];
|
|
689
|
+
const stack = [{ dir: root.path, depth: 0 }];
|
|
690
|
+
const visited = new Set();
|
|
691
|
+
while (stack.length > 0) {
|
|
692
|
+
const current = stack.pop();
|
|
693
|
+
let entries;
|
|
694
|
+
try {
|
|
695
|
+
entries = await readdir(current.dir, { withFileTypes: true });
|
|
696
|
+
}
|
|
697
|
+
catch {
|
|
698
|
+
continue;
|
|
699
|
+
}
|
|
700
|
+
if (current.depth >= options.minDepth && entries.some((entry) => entry.name === SKILL_FILE)) {
|
|
701
|
+
const file = join(current.dir, SKILL_FILE);
|
|
702
|
+
try {
|
|
703
|
+
const info = await stat(file);
|
|
704
|
+
parts.push(`${file}:${info.size}:${info.mtimeMs}`);
|
|
705
|
+
}
|
|
706
|
+
catch {
|
|
707
|
+
// The file vanished between listing and stat; the next scan settles it.
|
|
708
|
+
}
|
|
709
|
+
}
|
|
710
|
+
if (current.depth >= options.maxDepth)
|
|
711
|
+
continue;
|
|
712
|
+
for (const entry of entries) {
|
|
713
|
+
if (entry.isDirectory()) {
|
|
714
|
+
if (isIgnored(entry.name, options))
|
|
715
|
+
continue;
|
|
716
|
+
stack.push({ dir: join(current.dir, entry.name), depth: current.depth + 1 });
|
|
717
|
+
continue;
|
|
718
|
+
}
|
|
719
|
+
if (!entry.isSymbolicLink() || !options.followSymlinks)
|
|
720
|
+
continue;
|
|
721
|
+
try {
|
|
722
|
+
const info = await stat(join(current.dir, entry.name));
|
|
723
|
+
if (!info.isDirectory())
|
|
724
|
+
continue;
|
|
725
|
+
const real = await realpath(join(current.dir, entry.name));
|
|
726
|
+
if (visited.has(real))
|
|
727
|
+
continue;
|
|
728
|
+
visited.add(real);
|
|
729
|
+
stack.push({ dir: join(current.dir, entry.name), depth: current.depth + 1 });
|
|
730
|
+
}
|
|
731
|
+
catch (error) {
|
|
732
|
+
ctx.logger.warn(`utils-main: cannot follow ${join(current.dir, entry.name)}: ${errorMessage(error)}`);
|
|
733
|
+
}
|
|
734
|
+
}
|
|
735
|
+
}
|
|
736
|
+
return parts.sort().join('\n');
|
|
737
|
+
}
|
|
738
|
+
/**
|
|
739
|
+
* Whether a directory name is excluded from recursion.
|
|
740
|
+
* @param dirName - directory base name.
|
|
741
|
+
* @param options - normalized plugin options.
|
|
742
|
+
* @returns whether to skip it.
|
|
743
|
+
*/
|
|
744
|
+
function isIgnored(dirName, options) {
|
|
745
|
+
return options.ignoreDirs.includes(dirName);
|
|
746
|
+
}
|
|
747
|
+
/**
|
|
748
|
+
* Validate and normalize row config.
|
|
749
|
+
* @param ctx - plugin context for warnings about unknown keys.
|
|
750
|
+
* @param raw - raw row config.
|
|
751
|
+
* @returns normalized options.
|
|
752
|
+
*/
|
|
753
|
+
function normalizeConfig(ctx, raw) {
|
|
754
|
+
const root = (unwrap(raw) ?? {});
|
|
755
|
+
if (typeof root !== 'object' || Array.isArray(root))
|
|
756
|
+
throw new TypeError('utils-main: config must be an object');
|
|
757
|
+
const known = new Set(Object.keys(DEFAULTS));
|
|
758
|
+
for (const key of Object.keys(root)) {
|
|
759
|
+
if (!known.has(key))
|
|
760
|
+
ctx.logger.warn(`utils-main: unknown config key "${key}" ignored`);
|
|
761
|
+
}
|
|
762
|
+
const value = (key) => unwrap(root[key]);
|
|
763
|
+
const options = { ...DEFAULTS };
|
|
764
|
+
options.minDepth = positiveInteger('minDepth', value('minDepth') ?? DEFAULTS.minDepth, 1);
|
|
765
|
+
options.maxDepth = positiveInteger('maxDepth', value('maxDepth') ?? DEFAULTS.maxDepth, options.minDepth);
|
|
766
|
+
options.debounceMs = nonNegativeInteger('debounceMs', value('debounceMs') ?? DEFAULTS.debounceMs);
|
|
767
|
+
options.pollIntervalMs = positiveInteger('pollIntervalMs', value('pollIntervalMs') ?? DEFAULTS.pollIntervalMs, 250);
|
|
768
|
+
options.watch = booleanOption('watch', value('watch') ?? DEFAULTS.watch);
|
|
769
|
+
options.includeProjectRoots = booleanOption('includeProjectRoots', value('includeProjectRoots') ?? DEFAULTS.includeProjectRoots);
|
|
770
|
+
options.includeUserRoots = booleanOption('includeUserRoots', value('includeUserRoots') ?? DEFAULTS.includeUserRoots);
|
|
771
|
+
options.followSymlinks = booleanOption('followSymlinks', value('followSymlinks') ?? DEFAULTS.followSymlinks);
|
|
772
|
+
options.extraRoots = stringArray('extraRoots', value('extraRoots') ?? DEFAULTS.extraRoots).map((path) => resolve(path));
|
|
773
|
+
options.ignoreDirs = stringArray('ignoreDirs', value('ignoreDirs') ?? DEFAULTS.ignoreDirs);
|
|
774
|
+
return options;
|
|
775
|
+
}
|
|
776
|
+
/** Read a Loader volatile reference, or return a plain value. */
|
|
777
|
+
function unwrap(value) {
|
|
778
|
+
if (value !== null && typeof value === 'object' && typeof value.get === 'function') {
|
|
779
|
+
return value.get();
|
|
780
|
+
}
|
|
781
|
+
return value;
|
|
782
|
+
}
|
|
783
|
+
/** Whether two normalized option sets describe the same behavior. */
|
|
784
|
+
function sameOptions(a, b) {
|
|
785
|
+
return a.minDepth === b.minDepth
|
|
786
|
+
&& a.maxDepth === b.maxDepth
|
|
787
|
+
&& a.watch === b.watch
|
|
788
|
+
&& a.debounceMs === b.debounceMs
|
|
789
|
+
&& a.pollIntervalMs === b.pollIntervalMs
|
|
790
|
+
&& a.includeProjectRoots === b.includeProjectRoots
|
|
791
|
+
&& a.includeUserRoots === b.includeUserRoots
|
|
792
|
+
&& a.followSymlinks === b.followSymlinks
|
|
793
|
+
&& sameList(a.extraRoots, b.extraRoots)
|
|
794
|
+
&& sameList(a.ignoreDirs, b.ignoreDirs);
|
|
795
|
+
}
|
|
796
|
+
/** Whether two string arrays are equal. */
|
|
797
|
+
function sameList(a, b) {
|
|
798
|
+
return a.length === b.length && a.every((value, index) => value === b[index]);
|
|
799
|
+
}
|
|
800
|
+
/**
|
|
801
|
+
* Validate a positive integer option.
|
|
802
|
+
* @param field - option name.
|
|
803
|
+
* @param value - raw value.
|
|
804
|
+
* @param minimum - inclusive minimum.
|
|
805
|
+
* @returns validated value.
|
|
806
|
+
*/
|
|
807
|
+
function positiveInteger(field, value, minimum) {
|
|
808
|
+
if (!Number.isInteger(value) || value < minimum) {
|
|
809
|
+
throw new TypeError(`utils-main: ${field} must be an integer >= ${minimum}`);
|
|
810
|
+
}
|
|
811
|
+
return value;
|
|
812
|
+
}
|
|
813
|
+
/**
|
|
814
|
+
* Validate a non-negative integer option.
|
|
815
|
+
* @param field - option name.
|
|
816
|
+
* @param value - raw value.
|
|
817
|
+
* @returns validated value.
|
|
818
|
+
*/
|
|
819
|
+
function nonNegativeInteger(field, value) {
|
|
820
|
+
if (!Number.isInteger(value) || value < 0) {
|
|
821
|
+
throw new TypeError(`utils-main: ${field} must be a non-negative integer`);
|
|
822
|
+
}
|
|
823
|
+
return value;
|
|
824
|
+
}
|
|
825
|
+
/**
|
|
826
|
+
* Validate a boolean option.
|
|
827
|
+
* @param field - option name.
|
|
828
|
+
* @param value - raw value.
|
|
829
|
+
* @returns validated value.
|
|
830
|
+
*/
|
|
831
|
+
function booleanOption(field, value) {
|
|
832
|
+
if (typeof value !== 'boolean')
|
|
833
|
+
throw new TypeError(`utils-main: ${field} must be a boolean`);
|
|
834
|
+
return value;
|
|
835
|
+
}
|
|
836
|
+
/**
|
|
837
|
+
* Validate a string-array option.
|
|
838
|
+
* @param field - option name.
|
|
839
|
+
* @param value - raw value.
|
|
840
|
+
* @returns validated array.
|
|
841
|
+
*/
|
|
842
|
+
function stringArray(field, value) {
|
|
843
|
+
if (!Array.isArray(value) || value.some((entry) => typeof entry !== 'string' || entry.length === 0)) {
|
|
844
|
+
throw new TypeError(`utils-main: ${field} must be an array of non-empty strings`);
|
|
845
|
+
}
|
|
846
|
+
return [...value];
|
|
847
|
+
}
|
|
848
|
+
/**
|
|
849
|
+
* Whether an fs error means the path is simply absent.
|
|
850
|
+
* @param error - thrown value.
|
|
851
|
+
* @returns whether it is ENOENT or ENOTDIR.
|
|
852
|
+
*/
|
|
853
|
+
function isAbsent(error) {
|
|
854
|
+
return typeof error === 'object' && error !== null && 'code' in error
|
|
855
|
+
&& (error.code === 'ENOENT' || error.code === 'ENOTDIR');
|
|
856
|
+
}
|
|
857
|
+
/**
|
|
858
|
+
* Render an error for logs.
|
|
859
|
+
* @param error - thrown value.
|
|
860
|
+
* @returns message text.
|
|
861
|
+
*/
|
|
862
|
+
function errorMessage(error) {
|
|
863
|
+
return error instanceof Error ? error.message : String(error);
|
|
864
|
+
}
|
|
865
|
+
//# sourceMappingURL=index.js.map
|