dsh-plugin-slim 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +95 -2
- package/client.js +524 -0
- package/cordis.patch.yml +6 -0
- package/icon.svg +8 -0
- package/lib/attribution.js +627 -0
- package/lib/checkup.js +338 -0
- package/lib/footprint.js +134 -0
- package/lib/host.js +846 -0
- package/lib/http.js +231 -0
- package/lib/index.js +153 -0
- package/lib/patch.js +797 -0
- package/lib/routes.js +493 -0
- package/lib/usage.js +116 -0
- package/package.json +73 -4
|
@@ -0,0 +1,627 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Static tool-owner attribution for installed plugins (read-only, zero execution).
|
|
3
|
+
*
|
|
4
|
+
* The host tools service exposes only model-facing fields (name/description/
|
|
5
|
+
* parameters), never the registering plugin, so this module reads the installed
|
|
6
|
+
* package sources under <profilePath>/node_modules and looks for a literal
|
|
7
|
+
* occurrence of each registered tool name inside .js/.mjs/.cjs files.
|
|
8
|
+
*
|
|
9
|
+
* Safety contract:
|
|
10
|
+
* - read-only: it never writes, never executes scanned code and never imports a
|
|
11
|
+
* scanned package;
|
|
12
|
+
* - the package root may be a symlink (pnpm layout) and is followed on purpose;
|
|
13
|
+
* nested node_modules, test/tests/tests__/fixtures directories, *.test.* /
|
|
14
|
+
* *.spec.* files and symlinked entries inside a package are skipped;
|
|
15
|
+
* - every plugin scan is bounded to 200 source files, 1 MB of source text and
|
|
16
|
+
* 5000 walked directory entries; truncation is reported through stats/warnings;
|
|
17
|
+
* - an unreadable directory/file or an out-of-bounds plugin name degrades to a
|
|
18
|
+
* bounded, deduplicated warning instead of throwing.
|
|
19
|
+
*
|
|
20
|
+
* Output: one row per (tool, matching plugin) pair, so a tool registered by two
|
|
21
|
+
* plugins is reported under both without losing data. Input tool rows are kept
|
|
22
|
+
* whole (parameters, deferLoading and a preset owner are preserved). A preset
|
|
23
|
+
* owner that matches a plugin row is used directly, without a disk scan.
|
|
24
|
+
*
|
|
25
|
+
* @module dsh-plugin-slim/attribution
|
|
26
|
+
*/
|
|
27
|
+
import { readFile as fsReadFile, readdir as fsReaddir, stat as fsStat } from 'node:fs/promises'
|
|
28
|
+
import { extname, join } from 'node:path'
|
|
29
|
+
|
|
30
|
+
/** Per-plugin scan caps (handoff spec 4.1.1). */
|
|
31
|
+
const MAX_SCAN_FILES = 200
|
|
32
|
+
const MAX_SCAN_BYTES = 1024 * 1024
|
|
33
|
+
const MAX_WALK_ENTRIES = 5000
|
|
34
|
+
|
|
35
|
+
/** Only these source extensions are inspected. */
|
|
36
|
+
const SOURCE_EXTENSIONS = new Set(['.js', '.mjs', '.cjs'])
|
|
37
|
+
const NESTED_MODULES = 'node_modules'
|
|
38
|
+
|
|
39
|
+
/** Directories whose content is test data, not runtime registration. */
|
|
40
|
+
const TEST_DIRECTORIES = new Set(['test', 'tests', '__tests__', 'fixtures'])
|
|
41
|
+
const TEST_FILE_PATTERN = /\.(?:test|spec)\./i
|
|
42
|
+
|
|
43
|
+
/** Warning bounds: never grow without limit. */
|
|
44
|
+
const MAX_WARNINGS = 20
|
|
45
|
+
const MAX_WARNING_CHARS = 500
|
|
46
|
+
|
|
47
|
+
/** Default readers; tests may inject a subset through { io }. */
|
|
48
|
+
const DEFAULT_IO = Object.freeze({ readFile: fsReadFile, readdir: fsReaddir, stat: fsStat })
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* @typedef {object} ToolRecord
|
|
52
|
+
* @property {string} name
|
|
53
|
+
* @property {string} description
|
|
54
|
+
* @property {unknown} [parameters]
|
|
55
|
+
* @property {boolean} [deferLoading]
|
|
56
|
+
* @property {string} [owner]
|
|
57
|
+
*/
|
|
58
|
+
|
|
59
|
+
/** @param {unknown} value @returns {value is Record<string, unknown>} */
|
|
60
|
+
function isRecord(value) {
|
|
61
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** @param {unknown} value @returns {string} */
|
|
65
|
+
function textOf(value) {
|
|
66
|
+
return typeof value === 'string' ? value.trim() : ''
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Bound one warning to a single readable line. @param {string} message */
|
|
70
|
+
function boundWarning(message) {
|
|
71
|
+
const text = String(message ?? '')
|
|
72
|
+
return text.length <= MAX_WARNING_CHARS ? text : text.slice(0, MAX_WARNING_CHARS - 1) + '…'
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* De-duplicate and bound warnings while keeping first-seen order.
|
|
77
|
+
* @param {string[]} messages
|
|
78
|
+
* @returns {string[]}
|
|
79
|
+
*/
|
|
80
|
+
function finalizeWarnings(messages) {
|
|
81
|
+
const seen = new Set()
|
|
82
|
+
const out = []
|
|
83
|
+
for (const message of messages) {
|
|
84
|
+
if (typeof message !== 'string' || message === '') continue
|
|
85
|
+
const bounded = boundWarning(message)
|
|
86
|
+
if (seen.has(bounded)) continue
|
|
87
|
+
seen.add(bounded)
|
|
88
|
+
out.push(bounded)
|
|
89
|
+
if (out.length >= MAX_WARNINGS) break
|
|
90
|
+
}
|
|
91
|
+
return out
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Split an installed package name into safe node_modules path segments.
|
|
96
|
+
* Refuses traversal, absolute paths, backslashes and over-long names.
|
|
97
|
+
* A scoped package is exactly two segments and the first starts with @.
|
|
98
|
+
* @param {unknown} name
|
|
99
|
+
* @returns {string[] | null}
|
|
100
|
+
*/
|
|
101
|
+
export function packageSegments(name) {
|
|
102
|
+
if (typeof name !== 'string' || name.trim() === '') return null
|
|
103
|
+
const text = name.trim()
|
|
104
|
+
if (text.includes('\\') || text.startsWith('/') || text.includes('..')) return null
|
|
105
|
+
const parts = text.split('/')
|
|
106
|
+
if (parts.length > 2) return null
|
|
107
|
+
for (let index = 0; index < parts.length; index += 1) {
|
|
108
|
+
const part = parts[index]
|
|
109
|
+
if (index === 0 && parts.length === 2) {
|
|
110
|
+
if (!/^@[A-Za-z0-9][A-Za-z0-9._-]*$/.test(part)) return null
|
|
111
|
+
continue
|
|
112
|
+
}
|
|
113
|
+
if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(part)) return null
|
|
114
|
+
}
|
|
115
|
+
return parts
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** Fixed-point passes when tracing same-file registration wrapper aliases. */
|
|
119
|
+
const ALIAS_MAX_PASSES = 6
|
|
120
|
+
|
|
121
|
+
/** How far before a quoted literal its name: key / anchor call may sit. */
|
|
122
|
+
const ANCHOR_WINDOW = 240
|
|
123
|
+
|
|
124
|
+
/** How far around a name literal its tool-definition signal may sit. */
|
|
125
|
+
const SIGNAL_WINDOW = 400
|
|
126
|
+
|
|
127
|
+
/** How far into a candidate wrapper body an anchor call is looked for. */
|
|
128
|
+
const ALIAS_BODY_WINDOW = 600
|
|
129
|
+
|
|
130
|
+
/** Registration primitives; aliases of these are traced per source file. */
|
|
131
|
+
const ANCHOR_CALLEES = new Set(['defineTool', 'registerTool', 'register'])
|
|
132
|
+
|
|
133
|
+
/** A quoted tool-name literal as the value of a name: key. */
|
|
134
|
+
const NAME_KEY_SUFFIX = new RegExp('(?:^|[^A-Za-z0-9_$])name[ \\t]*:[ \\t]*$')
|
|
135
|
+
|
|
136
|
+
/** Tool-definition keys that prove a name: literal is a tool definition. */
|
|
137
|
+
const TOOL_DEFINITION_SIGNAL = new RegExp('\\b(?:description|execute|parameters|output|isConcurrencySafe)[ \\t]*[:(]')
|
|
138
|
+
|
|
139
|
+
/** Arrow/function definitions whose body may wrap a registration call. */
|
|
140
|
+
const ARROW_DEFINITION_PATTERN = new RegExp(
|
|
141
|
+
'(?:const|let|var)[ \\t]+([A-Za-z_$][\\w$]*)[ \\t]*=[ \\t]*(?:async[ \\t]+)?(?:\\([^()]*\\)|[A-Za-z_$][\\w$]*)[ \\t]*=>',
|
|
142
|
+
'g',
|
|
143
|
+
)
|
|
144
|
+
const FUNCTION_DEFINITION_PATTERN = new RegExp('function[ \\t]+([A-Za-z_$][\\w$]*)[ \\t]*\\([^()]*\\)[ \\t]*\\{', 'g')
|
|
145
|
+
|
|
146
|
+
/** Direct alias assignment: const reg = tools.register / defineTool. */
|
|
147
|
+
const ALIAS_ASSIGNMENT_PATTERN = new RegExp(
|
|
148
|
+
'(?:const|let|var)[ \\t]+([A-Za-z_$][\\w$]*)[ \\t]*=[ \\t]*(?:[A-Za-z_$][\\w$]*\\.)?(?:defineTool|registerTool|register)\\b',
|
|
149
|
+
'g',
|
|
150
|
+
)
|
|
151
|
+
|
|
152
|
+
/** One call expression's dotted callee. */
|
|
153
|
+
const CALL_PATTERN = new RegExp('([A-Za-z_$][\\w$]*(?:\\.[A-Za-z_$][\\w$]*)*)[ \\t]*\\(', 'g')
|
|
154
|
+
|
|
155
|
+
/** Characters that can appear in a dotted callee (peeled backwards). */
|
|
156
|
+
const CALLEE_CHARS = new Set('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_$.')
|
|
157
|
+
|
|
158
|
+
/** Characters treated as whitespace while peeling a call expression. */
|
|
159
|
+
const WHITESPACE_CHARS = new Set([' ', '\t', '\n', '\r'])
|
|
160
|
+
|
|
161
|
+
/** Trim trailing ASCII whitespace. @param {string} text */
|
|
162
|
+
function trimEndWhitespace(text) {
|
|
163
|
+
let index = text.length - 1
|
|
164
|
+
while (index >= 0 && WHITESPACE_CHARS.has(text[index])) index -= 1
|
|
165
|
+
return text.slice(0, index + 1)
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* Whether a dotted callee is a registration anchor: a primitive bare call
|
|
170
|
+
* (defineTool / registerTool / register / a traced wrapper alias), or the
|
|
171
|
+
* tools.register method.
|
|
172
|
+
* @param {string[]} tokens @param {Set<string>} aliases
|
|
173
|
+
*/
|
|
174
|
+
function isAnchorCallee(tokens, aliases) {
|
|
175
|
+
if (tokens.length === 0) return false
|
|
176
|
+
const last = tokens[tokens.length - 1]
|
|
177
|
+
if (tokens.length === 1) return aliases.has(last)
|
|
178
|
+
return last === 'register' && tokens[tokens.length - 2] === 'tools'
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/**
|
|
182
|
+
* Peel one call expression from the end of text (a dotted callee followed by an
|
|
183
|
+
* opening parenthesis) and say whether it is an anchor call.
|
|
184
|
+
*/
|
|
185
|
+
function peelAnchorCall(text, aliases) {
|
|
186
|
+
let rest = trimEndWhitespace(text)
|
|
187
|
+
if (!rest.endsWith('(')) return false
|
|
188
|
+
rest = trimEndWhitespace(rest.slice(0, -1))
|
|
189
|
+
let index = rest.length - 1
|
|
190
|
+
while (index >= 0 && CALLEE_CHARS.has(rest[index])) index -= 1
|
|
191
|
+
const callee = rest.slice(index + 1)
|
|
192
|
+
if (callee === '') return false
|
|
193
|
+
return isAnchorCallee(callee.split('.'), aliases)
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/**
|
|
197
|
+
* Whether text before a name: key shows a tool definition object passed
|
|
198
|
+
* directly to a registration call: reg({...}) / tools.register(defineTool({...})).
|
|
199
|
+
*/
|
|
200
|
+
function objectArgumentHasRegistration(tail, aliases) {
|
|
201
|
+
const trimmed = trimEndWhitespace(tail)
|
|
202
|
+
const nameKey = NAME_KEY_SUFFIX.exec(trimmed)
|
|
203
|
+
if (nameKey === null) return false
|
|
204
|
+
const prefix = trimEndWhitespace(trimmed.slice(0, nameKey.index))
|
|
205
|
+
if (!prefix.endsWith('{')) return false
|
|
206
|
+
return peelAnchorCall(prefix.slice(0, -1), aliases)
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/** Whether a text window contains a call to a known anchor. */
|
|
210
|
+
function bodyHasAnchorCall(body, aliases) {
|
|
211
|
+
CALL_PATTERN.lastIndex = 0
|
|
212
|
+
let match
|
|
213
|
+
while ((match = CALL_PATTERN.exec(body)) !== null) {
|
|
214
|
+
if (isAnchorCallee(match[1].split('.'), aliases)) return true
|
|
215
|
+
}
|
|
216
|
+
return false
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/**
|
|
220
|
+
* Call names a file treats as registration calls: the primitives, direct
|
|
221
|
+
* assignments (const reg = tools.register) and local wrapper functions/arrows
|
|
222
|
+
* whose body calls a primitive or another alias.
|
|
223
|
+
*/
|
|
224
|
+
function registrationAnchorNames(text) {
|
|
225
|
+
const aliases = new Set(ANCHOR_CALLEES)
|
|
226
|
+
ALIAS_ASSIGNMENT_PATTERN.lastIndex = 0
|
|
227
|
+
let match
|
|
228
|
+
while ((match = ALIAS_ASSIGNMENT_PATTERN.exec(text)) !== null) aliases.add(match[1])
|
|
229
|
+
const definitions = []
|
|
230
|
+
ARROW_DEFINITION_PATTERN.lastIndex = 0
|
|
231
|
+
while ((match = ARROW_DEFINITION_PATTERN.exec(text)) !== null) {
|
|
232
|
+
definitions.push({ name: match[1], bodyStart: match.index + match[0].length })
|
|
233
|
+
}
|
|
234
|
+
FUNCTION_DEFINITION_PATTERN.lastIndex = 0
|
|
235
|
+
while ((match = FUNCTION_DEFINITION_PATTERN.exec(text)) !== null) {
|
|
236
|
+
definitions.push({ name: match[1], bodyStart: match.index + match[0].length })
|
|
237
|
+
}
|
|
238
|
+
for (let pass = 0; pass < ALIAS_MAX_PASSES; pass += 1) {
|
|
239
|
+
let added = false
|
|
240
|
+
for (const definition of definitions) {
|
|
241
|
+
if (aliases.has(definition.name)) continue
|
|
242
|
+
const body = text.slice(definition.bodyStart, definition.bodyStart + ALIAS_BODY_WINDOW)
|
|
243
|
+
if (!bodyHasAnchorCall(body, aliases)) continue
|
|
244
|
+
aliases.add(definition.name)
|
|
245
|
+
added = true
|
|
246
|
+
}
|
|
247
|
+
if (!added) break
|
|
248
|
+
}
|
|
249
|
+
return aliases
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/** Whether a registration anchor sits near one literal (name-not-first fallback). */
|
|
253
|
+
function hasAnchorNear(text, index, aliases) {
|
|
254
|
+
const start = Math.max(0, index - ANCHOR_WINDOW)
|
|
255
|
+
const window = text.slice(start, Math.min(text.length, index + SIGNAL_WINDOW))
|
|
256
|
+
return bodyHasAnchorCall(window, aliases)
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
/** Whether tool-definition keys sit near one name literal. */
|
|
260
|
+
function hasDefinitionSignal(text, index) {
|
|
261
|
+
const start = Math.max(0, index - SIGNAL_WINDOW)
|
|
262
|
+
return TOOL_DEFINITION_SIGNAL.test(text.slice(start, index + SIGNAL_WINDOW))
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
/**
|
|
266
|
+
* Remove // and /*-*\/ comments while keeping filesystem length and string
|
|
267
|
+
* literals intact, so prose in a comment can never look like a registration.
|
|
268
|
+
* @param {string} text
|
|
269
|
+
* @returns {string}
|
|
270
|
+
*/
|
|
271
|
+
function stripComments(text) {
|
|
272
|
+
let out = ''
|
|
273
|
+
let mode = 'code'
|
|
274
|
+
for (let index = 0; index < text.length; index += 1) {
|
|
275
|
+
const char = text[index]
|
|
276
|
+
const next = index + 1 < text.length ? text[index + 1] : ''
|
|
277
|
+
if (mode === 'code') {
|
|
278
|
+
if (char === '/' && next === '/') {
|
|
279
|
+
mode = 'line'
|
|
280
|
+
out += ' '
|
|
281
|
+
index += 1
|
|
282
|
+
continue
|
|
283
|
+
}
|
|
284
|
+
if (char === '/' && next === '*') {
|
|
285
|
+
mode = 'block'
|
|
286
|
+
out += ' '
|
|
287
|
+
index += 1
|
|
288
|
+
continue
|
|
289
|
+
}
|
|
290
|
+
if (char === "'") mode = 'single'
|
|
291
|
+
else if (char === '"') mode = 'double'
|
|
292
|
+
else if (char === '`') mode = 'template'
|
|
293
|
+
out += char
|
|
294
|
+
continue
|
|
295
|
+
}
|
|
296
|
+
if (mode === 'line') {
|
|
297
|
+
if (char === '\n') {
|
|
298
|
+
mode = 'code'
|
|
299
|
+
out += '\n'
|
|
300
|
+
} else {
|
|
301
|
+
out += ' '
|
|
302
|
+
}
|
|
303
|
+
continue
|
|
304
|
+
}
|
|
305
|
+
if (mode === 'block') {
|
|
306
|
+
if (char === '*' && next === '/') {
|
|
307
|
+
mode = 'code'
|
|
308
|
+
out += ' '
|
|
309
|
+
index += 1
|
|
310
|
+
continue
|
|
311
|
+
}
|
|
312
|
+
out += char === '\n' ? '\n' : ' '
|
|
313
|
+
continue
|
|
314
|
+
}
|
|
315
|
+
// Inside a string/template: keep content, honour escapes, close on the quote.
|
|
316
|
+
out += char
|
|
317
|
+
if (char === '\\') {
|
|
318
|
+
if (next !== '') {
|
|
319
|
+
out += next
|
|
320
|
+
index += 1
|
|
321
|
+
}
|
|
322
|
+
continue
|
|
323
|
+
}
|
|
324
|
+
if ((mode === 'single' && char === "'") || (mode === 'double' && char === '"') || (mode === 'template' && char === '`')) {
|
|
325
|
+
mode = 'code'
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
return out
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
/** Per-file registration matching context (comments stripped, aliases known). */
|
|
332
|
+
function registrationContext(source) {
|
|
333
|
+
const text = stripComments(source)
|
|
334
|
+
return { text, aliases: registrationAnchorNames(text) }
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
/**
|
|
338
|
+
* Whether one source file registers the given tool name: a complete quoted
|
|
339
|
+
* literal is required (prose cannot match), and it must be the value of a
|
|
340
|
+
* name: key inside a registration call / near a registration anchor, or the
|
|
341
|
+
* direct argument of a registration call. A plain fetch()/const read = 1 is
|
|
342
|
+
* never evidence.
|
|
343
|
+
* @param {{ text: string, aliases: Set<string> }} context @param {string} name
|
|
344
|
+
* @returns {boolean}
|
|
345
|
+
*/
|
|
346
|
+
function hasRegisteredToolName(context, name) {
|
|
347
|
+
if (name === '') return false
|
|
348
|
+
const { text, aliases } = context
|
|
349
|
+
for (const quote of ["'", '"', '`']) {
|
|
350
|
+
const needle = quote + name + quote
|
|
351
|
+
let from = 0
|
|
352
|
+
for (;;) {
|
|
353
|
+
const index = text.indexOf(needle, from)
|
|
354
|
+
if (index < 0) break
|
|
355
|
+
from = index + 1
|
|
356
|
+
const before = text.slice(Math.max(0, index - ANCHOR_WINDOW), index)
|
|
357
|
+
if (NAME_KEY_SUFFIX.test(before)) {
|
|
358
|
+
if (objectArgumentHasRegistration(before, aliases)) return true
|
|
359
|
+
if (hasDefinitionSignal(text, index) && hasAnchorNear(text, index, aliases)) return true
|
|
360
|
+
continue
|
|
361
|
+
}
|
|
362
|
+
if (peelAnchorCall(before, aliases)) return true
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
return false
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
/**
|
|
369
|
+
* Normalize host tool rows while preserving every model-facing field the
|
|
370
|
+
* footprint estimator and the report need.
|
|
371
|
+
* @param {unknown} tools @param {string[]} warnings
|
|
372
|
+
* @returns {ToolRecord[]}
|
|
373
|
+
*/
|
|
374
|
+
function normalizeTools(tools, warnings) {
|
|
375
|
+
const rows = []
|
|
376
|
+
if (tools === undefined || tools === null) return rows
|
|
377
|
+
if (!Array.isArray(tools)) {
|
|
378
|
+
warnings.push('tools 不是数组:按空工具清单处理')
|
|
379
|
+
return rows
|
|
380
|
+
}
|
|
381
|
+
let invalid = 0
|
|
382
|
+
for (const row of tools) {
|
|
383
|
+
if (!isRecord(row) || textOf(row.name) === '') {
|
|
384
|
+
invalid += 1
|
|
385
|
+
continue
|
|
386
|
+
}
|
|
387
|
+
rows.push({ ...row })
|
|
388
|
+
}
|
|
389
|
+
if (invalid > 0) warnings.push('忽略 ' + invalid + ' 条无效工具行(缺少 name)')
|
|
390
|
+
return rows
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
/**
|
|
394
|
+
* Normalize plugin rows to one scannable descriptor per entry.
|
|
395
|
+
* @param {unknown} plugins @param {string[]} warnings
|
|
396
|
+
* @returns {{ key: string, name: string, segments: string[] | null }[]}
|
|
397
|
+
*/
|
|
398
|
+
function normalizePlugins(plugins, warnings) {
|
|
399
|
+
const out = []
|
|
400
|
+
if (plugins === undefined || plugins === null) return out
|
|
401
|
+
if (!Array.isArray(plugins)) {
|
|
402
|
+
warnings.push('plugins 不是数组:按空插件清单处理')
|
|
403
|
+
return out
|
|
404
|
+
}
|
|
405
|
+
const seen = new Set()
|
|
406
|
+
for (const row of plugins) {
|
|
407
|
+
if (!isRecord(row)) continue
|
|
408
|
+
const name = textOf(row.name)
|
|
409
|
+
const entryId = textOf(row.entryId) || textOf(row.id) || name
|
|
410
|
+
if (name === '' && entryId === '') continue
|
|
411
|
+
const key = entryId === '' ? name : entryId
|
|
412
|
+
if (seen.has(key)) continue
|
|
413
|
+
seen.add(key)
|
|
414
|
+
const segments = packageSegments(name === '' ? key : name)
|
|
415
|
+
if (segments === null) {
|
|
416
|
+
warnings.push('跳过无法安全定位安装目录的插件名:' + boundWarning(key).slice(0, 80))
|
|
417
|
+
continue
|
|
418
|
+
}
|
|
419
|
+
out.push({ key, name: name === '' ? key : name, segments })
|
|
420
|
+
}
|
|
421
|
+
return out
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
/** Read one file as UTF-8 text regardless of reader return type. */
|
|
425
|
+
async function readText(io, file) {
|
|
426
|
+
const raw = await io.readFile(file, 'utf8')
|
|
427
|
+
if (typeof raw === 'string') return raw
|
|
428
|
+
if (Buffer.isBuffer(raw)) return raw.toString('utf8')
|
|
429
|
+
return String(raw)
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
/** Read one file's byte size through the injected stat. */
|
|
433
|
+
async function fileSize(io, file) {
|
|
434
|
+
const info = await io.stat(file)
|
|
435
|
+
if (!isRecord(info) || typeof info.size !== 'number' || !Number.isFinite(info.size) || info.size < 0) {
|
|
436
|
+
throw new Error('无法读取文件大小')
|
|
437
|
+
}
|
|
438
|
+
return info.size
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
/**
|
|
442
|
+
* Breadth-first walk of one package root collecting candidate source files.
|
|
443
|
+
* Test/fixture directories and files are skipped, nested node_modules is never
|
|
444
|
+
* entered and symlinked entries are never followed. Stops after maxFiles+1
|
|
445
|
+
* candidates so a truncated scan is distinguishable from an exact-cap scan.
|
|
446
|
+
* @param {string} root @param {{ readdir: Function }} io @param {number} maxFiles
|
|
447
|
+
* @returns {Promise<{ files: string[], fileLimitHit: boolean, walkLimited: boolean, unreadableDirs: string[] }>}
|
|
448
|
+
*/
|
|
449
|
+
async function collectSourceFiles(root, io, maxFiles) {
|
|
450
|
+
/** @type {string[]} */
|
|
451
|
+
const files = []
|
|
452
|
+
/** @type {string[]} */
|
|
453
|
+
const queue = ['']
|
|
454
|
+
/** @type {string[]} */
|
|
455
|
+
const unreadableDirs = []
|
|
456
|
+
let entriesSeen = 0
|
|
457
|
+
let fileLimitHit = false
|
|
458
|
+
let walkLimited = false
|
|
459
|
+
for (let cursor = 0; cursor < queue.length; cursor += 1) {
|
|
460
|
+
const relativeDir = queue[cursor]
|
|
461
|
+
const absoluteDir = relativeDir === '' ? root : join(root, ...relativeDir.split('/'))
|
|
462
|
+
let entries
|
|
463
|
+
try {
|
|
464
|
+
entries = await io.readdir(absoluteDir, { withFileTypes: true })
|
|
465
|
+
} catch {
|
|
466
|
+
if (relativeDir !== '') unreadableDirs.push(relativeDir)
|
|
467
|
+
continue
|
|
468
|
+
}
|
|
469
|
+
entries.sort((left, right) => (left.name < right.name ? -1 : left.name > right.name ? 1 : 0))
|
|
470
|
+
for (const entry of entries) {
|
|
471
|
+
entriesSeen += 1
|
|
472
|
+
if (entriesSeen > MAX_WALK_ENTRIES) {
|
|
473
|
+
walkLimited = true
|
|
474
|
+
break
|
|
475
|
+
}
|
|
476
|
+
if (typeof entry?.isSymbolicLink === 'function' && entry.isSymbolicLink()) continue
|
|
477
|
+
const childRelative = relativeDir === '' ? entry.name : relativeDir + '/' + entry.name
|
|
478
|
+
if (typeof entry?.isDirectory === 'function' && entry.isDirectory()) {
|
|
479
|
+
const dirName = String(entry.name).toLowerCase()
|
|
480
|
+
if (dirName === NESTED_MODULES || TEST_DIRECTORIES.has(dirName)) continue
|
|
481
|
+
queue.push(childRelative)
|
|
482
|
+
continue
|
|
483
|
+
}
|
|
484
|
+
if (typeof entry?.isFile !== 'function' || !entry.isFile()) continue
|
|
485
|
+
if (TEST_FILE_PATTERN.test(entry.name)) continue
|
|
486
|
+
if (!SOURCE_EXTENSIONS.has(extname(entry.name).toLowerCase())) continue
|
|
487
|
+
files.push(childRelative)
|
|
488
|
+
if (files.length > maxFiles) {
|
|
489
|
+
files.pop()
|
|
490
|
+
fileLimitHit = true
|
|
491
|
+
break
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
if (walkLimited || fileLimitHit) break
|
|
495
|
+
}
|
|
496
|
+
return { files, fileLimitHit, walkLimited, unreadableDirs }
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
/**
|
|
500
|
+
* Attribute registered tools to installed plugins through a bounded static scan.
|
|
501
|
+
*
|
|
502
|
+
* @param {{
|
|
503
|
+
* tools?: unknown,
|
|
504
|
+
* plugins?: unknown,
|
|
505
|
+
* profilePath?: string,
|
|
506
|
+
* io?: { readFile?: Function, readdir?: Function, stat?: Function },
|
|
507
|
+
* }} [input]
|
|
508
|
+
* @returns {Promise<{
|
|
509
|
+
* tools: ToolRecord[],
|
|
510
|
+
* byTool: Map<string, string[]>,
|
|
511
|
+
* byPlugin: Map<string, ToolRecord[]>,
|
|
512
|
+
* unattributed: ToolRecord[],
|
|
513
|
+
* warnings: string[],
|
|
514
|
+
* stats: { pluginsScanned: number, filesRead: number, bytesRead: number, truncatedPlugins: number },
|
|
515
|
+
* }>}
|
|
516
|
+
*/
|
|
517
|
+
export async function attributeTools(input = {}) {
|
|
518
|
+
const options = isRecord(input) ? input : {}
|
|
519
|
+
const io = { ...DEFAULT_IO, ...(isRecord(options.io) ? options.io : {}) }
|
|
520
|
+
/** @type {string[]} */
|
|
521
|
+
const warnings = []
|
|
522
|
+
const tools = normalizeTools(options.tools, warnings)
|
|
523
|
+
const plugins = normalizePlugins(options.plugins, warnings)
|
|
524
|
+
const profilePath = typeof options.profilePath === 'string' ? options.profilePath : ''
|
|
525
|
+
|
|
526
|
+
/** @type {Map<string, string[]>} */
|
|
527
|
+
const byTool = new Map()
|
|
528
|
+
/** @type {Map<string, ToolRecord[]>} */
|
|
529
|
+
const byPlugin = new Map()
|
|
530
|
+
const stats = { pluginsScanned: 0, filesRead: 0, bytesRead: 0, truncatedPlugins: 0 }
|
|
531
|
+
|
|
532
|
+
const pluginByName = new Map()
|
|
533
|
+
for (const plugin of plugins) {
|
|
534
|
+
byPlugin.set(plugin.key, [])
|
|
535
|
+
pluginByName.set(plugin.key, plugin)
|
|
536
|
+
pluginByName.set(plugin.name, plugin)
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
/** Record one attribution, keeping tool rows whole (parameters/deferLoading/owner). */
|
|
540
|
+
const attribute = (tool, plugin) => {
|
|
541
|
+
const bucket = byPlugin.get(plugin.key)
|
|
542
|
+
if (bucket === undefined) return
|
|
543
|
+
if (bucket.some((row) => row.name === tool.name)) return
|
|
544
|
+
bucket.push({ ...tool })
|
|
545
|
+
const owners = byTool.get(tool.name)
|
|
546
|
+
if (owners === undefined) byTool.set(tool.name, [plugin.key])
|
|
547
|
+
else if (!owners.includes(plugin.key)) owners.push(plugin.key)
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
/** Preset owner (host-provided) wins over the static scan when it resolves. */
|
|
551
|
+
const unresolved = []
|
|
552
|
+
for (const tool of tools) {
|
|
553
|
+
const owner = textOf(tool.owner)
|
|
554
|
+
if (owner === '') {
|
|
555
|
+
unresolved.push(tool)
|
|
556
|
+
continue
|
|
557
|
+
}
|
|
558
|
+
const plugin = pluginByName.get(owner)
|
|
559
|
+
if (plugin === undefined) {
|
|
560
|
+
unresolved.push(tool)
|
|
561
|
+
continue
|
|
562
|
+
}
|
|
563
|
+
attribute(tool, plugin)
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
if (profilePath !== '' && unresolved.length > 0) {
|
|
567
|
+
for (const plugin of plugins) {
|
|
568
|
+
const packageDir = join(profilePath, 'node_modules', ...plugin.segments)
|
|
569
|
+
let rootExists = false
|
|
570
|
+
try {
|
|
571
|
+
await io.stat(packageDir)
|
|
572
|
+
rootExists = true
|
|
573
|
+
} catch {
|
|
574
|
+
// Not installed under this profile: a patch-only row has no scan target.
|
|
575
|
+
}
|
|
576
|
+
if (!rootExists) continue
|
|
577
|
+
stats.pluginsScanned += 1
|
|
578
|
+
let walk
|
|
579
|
+
try {
|
|
580
|
+
walk = await collectSourceFiles(packageDir, io, MAX_SCAN_FILES)
|
|
581
|
+
} catch (error) {
|
|
582
|
+
warnings.push('扫描插件 ' + plugin.name + ' 失败:' + String(error?.message ?? error))
|
|
583
|
+
continue
|
|
584
|
+
}
|
|
585
|
+
if (walk.fileLimitHit || walk.walkLimited) stats.truncatedPlugins += 1
|
|
586
|
+
if (walk.fileLimitHit) warnings.push('插件 ' + plugin.name + ' 源文件超过 ' + MAX_SCAN_FILES + ' 个,仅扫描前 ' + MAX_SCAN_FILES + ' 个')
|
|
587
|
+
if (walk.walkLimited) warnings.push('插件 ' + plugin.name + ' 目录项超过 ' + MAX_WALK_ENTRIES + ' 个,扫描已截断')
|
|
588
|
+
if (walk.unreadableDirs.length > 0) warnings.push('插件 ' + plugin.name + ' 有 ' + walk.unreadableDirs.length + ' 个子目录不可读,已跳过')
|
|
589
|
+
let bytesRead = 0
|
|
590
|
+
let byteLimited = false
|
|
591
|
+
for (const relativeFile of walk.files) {
|
|
592
|
+
const absoluteFile = join(packageDir, ...relativeFile.split('/'))
|
|
593
|
+
let size = 0
|
|
594
|
+
try {
|
|
595
|
+
size = await fileSize(io, absoluteFile)
|
|
596
|
+
} catch {
|
|
597
|
+
continue
|
|
598
|
+
}
|
|
599
|
+
if (bytesRead + size > MAX_SCAN_BYTES) {
|
|
600
|
+
byteLimited = true
|
|
601
|
+
break
|
|
602
|
+
}
|
|
603
|
+
let text
|
|
604
|
+
try {
|
|
605
|
+
text = await readText(io, absoluteFile)
|
|
606
|
+
} catch (error) {
|
|
607
|
+
warnings.push('读取 ' + plugin.name + '/' + relativeFile + ' 失败:' + String(error?.message ?? error))
|
|
608
|
+
continue
|
|
609
|
+
}
|
|
610
|
+
bytesRead += size
|
|
611
|
+
stats.filesRead += 1
|
|
612
|
+
const context = registrationContext(text)
|
|
613
|
+
for (const tool of unresolved) {
|
|
614
|
+
if (hasRegisteredToolName(context, tool.name)) attribute(tool, plugin)
|
|
615
|
+
}
|
|
616
|
+
}
|
|
617
|
+
stats.bytesRead += bytesRead
|
|
618
|
+
if (byteLimited) {
|
|
619
|
+
stats.truncatedPlugins += 1
|
|
620
|
+
warnings.push('插件 ' + plugin.name + ' 源码超过 1 MB,扫描已截断')
|
|
621
|
+
}
|
|
622
|
+
}
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
const unattributed = unresolved.filter((tool) => !byTool.has(tool.name))
|
|
626
|
+
return { tools, byTool, byPlugin, unattributed, warnings: finalizeWarnings(warnings), stats }
|
|
627
|
+
}
|