dsh-codegraph-visualizer 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/README.md +223 -0
- package/cordis.patch.yml +17 -0
- package/dist/client/index.css +2404 -0
- package/dist/client/index.esm.js +44283 -0
- package/dist/client/index.js +46706 -0
- package/dist/client-cjs/index.cjs +44283 -0
- package/dist/client-cjs/index.css +2404 -0
- package/dist/index.d.ts +40 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +2277 -0
- package/dist/index.js.map +1 -0
- package/package.json +96 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,2277 @@
|
|
|
1
|
+
import { defineTool } from "@deepseek-ai/dsh-tools";
|
|
2
|
+
import { createRequire } from "node:module";
|
|
3
|
+
import "@deepseek-ai/cordis";
|
|
4
|
+
import { existsSync, watch } from "node:fs";
|
|
5
|
+
import { isAbsolute, join, normalize } from "node:path";
|
|
6
|
+
import { spawnSync } from "node:child_process";
|
|
7
|
+
|
|
8
|
+
//#region node_modules/.pnpm/@deepseek-ai+cosmokit@1.8.2/node_modules/@deepseek-ai/cosmokit/lib/index.js
|
|
9
|
+
/** Return true when a value is `null` or `undefined`. */
|
|
10
|
+
function isNullable(value) {
|
|
11
|
+
return value === null || value === void 0;
|
|
12
|
+
}
|
|
13
|
+
/** Return true for non-array object values. */
|
|
14
|
+
function isPlainObject(data) {
|
|
15
|
+
return data && typeof data === "object" && !Array.isArray(data);
|
|
16
|
+
}
|
|
17
|
+
/** Filter object entries and return a new object. */
|
|
18
|
+
function filterKeys(object, filter) {
|
|
19
|
+
return Object.fromEntries(Object.entries(object).filter(([key, value]) => filter(key, value)));
|
|
20
|
+
}
|
|
21
|
+
/** Map object values while preserving the original key set. */
|
|
22
|
+
function mapValues(object, transform) {
|
|
23
|
+
return Object.fromEntries(Object.entries(object).map(([key, value]) => [key, transform(value, key)]));
|
|
24
|
+
}
|
|
25
|
+
/** Pick selected keys from an object, optionally including `undefined` values. */
|
|
26
|
+
function pick(source, keys, forced) {
|
|
27
|
+
if (!keys) return { ...source };
|
|
28
|
+
const result = {};
|
|
29
|
+
for (const key of keys) if (forced || source[key] !== void 0) result[key] = source[key];
|
|
30
|
+
return result;
|
|
31
|
+
}
|
|
32
|
+
/** Test values using `instanceof` with a `toStringTag` fallback. */
|
|
33
|
+
function is(type, value) {
|
|
34
|
+
if (arguments.length === 1) return (value$1) => is(type, value$1);
|
|
35
|
+
return type in globalThis && value instanceof globalThis[type] || Object.prototype.toString.call(value).slice(8, -1) === type;
|
|
36
|
+
}
|
|
37
|
+
function isArrayBufferLike(value) {
|
|
38
|
+
return is("ArrayBuffer", value) || is("SharedArrayBuffer", value);
|
|
39
|
+
}
|
|
40
|
+
function isArrayBufferSource(value) {
|
|
41
|
+
return isArrayBufferLike(value) || ArrayBuffer.isView(value);
|
|
42
|
+
}
|
|
43
|
+
/** Binary source detection and base64/hex conversion helpers. */
|
|
44
|
+
var Binary;
|
|
45
|
+
(function(Binary$1) {
|
|
46
|
+
Binary$1.is = isArrayBufferLike;
|
|
47
|
+
Binary$1.isSource = isArrayBufferSource;
|
|
48
|
+
function fromSource(source) {
|
|
49
|
+
if (ArrayBuffer.isView(source)) return source.buffer.slice(source.byteOffset, source.byteOffset + source.byteLength);
|
|
50
|
+
else return source;
|
|
51
|
+
}
|
|
52
|
+
Binary$1.fromSource = fromSource;
|
|
53
|
+
function toBase64(source) {
|
|
54
|
+
source = fromSource(source);
|
|
55
|
+
if (typeof Buffer !== "undefined") return Buffer.from(source).toString("base64");
|
|
56
|
+
let binary = "";
|
|
57
|
+
const bytes = new Uint8Array(source);
|
|
58
|
+
for (let i = 0; i < bytes.byteLength; i++) binary += String.fromCharCode(bytes[i]);
|
|
59
|
+
return btoa(binary);
|
|
60
|
+
}
|
|
61
|
+
Binary$1.toBase64 = toBase64;
|
|
62
|
+
function fromBase64(source) {
|
|
63
|
+
if (typeof Buffer !== "undefined") return fromSource(Buffer.from(source, "base64"));
|
|
64
|
+
return Uint8Array.from(atob(source), (c) => c.charCodeAt(0));
|
|
65
|
+
}
|
|
66
|
+
Binary$1.fromBase64 = fromBase64;
|
|
67
|
+
function toHex(source) {
|
|
68
|
+
source = fromSource(source);
|
|
69
|
+
if (typeof Buffer !== "undefined") return Buffer.from(source).toString("hex");
|
|
70
|
+
return Array.from(new Uint8Array(source), (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
71
|
+
}
|
|
72
|
+
Binary$1.toHex = toHex;
|
|
73
|
+
function fromHex(source) {
|
|
74
|
+
if (typeof Buffer !== "undefined") return fromSource(Buffer.from(source, "hex"));
|
|
75
|
+
const hex = source.length % 2 === 0 ? source : source.slice(0, source.length - 1);
|
|
76
|
+
const buffer = [];
|
|
77
|
+
for (let i = 0; i < hex.length; i += 2) buffer.push(parseInt(`${hex[i]}${hex[i + 1]}`, 16));
|
|
78
|
+
return Uint8Array.from(buffer).buffer;
|
|
79
|
+
}
|
|
80
|
+
Binary$1.fromHex = fromHex;
|
|
81
|
+
})(Binary || (Binary = {}));
|
|
82
|
+
/** Decode a base64 string into binary data. */
|
|
83
|
+
const base64ToArrayBuffer = Binary.fromBase64;
|
|
84
|
+
/** Encode binary data as base64. */
|
|
85
|
+
const arrayBufferToBase64 = Binary.toBase64;
|
|
86
|
+
/** Decode a hex string into binary data. */
|
|
87
|
+
const hexToArrayBuffer = Binary.fromHex;
|
|
88
|
+
/** Encode binary data as hex. */
|
|
89
|
+
const arrayBufferToHex = Binary.toHex;
|
|
90
|
+
/** Deep-clone common JavaScript values while preserving prototypes and cycles. */
|
|
91
|
+
function clone(source, refs = /* @__PURE__ */ new Map()) {
|
|
92
|
+
if (!source || typeof source !== "object") return source;
|
|
93
|
+
if (is("Date", source)) return new Date(source.valueOf());
|
|
94
|
+
if (is("RegExp", source)) return new RegExp(source.source, source.flags);
|
|
95
|
+
if (isArrayBufferLike(source)) return source.slice(0);
|
|
96
|
+
if (ArrayBuffer.isView(source)) return source.buffer.slice(source.byteOffset, source.byteOffset + source.byteLength);
|
|
97
|
+
const cached = refs.get(source);
|
|
98
|
+
if (cached) return cached;
|
|
99
|
+
if (Array.isArray(source)) {
|
|
100
|
+
const result$1 = [];
|
|
101
|
+
refs.set(source, result$1);
|
|
102
|
+
source.forEach((value, index) => {
|
|
103
|
+
result$1[index] = Reflect.apply(clone, null, [value, refs]);
|
|
104
|
+
});
|
|
105
|
+
return result$1;
|
|
106
|
+
}
|
|
107
|
+
const result = Object.create(Object.getPrototypeOf(source));
|
|
108
|
+
refs.set(source, result);
|
|
109
|
+
for (const key of Reflect.ownKeys(source)) {
|
|
110
|
+
const descriptor = { ...Reflect.getOwnPropertyDescriptor(source, key) };
|
|
111
|
+
if ("value" in descriptor) descriptor.value = Reflect.apply(clone, null, [descriptor.value, refs]);
|
|
112
|
+
Reflect.defineProperty(result, key, descriptor);
|
|
113
|
+
}
|
|
114
|
+
return result;
|
|
115
|
+
}
|
|
116
|
+
/** Deeply compare arrays, dates, regexps, buffers, and plain object fields. */
|
|
117
|
+
function deepEqual(a, b, strict) {
|
|
118
|
+
if (a === b) return true;
|
|
119
|
+
if (!strict && isNullable(a) && isNullable(b)) return true;
|
|
120
|
+
if (typeof a !== typeof b) return false;
|
|
121
|
+
if (typeof a !== "object") return false;
|
|
122
|
+
if (!a || !b) return false;
|
|
123
|
+
function check(test, then) {
|
|
124
|
+
return test(a) ? test(b) ? then(a, b) : false : test(b) ? false : void 0;
|
|
125
|
+
}
|
|
126
|
+
return check(Array.isArray, (a$1, b$1) => a$1.length === b$1.length && a$1.every((item, index) => deepEqual(item, b$1[index]))) ?? check(is("Date"), (a$1, b$1) => a$1.valueOf() === b$1.valueOf()) ?? check(is("RegExp"), (a$1, b$1) => a$1.source === b$1.source && a$1.flags === b$1.flags) ?? check(isArrayBufferLike, (a$1, b$1) => {
|
|
127
|
+
if (a$1.byteLength !== b$1.byteLength) return false;
|
|
128
|
+
const viewA = new Uint8Array(a$1);
|
|
129
|
+
const viewB = new Uint8Array(b$1);
|
|
130
|
+
for (let i = 0; i < viewA.length; i++) if (viewA[i] !== viewB[i]) return false;
|
|
131
|
+
return true;
|
|
132
|
+
}) ?? Object.keys({
|
|
133
|
+
...a,
|
|
134
|
+
...b
|
|
135
|
+
}).every((key) => deepEqual(a[key], b[key], strict));
|
|
136
|
+
}
|
|
137
|
+
/** Time constants plus parsing and formatting helpers. */
|
|
138
|
+
var Time;
|
|
139
|
+
(function(Time$1) {
|
|
140
|
+
Time$1.millisecond = 1;
|
|
141
|
+
Time$1.second = 1e3;
|
|
142
|
+
Time$1.minute = Time$1.second * 60;
|
|
143
|
+
Time$1.hour = Time$1.minute * 60;
|
|
144
|
+
Time$1.day = Time$1.hour * 24;
|
|
145
|
+
Time$1.week = Time$1.day * 7;
|
|
146
|
+
let timezoneOffset = (/* @__PURE__ */ new Date()).getTimezoneOffset();
|
|
147
|
+
function setTimezoneOffset(offset) {
|
|
148
|
+
timezoneOffset = offset;
|
|
149
|
+
}
|
|
150
|
+
Time$1.setTimezoneOffset = setTimezoneOffset;
|
|
151
|
+
function getTimezoneOffset() {
|
|
152
|
+
return timezoneOffset;
|
|
153
|
+
}
|
|
154
|
+
Time$1.getTimezoneOffset = getTimezoneOffset;
|
|
155
|
+
function getDateNumber(date = /* @__PURE__ */ new Date(), offset) {
|
|
156
|
+
if (typeof date === "number") date = new Date(date);
|
|
157
|
+
if (offset === void 0) offset = timezoneOffset;
|
|
158
|
+
return Math.floor((date.valueOf() / Time$1.minute - offset) / 1440);
|
|
159
|
+
}
|
|
160
|
+
Time$1.getDateNumber = getDateNumber;
|
|
161
|
+
function fromDateNumber(value, offset) {
|
|
162
|
+
const date = new Date(value * Time$1.day);
|
|
163
|
+
if (offset === void 0) offset = timezoneOffset;
|
|
164
|
+
return new Date(+date + offset * Time$1.minute);
|
|
165
|
+
}
|
|
166
|
+
Time$1.fromDateNumber = fromDateNumber;
|
|
167
|
+
const numeric = /\d+(?:\.\d+)?/.source;
|
|
168
|
+
const timeRegExp = new RegExp(`^${[
|
|
169
|
+
"w(?:eek(?:s)?)?",
|
|
170
|
+
"d(?:ay(?:s)?)?",
|
|
171
|
+
"h(?:our(?:s)?)?",
|
|
172
|
+
"m(?:in(?:ute)?(?:s)?)?",
|
|
173
|
+
"s(?:ec(?:ond)?(?:s)?)?"
|
|
174
|
+
].map((unit) => `(${numeric}${unit})?`).join("")}$`);
|
|
175
|
+
function parseTime(source) {
|
|
176
|
+
const capture = timeRegExp.exec(source);
|
|
177
|
+
if (!capture) return 0;
|
|
178
|
+
return (parseFloat(capture[1]) * Time$1.week || 0) + (parseFloat(capture[2]) * Time$1.day || 0) + (parseFloat(capture[3]) * Time$1.hour || 0) + (parseFloat(capture[4]) * Time$1.minute || 0) + (parseFloat(capture[5]) * Time$1.second || 0);
|
|
179
|
+
}
|
|
180
|
+
Time$1.parseTime = parseTime;
|
|
181
|
+
function parseDate(date) {
|
|
182
|
+
const parsed = parseTime(date);
|
|
183
|
+
if (parsed) date = Date.now() + parsed;
|
|
184
|
+
else if (/^\d{1,2}(:\d{1,2}){1,2}$/.test(date)) date = `${(/* @__PURE__ */ new Date()).toLocaleDateString()}-${date}`;
|
|
185
|
+
else if (/^\d{1,2}-\d{1,2}-\d{1,2}(:\d{1,2}){1,2}$/.test(date)) date = `${(/* @__PURE__ */ new Date()).getFullYear()}-${date}`;
|
|
186
|
+
return date ? new Date(date) : /* @__PURE__ */ new Date();
|
|
187
|
+
}
|
|
188
|
+
Time$1.parseDate = parseDate;
|
|
189
|
+
function format(ms) {
|
|
190
|
+
const abs = Math.abs(ms);
|
|
191
|
+
if (abs >= Time$1.day - Time$1.hour / 2) return Math.round(ms / Time$1.day) + "d";
|
|
192
|
+
else if (abs >= Time$1.hour - Time$1.minute / 2) return Math.round(ms / Time$1.hour) + "h";
|
|
193
|
+
else if (abs >= Time$1.minute - Time$1.second / 2) return Math.round(ms / Time$1.minute) + "m";
|
|
194
|
+
else if (abs >= Time$1.second) return Math.round(ms / Time$1.second) + "s";
|
|
195
|
+
return ms + "ms";
|
|
196
|
+
}
|
|
197
|
+
Time$1.format = format;
|
|
198
|
+
function toDigits(source, length = 2) {
|
|
199
|
+
return source.toString().padStart(length, "0");
|
|
200
|
+
}
|
|
201
|
+
Time$1.toDigits = toDigits;
|
|
202
|
+
function template(template$1, time = /* @__PURE__ */ new Date()) {
|
|
203
|
+
return template$1.replace("yyyy", time.getFullYear().toString()).replace("yy", time.getFullYear().toString().slice(2)).replace("MM", toDigits(time.getMonth() + 1)).replace("dd", toDigits(time.getDate())).replace("hh", toDigits(time.getHours())).replace("mm", toDigits(time.getMinutes())).replace("ss", toDigits(time.getSeconds())).replace("SSS", toDigits(time.getMilliseconds(), 3));
|
|
204
|
+
}
|
|
205
|
+
Time$1.template = template;
|
|
206
|
+
})(Time || (Time = {}));
|
|
207
|
+
|
|
208
|
+
//#endregion
|
|
209
|
+
//#region node_modules/.pnpm/@deepseek-ai+schemastery@3.18.1/node_modules/@deepseek-ai/schemastery/lib/index.mjs
|
|
210
|
+
const kSchema = Symbol.for("schemastery");
|
|
211
|
+
const kValidationError = Symbol.for("ValidationError");
|
|
212
|
+
globalThis.__schemastery_index__ ??= 0;
|
|
213
|
+
globalThis.__schemastery_refs__ = void 0;
|
|
214
|
+
var ValidationError = class extends TypeError {
|
|
215
|
+
options;
|
|
216
|
+
name = "ValidationError";
|
|
217
|
+
constructor(message, options) {
|
|
218
|
+
let prefix = "$";
|
|
219
|
+
for (const segment of options.path || []) if (typeof segment === "string") prefix += "." + segment;
|
|
220
|
+
else if (typeof segment === "number") prefix += "[" + segment + "]";
|
|
221
|
+
else if (typeof segment === "symbol") prefix += `[Symbol(${segment.toString()})]`;
|
|
222
|
+
if (prefix.startsWith(".")) prefix = prefix.slice(1);
|
|
223
|
+
super((prefix === "$" ? "" : `${prefix} `) + message);
|
|
224
|
+
this.options = options;
|
|
225
|
+
}
|
|
226
|
+
static is(error) {
|
|
227
|
+
return !!error?.[kValidationError];
|
|
228
|
+
}
|
|
229
|
+
};
|
|
230
|
+
Object.defineProperty(ValidationError.prototype, kValidationError, { value: true });
|
|
231
|
+
const Schema = function(options) {
|
|
232
|
+
const schema = function(data, options$1 = {}) {
|
|
233
|
+
return Schema.resolve(data, schema, options$1)[0];
|
|
234
|
+
};
|
|
235
|
+
if (options.refs) {
|
|
236
|
+
const refs = mapValues(options.refs, (options$1) => new Schema(options$1));
|
|
237
|
+
const getRef = (uid) => refs[uid];
|
|
238
|
+
for (const key in refs) {
|
|
239
|
+
const options$1 = refs[key];
|
|
240
|
+
options$1.sKey = getRef(options$1.sKey);
|
|
241
|
+
options$1.inner = getRef(options$1.inner);
|
|
242
|
+
options$1.list = options$1.list && options$1.list.map(getRef);
|
|
243
|
+
options$1.dict = options$1.dict && mapValues(options$1.dict, getRef);
|
|
244
|
+
}
|
|
245
|
+
return refs[options.uid];
|
|
246
|
+
}
|
|
247
|
+
Object.assign(schema, options);
|
|
248
|
+
if (typeof schema.callback === "string") try {
|
|
249
|
+
schema.callback = new Function("return " + schema.callback)();
|
|
250
|
+
} catch {}
|
|
251
|
+
Object.defineProperty(schema, "uid", { value: globalThis.__schemastery_index__++ });
|
|
252
|
+
Object.setPrototypeOf(schema, Schema.prototype);
|
|
253
|
+
schema.meta ||= {};
|
|
254
|
+
schema.toString = schema.toString.bind(schema);
|
|
255
|
+
return schema;
|
|
256
|
+
};
|
|
257
|
+
Schema.prototype = Object.create(Function.prototype);
|
|
258
|
+
Schema.prototype[kSchema] = true;
|
|
259
|
+
Object.defineProperty(Schema.prototype, "~standard", { get() {
|
|
260
|
+
return {
|
|
261
|
+
version: 1,
|
|
262
|
+
vendor: "schemastery",
|
|
263
|
+
validate: (value) => {
|
|
264
|
+
try {
|
|
265
|
+
return { value: Schema.resolve(value, this, {})[0] };
|
|
266
|
+
} catch (error) {
|
|
267
|
+
if (ValidationError.is(error)) return { issues: [{
|
|
268
|
+
message: error.message,
|
|
269
|
+
path: error.options.path
|
|
270
|
+
}] };
|
|
271
|
+
throw error;
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
};
|
|
275
|
+
} });
|
|
276
|
+
Schema.ValidationError = ValidationError;
|
|
277
|
+
Schema.prototype.toJSON = function toJSON() {
|
|
278
|
+
if (globalThis.__schemastery_refs__) {
|
|
279
|
+
globalThis.__schemastery_refs__[this.uid] ??= JSON.parse(JSON.stringify({ ...this }));
|
|
280
|
+
return this.uid;
|
|
281
|
+
}
|
|
282
|
+
globalThis.__schemastery_refs__ = { [this.uid]: { ...this } };
|
|
283
|
+
globalThis.__schemastery_refs__[this.uid] = JSON.parse(JSON.stringify({ ...this }));
|
|
284
|
+
const result = {
|
|
285
|
+
uid: this.uid,
|
|
286
|
+
refs: globalThis.__schemastery_refs__
|
|
287
|
+
};
|
|
288
|
+
globalThis.__schemastery_refs__ = void 0;
|
|
289
|
+
return result;
|
|
290
|
+
};
|
|
291
|
+
Schema.prototype.set = function set(key, value) {
|
|
292
|
+
this.dict[key] = value;
|
|
293
|
+
return this;
|
|
294
|
+
};
|
|
295
|
+
Schema.prototype.push = function push(value) {
|
|
296
|
+
this.list.push(value);
|
|
297
|
+
return this;
|
|
298
|
+
};
|
|
299
|
+
function mergeDesc(original, messages) {
|
|
300
|
+
const result = typeof original === "string" ? { "": original } : { ...original };
|
|
301
|
+
for (const locale in messages) {
|
|
302
|
+
const value = messages[locale];
|
|
303
|
+
if (value?.$description || value?.$desc) result[locale] = value.$description || value.$desc;
|
|
304
|
+
else if (typeof value === "string") result[locale] = value;
|
|
305
|
+
}
|
|
306
|
+
return result;
|
|
307
|
+
}
|
|
308
|
+
function getInner(value) {
|
|
309
|
+
return value?.$value ?? value?.$inner;
|
|
310
|
+
}
|
|
311
|
+
function extractKeys(data) {
|
|
312
|
+
return filterKeys(data ?? {}, (key) => !key.startsWith("$"));
|
|
313
|
+
}
|
|
314
|
+
Schema.prototype.i18n = function i18n(messages) {
|
|
315
|
+
const schema = Schema(this);
|
|
316
|
+
const desc = mergeDesc(schema.meta.description, messages);
|
|
317
|
+
if (Object.keys(desc).length) schema.meta.description = desc;
|
|
318
|
+
if (schema.dict) schema.dict = mapValues(schema.dict, (inner, key) => {
|
|
319
|
+
return inner.i18n(mapValues(messages, (data) => getInner(data)?.[key] ?? data?.[key]));
|
|
320
|
+
});
|
|
321
|
+
if (schema.list) schema.list = schema.list.map((inner, index) => {
|
|
322
|
+
return inner.i18n(mapValues(messages, (data = {}) => {
|
|
323
|
+
if (Array.isArray(getInner(data))) return getInner(data)[index];
|
|
324
|
+
if (Array.isArray(data)) return data[index];
|
|
325
|
+
return extractKeys(data);
|
|
326
|
+
}));
|
|
327
|
+
});
|
|
328
|
+
if (schema.inner) schema.inner = schema.inner.i18n(mapValues(messages, (data) => {
|
|
329
|
+
if (getInner(data)) return getInner(data);
|
|
330
|
+
return extractKeys(data);
|
|
331
|
+
}));
|
|
332
|
+
if (schema.sKey) schema.sKey = schema.sKey.i18n(mapValues(messages, (data) => data?.$key));
|
|
333
|
+
return schema;
|
|
334
|
+
};
|
|
335
|
+
Schema.prototype.extra = function extra(key, value) {
|
|
336
|
+
const schema = Schema(this);
|
|
337
|
+
schema.meta = {
|
|
338
|
+
...schema.meta,
|
|
339
|
+
[key]: value
|
|
340
|
+
};
|
|
341
|
+
return schema;
|
|
342
|
+
};
|
|
343
|
+
for (const key of [
|
|
344
|
+
"required",
|
|
345
|
+
"disabled",
|
|
346
|
+
"collapse",
|
|
347
|
+
"hidden",
|
|
348
|
+
"loose"
|
|
349
|
+
]) Object.assign(Schema.prototype, { [key](value = true) {
|
|
350
|
+
const schema = Schema(this);
|
|
351
|
+
schema.meta = {
|
|
352
|
+
...schema.meta,
|
|
353
|
+
[key]: value
|
|
354
|
+
};
|
|
355
|
+
return schema;
|
|
356
|
+
} });
|
|
357
|
+
Schema.prototype.deprecated = function deprecated() {
|
|
358
|
+
const schema = Schema(this);
|
|
359
|
+
schema.meta.badges ||= [];
|
|
360
|
+
schema.meta.badges.push({
|
|
361
|
+
text: "deprecated",
|
|
362
|
+
type: "danger"
|
|
363
|
+
});
|
|
364
|
+
return schema;
|
|
365
|
+
};
|
|
366
|
+
Schema.prototype.experimental = function experimental() {
|
|
367
|
+
const schema = Schema(this);
|
|
368
|
+
schema.meta.badges ||= [];
|
|
369
|
+
schema.meta.badges.push({
|
|
370
|
+
text: "experimental",
|
|
371
|
+
type: "warning"
|
|
372
|
+
});
|
|
373
|
+
return schema;
|
|
374
|
+
};
|
|
375
|
+
Schema.prototype.pattern = function pattern(regexp) {
|
|
376
|
+
const schema = Schema(this);
|
|
377
|
+
const pattern$1 = pick(regexp, ["source", "flags"]);
|
|
378
|
+
schema.meta = {
|
|
379
|
+
...schema.meta,
|
|
380
|
+
pattern: pattern$1
|
|
381
|
+
};
|
|
382
|
+
return schema;
|
|
383
|
+
};
|
|
384
|
+
Schema.prototype.simplify = function simplify(value) {
|
|
385
|
+
if (deepEqual(value, this.meta.default, this.type === "dict")) return null;
|
|
386
|
+
if (isNullable(value)) return value;
|
|
387
|
+
if (this.type === "object" || this.type === "dict") {
|
|
388
|
+
const result = {};
|
|
389
|
+
for (const key in value) {
|
|
390
|
+
const item = (this.type === "object" ? this.dict[key] : this.inner)?.simplify(value[key]);
|
|
391
|
+
if (this.type === "dict" || !isNullable(item)) result[key] = item;
|
|
392
|
+
}
|
|
393
|
+
if (deepEqual(result, this.meta.default, this.type === "dict")) return null;
|
|
394
|
+
return result;
|
|
395
|
+
} else if (this.type === "array" || this.type === "tuple") {
|
|
396
|
+
const result = [];
|
|
397
|
+
value.forEach((value$1, index) => {
|
|
398
|
+
const schema = this.type === "array" ? this.inner : this.list[index];
|
|
399
|
+
const item = schema ? schema.simplify(value$1) : value$1;
|
|
400
|
+
result.push(item);
|
|
401
|
+
});
|
|
402
|
+
return result;
|
|
403
|
+
} else if (this.type === "intersect") {
|
|
404
|
+
const result = {};
|
|
405
|
+
for (const item of this.list) Object.assign(result, item.simplify(value));
|
|
406
|
+
return result;
|
|
407
|
+
} else if (this.type === "union") for (const schema of this.list) try {
|
|
408
|
+
Schema.resolve(value, schema, {});
|
|
409
|
+
return schema.simplify(value);
|
|
410
|
+
} catch {}
|
|
411
|
+
return value;
|
|
412
|
+
};
|
|
413
|
+
Schema.prototype.toString = function toString(inline) {
|
|
414
|
+
return formatters[this.type]?.(this, inline) ?? `Schema<${this.type}>`;
|
|
415
|
+
};
|
|
416
|
+
Schema.prototype.role = function role(role$1, extra) {
|
|
417
|
+
const schema = Schema(this);
|
|
418
|
+
schema.meta = {
|
|
419
|
+
...schema.meta,
|
|
420
|
+
role: role$1,
|
|
421
|
+
extra
|
|
422
|
+
};
|
|
423
|
+
return schema;
|
|
424
|
+
};
|
|
425
|
+
for (const key of [
|
|
426
|
+
"default",
|
|
427
|
+
"link",
|
|
428
|
+
"comment",
|
|
429
|
+
"description",
|
|
430
|
+
"max",
|
|
431
|
+
"min",
|
|
432
|
+
"step"
|
|
433
|
+
]) Object.assign(Schema.prototype, { [key](value) {
|
|
434
|
+
const schema = Schema(this);
|
|
435
|
+
schema.meta = {
|
|
436
|
+
...schema.meta,
|
|
437
|
+
[key]: value
|
|
438
|
+
};
|
|
439
|
+
return schema;
|
|
440
|
+
} });
|
|
441
|
+
const resolvers = {};
|
|
442
|
+
Schema.extend = function extend(type, resolve) {
|
|
443
|
+
resolvers[type] = resolve;
|
|
444
|
+
};
|
|
445
|
+
Schema.resolve = function resolve(data, schema, options = {}, strict = false) {
|
|
446
|
+
if (!schema) return [data];
|
|
447
|
+
if (options.ignore?.(data, schema)) return [data];
|
|
448
|
+
if (isNullable(data) && schema.type !== "lazy") {
|
|
449
|
+
if (schema.meta.required) throw new ValidationError(`missing required value`, options);
|
|
450
|
+
let current = schema;
|
|
451
|
+
let fallback = schema.meta.default;
|
|
452
|
+
while (current?.type === "intersect" && isNullable(fallback)) {
|
|
453
|
+
current = current.list[0];
|
|
454
|
+
fallback = current?.meta.default;
|
|
455
|
+
}
|
|
456
|
+
if (isNullable(fallback)) return [data];
|
|
457
|
+
data = clone(fallback);
|
|
458
|
+
}
|
|
459
|
+
const callback = resolvers[schema.type];
|
|
460
|
+
if (!callback) throw new ValidationError(`unsupported type "${schema.type}"`, options);
|
|
461
|
+
try {
|
|
462
|
+
return callback(data, schema, options, strict);
|
|
463
|
+
} catch (error) {
|
|
464
|
+
if (!schema.meta.loose) throw error;
|
|
465
|
+
return [schema.meta.default];
|
|
466
|
+
}
|
|
467
|
+
};
|
|
468
|
+
Schema.from = function from(source) {
|
|
469
|
+
if (isNullable(source)) return Schema.any();
|
|
470
|
+
else if ([
|
|
471
|
+
"string",
|
|
472
|
+
"number",
|
|
473
|
+
"boolean"
|
|
474
|
+
].includes(typeof source)) return Schema.const(source).required();
|
|
475
|
+
else if (source[kSchema]) return source;
|
|
476
|
+
else if (typeof source === "function") switch (source) {
|
|
477
|
+
case String: return Schema.string().required();
|
|
478
|
+
case Number: return Schema.number().required();
|
|
479
|
+
case Boolean: return Schema.boolean().required();
|
|
480
|
+
case Function: return Schema.function().required();
|
|
481
|
+
default: return Schema.is(source).required();
|
|
482
|
+
}
|
|
483
|
+
else throw new TypeError(`cannot infer schema from ${source}`);
|
|
484
|
+
};
|
|
485
|
+
Schema.lazy = function lazy(builder) {
|
|
486
|
+
const toJSON = () => {
|
|
487
|
+
if (!schema.inner[kSchema]) {
|
|
488
|
+
schema.inner = schema.builder();
|
|
489
|
+
schema.inner.meta = {
|
|
490
|
+
...schema.meta,
|
|
491
|
+
...schema.inner.meta
|
|
492
|
+
};
|
|
493
|
+
}
|
|
494
|
+
return schema.inner.toJSON();
|
|
495
|
+
};
|
|
496
|
+
const schema = new Schema({
|
|
497
|
+
type: "lazy",
|
|
498
|
+
builder,
|
|
499
|
+
inner: { toJSON }
|
|
500
|
+
});
|
|
501
|
+
return schema;
|
|
502
|
+
};
|
|
503
|
+
Schema.natural = function natural() {
|
|
504
|
+
return Schema.number().step(1).min(0);
|
|
505
|
+
};
|
|
506
|
+
Schema.percent = function percent() {
|
|
507
|
+
return Schema.number().step(.01).min(0).max(1).role("slider");
|
|
508
|
+
};
|
|
509
|
+
Schema.date = function date() {
|
|
510
|
+
return Schema.union([Schema.is(Date), Schema.transform(Schema.string().role("datetime"), (value, options) => {
|
|
511
|
+
const date$1 = new Date(value);
|
|
512
|
+
if (isNaN(+date$1)) throw new ValidationError(`invalid date "${value}"`, options);
|
|
513
|
+
return date$1;
|
|
514
|
+
}, true)]);
|
|
515
|
+
};
|
|
516
|
+
Schema.regExp = function regExp(flag = "") {
|
|
517
|
+
return Schema.union([Schema.is(RegExp), Schema.transform(Schema.string().role("regexp", { flag }), (value, options) => {
|
|
518
|
+
try {
|
|
519
|
+
return new RegExp(value, flag);
|
|
520
|
+
} catch (e) {
|
|
521
|
+
throw new ValidationError(e.message, options);
|
|
522
|
+
}
|
|
523
|
+
}, true)]);
|
|
524
|
+
};
|
|
525
|
+
Schema.arrayBuffer = function arrayBuffer(encoding) {
|
|
526
|
+
return Schema.union([
|
|
527
|
+
Schema.is(ArrayBuffer),
|
|
528
|
+
Schema.is(SharedArrayBuffer),
|
|
529
|
+
Schema.transform(Schema.any(), (value, options) => {
|
|
530
|
+
if (Binary.isSource(value)) return Binary.fromSource(value);
|
|
531
|
+
throw new ValidationError(`expected ArrayBufferSource but got ${value}`, options);
|
|
532
|
+
}, true),
|
|
533
|
+
...encoding ? [Schema.transform(Schema.string(), (value, options) => {
|
|
534
|
+
try {
|
|
535
|
+
return encoding === "base64" ? Binary.fromBase64(value) : Binary.fromHex(value);
|
|
536
|
+
} catch (e) {
|
|
537
|
+
throw new ValidationError(e.message, options);
|
|
538
|
+
}
|
|
539
|
+
}, true)] : []
|
|
540
|
+
]);
|
|
541
|
+
};
|
|
542
|
+
Schema.extend("lazy", (data, schema, options, strict) => {
|
|
543
|
+
if (!schema.inner[kSchema]) {
|
|
544
|
+
schema.inner = schema.builder();
|
|
545
|
+
schema.inner.meta = {
|
|
546
|
+
...schema.meta,
|
|
547
|
+
...schema.inner.meta
|
|
548
|
+
};
|
|
549
|
+
}
|
|
550
|
+
return Schema.resolve(data, schema.inner, options, strict);
|
|
551
|
+
});
|
|
552
|
+
Schema.extend("any", (data) => {
|
|
553
|
+
return [data];
|
|
554
|
+
});
|
|
555
|
+
Schema.extend("never", (data, _, options) => {
|
|
556
|
+
throw new ValidationError(`expected nullable but got ${data}`, options);
|
|
557
|
+
});
|
|
558
|
+
Schema.extend("const", (data, { value }, options) => {
|
|
559
|
+
if (deepEqual(data, value)) return [value];
|
|
560
|
+
throw new ValidationError(`expected ${value} but got ${data}`, options);
|
|
561
|
+
});
|
|
562
|
+
function checkWithinRange(data, meta, description, options, skipMin = false) {
|
|
563
|
+
const { max = Infinity, min = -Infinity } = meta;
|
|
564
|
+
if (data > max) throw new ValidationError(`expected ${description} <= ${max} but got ${data}`, options);
|
|
565
|
+
if (data < min && !skipMin) throw new ValidationError(`expected ${description} >= ${min} but got ${data}`, options);
|
|
566
|
+
}
|
|
567
|
+
Schema.extend("string", (data, { meta }, options) => {
|
|
568
|
+
if (typeof data !== "string") throw new ValidationError(`expected string but got ${data}`, options);
|
|
569
|
+
if (meta.pattern) {
|
|
570
|
+
const regexp = new RegExp(meta.pattern.source, meta.pattern.flags);
|
|
571
|
+
if (!regexp.test(data)) throw new ValidationError(`expect string to match regexp ${regexp}`, options);
|
|
572
|
+
}
|
|
573
|
+
checkWithinRange(data.length, meta, "string length", options);
|
|
574
|
+
return [data];
|
|
575
|
+
});
|
|
576
|
+
function decimalShift(data, digits) {
|
|
577
|
+
const str = data.toString();
|
|
578
|
+
if (str.includes("e")) return data * Math.pow(10, digits);
|
|
579
|
+
const index = str.indexOf(".");
|
|
580
|
+
if (index === -1) return data * Math.pow(10, digits);
|
|
581
|
+
const frac = str.slice(index + 1);
|
|
582
|
+
const integer = str.slice(0, index);
|
|
583
|
+
if (frac.length <= digits) return +(integer + frac.padEnd(digits, "0"));
|
|
584
|
+
return +(integer + frac.slice(0, digits) + "." + frac.slice(digits));
|
|
585
|
+
}
|
|
586
|
+
function isMultipleOf(data, min, step) {
|
|
587
|
+
step = Math.abs(step);
|
|
588
|
+
if (!/^\d+\.\d+$/.test(step.toString())) return (data - min) % step === 0;
|
|
589
|
+
const index = step.toString().indexOf(".");
|
|
590
|
+
const digits = step.toString().slice(index + 1).length;
|
|
591
|
+
return Math.abs(decimalShift(data, digits) - decimalShift(min, digits)) % decimalShift(step, digits) === 0;
|
|
592
|
+
}
|
|
593
|
+
Schema.extend("number", (data, { meta }, options) => {
|
|
594
|
+
if (typeof data !== "number") throw new ValidationError(`expected number but got ${data}`, options);
|
|
595
|
+
checkWithinRange(data, meta, "number", options);
|
|
596
|
+
const { step } = meta;
|
|
597
|
+
if (step && !isMultipleOf(data, meta.min ?? 0, step)) throw new ValidationError(`expected number multiple of ${step} but got ${data}`, options);
|
|
598
|
+
return [data];
|
|
599
|
+
});
|
|
600
|
+
Schema.extend("boolean", (data, _, options) => {
|
|
601
|
+
if (typeof data === "boolean") return [data];
|
|
602
|
+
throw new ValidationError(`expected boolean but got ${data}`, options);
|
|
603
|
+
});
|
|
604
|
+
Schema.extend("bitset", (data, { bits, meta }, options) => {
|
|
605
|
+
let value = 0, keys = [];
|
|
606
|
+
if (typeof data === "number") {
|
|
607
|
+
value = data;
|
|
608
|
+
for (const key in bits) if (data & bits[key]) keys.push(key);
|
|
609
|
+
} else if (Array.isArray(data)) {
|
|
610
|
+
keys = data;
|
|
611
|
+
for (const key of keys) {
|
|
612
|
+
if (typeof key !== "string") throw new ValidationError(`expected string but got ${key}`, options);
|
|
613
|
+
if (key in bits) value |= bits[key];
|
|
614
|
+
}
|
|
615
|
+
} else throw new ValidationError(`expected number or array but got ${data}`, options);
|
|
616
|
+
if (value === meta.default) return [value];
|
|
617
|
+
return [value, keys];
|
|
618
|
+
});
|
|
619
|
+
Schema.extend("function", (data, _, options) => {
|
|
620
|
+
if (typeof data === "function") return [data];
|
|
621
|
+
throw new ValidationError(`expected function but got ${data}`, options);
|
|
622
|
+
});
|
|
623
|
+
Schema.extend("is", (data, { constructor }, options) => {
|
|
624
|
+
if (typeof constructor === "function") {
|
|
625
|
+
if (data instanceof constructor) return [data];
|
|
626
|
+
throw new ValidationError(`expected ${constructor.name} but got ${data}`, options);
|
|
627
|
+
} else {
|
|
628
|
+
if (isNullable(data)) throw new ValidationError(`expected ${constructor} but got ${data}`, options);
|
|
629
|
+
let prototype = Object.getPrototypeOf(data);
|
|
630
|
+
while (prototype) {
|
|
631
|
+
if (prototype.constructor?.name === constructor) return [data];
|
|
632
|
+
prototype = Object.getPrototypeOf(prototype);
|
|
633
|
+
}
|
|
634
|
+
throw new ValidationError(`expected ${constructor} but got ${data}`, options);
|
|
635
|
+
}
|
|
636
|
+
});
|
|
637
|
+
function property(data, key, schema, options) {
|
|
638
|
+
try {
|
|
639
|
+
const [value, adapted] = Schema.resolve(data[key], schema, {
|
|
640
|
+
...options,
|
|
641
|
+
path: [...options.path || [], key]
|
|
642
|
+
});
|
|
643
|
+
if (adapted !== void 0) data[key] = adapted;
|
|
644
|
+
return value;
|
|
645
|
+
} catch (e) {
|
|
646
|
+
if (!options?.autofix) throw e;
|
|
647
|
+
delete data[key];
|
|
648
|
+
return schema.meta.default;
|
|
649
|
+
}
|
|
650
|
+
}
|
|
651
|
+
Schema.extend("array", (data, { inner, meta }, options) => {
|
|
652
|
+
if (!Array.isArray(data)) throw new ValidationError(`expected array but got ${data}`, options);
|
|
653
|
+
checkWithinRange(data.length, meta, "array length", options, !isNullable(inner.meta.default));
|
|
654
|
+
return [data.map((_, index) => property(data, index, inner, options))];
|
|
655
|
+
});
|
|
656
|
+
Schema.extend("dict", (data, { inner, sKey }, options, strict) => {
|
|
657
|
+
if (!isPlainObject(data)) throw new ValidationError(`expected object but got ${data}`, options);
|
|
658
|
+
const result = {};
|
|
659
|
+
for (const key in data) {
|
|
660
|
+
let rKey;
|
|
661
|
+
try {
|
|
662
|
+
rKey = Schema.resolve(key, sKey, options)[0];
|
|
663
|
+
} catch (error) {
|
|
664
|
+
if (strict) continue;
|
|
665
|
+
throw error;
|
|
666
|
+
}
|
|
667
|
+
result[rKey] = property(data, key, inner, options);
|
|
668
|
+
data[rKey] = data[key];
|
|
669
|
+
if (key !== rKey) delete data[key];
|
|
670
|
+
}
|
|
671
|
+
return [result];
|
|
672
|
+
});
|
|
673
|
+
Schema.extend("tuple", (data, { list }, options, strict) => {
|
|
674
|
+
if (!Array.isArray(data)) throw new ValidationError(`expected array but got ${data}`, options);
|
|
675
|
+
const result = list.map((inner, index) => property(data, index, inner, options));
|
|
676
|
+
if (strict) return [result];
|
|
677
|
+
result.push(...data.slice(list.length));
|
|
678
|
+
return [result];
|
|
679
|
+
});
|
|
680
|
+
function merge(result, data) {
|
|
681
|
+
for (const key in data) {
|
|
682
|
+
if (key in result) continue;
|
|
683
|
+
result[key] = data[key];
|
|
684
|
+
}
|
|
685
|
+
}
|
|
686
|
+
Schema.extend("object", (data, { dict }, options, strict) => {
|
|
687
|
+
if (!isPlainObject(data)) throw new ValidationError(`expected object but got ${data}`, options);
|
|
688
|
+
const result = {};
|
|
689
|
+
for (const key in dict) {
|
|
690
|
+
const value = property(data, key, dict[key], options);
|
|
691
|
+
if (!isNullable(value) || key in data) result[key] = value;
|
|
692
|
+
}
|
|
693
|
+
if (!strict) merge(result, data);
|
|
694
|
+
return [result];
|
|
695
|
+
});
|
|
696
|
+
Schema.extend("union", (data, { list, toString }, options, strict) => {
|
|
697
|
+
const messages = [];
|
|
698
|
+
for (const inner of list) try {
|
|
699
|
+
return Schema.resolve(data, inner, options, strict);
|
|
700
|
+
} catch (error) {
|
|
701
|
+
messages.push(error);
|
|
702
|
+
}
|
|
703
|
+
throw new ValidationError(`expected ${toString()} but got ${JSON.stringify(data)}`, options);
|
|
704
|
+
});
|
|
705
|
+
Schema.extend("intersect", (data, { list, toString }, options, strict) => {
|
|
706
|
+
if (!list.length) return [data];
|
|
707
|
+
let result;
|
|
708
|
+
for (const inner of list) {
|
|
709
|
+
const value = Schema.resolve(data, inner, options, true)[0];
|
|
710
|
+
if (isNullable(value)) continue;
|
|
711
|
+
if (isNullable(result)) result = value;
|
|
712
|
+
else if (typeof result !== typeof value) throw new ValidationError(`expected ${toString()} but got ${JSON.stringify(data)}`, options);
|
|
713
|
+
else if (typeof value === "object") merge(result ??= {}, value);
|
|
714
|
+
else if (result !== value) throw new ValidationError(`expected ${toString()} but got ${JSON.stringify(data)}`, options);
|
|
715
|
+
}
|
|
716
|
+
if (!strict && isPlainObject(data)) merge(result, data);
|
|
717
|
+
return [result];
|
|
718
|
+
});
|
|
719
|
+
Schema.extend("transform", (data, { inner, callback, preserve }, options) => {
|
|
720
|
+
const [result, adapted = data] = Schema.resolve(data, inner, options, true);
|
|
721
|
+
if (preserve) return [callback(result)];
|
|
722
|
+
else return [callback(result), callback(adapted)];
|
|
723
|
+
});
|
|
724
|
+
const formatters = {};
|
|
725
|
+
function defineMethod(name$1, keys, format) {
|
|
726
|
+
formatters[name$1] = format;
|
|
727
|
+
Object.assign(Schema, { [name$1](...args) {
|
|
728
|
+
const schema = new Schema({ type: name$1 });
|
|
729
|
+
keys.forEach((key, index) => {
|
|
730
|
+
switch (key) {
|
|
731
|
+
case "sKey":
|
|
732
|
+
schema.sKey = args[index] ?? Schema.string();
|
|
733
|
+
break;
|
|
734
|
+
case "inner":
|
|
735
|
+
schema.inner = Schema.from(args[index]);
|
|
736
|
+
break;
|
|
737
|
+
case "list":
|
|
738
|
+
schema.list = args[index].map(Schema.from);
|
|
739
|
+
break;
|
|
740
|
+
case "dict":
|
|
741
|
+
schema.dict = mapValues(args[index], Schema.from);
|
|
742
|
+
break;
|
|
743
|
+
case "bits":
|
|
744
|
+
schema.bits = {};
|
|
745
|
+
for (const key$1 in args[index]) {
|
|
746
|
+
if (typeof args[index][key$1] !== "number") continue;
|
|
747
|
+
schema.bits[key$1] = args[index][key$1];
|
|
748
|
+
}
|
|
749
|
+
break;
|
|
750
|
+
case "callback": {
|
|
751
|
+
const callback = schema.callback = args[index];
|
|
752
|
+
callback["toJSON"] ||= () => callback.toString();
|
|
753
|
+
break;
|
|
754
|
+
}
|
|
755
|
+
case "constructor": {
|
|
756
|
+
const constructor = schema.constructor = args[index];
|
|
757
|
+
if (typeof constructor === "function") constructor["toJSON"] ||= () => constructor["name"];
|
|
758
|
+
break;
|
|
759
|
+
}
|
|
760
|
+
default: schema[key] = args[index];
|
|
761
|
+
}
|
|
762
|
+
});
|
|
763
|
+
if (name$1 === "object" || name$1 === "dict") schema.meta.default = {};
|
|
764
|
+
else if (name$1 === "array" || name$1 === "tuple") schema.meta.default = [];
|
|
765
|
+
else if (name$1 === "bitset") schema.meta.default = 0;
|
|
766
|
+
return schema;
|
|
767
|
+
} });
|
|
768
|
+
}
|
|
769
|
+
defineMethod("is", ["constructor"], ({ constructor }) => {
|
|
770
|
+
if (typeof constructor === "function") return constructor.name;
|
|
771
|
+
else return constructor;
|
|
772
|
+
});
|
|
773
|
+
defineMethod("any", [], () => "any");
|
|
774
|
+
defineMethod("never", [], () => "never");
|
|
775
|
+
defineMethod("const", ["value"], ({ value }) => typeof value === "string" ? JSON.stringify(value) : value);
|
|
776
|
+
defineMethod("string", [], () => "string");
|
|
777
|
+
defineMethod("number", [], () => "number");
|
|
778
|
+
defineMethod("boolean", [], () => "boolean");
|
|
779
|
+
defineMethod("bitset", ["bits"], () => "bitset");
|
|
780
|
+
defineMethod("function", [], () => "function");
|
|
781
|
+
defineMethod("array", ["inner"], ({ inner }) => `${inner.toString(true)}[]`);
|
|
782
|
+
defineMethod("dict", ["inner", "sKey"], ({ inner, sKey }) => `{ [key: ${sKey.toString()}]: ${inner.toString()} }`);
|
|
783
|
+
defineMethod("tuple", ["list"], ({ list }) => `[${list.map((inner) => inner.toString()).join(", ")}]`);
|
|
784
|
+
defineMethod("object", ["dict"], ({ dict }) => {
|
|
785
|
+
if (Object.keys(dict).length === 0) return "{}";
|
|
786
|
+
return `{ ${Object.entries(dict).map(([key, inner]) => {
|
|
787
|
+
return `${key}${inner.meta.required ? "" : "?"}: ${inner.toString()}`;
|
|
788
|
+
}).join(", ")} }`;
|
|
789
|
+
});
|
|
790
|
+
defineMethod("union", ["list"], ({ list }, inline) => {
|
|
791
|
+
const result = list.map(({ toString: format }) => format()).join(" | ");
|
|
792
|
+
return inline ? `(${result})` : result;
|
|
793
|
+
});
|
|
794
|
+
defineMethod("intersect", ["list"], ({ list }) => {
|
|
795
|
+
return `${list.map((inner) => inner.toString(true)).join(" & ")}`;
|
|
796
|
+
});
|
|
797
|
+
defineMethod("transform", [
|
|
798
|
+
"inner",
|
|
799
|
+
"callback",
|
|
800
|
+
"preserve"
|
|
801
|
+
], ({ inner }, isInner) => inner.toString(isInner));
|
|
802
|
+
|
|
803
|
+
//#endregion
|
|
804
|
+
//#region node_modules/.pnpm/@deepseek-ai+dsh-timeout@0.1.1-rc.2_@deepseek-ai+cordis@4.0.1_@deepseek-ai+dsh-invariants@0.1_2yxulatypvfilrzvurumr2xwty/node_modules/@deepseek-ai/dsh-timeout/lib/index.js
|
|
805
|
+
/** Largest delay Node schedules without clamping it to one millisecond. */
|
|
806
|
+
const MAX_TIMER_DELAY_MS = 2147483647;
|
|
807
|
+
|
|
808
|
+
//#endregion
|
|
809
|
+
//#region node_modules/.pnpm/@deepseek-ai+dsh-llm@0.1.1-rc.2_@deepseek-ai+cordis@4.0.1_@deepseek-ai+dsh-attachment@0.1.1-r_x2n35l65jyhywzqyfdn334iwva/node_modules/@deepseek-ai/dsh-llm/lib/index.js
|
|
810
|
+
/**
|
|
811
|
+
* Brand a string as a {@link CallId}.
|
|
812
|
+
* @param id - the provider-issued (or synthesized) call id.
|
|
813
|
+
* @returns the same string, branded; no validation is performed.
|
|
814
|
+
*/
|
|
815
|
+
function CallId(id) {
|
|
816
|
+
return id;
|
|
817
|
+
}
|
|
818
|
+
/**
|
|
819
|
+
* Canonical provider-neutral code for a response that completed normally but
|
|
820
|
+
* carried no content blocks at all. Providers occasionally emit a degenerate
|
|
821
|
+
* completion (a terminal stop with zero output); adapters classify it as this
|
|
822
|
+
* failure instead of yielding an empty assistant message, because an empty
|
|
823
|
+
* message silently ends the turn with nothing for the user or the loop to act
|
|
824
|
+
* on. The attempt produced nothing durable, so retry policy treats it as safe
|
|
825
|
+
* to repeat.
|
|
826
|
+
*/
|
|
827
|
+
const EMPTY_RESPONSE_CODE = "EMPTY_RESPONSE";
|
|
828
|
+
/** Structured codes and plain phrases that explicitly name a context bound being exceeded. */
|
|
829
|
+
const STRUCTURED_CONTEXT_OVERFLOW = new RegExp(String.raw`(?:^|[^a-z0-9])context[\s_-](?:length|window)[\s_-]` + String.raw`(?:exceed(?:ed|s)?|overflow(?:ed)?|limit[\s_-]exceeded)(?:$|[^a-z0-9])`, "i");
|
|
830
|
+
/** Request-size wording that ties "too large" directly to model context capacity. */
|
|
831
|
+
const TOO_LARGE_FOR_CONTEXT = new RegExp(String.raw`\b(?:request|prompt|input|messages?)\s+(?:is\s+|are\s+)?` + String.raw`too\s+(?:large|long)\s+for\s+(?:(?:this|the)\s+)?` + String.raw`(?:model(?:'s)?\s+)?context(?:\s+window)?\b`, "i");
|
|
832
|
+
/** "Exceeds" wording is safe only when its object is explicitly the model context. */
|
|
833
|
+
const EXCEEDS_MODEL_CONTEXT = new RegExp(String.raw`\b(?:input|prompt|request|messages?)\b.{0,40}` + String.raw`\b(?:exceed(?:s|ed)?|overflows?|is\s+larger\s+than)\b.{0,40}` + String.raw`\b(?:the\s+)?(?:model(?:'s)?\s+)?context(?:\s+(?:length|window))?\b`, "i");
|
|
834
|
+
/**
|
|
835
|
+
* Provider-owned request-retry policy configuration and resolution.
|
|
836
|
+
*
|
|
837
|
+
* Adapters expose one resolved policy per registered provider route; the
|
|
838
|
+
* optional dsh-llm-retry plugin executes it on the agent's failed-step extension point.
|
|
839
|
+
*
|
|
840
|
+
* @module @deepseek-ai/dsh-llm/retry-policy
|
|
841
|
+
*/
|
|
842
|
+
const DEFAULT_MAX_RETRIES = 5;
|
|
843
|
+
const DEFAULT_INITIAL_DELAY_MS = 500;
|
|
844
|
+
const DEFAULT_MAX_DELAY_MS = 1e4;
|
|
845
|
+
const DEFAULT_JITTER_RATIO = .1;
|
|
846
|
+
const DEFAULT_RETRYABLE_CODES = Object.freeze([
|
|
847
|
+
EMPTY_RESPONSE_CODE,
|
|
848
|
+
"RATE_LIMIT",
|
|
849
|
+
"SERVER",
|
|
850
|
+
"TIMEOUT",
|
|
851
|
+
"TRANSPORT"
|
|
852
|
+
]);
|
|
853
|
+
const backoffSchema = Schema.object({
|
|
854
|
+
initialDelayMs: Schema.number().max(MAX_TIMER_DELAY_MS).default(DEFAULT_INITIAL_DELAY_MS),
|
|
855
|
+
maxDelayMs: Schema.number().max(MAX_TIMER_DELAY_MS).default(DEFAULT_MAX_DELAY_MS),
|
|
856
|
+
jitterRatio: Schema.number().min(0).max(1).default(DEFAULT_JITTER_RATIO)
|
|
857
|
+
});
|
|
858
|
+
const normalPolicySchema = Schema.object({
|
|
859
|
+
mode: Schema.const("normal").required(),
|
|
860
|
+
maxRetries: Schema.number().step(1).min(0).max(Number.MAX_SAFE_INTEGER).default(DEFAULT_MAX_RETRIES),
|
|
861
|
+
retryableCodes: Schema.array(Schema.string()).default([...DEFAULT_RETRYABLE_CODES]),
|
|
862
|
+
backoff: backoffSchema
|
|
863
|
+
});
|
|
864
|
+
const alwaysPolicySchema = Schema.object({
|
|
865
|
+
mode: Schema.const("always").required(),
|
|
866
|
+
backoff: backoffSchema
|
|
867
|
+
});
|
|
868
|
+
/** Cordis schema embedded by each concrete provider configuration. */
|
|
869
|
+
const RetryPolicySchema = Schema.union([normalPolicySchema, alwaysPolicySchema]);
|
|
870
|
+
/**
|
|
871
|
+
* Centralize the non-secret product identity every provider request sends as `User-Agent`, keeping
|
|
872
|
+
* adapters from drifting. See
|
|
873
|
+
* `.agents/notes/implemented/architecture/2026-06-21-mandatory-app-attribution-headers.md`.
|
|
874
|
+
*
|
|
875
|
+
* App-attribution vocabulary for provider requests.
|
|
876
|
+
* @module @deepseek-ai/dsh-llm/attribution
|
|
877
|
+
*/
|
|
878
|
+
const { version } = createRequire(import.meta.url)("../package.json");
|
|
879
|
+
|
|
880
|
+
//#endregion
|
|
881
|
+
//#region src/types/index.ts
|
|
882
|
+
const RepoId = (id) => id;
|
|
883
|
+
const NodeId = (id) => id;
|
|
884
|
+
const EdgeId = (id) => id;
|
|
885
|
+
|
|
886
|
+
//#endregion
|
|
887
|
+
//#region src/shared/Logger.ts
|
|
888
|
+
const LEVEL_ORDER = {
|
|
889
|
+
debug: 0,
|
|
890
|
+
info: 1,
|
|
891
|
+
warn: 2,
|
|
892
|
+
error: 3
|
|
893
|
+
};
|
|
894
|
+
const RING_SIZE = 200;
|
|
895
|
+
var LoggerImpl = class {
|
|
896
|
+
buffer = [];
|
|
897
|
+
listeners = new Set();
|
|
898
|
+
minLevel = typeof globalThis !== "undefined" && globalThis.__CG_DEBUG ? "debug" : "info";
|
|
899
|
+
log(level, scope, message, data) {
|
|
900
|
+
if (LEVEL_ORDER[level] < LEVEL_ORDER[this.minLevel]) return;
|
|
901
|
+
const entry = {
|
|
902
|
+
ts: Date.now(),
|
|
903
|
+
level,
|
|
904
|
+
scope,
|
|
905
|
+
message,
|
|
906
|
+
data
|
|
907
|
+
};
|
|
908
|
+
this.buffer.push(entry);
|
|
909
|
+
if (this.buffer.length > RING_SIZE) this.buffer.splice(0, this.buffer.length - RING_SIZE);
|
|
910
|
+
this.emit();
|
|
911
|
+
const fn = level === "error" ? console.error : level === "warn" ? console.warn : console.log;
|
|
912
|
+
try {
|
|
913
|
+
fn(`[codegraph:${scope}] ${message}`, data ?? "");
|
|
914
|
+
} catch {}
|
|
915
|
+
}
|
|
916
|
+
debug(scope, message, data) {
|
|
917
|
+
this.log("debug", scope, message, data);
|
|
918
|
+
}
|
|
919
|
+
info(scope, message, data) {
|
|
920
|
+
this.log("info", scope, message, data);
|
|
921
|
+
}
|
|
922
|
+
warn(scope, message, data) {
|
|
923
|
+
this.log("warn", scope, message, data);
|
|
924
|
+
}
|
|
925
|
+
error(scope, message, data) {
|
|
926
|
+
this.log("error", scope, message, data);
|
|
927
|
+
}
|
|
928
|
+
entries() {
|
|
929
|
+
return this.buffer.slice();
|
|
930
|
+
}
|
|
931
|
+
clear() {
|
|
932
|
+
this.buffer = [];
|
|
933
|
+
this.emit();
|
|
934
|
+
}
|
|
935
|
+
subscribe(fn) {
|
|
936
|
+
this.listeners.add(fn);
|
|
937
|
+
fn(this.entries());
|
|
938
|
+
return () => {
|
|
939
|
+
this.listeners.delete(fn);
|
|
940
|
+
};
|
|
941
|
+
}
|
|
942
|
+
emit() {
|
|
943
|
+
const snapshot = this.entries();
|
|
944
|
+
for (const fn of this.listeners) try {
|
|
945
|
+
fn(snapshot);
|
|
946
|
+
} catch {}
|
|
947
|
+
}
|
|
948
|
+
};
|
|
949
|
+
const logger = new LoggerImpl();
|
|
950
|
+
function scoped(scope) {
|
|
951
|
+
return {
|
|
952
|
+
debug: (m, d) => logger.debug(scope, m, d),
|
|
953
|
+
info: (m, d) => logger.info(scope, m, d),
|
|
954
|
+
warn: (m, d) => logger.warn(scope, m, d),
|
|
955
|
+
error: (m, d) => logger.error(scope, m, d)
|
|
956
|
+
};
|
|
957
|
+
}
|
|
958
|
+
|
|
959
|
+
//#endregion
|
|
960
|
+
//#region src/adapters/CodeGraphAdapter.ts
|
|
961
|
+
const log$6 = scoped("codegraph-adapter");
|
|
962
|
+
const require = createRequire(import.meta.url);
|
|
963
|
+
const NODE_KIND_MAP = {
|
|
964
|
+
function: "function",
|
|
965
|
+
method: "function",
|
|
966
|
+
class: "class",
|
|
967
|
+
interface: "interface",
|
|
968
|
+
type_alias: "type",
|
|
969
|
+
constant: "variable",
|
|
970
|
+
variable: "variable",
|
|
971
|
+
property: "variable",
|
|
972
|
+
file: "module",
|
|
973
|
+
import: "module",
|
|
974
|
+
module: "module"
|
|
975
|
+
};
|
|
976
|
+
const EDGE_KIND_MAP = {
|
|
977
|
+
call: "call",
|
|
978
|
+
calls: "call",
|
|
979
|
+
import: "import",
|
|
980
|
+
imports: "import",
|
|
981
|
+
extend: "extend",
|
|
982
|
+
extends: "extend",
|
|
983
|
+
implement: "implement",
|
|
984
|
+
implements: "implement",
|
|
985
|
+
contains: "dependency",
|
|
986
|
+
dependency: "dependency",
|
|
987
|
+
depends: "dependency"
|
|
988
|
+
};
|
|
989
|
+
function mapNodeKind(kind) {
|
|
990
|
+
return NODE_KIND_MAP[kind] ?? "module";
|
|
991
|
+
}
|
|
992
|
+
function mapEdgeKind(kind) {
|
|
993
|
+
return EDGE_KIND_MAP[kind] ?? "dependency";
|
|
994
|
+
}
|
|
995
|
+
/** Locate the .codegraph/codegraph.db for a workspace path. */
|
|
996
|
+
function resolveDbPath(workspacePath) {
|
|
997
|
+
const root = workspacePath && workspacePath !== "." ? workspacePath : process.cwd();
|
|
998
|
+
return join(root, ".codegraph", "codegraph.db");
|
|
999
|
+
}
|
|
1000
|
+
/** Read the whole graph from a codegraph.db. Returns null when unreadable. */
|
|
1001
|
+
function readGraphFromDb(dbPath) {
|
|
1002
|
+
if (!existsSync(dbPath)) return null;
|
|
1003
|
+
try {
|
|
1004
|
+
const { DatabaseSync } = require("node:sqlite");
|
|
1005
|
+
const db = new DatabaseSync(dbPath, { readOnly: true });
|
|
1006
|
+
try {
|
|
1007
|
+
const nodes = db.prepare("SELECT id, kind, name, file_path, start_line, signature, docstring, is_exported FROM nodes").all();
|
|
1008
|
+
const edges = db.prepare("SELECT id, source, target, kind, line FROM edges").all();
|
|
1009
|
+
return {
|
|
1010
|
+
nodes,
|
|
1011
|
+
edges
|
|
1012
|
+
};
|
|
1013
|
+
} finally {
|
|
1014
|
+
db.close();
|
|
1015
|
+
}
|
|
1016
|
+
} catch (e) {
|
|
1017
|
+
log$6.warn("readGraphFromDb failed", e);
|
|
1018
|
+
return null;
|
|
1019
|
+
}
|
|
1020
|
+
}
|
|
1021
|
+
var CodeGraphAdapter = class {
|
|
1022
|
+
source = "codegraph";
|
|
1023
|
+
async fetchData(repoId, invoke) {
|
|
1024
|
+
const dbRows = readGraphFromDb(resolveDbPath(repoId));
|
|
1025
|
+
if (dbRows && dbRows.nodes.length > 0) return this.toAdapterResult(dbRows.nodes, dbRows.edges);
|
|
1026
|
+
const files = await invoke("codegraph_files", {
|
|
1027
|
+
path: repoId,
|
|
1028
|
+
format: "flat"
|
|
1029
|
+
});
|
|
1030
|
+
if (!files || typeof files !== "object") return {
|
|
1031
|
+
nodes: [],
|
|
1032
|
+
edges: [],
|
|
1033
|
+
source: this.source,
|
|
1034
|
+
timestamp: Date.now()
|
|
1035
|
+
};
|
|
1036
|
+
const rawFiles = this.extractFileList(files);
|
|
1037
|
+
const nodes = rawFiles.map((f, i) => ({
|
|
1038
|
+
id: NodeId(`file:${f.path}`),
|
|
1039
|
+
label: f.path.split("/").pop() ?? f.path,
|
|
1040
|
+
type: "module",
|
|
1041
|
+
filePath: f.path,
|
|
1042
|
+
lineNumber: 1,
|
|
1043
|
+
properties: {
|
|
1044
|
+
kind: "file",
|
|
1045
|
+
language: f.language ?? null,
|
|
1046
|
+
index: i
|
|
1047
|
+
}
|
|
1048
|
+
}));
|
|
1049
|
+
return {
|
|
1050
|
+
nodes,
|
|
1051
|
+
edges: [],
|
|
1052
|
+
source: this.source,
|
|
1053
|
+
timestamp: Date.now()
|
|
1054
|
+
};
|
|
1055
|
+
}
|
|
1056
|
+
extractFileList(files) {
|
|
1057
|
+
if (Array.isArray(files)) return files.flatMap((f) => {
|
|
1058
|
+
if (typeof f === "string") return [{ path: f }];
|
|
1059
|
+
const rec = f;
|
|
1060
|
+
if (typeof rec.path === "string") return [{
|
|
1061
|
+
path: rec.path,
|
|
1062
|
+
language: rec.language
|
|
1063
|
+
}];
|
|
1064
|
+
return [];
|
|
1065
|
+
});
|
|
1066
|
+
const obj = files;
|
|
1067
|
+
const inner = obj?.files ?? obj?.items;
|
|
1068
|
+
return Array.isArray(inner) ? this.extractFileList(inner) : [];
|
|
1069
|
+
}
|
|
1070
|
+
toAdapterResult(dbNodes, dbEdges) {
|
|
1071
|
+
const nodeIds = new Set(dbNodes.map((n) => n.id));
|
|
1072
|
+
const fileNodeIds = new Map();
|
|
1073
|
+
for (const n of dbNodes) if (n.kind === "file" || n.kind === "module") fileNodeIds.set(n.file_path, n.id);
|
|
1074
|
+
const nodes = dbNodes.map((n) => {
|
|
1075
|
+
const parentId = n.kind !== "file" && n.kind !== "module" && n.kind !== "import" ? fileNodeIds.get(n.file_path) ?? void 0 : void 0;
|
|
1076
|
+
return {
|
|
1077
|
+
id: NodeId(n.id),
|
|
1078
|
+
label: n.name,
|
|
1079
|
+
type: mapNodeKind(n.kind),
|
|
1080
|
+
filePath: n.file_path,
|
|
1081
|
+
lineNumber: n.start_line ?? 1,
|
|
1082
|
+
properties: {
|
|
1083
|
+
kind: n.kind,
|
|
1084
|
+
...n.signature ? { signature: n.signature } : {},
|
|
1085
|
+
...n.docstring ? { docstring: n.docstring } : {},
|
|
1086
|
+
exported: n.is_exported === 1
|
|
1087
|
+
},
|
|
1088
|
+
...parentId ? { parentId: NodeId(parentId) } : {}
|
|
1089
|
+
};
|
|
1090
|
+
});
|
|
1091
|
+
const edges = dbEdges.filter((e) => nodeIds.has(e.source) && nodeIds.has(e.target)).map((e) => ({
|
|
1092
|
+
id: EdgeId(String(e.id)),
|
|
1093
|
+
source: NodeId(e.source),
|
|
1094
|
+
target: NodeId(e.target),
|
|
1095
|
+
type: mapEdgeKind(e.kind),
|
|
1096
|
+
properties: e.line != null ? { line: e.line } : {}
|
|
1097
|
+
}));
|
|
1098
|
+
return {
|
|
1099
|
+
nodes,
|
|
1100
|
+
edges,
|
|
1101
|
+
source: this.source,
|
|
1102
|
+
timestamp: Date.now()
|
|
1103
|
+
};
|
|
1104
|
+
}
|
|
1105
|
+
};
|
|
1106
|
+
|
|
1107
|
+
//#endregion
|
|
1108
|
+
//#region src/adapters/LensAdapter.ts
|
|
1109
|
+
const log$5 = scoped("lens-adapter");
|
|
1110
|
+
var LensAdapter = class {
|
|
1111
|
+
source = "lens";
|
|
1112
|
+
async fetchData(repoId, invoke) {
|
|
1113
|
+
try {
|
|
1114
|
+
const raw = await invoke("lens_analyze", { repoId });
|
|
1115
|
+
if (!raw) return {
|
|
1116
|
+
nodes: [],
|
|
1117
|
+
edges: [],
|
|
1118
|
+
source: this.source,
|
|
1119
|
+
timestamp: Date.now()
|
|
1120
|
+
};
|
|
1121
|
+
const symbols = Array.isArray(raw.symbols) ? raw.symbols : [];
|
|
1122
|
+
const references = Array.isArray(raw.references) ? raw.references : [];
|
|
1123
|
+
const fileNodeMap = new Map();
|
|
1124
|
+
for (const s of symbols) if (s.category === "module" || s.category === "file") fileNodeMap.set(s.file, s.id);
|
|
1125
|
+
const nodes = symbols.map((s) => {
|
|
1126
|
+
const parentId = s.category !== "module" && s.category !== "file" ? fileNodeMap.get(s.file) : void 0;
|
|
1127
|
+
return {
|
|
1128
|
+
id: NodeId(s.id),
|
|
1129
|
+
label: s.name,
|
|
1130
|
+
type: this.mapCategory(s.category),
|
|
1131
|
+
filePath: s.file,
|
|
1132
|
+
lineNumber: s.line,
|
|
1133
|
+
properties: { scope: s.scope },
|
|
1134
|
+
...parentId ? { parentId: NodeId(parentId) } : {}
|
|
1135
|
+
};
|
|
1136
|
+
});
|
|
1137
|
+
const edges = references.map((r) => ({
|
|
1138
|
+
id: EdgeId(`${r.from}->${r.to}`),
|
|
1139
|
+
source: NodeId(r.from),
|
|
1140
|
+
target: NodeId(r.to),
|
|
1141
|
+
type: this.mapRelation(r.relation),
|
|
1142
|
+
properties: {}
|
|
1143
|
+
}));
|
|
1144
|
+
return {
|
|
1145
|
+
nodes,
|
|
1146
|
+
edges,
|
|
1147
|
+
source: this.source,
|
|
1148
|
+
timestamp: Date.now()
|
|
1149
|
+
};
|
|
1150
|
+
} catch (e) {
|
|
1151
|
+
const errorMsg = e instanceof Error ? e.message : String(e);
|
|
1152
|
+
log$5.warn("Lens fetchData failed — lens is optional, returning empty", e);
|
|
1153
|
+
return {
|
|
1154
|
+
nodes: [],
|
|
1155
|
+
edges: [],
|
|
1156
|
+
source: this.source,
|
|
1157
|
+
timestamp: Date.now(),
|
|
1158
|
+
error: errorMsg
|
|
1159
|
+
};
|
|
1160
|
+
}
|
|
1161
|
+
}
|
|
1162
|
+
mapCategory(cat) {
|
|
1163
|
+
const map = {
|
|
1164
|
+
function: "function",
|
|
1165
|
+
class: "class",
|
|
1166
|
+
variable: "variable",
|
|
1167
|
+
module: "module",
|
|
1168
|
+
interface: "interface",
|
|
1169
|
+
type: "type"
|
|
1170
|
+
};
|
|
1171
|
+
return map[cat] ?? "module";
|
|
1172
|
+
}
|
|
1173
|
+
mapRelation(rel) {
|
|
1174
|
+
const map = {
|
|
1175
|
+
call: "call",
|
|
1176
|
+
reference: "dependency",
|
|
1177
|
+
import: "import",
|
|
1178
|
+
extend: "extend",
|
|
1179
|
+
implement: "implement"
|
|
1180
|
+
};
|
|
1181
|
+
return map[rel] ?? "dependency";
|
|
1182
|
+
}
|
|
1183
|
+
};
|
|
1184
|
+
|
|
1185
|
+
//#endregion
|
|
1186
|
+
//#region src/merger/GraphDataMerger.ts
|
|
1187
|
+
var GraphDataMerger = class {
|
|
1188
|
+
merge(results, repoId) {
|
|
1189
|
+
const nodes = new Map();
|
|
1190
|
+
const edges = new Map();
|
|
1191
|
+
for (const r of results) {
|
|
1192
|
+
for (const node of r.nodes) nodes.set(node.id, {
|
|
1193
|
+
...node,
|
|
1194
|
+
properties: {
|
|
1195
|
+
...node.properties,
|
|
1196
|
+
__source: r.source
|
|
1197
|
+
}
|
|
1198
|
+
});
|
|
1199
|
+
for (const edge of r.edges) edges.set(edge.id, {
|
|
1200
|
+
...edge,
|
|
1201
|
+
properties: {
|
|
1202
|
+
...edge.properties,
|
|
1203
|
+
__source: r.source
|
|
1204
|
+
}
|
|
1205
|
+
});
|
|
1206
|
+
}
|
|
1207
|
+
return {
|
|
1208
|
+
nodes: Array.from(nodes.values()),
|
|
1209
|
+
edges: Array.from(edges.values()),
|
|
1210
|
+
metadata: {
|
|
1211
|
+
repoId: RepoId(repoId),
|
|
1212
|
+
timestamp: Date.now(),
|
|
1213
|
+
nodeCount: nodes.size,
|
|
1214
|
+
edgeCount: edges.size
|
|
1215
|
+
}
|
|
1216
|
+
};
|
|
1217
|
+
}
|
|
1218
|
+
applyDelta(current, delta) {
|
|
1219
|
+
const nodes = new Map(current.nodes.map((n) => [n.id, n]));
|
|
1220
|
+
const edges = new Map(current.edges.map((e) => [e.id, e]));
|
|
1221
|
+
for (const node of delta.nodes) {
|
|
1222
|
+
const existing = nodes.get(node.id);
|
|
1223
|
+
if (existing) nodes.set(node.id, {
|
|
1224
|
+
...existing,
|
|
1225
|
+
...node,
|
|
1226
|
+
properties: {
|
|
1227
|
+
...existing.properties,
|
|
1228
|
+
...node.properties
|
|
1229
|
+
}
|
|
1230
|
+
});
|
|
1231
|
+
else nodes.set(node.id, node);
|
|
1232
|
+
}
|
|
1233
|
+
for (const edge of delta.edges) {
|
|
1234
|
+
const existing = edges.get(edge.id);
|
|
1235
|
+
if (existing) edges.set(edge.id, {
|
|
1236
|
+
...existing,
|
|
1237
|
+
...edge,
|
|
1238
|
+
properties: {
|
|
1239
|
+
...existing.properties,
|
|
1240
|
+
...edge.properties
|
|
1241
|
+
}
|
|
1242
|
+
});
|
|
1243
|
+
else edges.set(edge.id, edge);
|
|
1244
|
+
}
|
|
1245
|
+
return {
|
|
1246
|
+
nodes: Array.from(nodes.values()),
|
|
1247
|
+
edges: Array.from(edges.values()),
|
|
1248
|
+
metadata: {
|
|
1249
|
+
...current.metadata,
|
|
1250
|
+
timestamp: Date.now(),
|
|
1251
|
+
nodeCount: nodes.size,
|
|
1252
|
+
edgeCount: edges.size
|
|
1253
|
+
}
|
|
1254
|
+
};
|
|
1255
|
+
}
|
|
1256
|
+
};
|
|
1257
|
+
|
|
1258
|
+
//#endregion
|
|
1259
|
+
//#region src/tools.ts
|
|
1260
|
+
const log$4 = scoped("tools");
|
|
1261
|
+
const codegraphAdapter = new CodeGraphAdapter();
|
|
1262
|
+
const lensAdapter = new LensAdapter();
|
|
1263
|
+
const merger = new GraphDataMerger();
|
|
1264
|
+
const GRAPH_CACHE_LIMIT = 8;
|
|
1265
|
+
const graphCache = new Map();
|
|
1266
|
+
function cacheGraph(repoId, data) {
|
|
1267
|
+
graphCache.delete(repoId);
|
|
1268
|
+
graphCache.set(repoId, data);
|
|
1269
|
+
if (graphCache.size > GRAPH_CACHE_LIMIT) {
|
|
1270
|
+
const oldest = graphCache.keys().next().value;
|
|
1271
|
+
if (oldest !== void 0) graphCache.delete(oldest);
|
|
1272
|
+
}
|
|
1273
|
+
}
|
|
1274
|
+
async function fetchMergedGraph(invoke, repoId, source = "both") {
|
|
1275
|
+
const tasks = [];
|
|
1276
|
+
if (source === "codegraph" || source === "both") tasks.push(codegraphAdapter.fetchData(repoId, invoke));
|
|
1277
|
+
if (source === "lens" || source === "both") tasks.push(lensAdapter.fetchData(repoId, invoke));
|
|
1278
|
+
const settled = await Promise.allSettled(tasks);
|
|
1279
|
+
const results = settled.filter((r) => r.status === "fulfilled").map((r) => r.value);
|
|
1280
|
+
return merger.merge(results, RepoId(repoId));
|
|
1281
|
+
}
|
|
1282
|
+
function summarizeGraph(data) {
|
|
1283
|
+
const nodeByType = new Map();
|
|
1284
|
+
const edgeByType = new Map();
|
|
1285
|
+
for (const n of data.nodes) nodeByType.set(n.type, (nodeByType.get(n.type) ?? 0) + 1);
|
|
1286
|
+
for (const e of data.edges) edgeByType.set(e.type, (edgeByType.get(e.type) ?? 0) + 1);
|
|
1287
|
+
const nodeStats = [...nodeByType.entries()].map(([t, c]) => `${t}:${c}`).join(", ");
|
|
1288
|
+
const edgeStats = [...edgeByType.entries()].map(([t, c]) => `${t}:${c}`).join(", ");
|
|
1289
|
+
const topNodes = data.nodes.slice(0, 10).map((n) => ` • ${n.label} (${n.type}) @ ${n.filePath}:${n.lineNumber}`).join("\n");
|
|
1290
|
+
const topEdges = data.edges.slice(0, 10).map((e) => ` ${e.source} →${e.type}→ ${e.target}`).join("\n");
|
|
1291
|
+
return [
|
|
1292
|
+
`Graph: ${data.metadata.nodeCount} nodes [${nodeStats}], ${data.metadata.edgeCount} edges [${edgeStats}]`,
|
|
1293
|
+
topNodes ? `\nTop nodes:\n${topNodes}` : "",
|
|
1294
|
+
topEdges ? `\nTop edges:\n${topEdges}` : ""
|
|
1295
|
+
].join("");
|
|
1296
|
+
}
|
|
1297
|
+
function normalizeImpact(raw) {
|
|
1298
|
+
if (typeof raw === "string") try {
|
|
1299
|
+
raw = JSON.parse(raw);
|
|
1300
|
+
} catch {
|
|
1301
|
+
log$4.warn("normalizeImpact: JSON.parse failed");
|
|
1302
|
+
return null;
|
|
1303
|
+
}
|
|
1304
|
+
if (!raw || typeof raw !== "object") return null;
|
|
1305
|
+
const obj = raw;
|
|
1306
|
+
const list = obj.affected ?? obj.affectedNodes ?? obj.nodes;
|
|
1307
|
+
if (!Array.isArray(list)) return null;
|
|
1308
|
+
return {
|
|
1309
|
+
affected: list.map((it) => {
|
|
1310
|
+
if (typeof it === "string") return it;
|
|
1311
|
+
const rec = it;
|
|
1312
|
+
return String(rec.name ?? rec.id ?? "?");
|
|
1313
|
+
}),
|
|
1314
|
+
depth: typeof obj.depth === "number" ? obj.depth : 2
|
|
1315
|
+
};
|
|
1316
|
+
}
|
|
1317
|
+
function pickBestMatch(raw, symbolId) {
|
|
1318
|
+
let payload = raw;
|
|
1319
|
+
if (typeof payload === "string") try {
|
|
1320
|
+
payload = JSON.parse(payload);
|
|
1321
|
+
} catch {
|
|
1322
|
+
log$4.warn("normalizeCallers: JSON.parse failed");
|
|
1323
|
+
return null;
|
|
1324
|
+
}
|
|
1325
|
+
const items = Array.isArray(payload) ? payload : payload?.results ?? payload?.nodes;
|
|
1326
|
+
if (!Array.isArray(items) || items.length === 0) return null;
|
|
1327
|
+
const wanted = symbolId.toLowerCase();
|
|
1328
|
+
const best = items.find((it) => {
|
|
1329
|
+
const rec = it;
|
|
1330
|
+
return String(rec.name ?? "").toLowerCase() === wanted || rec.id === symbolId;
|
|
1331
|
+
});
|
|
1332
|
+
const chosen = best ?? items[0];
|
|
1333
|
+
return {
|
|
1334
|
+
symbolId,
|
|
1335
|
+
name: chosen.name ?? chosen.qualified_name ?? symbolId,
|
|
1336
|
+
category: chosen.kind ?? "unknown",
|
|
1337
|
+
file: chosen.filePath ?? chosen.file_path ?? "?",
|
|
1338
|
+
line: chosen.startLine ?? chosen.start_line ?? 0,
|
|
1339
|
+
signature: chosen.signature ?? null
|
|
1340
|
+
};
|
|
1341
|
+
}
|
|
1342
|
+
function createInvoke(ctx, requestTimeout = 5e3) {
|
|
1343
|
+
return async (tool, args) => {
|
|
1344
|
+
try {
|
|
1345
|
+
const result = await ctx.tools.execute({
|
|
1346
|
+
callId: CallId(`codegraph:${tool}`),
|
|
1347
|
+
name: tool,
|
|
1348
|
+
arguments: args,
|
|
1349
|
+
signal: AbortSignal.timeout(requestTimeout)
|
|
1350
|
+
});
|
|
1351
|
+
if (result.isError) return null;
|
|
1352
|
+
return result.value ?? null;
|
|
1353
|
+
} catch (e) {
|
|
1354
|
+
log$4.warn("createInvoke: tool execution failed", {
|
|
1355
|
+
tool,
|
|
1356
|
+
error: e
|
|
1357
|
+
});
|
|
1358
|
+
return null;
|
|
1359
|
+
}
|
|
1360
|
+
};
|
|
1361
|
+
}
|
|
1362
|
+
function renderGraphStatus(_args, value) {
|
|
1363
|
+
const v = value;
|
|
1364
|
+
const srcInfo = v.sources ? ` [codegraph:${v.sources.codegraph ? "✓" : "✗"} lens:${v.sources.lens ? "✓" : "✗"}]` : "";
|
|
1365
|
+
return [{
|
|
1366
|
+
type: "text",
|
|
1367
|
+
text: `Graph status: ${v.status} (${v.nodeCount} nodes, ${v.edgeCount} edges)${srcInfo}`
|
|
1368
|
+
}];
|
|
1369
|
+
}
|
|
1370
|
+
async function executeGraphStatus(args, invoke) {
|
|
1371
|
+
const [cgResult, lensResult] = await Promise.allSettled([codegraphAdapter.fetchData(args.repoId, invoke), lensAdapter.fetchData(args.repoId, invoke)]);
|
|
1372
|
+
const results = [cgResult, lensResult].filter((r) => r.status === "fulfilled").map((r) => r.value);
|
|
1373
|
+
const data = merger.merge(results, RepoId(args.repoId));
|
|
1374
|
+
return {
|
|
1375
|
+
status: data.nodes.length > 0 ? "ready" : "unavailable",
|
|
1376
|
+
nodeCount: data.metadata.nodeCount,
|
|
1377
|
+
edgeCount: data.metadata.edgeCount,
|
|
1378
|
+
sources: {
|
|
1379
|
+
codegraph: cgResult.status === "fulfilled" && cgResult.value.nodes.length > 0,
|
|
1380
|
+
lens: lensResult.status === "fulfilled" && lensResult.value.nodes.length > 0
|
|
1381
|
+
}
|
|
1382
|
+
};
|
|
1383
|
+
}
|
|
1384
|
+
function renderGraphData(_args, value) {
|
|
1385
|
+
const data = value;
|
|
1386
|
+
return [{
|
|
1387
|
+
type: "text",
|
|
1388
|
+
text: summarizeGraph(data)
|
|
1389
|
+
}];
|
|
1390
|
+
}
|
|
1391
|
+
async function executeGraphData(args, invoke, emitUpdate, emitData) {
|
|
1392
|
+
const source = args.source ?? "both";
|
|
1393
|
+
const fresh = await fetchMergedGraph(invoke, args.repoId, source);
|
|
1394
|
+
const cached = graphCache.get(args.repoId);
|
|
1395
|
+
const deltaSource = source === "lens" ? "lens" : "codegraph";
|
|
1396
|
+
const merged = cached ? merger.applyDelta(cached, {
|
|
1397
|
+
nodes: fresh.nodes,
|
|
1398
|
+
edges: fresh.edges,
|
|
1399
|
+
source: deltaSource,
|
|
1400
|
+
timestamp: fresh.metadata.timestamp
|
|
1401
|
+
}) : fresh;
|
|
1402
|
+
cacheGraph(args.repoId, merged);
|
|
1403
|
+
emitUpdate({
|
|
1404
|
+
repoId: args.repoId,
|
|
1405
|
+
nodeCount: merged.metadata.nodeCount,
|
|
1406
|
+
edgeCount: merged.metadata.edgeCount,
|
|
1407
|
+
timestamp: merged.metadata.timestamp
|
|
1408
|
+
});
|
|
1409
|
+
emitData({
|
|
1410
|
+
repoId: args.repoId,
|
|
1411
|
+
nodes: merged.nodes,
|
|
1412
|
+
edges: merged.edges,
|
|
1413
|
+
timestamp: merged.metadata.timestamp
|
|
1414
|
+
});
|
|
1415
|
+
return merged;
|
|
1416
|
+
}
|
|
1417
|
+
function renderGraphSymbol(_args, value) {
|
|
1418
|
+
const v = value;
|
|
1419
|
+
if (!v) return [{
|
|
1420
|
+
type: "text",
|
|
1421
|
+
text: "Symbol not found."
|
|
1422
|
+
}];
|
|
1423
|
+
return [{
|
|
1424
|
+
type: "text",
|
|
1425
|
+
text: `${v.name ?? v.symbolId ?? "?"} (${v.category ?? "unknown"}) @ ${v.file ?? "?"}:${v.line ?? "?"}`
|
|
1426
|
+
}];
|
|
1427
|
+
}
|
|
1428
|
+
async function executeGraphSymbol(args, invoke) {
|
|
1429
|
+
const raw = await invoke("codegraph_query", {
|
|
1430
|
+
search: args.symbolId,
|
|
1431
|
+
limit: 1
|
|
1432
|
+
});
|
|
1433
|
+
return pickBestMatch(raw, args.symbolId);
|
|
1434
|
+
}
|
|
1435
|
+
function renderGraphImpact(_args, value) {
|
|
1436
|
+
const v = value;
|
|
1437
|
+
const count = v.affected?.length ?? 0;
|
|
1438
|
+
const list = v.affected?.slice(0, 10).join(", ") ?? "";
|
|
1439
|
+
return [{
|
|
1440
|
+
type: "text",
|
|
1441
|
+
text: `Impact: ${count} symbols affected (depth ${v.depth ?? 0})${list ? `\n ${list}` : ""}`
|
|
1442
|
+
}];
|
|
1443
|
+
}
|
|
1444
|
+
async function executeGraphImpact(args, invoke) {
|
|
1445
|
+
const raw = await invoke("codegraph_impact", {
|
|
1446
|
+
symbol: args.symbolId,
|
|
1447
|
+
depth: 2
|
|
1448
|
+
});
|
|
1449
|
+
const normalized = normalizeImpact(raw);
|
|
1450
|
+
if (normalized) return normalized;
|
|
1451
|
+
const lens = await invoke("lens_impact", { symbolId: args.symbolId });
|
|
1452
|
+
return lens ?? {
|
|
1453
|
+
affected: [],
|
|
1454
|
+
depth: 0
|
|
1455
|
+
};
|
|
1456
|
+
}
|
|
1457
|
+
const createGraphTools = (ctx, options = {}) => {
|
|
1458
|
+
const invoke = createInvoke(ctx, options.requestTimeout);
|
|
1459
|
+
const emitUpdate = (event) => {
|
|
1460
|
+
ctx.emit("codegraph/graph/updated", event);
|
|
1461
|
+
};
|
|
1462
|
+
const emitData = (event) => {
|
|
1463
|
+
ctx.emit("codegraph/graph/data", event);
|
|
1464
|
+
};
|
|
1465
|
+
const graphStatus = defineTool({
|
|
1466
|
+
name: "graph_status",
|
|
1467
|
+
description: "Check whether an interactive code graph is available for a repository.",
|
|
1468
|
+
parameters: { repoId: {
|
|
1469
|
+
type: "string",
|
|
1470
|
+
required: true,
|
|
1471
|
+
description: "Repository id."
|
|
1472
|
+
} },
|
|
1473
|
+
output: {
|
|
1474
|
+
schema: { type: "json" },
|
|
1475
|
+
render: renderGraphStatus
|
|
1476
|
+
},
|
|
1477
|
+
execute: (args) => executeGraphStatus(args, invoke)
|
|
1478
|
+
});
|
|
1479
|
+
const graphData = defineTool({
|
|
1480
|
+
name: "graph_data",
|
|
1481
|
+
description: "Fetch the merged code relationship graph for a repository (calls + dependencies). Uses incremental delta merge on repeat calls.",
|
|
1482
|
+
parameters: {
|
|
1483
|
+
repoId: {
|
|
1484
|
+
type: "string",
|
|
1485
|
+
required: true,
|
|
1486
|
+
description: "Repository id."
|
|
1487
|
+
},
|
|
1488
|
+
source: {
|
|
1489
|
+
type: "string",
|
|
1490
|
+
enum: [
|
|
1491
|
+
"codegraph",
|
|
1492
|
+
"lens",
|
|
1493
|
+
"both"
|
|
1494
|
+
],
|
|
1495
|
+
description: "Data source; defaults to both."
|
|
1496
|
+
}
|
|
1497
|
+
},
|
|
1498
|
+
output: {
|
|
1499
|
+
schema: { type: "json" },
|
|
1500
|
+
render: renderGraphData
|
|
1501
|
+
},
|
|
1502
|
+
execute: (args) => executeGraphData(args, invoke, emitUpdate, emitData)
|
|
1503
|
+
});
|
|
1504
|
+
const graphSymbol = defineTool({
|
|
1505
|
+
name: "graph_symbol",
|
|
1506
|
+
description: "Resolve the details (file path and line number) of one graph node by symbol id.",
|
|
1507
|
+
parameters: { symbolId: {
|
|
1508
|
+
type: "string",
|
|
1509
|
+
required: true,
|
|
1510
|
+
description: "Symbol id."
|
|
1511
|
+
} },
|
|
1512
|
+
output: {
|
|
1513
|
+
schema: { type: "json" },
|
|
1514
|
+
render: renderGraphSymbol
|
|
1515
|
+
},
|
|
1516
|
+
execute: (args) => executeGraphSymbol(args, invoke)
|
|
1517
|
+
});
|
|
1518
|
+
const graphImpact = defineTool({
|
|
1519
|
+
name: "graph_impact",
|
|
1520
|
+
description: "Analyze the impact of changing one symbol: which symbols are transitively affected.",
|
|
1521
|
+
parameters: { symbolId: {
|
|
1522
|
+
type: "string",
|
|
1523
|
+
required: true,
|
|
1524
|
+
description: "Symbol id to analyze."
|
|
1525
|
+
} },
|
|
1526
|
+
output: {
|
|
1527
|
+
schema: { type: "json" },
|
|
1528
|
+
render: renderGraphImpact
|
|
1529
|
+
},
|
|
1530
|
+
execute: (args) => executeGraphImpact(args, invoke)
|
|
1531
|
+
});
|
|
1532
|
+
return {
|
|
1533
|
+
graphStatus,
|
|
1534
|
+
graphData,
|
|
1535
|
+
graphSymbol,
|
|
1536
|
+
graphImpact
|
|
1537
|
+
};
|
|
1538
|
+
};
|
|
1539
|
+
|
|
1540
|
+
//#endregion
|
|
1541
|
+
//#region src/generated/version.ts
|
|
1542
|
+
const PLUGIN_VERSION = "0.1.0";
|
|
1543
|
+
|
|
1544
|
+
//#endregion
|
|
1545
|
+
//#region src/host/config.ts
|
|
1546
|
+
const DEFAULT_CONFIG = {
|
|
1547
|
+
dataSource: "auto",
|
|
1548
|
+
requestTimeout: 5e3,
|
|
1549
|
+
scanCacheTtl: 3e4,
|
|
1550
|
+
scanCacheLimit: 4,
|
|
1551
|
+
maxBodyBytes: 1024 * 1024,
|
|
1552
|
+
prerequisiteRetryDelay: 3e3,
|
|
1553
|
+
watchDebounce: 500,
|
|
1554
|
+
maxNodes: 1e4
|
|
1555
|
+
};
|
|
1556
|
+
function resolveConfig(userConfig) {
|
|
1557
|
+
const config = {
|
|
1558
|
+
...DEFAULT_CONFIG,
|
|
1559
|
+
...userConfig
|
|
1560
|
+
};
|
|
1561
|
+
const errors = [];
|
|
1562
|
+
if (config.dataSource !== "auto" && config.dataSource !== "codegraph" && config.dataSource !== "lens") errors.push(`dataSource must be auto|codegraph|lens, got ${String(config.dataSource)}`);
|
|
1563
|
+
const positiveFields = [
|
|
1564
|
+
["requestTimeout", config.requestTimeout],
|
|
1565
|
+
["scanCacheTtl", config.scanCacheTtl],
|
|
1566
|
+
["scanCacheLimit", config.scanCacheLimit],
|
|
1567
|
+
["maxBodyBytes", config.maxBodyBytes],
|
|
1568
|
+
["prerequisiteRetryDelay", config.prerequisiteRetryDelay],
|
|
1569
|
+
["watchDebounce", config.watchDebounce],
|
|
1570
|
+
["maxNodes", config.maxNodes]
|
|
1571
|
+
];
|
|
1572
|
+
for (const [field, value] of positiveFields) if (!Number.isFinite(value) || value <= 0) errors.push(`${field} must be a positive finite number, got ${String(value)}`);
|
|
1573
|
+
if (errors.length > 0) throw new Error(`[dsh-codegraph-visualizer] invalid config: ${errors.join("; ")}`);
|
|
1574
|
+
return config;
|
|
1575
|
+
}
|
|
1576
|
+
|
|
1577
|
+
//#endregion
|
|
1578
|
+
//#region src/host/security.ts
|
|
1579
|
+
let allowedWorkspaceRoots = [];
|
|
1580
|
+
function setAllowedWorkspaceRoots(roots) {
|
|
1581
|
+
allowedWorkspaceRoots = roots.map((r) => normalize(r));
|
|
1582
|
+
}
|
|
1583
|
+
function isPathAllowed(path) {
|
|
1584
|
+
if (!path || path === ".") return true;
|
|
1585
|
+
const normalized = normalize(path);
|
|
1586
|
+
if (!isAbsolute(normalized)) return false;
|
|
1587
|
+
if (normalized.includes("..")) return false;
|
|
1588
|
+
if (allowedWorkspaceRoots.length === 0) return false;
|
|
1589
|
+
return allowedWorkspaceRoots.some((root) => normalized === root || normalized.startsWith(root + "\\") || normalized.startsWith(root + "/"));
|
|
1590
|
+
}
|
|
1591
|
+
|
|
1592
|
+
//#endregion
|
|
1593
|
+
//#region src/host/prerequisites.ts
|
|
1594
|
+
const log$3 = scoped("host");
|
|
1595
|
+
function detectCodegraphCli() {
|
|
1596
|
+
try {
|
|
1597
|
+
const cmd = process.platform === "win32" ? "codegraph.cmd" : "codegraph";
|
|
1598
|
+
const r = spawnSync(cmd, ["--version"], {
|
|
1599
|
+
encoding: "utf8",
|
|
1600
|
+
timeout: 3e3,
|
|
1601
|
+
shell: process.platform === "win32"
|
|
1602
|
+
});
|
|
1603
|
+
return r.status === 0;
|
|
1604
|
+
} catch (e) {
|
|
1605
|
+
log$3.warn("detectCodegraphCli failed", e);
|
|
1606
|
+
return false;
|
|
1607
|
+
}
|
|
1608
|
+
}
|
|
1609
|
+
function checkPrerequisites(ctx) {
|
|
1610
|
+
try {
|
|
1611
|
+
const cg = ctx.tools.get("codegraph_status") ?? ctx.tools.get("codegraph_graph") ?? ctx.tools.get("codegraph_query");
|
|
1612
|
+
const lens = ctx.tools.get("lens_analyze");
|
|
1613
|
+
return {
|
|
1614
|
+
codegraph: !!cg || detectCodegraphCli(),
|
|
1615
|
+
lens: !!lens
|
|
1616
|
+
};
|
|
1617
|
+
} catch (e) {
|
|
1618
|
+
log$3.warn("checkPrerequisites failed", e);
|
|
1619
|
+
return {
|
|
1620
|
+
codegraph: detectCodegraphCli(),
|
|
1621
|
+
lens: false
|
|
1622
|
+
};
|
|
1623
|
+
}
|
|
1624
|
+
}
|
|
1625
|
+
function extractWorkspacePaths(ctx) {
|
|
1626
|
+
try {
|
|
1627
|
+
const wsr = ctx.workspaceRegistry;
|
|
1628
|
+
if (wsr?.list) {
|
|
1629
|
+
const workspaces = wsr.list();
|
|
1630
|
+
const paths = workspaces.map((w) => w.path).filter((p) => !!p);
|
|
1631
|
+
if (paths.length > 0) return paths;
|
|
1632
|
+
}
|
|
1633
|
+
} catch (e) {
|
|
1634
|
+
log$3.warn("extractWorkspacePaths: workspaceRegistry failed", e);
|
|
1635
|
+
}
|
|
1636
|
+
try {
|
|
1637
|
+
const sessions = ctx.sessions;
|
|
1638
|
+
if (sessions?.list) {
|
|
1639
|
+
const all = sessions.list();
|
|
1640
|
+
const seen = new Set();
|
|
1641
|
+
const paths = [];
|
|
1642
|
+
for (const session of all) {
|
|
1643
|
+
const cwd = session?.header?.cwd;
|
|
1644
|
+
if (cwd && !seen.has(cwd)) {
|
|
1645
|
+
seen.add(cwd);
|
|
1646
|
+
paths.push(cwd);
|
|
1647
|
+
}
|
|
1648
|
+
}
|
|
1649
|
+
if (paths.length > 0) return paths;
|
|
1650
|
+
}
|
|
1651
|
+
} catch (e) {
|
|
1652
|
+
log$3.warn("extractWorkspacePaths: sessions failed", e);
|
|
1653
|
+
}
|
|
1654
|
+
return [process.cwd()];
|
|
1655
|
+
}
|
|
1656
|
+
function findWorkspacePath(ctx) {
|
|
1657
|
+
try {
|
|
1658
|
+
const wsr = ctx.workspaceRegistry;
|
|
1659
|
+
if (wsr?.list) {
|
|
1660
|
+
const workspaces = wsr.list();
|
|
1661
|
+
if (workspaces.length > 0 && workspaces[0]?.path) return workspaces[0].path;
|
|
1662
|
+
}
|
|
1663
|
+
} catch (e) {
|
|
1664
|
+
log$3.warn("findWorkspacePath: workspaceRegistry failed", e);
|
|
1665
|
+
}
|
|
1666
|
+
try {
|
|
1667
|
+
const sessions = ctx.sessions;
|
|
1668
|
+
if (sessions?.list) {
|
|
1669
|
+
const all = sessions.list();
|
|
1670
|
+
for (const session of all) {
|
|
1671
|
+
const cwd = session?.header?.cwd;
|
|
1672
|
+
if (cwd) return cwd;
|
|
1673
|
+
}
|
|
1674
|
+
}
|
|
1675
|
+
} catch (e) {
|
|
1676
|
+
log$3.warn("findWorkspacePath: sessions failed", e);
|
|
1677
|
+
}
|
|
1678
|
+
return process.cwd();
|
|
1679
|
+
}
|
|
1680
|
+
|
|
1681
|
+
//#endregion
|
|
1682
|
+
//#region src/host/routes.ts
|
|
1683
|
+
const log$2 = scoped("host");
|
|
1684
|
+
function slimGraphData(data, maxNodes) {
|
|
1685
|
+
const cap = maxNodes;
|
|
1686
|
+
const truncated = data.nodes.length > cap;
|
|
1687
|
+
const slimNodes = (truncated ? data.nodes.slice(0, cap) : data.nodes).map((n) => ({
|
|
1688
|
+
id: n.id,
|
|
1689
|
+
label: n.label,
|
|
1690
|
+
type: n.type,
|
|
1691
|
+
filePath: n.filePath,
|
|
1692
|
+
lineNumber: n.lineNumber,
|
|
1693
|
+
properties: n.properties?.exported === true ? { exported: true } : {}
|
|
1694
|
+
}));
|
|
1695
|
+
const allowedIds = new Set(slimNodes.map((n) => n.id));
|
|
1696
|
+
const slimEdges = data.edges.filter((e) => allowedIds.has(e.source) && allowedIds.has(e.target)).map((e) => ({
|
|
1697
|
+
id: e.id,
|
|
1698
|
+
source: e.source,
|
|
1699
|
+
target: e.target,
|
|
1700
|
+
type: e.type,
|
|
1701
|
+
properties: {}
|
|
1702
|
+
}));
|
|
1703
|
+
return {
|
|
1704
|
+
nodes: slimNodes,
|
|
1705
|
+
edges: slimEdges,
|
|
1706
|
+
metadata: {
|
|
1707
|
+
...data.metadata,
|
|
1708
|
+
truncated,
|
|
1709
|
+
nodeCount: slimNodes.length,
|
|
1710
|
+
edgeCount: slimEdges.length,
|
|
1711
|
+
totalNodeCount: data.metadata.totalNodeCount ?? data.nodes.length,
|
|
1712
|
+
totalEdgeCount: data.metadata.totalEdgeCount ?? data.edges.length
|
|
1713
|
+
}
|
|
1714
|
+
};
|
|
1715
|
+
}
|
|
1716
|
+
function createInvokeUpstream(ctx, config) {
|
|
1717
|
+
return async (tool, args) => {
|
|
1718
|
+
try {
|
|
1719
|
+
const result = await ctx.tools.execute({
|
|
1720
|
+
callId: CallId(`codegraph:${tool}`),
|
|
1721
|
+
name: tool,
|
|
1722
|
+
arguments: args,
|
|
1723
|
+
signal: AbortSignal.timeout(config.requestTimeout)
|
|
1724
|
+
});
|
|
1725
|
+
if (result.isError) return null;
|
|
1726
|
+
return result.value ?? null;
|
|
1727
|
+
} catch (e) {
|
|
1728
|
+
log$2.warn("invokeUpstream failed", {
|
|
1729
|
+
tool,
|
|
1730
|
+
error: e
|
|
1731
|
+
});
|
|
1732
|
+
return null;
|
|
1733
|
+
}
|
|
1734
|
+
};
|
|
1735
|
+
}
|
|
1736
|
+
function registerService(deps) {
|
|
1737
|
+
const { ctx, config } = deps;
|
|
1738
|
+
const invokeUpstream = createInvokeUpstream(ctx, config);
|
|
1739
|
+
ctx.effect(() => {
|
|
1740
|
+
const service = {
|
|
1741
|
+
getCurrentGraph: () => deps.getLastGraphData(),
|
|
1742
|
+
getGraphData: async (repoId) => {
|
|
1743
|
+
try {
|
|
1744
|
+
const raw = await fetchMergedGraph(invokeUpstream, repoId, "both");
|
|
1745
|
+
return slimGraphData(raw, config.maxNodes);
|
|
1746
|
+
} catch {
|
|
1747
|
+
return null;
|
|
1748
|
+
}
|
|
1749
|
+
},
|
|
1750
|
+
getSymbolDetail: async (symbolId) => {
|
|
1751
|
+
return invokeUpstream("codegraph_query", {
|
|
1752
|
+
search: symbolId,
|
|
1753
|
+
limit: 1
|
|
1754
|
+
});
|
|
1755
|
+
},
|
|
1756
|
+
getImpactAnalysis: async (symbolId) => {
|
|
1757
|
+
return invokeUpstream("codegraph_impact", {
|
|
1758
|
+
symbol: symbolId,
|
|
1759
|
+
depth: 2
|
|
1760
|
+
});
|
|
1761
|
+
},
|
|
1762
|
+
onGraphUpdate: (callback) => {
|
|
1763
|
+
return ctx.on("codegraph/graph/data", (event) => {
|
|
1764
|
+
callback({
|
|
1765
|
+
nodes: event.nodes,
|
|
1766
|
+
edges: event.edges,
|
|
1767
|
+
metadata: {
|
|
1768
|
+
repoId: event.repoId,
|
|
1769
|
+
timestamp: event.timestamp,
|
|
1770
|
+
nodeCount: event.nodes.length,
|
|
1771
|
+
edgeCount: event.edges.length
|
|
1772
|
+
}
|
|
1773
|
+
});
|
|
1774
|
+
});
|
|
1775
|
+
}
|
|
1776
|
+
};
|
|
1777
|
+
return ctx.provide("graphVisualizer", service);
|
|
1778
|
+
}, "codegraph: service registration");
|
|
1779
|
+
}
|
|
1780
|
+
function sendJson(res, code, data) {
|
|
1781
|
+
res.writeHead(code, { "content-type": "application/json" });
|
|
1782
|
+
res.end(JSON.stringify(data));
|
|
1783
|
+
}
|
|
1784
|
+
function readBody(req, maxBodyBytes) {
|
|
1785
|
+
return new Promise((resolve, reject) => {
|
|
1786
|
+
let body = "";
|
|
1787
|
+
let totalBytes = 0;
|
|
1788
|
+
req.on("data", (chunk) => {
|
|
1789
|
+
if (!chunk) return;
|
|
1790
|
+
totalBytes += chunk.length;
|
|
1791
|
+
if (totalBytes > maxBodyBytes) {
|
|
1792
|
+
reject(new Error("Request body too large"));
|
|
1793
|
+
return;
|
|
1794
|
+
}
|
|
1795
|
+
body += chunk.toString();
|
|
1796
|
+
});
|
|
1797
|
+
req.on("end", () => resolve(body));
|
|
1798
|
+
req.on("error", reject);
|
|
1799
|
+
});
|
|
1800
|
+
}
|
|
1801
|
+
function parseJsonBody(body) {
|
|
1802
|
+
const parsed = JSON.parse(body || "{}");
|
|
1803
|
+
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) throw new Error("Invalid JSON body: expected object");
|
|
1804
|
+
return parsed;
|
|
1805
|
+
}
|
|
1806
|
+
function extractStringField(obj, field) {
|
|
1807
|
+
const v = obj[field];
|
|
1808
|
+
return typeof v === "string" ? v : void 0;
|
|
1809
|
+
}
|
|
1810
|
+
function extractBooleanField(obj, field) {
|
|
1811
|
+
const v = obj[field];
|
|
1812
|
+
return typeof v === "boolean" ? v : void 0;
|
|
1813
|
+
}
|
|
1814
|
+
function registerRoutes(deps) {
|
|
1815
|
+
const { ctx, config } = deps;
|
|
1816
|
+
const invokeUpstream = createInvokeUpstream(ctx, config);
|
|
1817
|
+
ctx.effect(() => ctx.webServer.register({
|
|
1818
|
+
kind: "exact",
|
|
1819
|
+
path: "/api/codegraph/status",
|
|
1820
|
+
handler: (_req, res) => {
|
|
1821
|
+
const status = checkPrerequisites(ctx);
|
|
1822
|
+
sendJson(res, 200, {
|
|
1823
|
+
codegraph: status.codegraph,
|
|
1824
|
+
lens: status.lens
|
|
1825
|
+
});
|
|
1826
|
+
}
|
|
1827
|
+
}), "codegraph: status route");
|
|
1828
|
+
ctx.effect(() => ctx.webServer.register({
|
|
1829
|
+
kind: "exact",
|
|
1830
|
+
path: "/api/codegraph/workspace",
|
|
1831
|
+
handler: (_req, res) => {
|
|
1832
|
+
const current = findWorkspacePath(ctx);
|
|
1833
|
+
const list = extractWorkspacePaths(ctx);
|
|
1834
|
+
sendJson(res, 200, {
|
|
1835
|
+
path: current,
|
|
1836
|
+
list
|
|
1837
|
+
});
|
|
1838
|
+
}
|
|
1839
|
+
}), "codegraph: workspace route");
|
|
1840
|
+
ctx.effect(() => ctx.webServer.register({
|
|
1841
|
+
kind: "exact",
|
|
1842
|
+
path: "/api/codegraph/data",
|
|
1843
|
+
handler: (req, res) => {
|
|
1844
|
+
const ifNoneMatch = req.headers["if-none-match"];
|
|
1845
|
+
const lastGraphData = deps.getLastGraphData();
|
|
1846
|
+
if (ifNoneMatch && lastGraphData) {
|
|
1847
|
+
const clientTimestamp = parseInt(String(ifNoneMatch), 10);
|
|
1848
|
+
if (clientTimestamp >= lastGraphData.metadata.timestamp) {
|
|
1849
|
+
res.writeHead(304, { "etag": String(lastGraphData.metadata.timestamp) });
|
|
1850
|
+
res.end();
|
|
1851
|
+
return;
|
|
1852
|
+
}
|
|
1853
|
+
}
|
|
1854
|
+
if (lastGraphData) {
|
|
1855
|
+
res.writeHead(200, {
|
|
1856
|
+
"content-type": "application/json",
|
|
1857
|
+
"etag": String(lastGraphData.metadata.timestamp)
|
|
1858
|
+
});
|
|
1859
|
+
res.end(JSON.stringify(lastGraphData));
|
|
1860
|
+
} else sendJson(res, 200, {
|
|
1861
|
+
nodes: [],
|
|
1862
|
+
edges: [],
|
|
1863
|
+
metadata: {
|
|
1864
|
+
repoId: null,
|
|
1865
|
+
timestamp: 0,
|
|
1866
|
+
nodeCount: 0,
|
|
1867
|
+
edgeCount: 0
|
|
1868
|
+
}
|
|
1869
|
+
});
|
|
1870
|
+
}
|
|
1871
|
+
}), "codegraph: data route");
|
|
1872
|
+
ctx.effect(() => ctx.webServer.register({
|
|
1873
|
+
kind: "exact",
|
|
1874
|
+
path: "/api/codegraph/scan",
|
|
1875
|
+
handler: async (req, res) => {
|
|
1876
|
+
try {
|
|
1877
|
+
const body = await readBody(req, config.maxBodyBytes);
|
|
1878
|
+
const parsed = parseJsonBody(body);
|
|
1879
|
+
const path = extractStringField(parsed, "path");
|
|
1880
|
+
if (path && path !== "." && !isPathAllowed(path)) {
|
|
1881
|
+
sendJson(res, 403, {
|
|
1882
|
+
success: false,
|
|
1883
|
+
nodes: [],
|
|
1884
|
+
edges: [],
|
|
1885
|
+
metadata: {
|
|
1886
|
+
repoId: null,
|
|
1887
|
+
timestamp: 0,
|
|
1888
|
+
nodeCount: 0,
|
|
1889
|
+
edgeCount: 0
|
|
1890
|
+
}
|
|
1891
|
+
});
|
|
1892
|
+
return;
|
|
1893
|
+
}
|
|
1894
|
+
const scanPath = path && path !== "." ? path : findWorkspacePath(ctx);
|
|
1895
|
+
const repoId = scanPath || `workspace-${Date.now()}`;
|
|
1896
|
+
const scanCache = deps.getScanCache();
|
|
1897
|
+
const cached = scanCache.get(scanPath);
|
|
1898
|
+
if (cached && Date.now() - cached.timestamp < config.scanCacheTtl) {
|
|
1899
|
+
deps.setLastGraphData(cached.data);
|
|
1900
|
+
sendJson(res, 200, {
|
|
1901
|
+
success: true,
|
|
1902
|
+
...cached.data
|
|
1903
|
+
});
|
|
1904
|
+
return;
|
|
1905
|
+
}
|
|
1906
|
+
const inFlight = deps.getScanInFlight();
|
|
1907
|
+
if (inFlight) {
|
|
1908
|
+
const data = await inFlight;
|
|
1909
|
+
sendJson(res, 200, {
|
|
1910
|
+
success: true,
|
|
1911
|
+
...data
|
|
1912
|
+
});
|
|
1913
|
+
return;
|
|
1914
|
+
}
|
|
1915
|
+
const scanPromise = fetchMergedGraph(invokeUpstream, repoId, "both");
|
|
1916
|
+
deps.setScanInFlight(scanPromise);
|
|
1917
|
+
try {
|
|
1918
|
+
const raw = await scanPromise;
|
|
1919
|
+
deps.setScanInFlight(null);
|
|
1920
|
+
const data = slimGraphData(raw, config.maxNodes);
|
|
1921
|
+
deps.setLastGraphData(data);
|
|
1922
|
+
scanCache.set(scanPath, {
|
|
1923
|
+
data,
|
|
1924
|
+
timestamp: Date.now()
|
|
1925
|
+
});
|
|
1926
|
+
if (scanCache.size > config.scanCacheLimit) {
|
|
1927
|
+
const oldest = scanCache.keys().next().value;
|
|
1928
|
+
if (oldest !== void 0) scanCache.delete(oldest);
|
|
1929
|
+
}
|
|
1930
|
+
ctx.emit("codegraph/graph/updated", {
|
|
1931
|
+
repoId,
|
|
1932
|
+
nodeCount: data.metadata.nodeCount,
|
|
1933
|
+
edgeCount: data.metadata.edgeCount,
|
|
1934
|
+
timestamp: data.metadata.timestamp
|
|
1935
|
+
});
|
|
1936
|
+
ctx.emit("codegraph/graph/data", {
|
|
1937
|
+
repoId,
|
|
1938
|
+
nodes: data.nodes,
|
|
1939
|
+
edges: data.edges,
|
|
1940
|
+
timestamp: data.metadata.timestamp
|
|
1941
|
+
});
|
|
1942
|
+
log$2.info("scan completed", {
|
|
1943
|
+
repoId,
|
|
1944
|
+
nodes: data.metadata.nodeCount,
|
|
1945
|
+
edges: data.metadata.edgeCount
|
|
1946
|
+
});
|
|
1947
|
+
sendJson(res, 200, {
|
|
1948
|
+
success: true,
|
|
1949
|
+
...data
|
|
1950
|
+
});
|
|
1951
|
+
} catch (e) {
|
|
1952
|
+
deps.setScanInFlight(null);
|
|
1953
|
+
throw e;
|
|
1954
|
+
}
|
|
1955
|
+
} catch (e) {
|
|
1956
|
+
log$2.error("scan failed", e);
|
|
1957
|
+
sendJson(res, 500, {
|
|
1958
|
+
success: false,
|
|
1959
|
+
nodes: [],
|
|
1960
|
+
edges: [],
|
|
1961
|
+
metadata: {
|
|
1962
|
+
repoId: null,
|
|
1963
|
+
timestamp: 0,
|
|
1964
|
+
nodeCount: 0,
|
|
1965
|
+
edgeCount: 0
|
|
1966
|
+
}
|
|
1967
|
+
});
|
|
1968
|
+
}
|
|
1969
|
+
}
|
|
1970
|
+
}), "codegraph: scan route");
|
|
1971
|
+
ctx.effect(() => ctx.webServer.register({
|
|
1972
|
+
kind: "exact",
|
|
1973
|
+
path: "/api/codegraph/init",
|
|
1974
|
+
handler: async (req, res) => {
|
|
1975
|
+
try {
|
|
1976
|
+
const body = await readBody(req, config.maxBodyBytes);
|
|
1977
|
+
const parsed = parseJsonBody(body);
|
|
1978
|
+
const path = extractStringField(parsed, "path");
|
|
1979
|
+
if (path && path !== "." && !isPathAllowed(path)) {
|
|
1980
|
+
sendJson(res, 403, {
|
|
1981
|
+
success: false,
|
|
1982
|
+
path: "",
|
|
1983
|
+
message: "Path not allowed",
|
|
1984
|
+
timestamp: Date.now()
|
|
1985
|
+
});
|
|
1986
|
+
return;
|
|
1987
|
+
}
|
|
1988
|
+
const initPath = path && path !== "." ? path : findWorkspacePath(ctx);
|
|
1989
|
+
log$2.info("init requested", { path: initPath });
|
|
1990
|
+
const result = await invokeUpstream("codegraph_init", {
|
|
1991
|
+
path: initPath,
|
|
1992
|
+
force: true
|
|
1993
|
+
});
|
|
1994
|
+
const success = result !== null;
|
|
1995
|
+
const initResult = {
|
|
1996
|
+
success,
|
|
1997
|
+
path: initPath,
|
|
1998
|
+
message: success ? "Graph initialized successfully" : "Initialization failed — is dsh-codegraph installed?",
|
|
1999
|
+
timestamp: Date.now()
|
|
2000
|
+
};
|
|
2001
|
+
deps.setLastInitResult(initResult);
|
|
2002
|
+
ctx.emit("codegraph/graph/init-result", initResult);
|
|
2003
|
+
if (success) {
|
|
2004
|
+
const repoId = initPath || `workspace-${Date.now()}`;
|
|
2005
|
+
const data = await fetchMergedGraph(invokeUpstream, repoId, "both");
|
|
2006
|
+
deps.setLastGraphData(data);
|
|
2007
|
+
ctx.emit("codegraph/graph/data", {
|
|
2008
|
+
repoId,
|
|
2009
|
+
nodes: data.nodes,
|
|
2010
|
+
edges: data.edges,
|
|
2011
|
+
timestamp: data.metadata.timestamp
|
|
2012
|
+
});
|
|
2013
|
+
}
|
|
2014
|
+
sendJson(res, 200, initResult);
|
|
2015
|
+
} catch (e) {
|
|
2016
|
+
const errorResult = {
|
|
2017
|
+
success: false,
|
|
2018
|
+
path: "",
|
|
2019
|
+
message: e instanceof Error ? e.message : String(e),
|
|
2020
|
+
timestamp: Date.now()
|
|
2021
|
+
};
|
|
2022
|
+
deps.setLastInitResult(errorResult);
|
|
2023
|
+
sendJson(res, 500, errorResult);
|
|
2024
|
+
}
|
|
2025
|
+
}
|
|
2026
|
+
}), "codegraph: init route");
|
|
2027
|
+
ctx.effect(() => ctx.webServer.register({
|
|
2028
|
+
kind: "exact",
|
|
2029
|
+
path: "/api/codegraph/watch",
|
|
2030
|
+
handler: async (req, res) => {
|
|
2031
|
+
try {
|
|
2032
|
+
const body = await readBody(req, config.maxBodyBytes);
|
|
2033
|
+
const parsed = parseJsonBody(body);
|
|
2034
|
+
const enabled = extractBooleanField(parsed, "enabled");
|
|
2035
|
+
const path = extractStringField(parsed, "path");
|
|
2036
|
+
if (path && path !== "." && !isPathAllowed(path)) {
|
|
2037
|
+
sendJson(res, 403, {
|
|
2038
|
+
success: false,
|
|
2039
|
+
message: "Path not allowed"
|
|
2040
|
+
});
|
|
2041
|
+
return;
|
|
2042
|
+
}
|
|
2043
|
+
const watchPath = path && path !== "." ? path : findWorkspacePath(ctx);
|
|
2044
|
+
ctx.emit("codegraph/watch/toggle", {
|
|
2045
|
+
enabled: !!enabled,
|
|
2046
|
+
path: watchPath,
|
|
2047
|
+
timestamp: Date.now()
|
|
2048
|
+
});
|
|
2049
|
+
sendJson(res, 200, { success: true });
|
|
2050
|
+
} catch (e) {
|
|
2051
|
+
sendJson(res, 500, {
|
|
2052
|
+
success: false,
|
|
2053
|
+
message: e instanceof Error ? e.message : String(e)
|
|
2054
|
+
});
|
|
2055
|
+
}
|
|
2056
|
+
}
|
|
2057
|
+
}), "codegraph: watch route");
|
|
2058
|
+
}
|
|
2059
|
+
|
|
2060
|
+
//#endregion
|
|
2061
|
+
//#region src/host/watcher.ts
|
|
2062
|
+
const log$1 = scoped("host");
|
|
2063
|
+
let watchTimer = null;
|
|
2064
|
+
let activeWatcher = null;
|
|
2065
|
+
function closeActiveWatcher() {
|
|
2066
|
+
if (activeWatcher) {
|
|
2067
|
+
try {
|
|
2068
|
+
activeWatcher.close();
|
|
2069
|
+
} catch {}
|
|
2070
|
+
activeWatcher = null;
|
|
2071
|
+
}
|
|
2072
|
+
if (watchTimer) {
|
|
2073
|
+
clearTimeout(watchTimer);
|
|
2074
|
+
watchTimer = null;
|
|
2075
|
+
}
|
|
2076
|
+
}
|
|
2077
|
+
function registerWatcher(ctx, config, invokeUpstream) {
|
|
2078
|
+
const scanAndPush = async (path) => {
|
|
2079
|
+
log$1.info("scan requested", { path });
|
|
2080
|
+
try {
|
|
2081
|
+
const repoId = path || `workspace-${Date.now()}`;
|
|
2082
|
+
const data = await fetchMergedGraph(invokeUpstream, repoId, "both");
|
|
2083
|
+
ctx.emit("codegraph/graph/updated", {
|
|
2084
|
+
repoId,
|
|
2085
|
+
nodeCount: data.metadata.nodeCount,
|
|
2086
|
+
edgeCount: data.metadata.edgeCount,
|
|
2087
|
+
timestamp: data.metadata.timestamp
|
|
2088
|
+
});
|
|
2089
|
+
ctx.emit("codegraph/graph/data", {
|
|
2090
|
+
repoId,
|
|
2091
|
+
nodes: data.nodes,
|
|
2092
|
+
edges: data.edges,
|
|
2093
|
+
timestamp: data.metadata.timestamp
|
|
2094
|
+
});
|
|
2095
|
+
log$1.info("scan completed", {
|
|
2096
|
+
repoId,
|
|
2097
|
+
nodes: data.metadata.nodeCount,
|
|
2098
|
+
edges: data.metadata.edgeCount
|
|
2099
|
+
});
|
|
2100
|
+
} catch (e) {
|
|
2101
|
+
log$1.error("scan failed", e);
|
|
2102
|
+
}
|
|
2103
|
+
};
|
|
2104
|
+
ctx.effect(() => {
|
|
2105
|
+
const dispose = ctx.on("codegraph/watch/toggle", (event) => {
|
|
2106
|
+
closeActiveWatcher();
|
|
2107
|
+
if (!event.enabled) {
|
|
2108
|
+
log$1.info("watch disabled");
|
|
2109
|
+
return;
|
|
2110
|
+
}
|
|
2111
|
+
log$1.info("watch enabled", { path: event.path });
|
|
2112
|
+
try {
|
|
2113
|
+
activeWatcher = watch(event.path, { recursive: true }, (_eventType, filename) => {
|
|
2114
|
+
if (filename && filename.includes(".codegraph")) return;
|
|
2115
|
+
if (filename && filename.includes("node_modules")) return;
|
|
2116
|
+
if (filename && filename.includes(".git")) return;
|
|
2117
|
+
if (watchTimer) clearTimeout(watchTimer);
|
|
2118
|
+
watchTimer = setTimeout(() => {
|
|
2119
|
+
watchTimer = null;
|
|
2120
|
+
log$1.info("file changed, syncing + re-scanning", { filename });
|
|
2121
|
+
invokeUpstream("codegraph_sync", { path: event.path }).then(() => scanAndPush(event.path)).catch((e) => log$1.error("watch re-scan failed", e));
|
|
2122
|
+
}, config.watchDebounce);
|
|
2123
|
+
});
|
|
2124
|
+
} catch (e) {
|
|
2125
|
+
log$1.error("watch setup failed", e);
|
|
2126
|
+
}
|
|
2127
|
+
});
|
|
2128
|
+
return () => {
|
|
2129
|
+
dispose();
|
|
2130
|
+
closeActiveWatcher();
|
|
2131
|
+
};
|
|
2132
|
+
}, "codegraph: watch toggle listener");
|
|
2133
|
+
}
|
|
2134
|
+
function registerEventListeners(ctx, invokeUpstream) {
|
|
2135
|
+
const scanAndPush = async (path) => {
|
|
2136
|
+
log$1.info("scan requested", { path });
|
|
2137
|
+
try {
|
|
2138
|
+
const repoId = path || `workspace-${Date.now()}`;
|
|
2139
|
+
const data = await fetchMergedGraph(invokeUpstream, repoId, "both");
|
|
2140
|
+
ctx.emit("codegraph/graph/updated", {
|
|
2141
|
+
repoId,
|
|
2142
|
+
nodeCount: data.metadata.nodeCount,
|
|
2143
|
+
edgeCount: data.metadata.edgeCount,
|
|
2144
|
+
timestamp: data.metadata.timestamp
|
|
2145
|
+
});
|
|
2146
|
+
ctx.emit("codegraph/graph/data", {
|
|
2147
|
+
repoId,
|
|
2148
|
+
nodes: data.nodes,
|
|
2149
|
+
edges: data.edges,
|
|
2150
|
+
timestamp: data.metadata.timestamp
|
|
2151
|
+
});
|
|
2152
|
+
log$1.info("scan completed", {
|
|
2153
|
+
repoId,
|
|
2154
|
+
nodes: data.metadata.nodeCount,
|
|
2155
|
+
edges: data.metadata.edgeCount
|
|
2156
|
+
});
|
|
2157
|
+
} catch (e) {
|
|
2158
|
+
log$1.error("scan failed", e);
|
|
2159
|
+
}
|
|
2160
|
+
};
|
|
2161
|
+
ctx.effect(() => ctx.on("codegraph/repo/imported", (event) => {
|
|
2162
|
+
ctx.emit("codegraph/graph/updated", {
|
|
2163
|
+
repoId: event.repoId,
|
|
2164
|
+
nodeCount: 0,
|
|
2165
|
+
edgeCount: 0,
|
|
2166
|
+
timestamp: event.timestamp
|
|
2167
|
+
});
|
|
2168
|
+
}), "codegraph: repo imported listener");
|
|
2169
|
+
ctx.effect(() => ctx.on("codegraph/repo/scanned", (event) => {
|
|
2170
|
+
ctx.emit("codegraph/graph/updated", {
|
|
2171
|
+
repoId: event.repoId,
|
|
2172
|
+
nodeCount: 0,
|
|
2173
|
+
edgeCount: 0,
|
|
2174
|
+
timestamp: event.timestamp
|
|
2175
|
+
});
|
|
2176
|
+
}), "codegraph: repo scanned listener");
|
|
2177
|
+
ctx.effect(() => ctx.on("codegraph/repo/request-scan", async (event) => {
|
|
2178
|
+
await scanAndPush(event.path);
|
|
2179
|
+
}), "codegraph: repo request-scan listener");
|
|
2180
|
+
ctx.effect(() => ctx.on("codegraph/graph/init", async (event) => {
|
|
2181
|
+
log$1.info("init requested", { path: event.path });
|
|
2182
|
+
try {
|
|
2183
|
+
const result = await invokeUpstream("codegraph_init", {
|
|
2184
|
+
path: event.path,
|
|
2185
|
+
force: true
|
|
2186
|
+
});
|
|
2187
|
+
const success = result !== null;
|
|
2188
|
+
ctx.emit("codegraph/graph/init-result", {
|
|
2189
|
+
success,
|
|
2190
|
+
path: event.path,
|
|
2191
|
+
message: success ? "Graph initialized successfully" : "Initialization failed — is dsh-codegraph installed?",
|
|
2192
|
+
timestamp: Date.now()
|
|
2193
|
+
});
|
|
2194
|
+
if (success) await scanAndPush(event.path);
|
|
2195
|
+
} catch (e) {
|
|
2196
|
+
ctx.emit("codegraph/graph/init-result", {
|
|
2197
|
+
success: false,
|
|
2198
|
+
path: event.path,
|
|
2199
|
+
message: e instanceof Error ? e.message : String(e),
|
|
2200
|
+
timestamp: Date.now()
|
|
2201
|
+
});
|
|
2202
|
+
}
|
|
2203
|
+
}), "codegraph: graph init listener");
|
|
2204
|
+
}
|
|
2205
|
+
|
|
2206
|
+
//#endregion
|
|
2207
|
+
//#region src/index.ts
|
|
2208
|
+
const log = scoped("host");
|
|
2209
|
+
const name = "dsh-codegraph-visualizer";
|
|
2210
|
+
const inject = [
|
|
2211
|
+
"tools",
|
|
2212
|
+
"webServer",
|
|
2213
|
+
"sessions",
|
|
2214
|
+
"workspaceRegistry"
|
|
2215
|
+
];
|
|
2216
|
+
function apply(ctx, userConfig) {
|
|
2217
|
+
const config = resolveConfig(userConfig);
|
|
2218
|
+
setAllowedWorkspaceRoots(extractWorkspacePaths(ctx));
|
|
2219
|
+
const { graphStatus, graphData, graphSymbol, graphImpact } = createGraphTools(ctx, { requestTimeout: config.requestTimeout });
|
|
2220
|
+
ctx.effect(() => {
|
|
2221
|
+
const d1 = ctx.tools.register(graphStatus);
|
|
2222
|
+
const d2 = ctx.tools.register(graphData);
|
|
2223
|
+
const d3 = ctx.tools.register(graphSymbol);
|
|
2224
|
+
const d4 = ctx.tools.register(graphImpact);
|
|
2225
|
+
return () => {
|
|
2226
|
+
d1();
|
|
2227
|
+
d2();
|
|
2228
|
+
d3();
|
|
2229
|
+
d4();
|
|
2230
|
+
};
|
|
2231
|
+
}, "codegraph: tool registrations");
|
|
2232
|
+
let lastGraphData = null;
|
|
2233
|
+
let lastInitResult = null;
|
|
2234
|
+
let scanInFlight = null;
|
|
2235
|
+
const scanCache = new Map();
|
|
2236
|
+
const routeDeps = {
|
|
2237
|
+
ctx,
|
|
2238
|
+
config,
|
|
2239
|
+
getLastGraphData: () => lastGraphData,
|
|
2240
|
+
setLastGraphData: (data) => {
|
|
2241
|
+
lastGraphData = data;
|
|
2242
|
+
},
|
|
2243
|
+
getLastInitResult: () => lastInitResult,
|
|
2244
|
+
setLastInitResult: (data) => {
|
|
2245
|
+
lastInitResult = data;
|
|
2246
|
+
},
|
|
2247
|
+
getScanCache: () => scanCache,
|
|
2248
|
+
getScanInFlight: () => scanInFlight,
|
|
2249
|
+
setScanInFlight: (p) => {
|
|
2250
|
+
scanInFlight = p;
|
|
2251
|
+
}
|
|
2252
|
+
};
|
|
2253
|
+
registerService(routeDeps);
|
|
2254
|
+
registerRoutes(routeDeps);
|
|
2255
|
+
const invokeUpstream = createInvokeUpstream(ctx, config);
|
|
2256
|
+
const emitPrereqStatus = () => {
|
|
2257
|
+
const status = checkPrerequisites(ctx);
|
|
2258
|
+
ctx.emit("codegraph/prerequisite/status", {
|
|
2259
|
+
codegraph: status.codegraph,
|
|
2260
|
+
lens: status.lens,
|
|
2261
|
+
timestamp: Date.now()
|
|
2262
|
+
});
|
|
2263
|
+
log.info("prerequisite status", status);
|
|
2264
|
+
};
|
|
2265
|
+
emitPrereqStatus();
|
|
2266
|
+
const prereqTimer = setTimeout(emitPrereqStatus, config.prerequisiteRetryDelay);
|
|
2267
|
+
ctx.effect(() => () => clearTimeout(prereqTimer), "codegraph: prereq re-check timer");
|
|
2268
|
+
ctx.effect(() => ctx.on("codegraph/prerequisite/request", () => {
|
|
2269
|
+
emitPrereqStatus();
|
|
2270
|
+
}), "codegraph: prerequisite request listener");
|
|
2271
|
+
registerEventListeners(ctx, invokeUpstream);
|
|
2272
|
+
registerWatcher(ctx, config, invokeUpstream);
|
|
2273
|
+
}
|
|
2274
|
+
|
|
2275
|
+
//#endregion
|
|
2276
|
+
export { DEFAULT_CONFIG, PLUGIN_VERSION, apply, inject, isPathAllowed, name, resolveConfig, setAllowedWorkspaceRoots };
|
|
2277
|
+
//# sourceMappingURL=index.js.map
|