dsh-diff-approval 0.19.3 → 0.20.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/client.js +2046 -601
- package/lib/index.js +1251 -60
- package/lib/types/client/PathPicker.d.ts +43 -0
- package/lib/types/client/PendingPanel.d.ts +9 -17
- package/lib/types/client/highlight.d.ts +51 -8
- package/lib/types/client/lang.d.ts +8 -0
- package/lib/types/client/locales.d.ts +43 -0
- package/lib/types/client/port.d.ts +5 -1
- package/lib/types/client/settings.d.ts +16 -0
- package/lib/types/client/slots.d.ts +5 -1
- package/lib/types/client/store.d.ts +5 -1
- package/lib/types/client/whole-file-diff.d.ts +21 -0
- package/lib/types/client/windowed-highlight.d.ts +66 -0
- package/lib/types/pending.d.ts +10 -0
- package/lib/types/types.d.ts +51 -0
- package/package.json +1 -13
package/lib/index.js
CHANGED
|
@@ -1,9 +1,873 @@
|
|
|
1
|
+
import { createRequire } from "node:module";
|
|
1
2
|
import { mkdir, readFile, readdir, rename, rm, writeFile } from "node:fs/promises";
|
|
2
3
|
import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
3
4
|
import { dshHomePath, expandHomePath } from "@deepseek-ai/dsh-home-paths";
|
|
4
|
-
import
|
|
5
|
+
import "@deepseek-ai/cordis";
|
|
5
6
|
import { spawn } from "node:child_process";
|
|
6
7
|
import { existsSync } from "node:fs";
|
|
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) => is(type, value);
|
|
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) {
|
|
46
|
+
Binary.is = isArrayBufferLike;
|
|
47
|
+
Binary.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.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.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.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.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.fromHex = fromHex;
|
|
81
|
+
})(Binary || (Binary = {}));
|
|
82
|
+
Binary.fromBase64;
|
|
83
|
+
Binary.toBase64;
|
|
84
|
+
Binary.fromHex;
|
|
85
|
+
Binary.toHex;
|
|
86
|
+
/** Deep-clone common JavaScript values while preserving prototypes and cycles. */
|
|
87
|
+
function clone(source, refs = /* @__PURE__ */ new Map()) {
|
|
88
|
+
if (!source || typeof source !== "object") return source;
|
|
89
|
+
if (is("Date", source)) return new Date(source.valueOf());
|
|
90
|
+
if (is("RegExp", source)) return new RegExp(source.source, source.flags);
|
|
91
|
+
if (isArrayBufferLike(source)) return source.slice(0);
|
|
92
|
+
if (ArrayBuffer.isView(source)) return source.buffer.slice(source.byteOffset, source.byteOffset + source.byteLength);
|
|
93
|
+
const cached = refs.get(source);
|
|
94
|
+
if (cached) return cached;
|
|
95
|
+
if (Array.isArray(source)) {
|
|
96
|
+
const result = [];
|
|
97
|
+
refs.set(source, result);
|
|
98
|
+
source.forEach((value, index) => {
|
|
99
|
+
result[index] = Reflect.apply(clone, null, [value, refs]);
|
|
100
|
+
});
|
|
101
|
+
return result;
|
|
102
|
+
}
|
|
103
|
+
const result = Object.create(Object.getPrototypeOf(source));
|
|
104
|
+
refs.set(source, result);
|
|
105
|
+
for (const key of Reflect.ownKeys(source)) {
|
|
106
|
+
const descriptor = { ...Reflect.getOwnPropertyDescriptor(source, key) };
|
|
107
|
+
if ("value" in descriptor) descriptor.value = Reflect.apply(clone, null, [descriptor.value, refs]);
|
|
108
|
+
Reflect.defineProperty(result, key, descriptor);
|
|
109
|
+
}
|
|
110
|
+
return result;
|
|
111
|
+
}
|
|
112
|
+
/** Deeply compare arrays, dates, regexps, buffers, and plain object fields. */
|
|
113
|
+
function deepEqual(a, b, strict) {
|
|
114
|
+
if (a === b) return true;
|
|
115
|
+
if (!strict && isNullable(a) && isNullable(b)) return true;
|
|
116
|
+
if (typeof a !== typeof b) return false;
|
|
117
|
+
if (typeof a !== "object") return false;
|
|
118
|
+
if (!a || !b) return false;
|
|
119
|
+
function check(test, then) {
|
|
120
|
+
return test(a) ? test(b) ? then(a, b) : false : test(b) ? false : void 0;
|
|
121
|
+
}
|
|
122
|
+
return check(Array.isArray, (a, b) => a.length === b.length && a.every((item, index) => deepEqual(item, b[index]))) ?? check(is("Date"), (a, b) => a.valueOf() === b.valueOf()) ?? check(is("RegExp"), (a, b) => a.source === b.source && a.flags === b.flags) ?? check(isArrayBufferLike, (a, b) => {
|
|
123
|
+
if (a.byteLength !== b.byteLength) return false;
|
|
124
|
+
const viewA = new Uint8Array(a);
|
|
125
|
+
const viewB = new Uint8Array(b);
|
|
126
|
+
for (let i = 0; i < viewA.length; i++) if (viewA[i] !== viewB[i]) return false;
|
|
127
|
+
return true;
|
|
128
|
+
}) ?? Object.keys({
|
|
129
|
+
...a,
|
|
130
|
+
...b
|
|
131
|
+
}).every((key) => deepEqual(a[key], b[key], strict));
|
|
132
|
+
}
|
|
133
|
+
/** Time constants plus parsing and formatting helpers. */
|
|
134
|
+
var Time;
|
|
135
|
+
(function(Time) {
|
|
136
|
+
Time.millisecond = 1;
|
|
137
|
+
Time.second = 1e3;
|
|
138
|
+
Time.minute = Time.second * 60;
|
|
139
|
+
Time.hour = Time.minute * 60;
|
|
140
|
+
Time.day = Time.hour * 24;
|
|
141
|
+
Time.week = Time.day * 7;
|
|
142
|
+
let timezoneOffset = (/* @__PURE__ */ new Date()).getTimezoneOffset();
|
|
143
|
+
function setTimezoneOffset(offset) {
|
|
144
|
+
timezoneOffset = offset;
|
|
145
|
+
}
|
|
146
|
+
Time.setTimezoneOffset = setTimezoneOffset;
|
|
147
|
+
function getTimezoneOffset() {
|
|
148
|
+
return timezoneOffset;
|
|
149
|
+
}
|
|
150
|
+
Time.getTimezoneOffset = getTimezoneOffset;
|
|
151
|
+
function getDateNumber(date = /* @__PURE__ */ new Date(), offset) {
|
|
152
|
+
if (typeof date === "number") date = new Date(date);
|
|
153
|
+
if (offset === void 0) offset = timezoneOffset;
|
|
154
|
+
return Math.floor((date.valueOf() / Time.minute - offset) / 1440);
|
|
155
|
+
}
|
|
156
|
+
Time.getDateNumber = getDateNumber;
|
|
157
|
+
function fromDateNumber(value, offset) {
|
|
158
|
+
const date = new Date(value * Time.day);
|
|
159
|
+
if (offset === void 0) offset = timezoneOffset;
|
|
160
|
+
return new Date(+date + offset * Time.minute);
|
|
161
|
+
}
|
|
162
|
+
Time.fromDateNumber = fromDateNumber;
|
|
163
|
+
const numeric = /\d+(?:\.\d+)?/.source;
|
|
164
|
+
const timeRegExp = new RegExp(`^${[
|
|
165
|
+
"w(?:eek(?:s)?)?",
|
|
166
|
+
"d(?:ay(?:s)?)?",
|
|
167
|
+
"h(?:our(?:s)?)?",
|
|
168
|
+
"m(?:in(?:ute)?(?:s)?)?",
|
|
169
|
+
"s(?:ec(?:ond)?(?:s)?)?"
|
|
170
|
+
].map((unit) => `(${numeric}${unit})?`).join("")}$`);
|
|
171
|
+
function parseTime(source) {
|
|
172
|
+
const capture = timeRegExp.exec(source);
|
|
173
|
+
if (!capture) return 0;
|
|
174
|
+
return (parseFloat(capture[1]) * Time.week || 0) + (parseFloat(capture[2]) * Time.day || 0) + (parseFloat(capture[3]) * Time.hour || 0) + (parseFloat(capture[4]) * Time.minute || 0) + (parseFloat(capture[5]) * Time.second || 0);
|
|
175
|
+
}
|
|
176
|
+
Time.parseTime = parseTime;
|
|
177
|
+
function parseDate(date) {
|
|
178
|
+
const parsed = parseTime(date);
|
|
179
|
+
if (parsed) date = Date.now() + parsed;
|
|
180
|
+
else if (/^\d{1,2}(:\d{1,2}){1,2}$/.test(date)) date = `${(/* @__PURE__ */ new Date()).toLocaleDateString()}-${date}`;
|
|
181
|
+
else if (/^\d{1,2}-\d{1,2}-\d{1,2}(:\d{1,2}){1,2}$/.test(date)) date = `${(/* @__PURE__ */ new Date()).getFullYear()}-${date}`;
|
|
182
|
+
return date ? new Date(date) : /* @__PURE__ */ new Date();
|
|
183
|
+
}
|
|
184
|
+
Time.parseDate = parseDate;
|
|
185
|
+
function format(ms) {
|
|
186
|
+
const abs = Math.abs(ms);
|
|
187
|
+
if (abs >= Time.day - Time.hour / 2) return Math.round(ms / Time.day) + "d";
|
|
188
|
+
else if (abs >= Time.hour - Time.minute / 2) return Math.round(ms / Time.hour) + "h";
|
|
189
|
+
else if (abs >= Time.minute - Time.second / 2) return Math.round(ms / Time.minute) + "m";
|
|
190
|
+
else if (abs >= Time.second) return Math.round(ms / Time.second) + "s";
|
|
191
|
+
return ms + "ms";
|
|
192
|
+
}
|
|
193
|
+
Time.format = format;
|
|
194
|
+
function toDigits(source, length = 2) {
|
|
195
|
+
return source.toString().padStart(length, "0");
|
|
196
|
+
}
|
|
197
|
+
Time.toDigits = toDigits;
|
|
198
|
+
function template(template, time = /* @__PURE__ */ new Date()) {
|
|
199
|
+
return template.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));
|
|
200
|
+
}
|
|
201
|
+
Time.template = template;
|
|
202
|
+
})(Time || (Time = {}));
|
|
203
|
+
//#endregion
|
|
204
|
+
//#region node_modules/.pnpm/@deepseek-ai+schemastery@3.18.1/node_modules/@deepseek-ai/schemastery/lib/index.mjs
|
|
205
|
+
const kSchema = Symbol.for("schemastery");
|
|
206
|
+
const kValidationError = Symbol.for("ValidationError");
|
|
207
|
+
globalThis.__schemastery_index__ ??= 0;
|
|
208
|
+
globalThis.__schemastery_refs__ = void 0;
|
|
209
|
+
var ValidationError = class extends TypeError {
|
|
210
|
+
options;
|
|
211
|
+
name = "ValidationError";
|
|
212
|
+
constructor(message, options) {
|
|
213
|
+
let prefix = "$";
|
|
214
|
+
for (const segment of options.path || []) if (typeof segment === "string") prefix += "." + segment;
|
|
215
|
+
else if (typeof segment === "number") prefix += "[" + segment + "]";
|
|
216
|
+
else if (typeof segment === "symbol") prefix += `[Symbol(${segment.toString()})]`;
|
|
217
|
+
if (prefix.startsWith(".")) prefix = prefix.slice(1);
|
|
218
|
+
super((prefix === "$" ? "" : `${prefix} `) + message);
|
|
219
|
+
this.options = options;
|
|
220
|
+
}
|
|
221
|
+
static is(error) {
|
|
222
|
+
return !!error?.[kValidationError];
|
|
223
|
+
}
|
|
224
|
+
};
|
|
225
|
+
Object.defineProperty(ValidationError.prototype, kValidationError, { value: true });
|
|
226
|
+
const Schema = function(options) {
|
|
227
|
+
const schema = function(data, options = {}) {
|
|
228
|
+
return Schema.resolve(data, schema, options)[0];
|
|
229
|
+
};
|
|
230
|
+
if (options.refs) {
|
|
231
|
+
const refs = mapValues(options.refs, (options) => new Schema(options));
|
|
232
|
+
const getRef = (uid) => refs[uid];
|
|
233
|
+
for (const key in refs) {
|
|
234
|
+
const options = refs[key];
|
|
235
|
+
options.sKey = getRef(options.sKey);
|
|
236
|
+
options.inner = getRef(options.inner);
|
|
237
|
+
options.list = options.list && options.list.map(getRef);
|
|
238
|
+
options.dict = options.dict && mapValues(options.dict, getRef);
|
|
239
|
+
}
|
|
240
|
+
return refs[options.uid];
|
|
241
|
+
}
|
|
242
|
+
Object.assign(schema, options);
|
|
243
|
+
if (typeof schema.callback === "string") try {
|
|
244
|
+
schema.callback = new Function("return " + schema.callback)();
|
|
245
|
+
} catch {}
|
|
246
|
+
Object.defineProperty(schema, "uid", { value: globalThis.__schemastery_index__++ });
|
|
247
|
+
Object.setPrototypeOf(schema, Schema.prototype);
|
|
248
|
+
schema.meta ||= {};
|
|
249
|
+
schema.toString = schema.toString.bind(schema);
|
|
250
|
+
return schema;
|
|
251
|
+
};
|
|
252
|
+
Schema.prototype = Object.create(Function.prototype);
|
|
253
|
+
Schema.prototype[kSchema] = true;
|
|
254
|
+
Object.defineProperty(Schema.prototype, "~standard", { get() {
|
|
255
|
+
return {
|
|
256
|
+
version: 1,
|
|
257
|
+
vendor: "schemastery",
|
|
258
|
+
validate: (value) => {
|
|
259
|
+
try {
|
|
260
|
+
return { value: Schema.resolve(value, this, {})[0] };
|
|
261
|
+
} catch (error) {
|
|
262
|
+
if (ValidationError.is(error)) return { issues: [{
|
|
263
|
+
message: error.message,
|
|
264
|
+
path: error.options.path
|
|
265
|
+
}] };
|
|
266
|
+
throw error;
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
};
|
|
270
|
+
} });
|
|
271
|
+
Schema.ValidationError = ValidationError;
|
|
272
|
+
Schema.prototype.toJSON = function toJSON() {
|
|
273
|
+
if (globalThis.__schemastery_refs__) {
|
|
274
|
+
globalThis.__schemastery_refs__[this.uid] ??= JSON.parse(JSON.stringify({ ...this }));
|
|
275
|
+
return this.uid;
|
|
276
|
+
}
|
|
277
|
+
globalThis.__schemastery_refs__ = { [this.uid]: { ...this } };
|
|
278
|
+
globalThis.__schemastery_refs__[this.uid] = JSON.parse(JSON.stringify({ ...this }));
|
|
279
|
+
const result = {
|
|
280
|
+
uid: this.uid,
|
|
281
|
+
refs: globalThis.__schemastery_refs__
|
|
282
|
+
};
|
|
283
|
+
globalThis.__schemastery_refs__ = void 0;
|
|
284
|
+
return result;
|
|
285
|
+
};
|
|
286
|
+
Schema.prototype.set = function set(key, value) {
|
|
287
|
+
this.dict[key] = value;
|
|
288
|
+
return this;
|
|
289
|
+
};
|
|
290
|
+
Schema.prototype.push = function push(value) {
|
|
291
|
+
this.list.push(value);
|
|
292
|
+
return this;
|
|
293
|
+
};
|
|
294
|
+
function mergeDesc(original, messages) {
|
|
295
|
+
const result = typeof original === "string" ? { "": original } : { ...original };
|
|
296
|
+
for (const locale in messages) {
|
|
297
|
+
const value = messages[locale];
|
|
298
|
+
if (value?.$description || value?.$desc) result[locale] = value.$description || value.$desc;
|
|
299
|
+
else if (typeof value === "string") result[locale] = value;
|
|
300
|
+
}
|
|
301
|
+
return result;
|
|
302
|
+
}
|
|
303
|
+
function getInner(value) {
|
|
304
|
+
return value?.$value ?? value?.$inner;
|
|
305
|
+
}
|
|
306
|
+
function extractKeys(data) {
|
|
307
|
+
return filterKeys(data ?? {}, (key) => !key.startsWith("$"));
|
|
308
|
+
}
|
|
309
|
+
Schema.prototype.i18n = function i18n(messages) {
|
|
310
|
+
const schema = Schema(this);
|
|
311
|
+
const desc = mergeDesc(schema.meta.description, messages);
|
|
312
|
+
if (Object.keys(desc).length) schema.meta.description = desc;
|
|
313
|
+
if (schema.dict) schema.dict = mapValues(schema.dict, (inner, key) => {
|
|
314
|
+
return inner.i18n(mapValues(messages, (data) => getInner(data)?.[key] ?? data?.[key]));
|
|
315
|
+
});
|
|
316
|
+
if (schema.list) schema.list = schema.list.map((inner, index) => {
|
|
317
|
+
return inner.i18n(mapValues(messages, (data = {}) => {
|
|
318
|
+
if (Array.isArray(getInner(data))) return getInner(data)[index];
|
|
319
|
+
if (Array.isArray(data)) return data[index];
|
|
320
|
+
return extractKeys(data);
|
|
321
|
+
}));
|
|
322
|
+
});
|
|
323
|
+
if (schema.inner) schema.inner = schema.inner.i18n(mapValues(messages, (data) => {
|
|
324
|
+
if (getInner(data)) return getInner(data);
|
|
325
|
+
return extractKeys(data);
|
|
326
|
+
}));
|
|
327
|
+
if (schema.sKey) schema.sKey = schema.sKey.i18n(mapValues(messages, (data) => data?.$key));
|
|
328
|
+
return schema;
|
|
329
|
+
};
|
|
330
|
+
Schema.prototype.extra = function extra(key, value) {
|
|
331
|
+
const schema = Schema(this);
|
|
332
|
+
schema.meta = {
|
|
333
|
+
...schema.meta,
|
|
334
|
+
[key]: value
|
|
335
|
+
};
|
|
336
|
+
return schema;
|
|
337
|
+
};
|
|
338
|
+
for (const key of [
|
|
339
|
+
"required",
|
|
340
|
+
"disabled",
|
|
341
|
+
"collapse",
|
|
342
|
+
"hidden",
|
|
343
|
+
"loose"
|
|
344
|
+
]) Object.assign(Schema.prototype, { [key](value = true) {
|
|
345
|
+
const schema = Schema(this);
|
|
346
|
+
schema.meta = {
|
|
347
|
+
...schema.meta,
|
|
348
|
+
[key]: value
|
|
349
|
+
};
|
|
350
|
+
return schema;
|
|
351
|
+
} });
|
|
352
|
+
Schema.prototype.deprecated = function deprecated() {
|
|
353
|
+
const schema = Schema(this);
|
|
354
|
+
schema.meta.badges ||= [];
|
|
355
|
+
schema.meta.badges.push({
|
|
356
|
+
text: "deprecated",
|
|
357
|
+
type: "danger"
|
|
358
|
+
});
|
|
359
|
+
return schema;
|
|
360
|
+
};
|
|
361
|
+
Schema.prototype.experimental = function experimental() {
|
|
362
|
+
const schema = Schema(this);
|
|
363
|
+
schema.meta.badges ||= [];
|
|
364
|
+
schema.meta.badges.push({
|
|
365
|
+
text: "experimental",
|
|
366
|
+
type: "warning"
|
|
367
|
+
});
|
|
368
|
+
return schema;
|
|
369
|
+
};
|
|
370
|
+
Schema.prototype.pattern = function pattern(regexp) {
|
|
371
|
+
const schema = Schema(this);
|
|
372
|
+
const pattern = pick(regexp, ["source", "flags"]);
|
|
373
|
+
schema.meta = {
|
|
374
|
+
...schema.meta,
|
|
375
|
+
pattern
|
|
376
|
+
};
|
|
377
|
+
return schema;
|
|
378
|
+
};
|
|
379
|
+
Schema.prototype.simplify = function simplify(value) {
|
|
380
|
+
if (deepEqual(value, this.meta.default, this.type === "dict")) return null;
|
|
381
|
+
if (isNullable(value)) return value;
|
|
382
|
+
if (this.type === "object" || this.type === "dict") {
|
|
383
|
+
const result = {};
|
|
384
|
+
for (const key in value) {
|
|
385
|
+
const item = (this.type === "object" ? this.dict[key] : this.inner)?.simplify(value[key]);
|
|
386
|
+
if (this.type === "dict" || !isNullable(item)) result[key] = item;
|
|
387
|
+
}
|
|
388
|
+
if (deepEqual(result, this.meta.default, this.type === "dict")) return null;
|
|
389
|
+
return result;
|
|
390
|
+
} else if (this.type === "array" || this.type === "tuple") {
|
|
391
|
+
const result = [];
|
|
392
|
+
value.forEach((value, index) => {
|
|
393
|
+
const schema = this.type === "array" ? this.inner : this.list[index];
|
|
394
|
+
const item = schema ? schema.simplify(value) : value;
|
|
395
|
+
result.push(item);
|
|
396
|
+
});
|
|
397
|
+
return result;
|
|
398
|
+
} else if (this.type === "intersect") {
|
|
399
|
+
const result = {};
|
|
400
|
+
for (const item of this.list) Object.assign(result, item.simplify(value));
|
|
401
|
+
return result;
|
|
402
|
+
} else if (this.type === "union") for (const schema of this.list) try {
|
|
403
|
+
Schema.resolve(value, schema, {});
|
|
404
|
+
return schema.simplify(value);
|
|
405
|
+
} catch {}
|
|
406
|
+
return value;
|
|
407
|
+
};
|
|
408
|
+
Schema.prototype.toString = function toString(inline) {
|
|
409
|
+
return formatters[this.type]?.(this, inline) ?? `Schema<${this.type}>`;
|
|
410
|
+
};
|
|
411
|
+
Schema.prototype.role = function role(role, extra) {
|
|
412
|
+
const schema = Schema(this);
|
|
413
|
+
schema.meta = {
|
|
414
|
+
...schema.meta,
|
|
415
|
+
role,
|
|
416
|
+
extra
|
|
417
|
+
};
|
|
418
|
+
return schema;
|
|
419
|
+
};
|
|
420
|
+
for (const key of [
|
|
421
|
+
"default",
|
|
422
|
+
"link",
|
|
423
|
+
"comment",
|
|
424
|
+
"description",
|
|
425
|
+
"max",
|
|
426
|
+
"min",
|
|
427
|
+
"step"
|
|
428
|
+
]) Object.assign(Schema.prototype, { [key](value) {
|
|
429
|
+
const schema = Schema(this);
|
|
430
|
+
schema.meta = {
|
|
431
|
+
...schema.meta,
|
|
432
|
+
[key]: value
|
|
433
|
+
};
|
|
434
|
+
return schema;
|
|
435
|
+
} });
|
|
436
|
+
const resolvers = {};
|
|
437
|
+
Schema.extend = function extend(type, resolve) {
|
|
438
|
+
resolvers[type] = resolve;
|
|
439
|
+
};
|
|
440
|
+
Schema.resolve = function resolve(data, schema, options = {}, strict = false) {
|
|
441
|
+
if (!schema) return [data];
|
|
442
|
+
if (options.ignore?.(data, schema)) return [data];
|
|
443
|
+
if (isNullable(data) && schema.type !== "lazy") {
|
|
444
|
+
if (schema.meta.required) throw new ValidationError(`missing required value`, options);
|
|
445
|
+
let current = schema;
|
|
446
|
+
let fallback = schema.meta.default;
|
|
447
|
+
while (current?.type === "intersect" && isNullable(fallback)) {
|
|
448
|
+
current = current.list[0];
|
|
449
|
+
fallback = current?.meta.default;
|
|
450
|
+
}
|
|
451
|
+
if (isNullable(fallback)) return [data];
|
|
452
|
+
data = clone(fallback);
|
|
453
|
+
}
|
|
454
|
+
const callback = resolvers[schema.type];
|
|
455
|
+
if (!callback) throw new ValidationError(`unsupported type "${schema.type}"`, options);
|
|
456
|
+
try {
|
|
457
|
+
return callback(data, schema, options, strict);
|
|
458
|
+
} catch (error) {
|
|
459
|
+
if (!schema.meta.loose) throw error;
|
|
460
|
+
return [schema.meta.default];
|
|
461
|
+
}
|
|
462
|
+
};
|
|
463
|
+
Schema.from = function from(source) {
|
|
464
|
+
if (isNullable(source)) return Schema.any();
|
|
465
|
+
else if ([
|
|
466
|
+
"string",
|
|
467
|
+
"number",
|
|
468
|
+
"boolean"
|
|
469
|
+
].includes(typeof source)) return Schema.const(source).required();
|
|
470
|
+
else if (source[kSchema]) return source;
|
|
471
|
+
else if (typeof source === "function") switch (source) {
|
|
472
|
+
case String: return Schema.string().required();
|
|
473
|
+
case Number: return Schema.number().required();
|
|
474
|
+
case Boolean: return Schema.boolean().required();
|
|
475
|
+
case Function: return Schema.function().required();
|
|
476
|
+
default: return Schema.is(source).required();
|
|
477
|
+
}
|
|
478
|
+
else throw new TypeError(`cannot infer schema from ${source}`);
|
|
479
|
+
};
|
|
480
|
+
Schema.lazy = function lazy(builder) {
|
|
481
|
+
const toJSON = () => {
|
|
482
|
+
if (!schema.inner[kSchema]) {
|
|
483
|
+
schema.inner = schema.builder();
|
|
484
|
+
schema.inner.meta = {
|
|
485
|
+
...schema.meta,
|
|
486
|
+
...schema.inner.meta
|
|
487
|
+
};
|
|
488
|
+
}
|
|
489
|
+
return schema.inner.toJSON();
|
|
490
|
+
};
|
|
491
|
+
const schema = new Schema({
|
|
492
|
+
type: "lazy",
|
|
493
|
+
builder,
|
|
494
|
+
inner: { toJSON }
|
|
495
|
+
});
|
|
496
|
+
return schema;
|
|
497
|
+
};
|
|
498
|
+
Schema.natural = function natural() {
|
|
499
|
+
return Schema.number().step(1).min(0);
|
|
500
|
+
};
|
|
501
|
+
Schema.percent = function percent() {
|
|
502
|
+
return Schema.number().step(.01).min(0).max(1).role("slider");
|
|
503
|
+
};
|
|
504
|
+
Schema.date = function date() {
|
|
505
|
+
return Schema.union([Schema.is(Date), Schema.transform(Schema.string().role("datetime"), (value, options) => {
|
|
506
|
+
const date = new Date(value);
|
|
507
|
+
if (isNaN(+date)) throw new ValidationError(`invalid date "${value}"`, options);
|
|
508
|
+
return date;
|
|
509
|
+
}, true)]);
|
|
510
|
+
};
|
|
511
|
+
Schema.regExp = function regExp(flag = "") {
|
|
512
|
+
return Schema.union([Schema.is(RegExp), Schema.transform(Schema.string().role("regexp", { flag }), (value, options) => {
|
|
513
|
+
try {
|
|
514
|
+
return new RegExp(value, flag);
|
|
515
|
+
} catch (e) {
|
|
516
|
+
throw new ValidationError(e.message, options);
|
|
517
|
+
}
|
|
518
|
+
}, true)]);
|
|
519
|
+
};
|
|
520
|
+
Schema.arrayBuffer = function arrayBuffer(encoding) {
|
|
521
|
+
return Schema.union([
|
|
522
|
+
Schema.is(ArrayBuffer),
|
|
523
|
+
Schema.is(SharedArrayBuffer),
|
|
524
|
+
Schema.transform(Schema.any(), (value, options) => {
|
|
525
|
+
if (Binary.isSource(value)) return Binary.fromSource(value);
|
|
526
|
+
throw new ValidationError(`expected ArrayBufferSource but got ${value}`, options);
|
|
527
|
+
}, true),
|
|
528
|
+
...encoding ? [Schema.transform(Schema.string(), (value, options) => {
|
|
529
|
+
try {
|
|
530
|
+
return encoding === "base64" ? Binary.fromBase64(value) : Binary.fromHex(value);
|
|
531
|
+
} catch (e) {
|
|
532
|
+
throw new ValidationError(e.message, options);
|
|
533
|
+
}
|
|
534
|
+
}, true)] : []
|
|
535
|
+
]);
|
|
536
|
+
};
|
|
537
|
+
Schema.extend("lazy", (data, schema, options, strict) => {
|
|
538
|
+
if (!schema.inner[kSchema]) {
|
|
539
|
+
schema.inner = schema.builder();
|
|
540
|
+
schema.inner.meta = {
|
|
541
|
+
...schema.meta,
|
|
542
|
+
...schema.inner.meta
|
|
543
|
+
};
|
|
544
|
+
}
|
|
545
|
+
return Schema.resolve(data, schema.inner, options, strict);
|
|
546
|
+
});
|
|
547
|
+
Schema.extend("any", (data) => {
|
|
548
|
+
return [data];
|
|
549
|
+
});
|
|
550
|
+
Schema.extend("never", (data, _, options) => {
|
|
551
|
+
throw new ValidationError(`expected nullable but got ${data}`, options);
|
|
552
|
+
});
|
|
553
|
+
Schema.extend("const", (data, { value }, options) => {
|
|
554
|
+
if (deepEqual(data, value)) return [value];
|
|
555
|
+
throw new ValidationError(`expected ${value} but got ${data}`, options);
|
|
556
|
+
});
|
|
557
|
+
function checkWithinRange(data, meta, description, options, skipMin = false) {
|
|
558
|
+
const { max = Infinity, min = -Infinity } = meta;
|
|
559
|
+
if (data > max) throw new ValidationError(`expected ${description} <= ${max} but got ${data}`, options);
|
|
560
|
+
if (data < min && !skipMin) throw new ValidationError(`expected ${description} >= ${min} but got ${data}`, options);
|
|
561
|
+
}
|
|
562
|
+
Schema.extend("string", (data, { meta }, options) => {
|
|
563
|
+
if (typeof data !== "string") throw new ValidationError(`expected string but got ${data}`, options);
|
|
564
|
+
if (meta.pattern) {
|
|
565
|
+
const regexp = new RegExp(meta.pattern.source, meta.pattern.flags);
|
|
566
|
+
if (!regexp.test(data)) throw new ValidationError(`expect string to match regexp ${regexp}`, options);
|
|
567
|
+
}
|
|
568
|
+
checkWithinRange(data.length, meta, "string length", options);
|
|
569
|
+
return [data];
|
|
570
|
+
});
|
|
571
|
+
function decimalShift(data, digits) {
|
|
572
|
+
const str = data.toString();
|
|
573
|
+
if (str.includes("e")) return data * Math.pow(10, digits);
|
|
574
|
+
const index = str.indexOf(".");
|
|
575
|
+
if (index === -1) return data * Math.pow(10, digits);
|
|
576
|
+
const frac = str.slice(index + 1);
|
|
577
|
+
const integer = str.slice(0, index);
|
|
578
|
+
if (frac.length <= digits) return +(integer + frac.padEnd(digits, "0"));
|
|
579
|
+
return +(integer + frac.slice(0, digits) + "." + frac.slice(digits));
|
|
580
|
+
}
|
|
581
|
+
function isMultipleOf(data, min, step) {
|
|
582
|
+
step = Math.abs(step);
|
|
583
|
+
if (!/^\d+\.\d+$/.test(step.toString())) return (data - min) % step === 0;
|
|
584
|
+
const index = step.toString().indexOf(".");
|
|
585
|
+
const digits = step.toString().slice(index + 1).length;
|
|
586
|
+
return Math.abs(decimalShift(data, digits) - decimalShift(min, digits)) % decimalShift(step, digits) === 0;
|
|
587
|
+
}
|
|
588
|
+
Schema.extend("number", (data, { meta }, options) => {
|
|
589
|
+
if (typeof data !== "number") throw new ValidationError(`expected number but got ${data}`, options);
|
|
590
|
+
checkWithinRange(data, meta, "number", options);
|
|
591
|
+
const { step } = meta;
|
|
592
|
+
if (step && !isMultipleOf(data, meta.min ?? 0, step)) throw new ValidationError(`expected number multiple of ${step} but got ${data}`, options);
|
|
593
|
+
return [data];
|
|
594
|
+
});
|
|
595
|
+
Schema.extend("boolean", (data, _, options) => {
|
|
596
|
+
if (typeof data === "boolean") return [data];
|
|
597
|
+
throw new ValidationError(`expected boolean but got ${data}`, options);
|
|
598
|
+
});
|
|
599
|
+
Schema.extend("bitset", (data, { bits, meta }, options) => {
|
|
600
|
+
let value = 0, keys = [];
|
|
601
|
+
if (typeof data === "number") {
|
|
602
|
+
value = data;
|
|
603
|
+
for (const key in bits) if (data & bits[key]) keys.push(key);
|
|
604
|
+
} else if (Array.isArray(data)) {
|
|
605
|
+
keys = data;
|
|
606
|
+
for (const key of keys) {
|
|
607
|
+
if (typeof key !== "string") throw new ValidationError(`expected string but got ${key}`, options);
|
|
608
|
+
if (key in bits) value |= bits[key];
|
|
609
|
+
}
|
|
610
|
+
} else throw new ValidationError(`expected number or array but got ${data}`, options);
|
|
611
|
+
if (value === meta.default) return [value];
|
|
612
|
+
return [value, keys];
|
|
613
|
+
});
|
|
614
|
+
Schema.extend("function", (data, _, options) => {
|
|
615
|
+
if (typeof data === "function") return [data];
|
|
616
|
+
throw new ValidationError(`expected function but got ${data}`, options);
|
|
617
|
+
});
|
|
618
|
+
Schema.extend("is", (data, { constructor }, options) => {
|
|
619
|
+
if (typeof constructor === "function") {
|
|
620
|
+
if (data instanceof constructor) return [data];
|
|
621
|
+
throw new ValidationError(`expected ${constructor.name} but got ${data}`, options);
|
|
622
|
+
} else {
|
|
623
|
+
if (isNullable(data)) throw new ValidationError(`expected ${constructor} but got ${data}`, options);
|
|
624
|
+
let prototype = Object.getPrototypeOf(data);
|
|
625
|
+
while (prototype) {
|
|
626
|
+
if (prototype.constructor?.name === constructor) return [data];
|
|
627
|
+
prototype = Object.getPrototypeOf(prototype);
|
|
628
|
+
}
|
|
629
|
+
throw new ValidationError(`expected ${constructor} but got ${data}`, options);
|
|
630
|
+
}
|
|
631
|
+
});
|
|
632
|
+
function property(data, key, schema, options) {
|
|
633
|
+
try {
|
|
634
|
+
const [value, adapted] = Schema.resolve(data[key], schema, {
|
|
635
|
+
...options,
|
|
636
|
+
path: [...options.path || [], key]
|
|
637
|
+
});
|
|
638
|
+
if (adapted !== void 0) data[key] = adapted;
|
|
639
|
+
return value;
|
|
640
|
+
} catch (e) {
|
|
641
|
+
if (!options?.autofix) throw e;
|
|
642
|
+
delete data[key];
|
|
643
|
+
return schema.meta.default;
|
|
644
|
+
}
|
|
645
|
+
}
|
|
646
|
+
Schema.extend("array", (data, { inner, meta }, options) => {
|
|
647
|
+
if (!Array.isArray(data)) throw new ValidationError(`expected array but got ${data}`, options);
|
|
648
|
+
checkWithinRange(data.length, meta, "array length", options, !isNullable(inner.meta.default));
|
|
649
|
+
return [data.map((_, index) => property(data, index, inner, options))];
|
|
650
|
+
});
|
|
651
|
+
Schema.extend("dict", (data, { inner, sKey }, options, strict) => {
|
|
652
|
+
if (!isPlainObject(data)) throw new ValidationError(`expected object but got ${data}`, options);
|
|
653
|
+
const result = {};
|
|
654
|
+
for (const key in data) {
|
|
655
|
+
let rKey;
|
|
656
|
+
try {
|
|
657
|
+
rKey = Schema.resolve(key, sKey, options)[0];
|
|
658
|
+
} catch (error) {
|
|
659
|
+
if (strict) continue;
|
|
660
|
+
throw error;
|
|
661
|
+
}
|
|
662
|
+
result[rKey] = property(data, key, inner, options);
|
|
663
|
+
data[rKey] = data[key];
|
|
664
|
+
if (key !== rKey) delete data[key];
|
|
665
|
+
}
|
|
666
|
+
return [result];
|
|
667
|
+
});
|
|
668
|
+
Schema.extend("tuple", (data, { list }, options, strict) => {
|
|
669
|
+
if (!Array.isArray(data)) throw new ValidationError(`expected array but got ${data}`, options);
|
|
670
|
+
const result = list.map((inner, index) => property(data, index, inner, options));
|
|
671
|
+
if (strict) return [result];
|
|
672
|
+
result.push(...data.slice(list.length));
|
|
673
|
+
return [result];
|
|
674
|
+
});
|
|
675
|
+
function merge(result, data) {
|
|
676
|
+
for (const key in data) {
|
|
677
|
+
if (key in result) continue;
|
|
678
|
+
result[key] = data[key];
|
|
679
|
+
}
|
|
680
|
+
}
|
|
681
|
+
Schema.extend("object", (data, { dict }, options, strict) => {
|
|
682
|
+
if (!isPlainObject(data)) throw new ValidationError(`expected object but got ${data}`, options);
|
|
683
|
+
const result = {};
|
|
684
|
+
for (const key in dict) {
|
|
685
|
+
const value = property(data, key, dict[key], options);
|
|
686
|
+
if (!isNullable(value) || key in data) result[key] = value;
|
|
687
|
+
}
|
|
688
|
+
if (!strict) merge(result, data);
|
|
689
|
+
return [result];
|
|
690
|
+
});
|
|
691
|
+
Schema.extend("union", (data, { list, toString }, options, strict) => {
|
|
692
|
+
const messages = [];
|
|
693
|
+
for (const inner of list) try {
|
|
694
|
+
return Schema.resolve(data, inner, options, strict);
|
|
695
|
+
} catch (error) {
|
|
696
|
+
messages.push(error);
|
|
697
|
+
}
|
|
698
|
+
throw new ValidationError(`expected ${toString()} but got ${JSON.stringify(data)}`, options);
|
|
699
|
+
});
|
|
700
|
+
Schema.extend("intersect", (data, { list, toString }, options, strict) => {
|
|
701
|
+
if (!list.length) return [data];
|
|
702
|
+
let result;
|
|
703
|
+
for (const inner of list) {
|
|
704
|
+
const value = Schema.resolve(data, inner, options, true)[0];
|
|
705
|
+
if (isNullable(value)) continue;
|
|
706
|
+
if (isNullable(result)) result = value;
|
|
707
|
+
else if (typeof result !== typeof value) throw new ValidationError(`expected ${toString()} but got ${JSON.stringify(data)}`, options);
|
|
708
|
+
else if (typeof value === "object") merge(result ??= {}, value);
|
|
709
|
+
else if (result !== value) throw new ValidationError(`expected ${toString()} but got ${JSON.stringify(data)}`, options);
|
|
710
|
+
}
|
|
711
|
+
if (!strict && isPlainObject(data)) merge(result, data);
|
|
712
|
+
return [result];
|
|
713
|
+
});
|
|
714
|
+
Schema.extend("transform", (data, { inner, callback, preserve }, options) => {
|
|
715
|
+
const [result, adapted = data] = Schema.resolve(data, inner, options, true);
|
|
716
|
+
if (preserve) return [callback(result)];
|
|
717
|
+
else return [callback(result), callback(adapted)];
|
|
718
|
+
});
|
|
719
|
+
const formatters = {};
|
|
720
|
+
function defineMethod(name, keys, format) {
|
|
721
|
+
formatters[name] = format;
|
|
722
|
+
Object.assign(Schema, { [name](...args) {
|
|
723
|
+
const schema = new Schema({ type: name });
|
|
724
|
+
keys.forEach((key, index) => {
|
|
725
|
+
switch (key) {
|
|
726
|
+
case "sKey":
|
|
727
|
+
schema.sKey = args[index] ?? Schema.string();
|
|
728
|
+
break;
|
|
729
|
+
case "inner":
|
|
730
|
+
schema.inner = Schema.from(args[index]);
|
|
731
|
+
break;
|
|
732
|
+
case "list":
|
|
733
|
+
schema.list = args[index].map(Schema.from);
|
|
734
|
+
break;
|
|
735
|
+
case "dict":
|
|
736
|
+
schema.dict = mapValues(args[index], Schema.from);
|
|
737
|
+
break;
|
|
738
|
+
case "bits":
|
|
739
|
+
schema.bits = {};
|
|
740
|
+
for (const key in args[index]) {
|
|
741
|
+
if (typeof args[index][key] !== "number") continue;
|
|
742
|
+
schema.bits[key] = args[index][key];
|
|
743
|
+
}
|
|
744
|
+
break;
|
|
745
|
+
case "callback": {
|
|
746
|
+
const callback = schema.callback = args[index];
|
|
747
|
+
callback["toJSON"] ||= () => callback.toString();
|
|
748
|
+
break;
|
|
749
|
+
}
|
|
750
|
+
case "constructor": {
|
|
751
|
+
const constructor = schema.constructor = args[index];
|
|
752
|
+
if (typeof constructor === "function") constructor["toJSON"] ||= () => constructor["name"];
|
|
753
|
+
break;
|
|
754
|
+
}
|
|
755
|
+
default: schema[key] = args[index];
|
|
756
|
+
}
|
|
757
|
+
});
|
|
758
|
+
if (name === "object" || name === "dict") schema.meta.default = {};
|
|
759
|
+
else if (name === "array" || name === "tuple") schema.meta.default = [];
|
|
760
|
+
else if (name === "bitset") schema.meta.default = 0;
|
|
761
|
+
return schema;
|
|
762
|
+
} });
|
|
763
|
+
}
|
|
764
|
+
defineMethod("is", ["constructor"], ({ constructor }) => {
|
|
765
|
+
if (typeof constructor === "function") return constructor.name;
|
|
766
|
+
else return constructor;
|
|
767
|
+
});
|
|
768
|
+
defineMethod("any", [], () => "any");
|
|
769
|
+
defineMethod("never", [], () => "never");
|
|
770
|
+
defineMethod("const", ["value"], ({ value }) => typeof value === "string" ? JSON.stringify(value) : value);
|
|
771
|
+
defineMethod("string", [], () => "string");
|
|
772
|
+
defineMethod("number", [], () => "number");
|
|
773
|
+
defineMethod("boolean", [], () => "boolean");
|
|
774
|
+
defineMethod("bitset", ["bits"], () => "bitset");
|
|
775
|
+
defineMethod("function", [], () => "function");
|
|
776
|
+
defineMethod("array", ["inner"], ({ inner }) => `${inner.toString(true)}[]`);
|
|
777
|
+
defineMethod("dict", ["inner", "sKey"], ({ inner, sKey }) => `{ [key: ${sKey.toString()}]: ${inner.toString()} }`);
|
|
778
|
+
defineMethod("tuple", ["list"], ({ list }) => `[${list.map((inner) => inner.toString()).join(", ")}]`);
|
|
779
|
+
defineMethod("object", ["dict"], ({ dict }) => {
|
|
780
|
+
if (Object.keys(dict).length === 0) return "{}";
|
|
781
|
+
return `{ ${Object.entries(dict).map(([key, inner]) => {
|
|
782
|
+
return `${key}${inner.meta.required ? "" : "?"}: ${inner.toString()}`;
|
|
783
|
+
}).join(", ")} }`;
|
|
784
|
+
});
|
|
785
|
+
defineMethod("union", ["list"], ({ list }, inline) => {
|
|
786
|
+
const result = list.map(({ toString: format }) => format()).join(" | ");
|
|
787
|
+
return inline ? `(${result})` : result;
|
|
788
|
+
});
|
|
789
|
+
defineMethod("intersect", ["list"], ({ list }) => {
|
|
790
|
+
return `${list.map((inner) => inner.toString(true)).join(" & ")}`;
|
|
791
|
+
});
|
|
792
|
+
defineMethod("transform", [
|
|
793
|
+
"inner",
|
|
794
|
+
"callback",
|
|
795
|
+
"preserve"
|
|
796
|
+
], ({ inner }, isInner) => inner.toString(isInner));
|
|
797
|
+
//#endregion
|
|
798
|
+
//#region node_modules/.pnpm/@deepseek-ai+dsh-timeout@0.1.0-rc.6_@deepseek-ai+cordis@4.0.1_@deepseek-ai+dsh-invarian_8c173ab999b05cf1db05d479dd44e888/node_modules/@deepseek-ai/dsh-timeout/lib/index.js
|
|
799
|
+
/** Largest delay Node schedules without clamping it to one millisecond. */
|
|
800
|
+
const MAX_TIMER_DELAY_MS = 2147483647;
|
|
801
|
+
//#endregion
|
|
802
|
+
//#region node_modules/.pnpm/@deepseek-ai+dsh-llm@0.1.0-rc.6_@deepseek-ai+cordis@4.0.1_@deepseek-ai+dsh-attachment@0_4ed4e5c71eb965b0bd6912871e829940/node_modules/@deepseek-ai/dsh-llm/lib/index.js
|
|
803
|
+
/**
|
|
804
|
+
* Canonical provider-neutral code for a response that completed normally but
|
|
805
|
+
* carried no content blocks at all. Providers occasionally emit a degenerate
|
|
806
|
+
* completion (a terminal stop with zero output); adapters classify it as this
|
|
807
|
+
* failure instead of yielding an empty assistant message, because an empty
|
|
808
|
+
* message silently ends the turn with nothing for the user or the loop to act
|
|
809
|
+
* on. The attempt produced nothing durable, so retry policy treats it as safe
|
|
810
|
+
* to repeat.
|
|
811
|
+
*/
|
|
812
|
+
const EMPTY_RESPONSE_CODE = "EMPTY_RESPONSE";
|
|
813
|
+
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");
|
|
814
|
+
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");
|
|
815
|
+
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");
|
|
816
|
+
/**
|
|
817
|
+
* Provider-owned request-retry policy configuration and resolution.
|
|
818
|
+
*
|
|
819
|
+
* Adapters expose one resolved policy per registered provider route; the
|
|
820
|
+
* optional dsh-llm-retry plugin executes it on the agent's failed-step extension point.
|
|
821
|
+
*
|
|
822
|
+
* @module @deepseek-ai/dsh-llm/retry-policy
|
|
823
|
+
*/
|
|
824
|
+
const DEFAULT_MAX_RETRIES = 2;
|
|
825
|
+
const DEFAULT_INITIAL_DELAY_MS = 500;
|
|
826
|
+
const DEFAULT_MAX_DELAY_MS = 1e4;
|
|
827
|
+
const DEFAULT_JITTER_RATIO = .1;
|
|
828
|
+
const DEFAULT_RETRYABLE_CODES = Object.freeze([
|
|
829
|
+
EMPTY_RESPONSE_CODE,
|
|
830
|
+
"RATE_LIMIT",
|
|
831
|
+
"SERVER",
|
|
832
|
+
"TIMEOUT",
|
|
833
|
+
"TRANSPORT"
|
|
834
|
+
]);
|
|
835
|
+
const backoffSchema = Schema.object({
|
|
836
|
+
initialDelayMs: Schema.number().max(MAX_TIMER_DELAY_MS).default(DEFAULT_INITIAL_DELAY_MS),
|
|
837
|
+
maxDelayMs: Schema.number().max(MAX_TIMER_DELAY_MS).default(DEFAULT_MAX_DELAY_MS),
|
|
838
|
+
jitterRatio: Schema.number().min(0).max(1).default(DEFAULT_JITTER_RATIO)
|
|
839
|
+
});
|
|
840
|
+
const normalPolicySchema = Schema.object({
|
|
841
|
+
mode: Schema.const("normal").required(),
|
|
842
|
+
maxRetries: Schema.number().step(1).min(0).max(Number.MAX_SAFE_INTEGER).default(DEFAULT_MAX_RETRIES),
|
|
843
|
+
retryableCodes: Schema.array(Schema.string()).default([...DEFAULT_RETRYABLE_CODES]),
|
|
844
|
+
backoff: backoffSchema
|
|
845
|
+
});
|
|
846
|
+
const alwaysPolicySchema = Schema.object({
|
|
847
|
+
mode: Schema.const("always").required(),
|
|
848
|
+
backoff: backoffSchema
|
|
849
|
+
});
|
|
850
|
+
Schema.union([normalPolicySchema, alwaysPolicySchema]);
|
|
851
|
+
/**
|
|
852
|
+
* Centralize the non-secret product identity every provider request sends as `User-Agent`, keeping
|
|
853
|
+
* adapters from drifting. See
|
|
854
|
+
* `.agents/notes/implemented/architecture/2026-06-21-mandatory-app-attribution-headers.md`.
|
|
855
|
+
*
|
|
856
|
+
* App-attribution vocabulary for provider requests.
|
|
857
|
+
* @module @deepseek-ai/dsh-llm/attribution
|
|
858
|
+
*/
|
|
859
|
+
const { version } = createRequire(import.meta.url)("../package.json");
|
|
860
|
+
//#endregion
|
|
861
|
+
//#region node_modules/.pnpm/@deepseek-ai+dsh-session@0.1.0-rc.6_6fd26f59436a18b115f326d6060415e6/node_modules/@deepseek-ai/dsh-session/lib/index.js
|
|
862
|
+
/**
|
|
863
|
+
* Brand a string as a {@link SessionId}.
|
|
864
|
+
* @param id - the raw session id string.
|
|
865
|
+
* @returns the same string, branded (a compile-time cast — no runtime cost).
|
|
866
|
+
*/
|
|
867
|
+
function SessionId(id) {
|
|
868
|
+
return id;
|
|
869
|
+
}
|
|
870
|
+
//#endregion
|
|
7
871
|
//#region lib/types/pending.js
|
|
8
872
|
/**
|
|
9
873
|
* In-memory pending-diff store: one entry per file path, globally, holding the
|
|
@@ -138,6 +1002,18 @@ var PendingDiffStore = class {
|
|
|
138
1002
|
return true;
|
|
139
1003
|
}
|
|
140
1004
|
/**
|
|
1005
|
+
* Admit one entry into the list without the change guard {@link fold} applies.
|
|
1006
|
+
* A listed entry may carry no diff at all: a path the user added by hand has
|
|
1007
|
+
* no local change until one appears, and a fully-resolved file has already
|
|
1008
|
+
* folded its diff away. This is the guard-free put {@link restore} performs,
|
|
1009
|
+
* named for its other caller.
|
|
1010
|
+
* @param entry - the entry to insert or replace by path.
|
|
1011
|
+
* @returns whether the store changed.
|
|
1012
|
+
*/
|
|
1013
|
+
insert(entry) {
|
|
1014
|
+
return this.restore(entry);
|
|
1015
|
+
}
|
|
1016
|
+
/**
|
|
141
1017
|
* Merge persisted entries into the store, one per path after folding. A live
|
|
142
1018
|
* entry wins over a persisted one only when its time is newer (folders are
|
|
143
1019
|
* applied in capture order, so a later persisted capture is strictly newer).
|
|
@@ -820,6 +1696,50 @@ function writeOutcomeOf(value) {
|
|
|
820
1696
|
function errorMessage(error) {
|
|
821
1697
|
return error instanceof Error ? error.message : String(error);
|
|
822
1698
|
}
|
|
1699
|
+
/** Directories one browse level hides: VCS/build noise a review list never wants.
|
|
1700
|
+
* The path box can still reach them by typing the path outright. */
|
|
1701
|
+
const BROWSE_HIDDEN_NAMES = /* @__PURE__ */ new Set([".git", "node_modules"]);
|
|
1702
|
+
/** Cap on one browse level's children: the panel renders a list, not a dump of a
|
|
1703
|
+
* huge directory, and it reports `truncated` rather than silently cutting. */
|
|
1704
|
+
const BROWSE_ENTRY_CAP = 500;
|
|
1705
|
+
/** Cap on the files one no-change walk reads: ticking the box on a directory
|
|
1706
|
+
* asks for "everything under here", which must not mean reading a whole tree
|
|
1707
|
+
* (every file's text) inside one call. */
|
|
1708
|
+
const ADD_UNCHANGED_CAP = 300;
|
|
1709
|
+
/**
|
|
1710
|
+
* One absolute path as a workspace-relative path with `/` separators, or
|
|
1711
|
+
* `undefined` when it lies outside the root. `''` is the root itself.
|
|
1712
|
+
* @param root - the workspace root.
|
|
1713
|
+
* @param absolute - the path to express relative to it.
|
|
1714
|
+
* @returns the relative path, or undefined when outside.
|
|
1715
|
+
*/
|
|
1716
|
+
function workspaceRelativeOf(root, absolute) {
|
|
1717
|
+
const rel = relative(resolve(root), resolve(absolute));
|
|
1718
|
+
if (rel === "") return "";
|
|
1719
|
+
if (isAbsolute(rel)) return void 0;
|
|
1720
|
+
const parts = rel.split(/[\\/]/);
|
|
1721
|
+
if (parts[0] === "..") return void 0;
|
|
1722
|
+
return parts.join("/");
|
|
1723
|
+
}
|
|
1724
|
+
/**
|
|
1725
|
+
* Resolve one caller-supplied path against the workspace root. A relative path
|
|
1726
|
+
* is taken as workspace-relative; an absolute one must still land inside.
|
|
1727
|
+
* @param root - the workspace root.
|
|
1728
|
+
* @param input - the caller's path (absolute or workspace-relative).
|
|
1729
|
+
* @returns the absolute path, or undefined when it escapes the workspace.
|
|
1730
|
+
*/
|
|
1731
|
+
function resolveInsideWorkspace(root, input) {
|
|
1732
|
+
const absolute = isAbsolute(input) ? resolve(input) : resolve(root, input);
|
|
1733
|
+
return workspaceRelativeOf(root, absolute) === void 0 ? void 0 : absolute;
|
|
1734
|
+
}
|
|
1735
|
+
/** The workspace-relative parent of a relative directory path (`''` at the root). */
|
|
1736
|
+
/** Fold one path for comparison: absolute, `/`-separated, case-folded on Windows.
|
|
1737
|
+
* Entries are keyed by the path spelling their capture carried (a tool's display
|
|
1738
|
+
* path or a scan's absolute one), so an equality test has to normalize first. */
|
|
1739
|
+
function pathIdentity(absolute) {
|
|
1740
|
+
const unified = resolve(absolute).split(/[\\/]/).join("/");
|
|
1741
|
+
return process.platform === "win32" ? unified.toLowerCase() : unified;
|
|
1742
|
+
}
|
|
823
1743
|
/** Narrow a tool-execution-shaped value to its name, call id, and agent. */
|
|
824
1744
|
function actorOf(value) {
|
|
825
1745
|
if (typeof value !== "object" || value === null) return void 0;
|
|
@@ -1103,6 +2023,138 @@ function apply(ctx, config) {
|
|
|
1103
2023
|
};
|
|
1104
2024
|
}
|
|
1105
2025
|
/**
|
|
2026
|
+
* Fold a batch of entries into one session's list as a single undoable action.
|
|
2027
|
+
* Nothing touches the files, so the batch is undone by restoring each affected
|
|
2028
|
+
* path's pre-fold entry (or removing it when the path was not listed), which is
|
|
2029
|
+
* what the import and the hand-add path both want.
|
|
2030
|
+
* @param sessionId - the session whose list gains the entries.
|
|
2031
|
+
* @param entries - the entries to fold, in capture order.
|
|
2032
|
+
* @param admitNoDiff - also admit entries that carry no diff at all (the
|
|
2033
|
+
* guard-free insert), which is how a hand-added clean path is listed.
|
|
2034
|
+
* @returns how many entries landed; 0 leaves the store, persistence, and the
|
|
2035
|
+
* undo queue untouched.
|
|
2036
|
+
*/
|
|
2037
|
+
async function foldBatch(sessionId, entries, admitNoDiff = false) {
|
|
2038
|
+
await ensureLoaded();
|
|
2039
|
+
const before = new Map(store.list(sessionId).map((entry) => [entry.path, entry]));
|
|
2040
|
+
let folded = 0;
|
|
2041
|
+
const changedPaths = [];
|
|
2042
|
+
for (const entry of entries) if (entry.oldText === entry.newText ? admitNoDiff && store.insert(entry) : store.fold(entry)) {
|
|
2043
|
+
folded += 1;
|
|
2044
|
+
changedPaths.push(entry.path);
|
|
2045
|
+
}
|
|
2046
|
+
if (folded === 0) return 0;
|
|
2047
|
+
persistSession(true);
|
|
2048
|
+
const after = new Map(store.list(sessionId).map((entry) => [entry.path, entry]));
|
|
2049
|
+
const batchBefore = [];
|
|
2050
|
+
const batchAfter = [];
|
|
2051
|
+
for (const path of changedPaths) {
|
|
2052
|
+
const final = after.get(path);
|
|
2053
|
+
if (final === void 0) continue;
|
|
2054
|
+
const pre = before.get(path);
|
|
2055
|
+
batchAfter.push({
|
|
2056
|
+
id: final.id,
|
|
2057
|
+
path,
|
|
2058
|
+
entry: final,
|
|
2059
|
+
fileText: void 0
|
|
2060
|
+
});
|
|
2061
|
+
batchBefore.push({
|
|
2062
|
+
id: final.id,
|
|
2063
|
+
path,
|
|
2064
|
+
entry: pre,
|
|
2065
|
+
fileText: void 0
|
|
2066
|
+
});
|
|
2067
|
+
}
|
|
2068
|
+
if (batchBefore.length > 0) pushUndo(sessionId, {
|
|
2069
|
+
id: batchBefore[0].id,
|
|
2070
|
+
path: batchBefore[0].path,
|
|
2071
|
+
entry: void 0,
|
|
2072
|
+
fileText: void 0,
|
|
2073
|
+
batch: batchBefore
|
|
2074
|
+
}, {
|
|
2075
|
+
id: batchAfter[0].id,
|
|
2076
|
+
path: batchAfter[0].path,
|
|
2077
|
+
entry: void 0,
|
|
2078
|
+
fileText: void 0,
|
|
2079
|
+
batch: batchAfter
|
|
2080
|
+
});
|
|
2081
|
+
return folded;
|
|
2082
|
+
}
|
|
2083
|
+
/**
|
|
2084
|
+
* One path's text, or `undefined` when it is absent or not readable as text
|
|
2085
|
+
* (a binary, an unreadable permission). An empty file reads as `''`, which is
|
|
2086
|
+
* a value: a listed entry may carry no content at all.
|
|
2087
|
+
* @param absolute - the path to read.
|
|
2088
|
+
* @param signal - caller lifetime.
|
|
2089
|
+
* @returns the text, or undefined.
|
|
2090
|
+
*/
|
|
2091
|
+
async function readTextOrNone(absolute, signal) {
|
|
2092
|
+
try {
|
|
2093
|
+
return await ctx.fs.readText(await ctx.fs.resolve(absolute, { signal }), signal);
|
|
2094
|
+
} catch {
|
|
2095
|
+
return;
|
|
2096
|
+
}
|
|
2097
|
+
}
|
|
2098
|
+
/**
|
|
2099
|
+
* Every regular file under one directory, with its text. Breadth-first in the
|
|
2100
|
+
* backend's name order, hiding the browse's noise names, skipping whatever is
|
|
2101
|
+
* not readable as text, and stopping at {@link ADD_UNCHANGED_CAP} files so
|
|
2102
|
+
* "include paths with no change" cannot read an unbounded tree in one call.
|
|
2103
|
+
* Symlinked directories are followed once, so a cycle ends rather than loops.
|
|
2104
|
+
* @param root - the resolved directory target to walk.
|
|
2105
|
+
* @param rootAbsolute - that directory's absolute path.
|
|
2106
|
+
* @param signal - caller lifetime.
|
|
2107
|
+
* @returns the files found and whether the cap cut the walk short.
|
|
2108
|
+
*/
|
|
2109
|
+
async function collectFilesUnder(root, rootAbsolute, signal) {
|
|
2110
|
+
const files = [];
|
|
2111
|
+
const visited = /* @__PURE__ */ new Set();
|
|
2112
|
+
if (typeof root.targetKey === "string" && root.targetKey !== "") visited.add(root.targetKey);
|
|
2113
|
+
const queue = [{
|
|
2114
|
+
absolute: rootAbsolute,
|
|
2115
|
+
target: root
|
|
2116
|
+
}];
|
|
2117
|
+
while (queue.length > 0) {
|
|
2118
|
+
const current = queue.shift();
|
|
2119
|
+
if (current === void 0) break;
|
|
2120
|
+
let children;
|
|
2121
|
+
try {
|
|
2122
|
+
children = await ctx.fs.listDir(current.target, signal);
|
|
2123
|
+
} catch {
|
|
2124
|
+
continue;
|
|
2125
|
+
}
|
|
2126
|
+
for (const child of children) {
|
|
2127
|
+
if (BROWSE_HIDDEN_NAMES.has(child.name)) continue;
|
|
2128
|
+
const absolute = resolve(current.absolute, child.name);
|
|
2129
|
+
if (child.type === "directory") {
|
|
2130
|
+
const key = child.target.targetKey;
|
|
2131
|
+
if (typeof key === "string" && key !== "") {
|
|
2132
|
+
if (visited.has(key)) continue;
|
|
2133
|
+
visited.add(key);
|
|
2134
|
+
}
|
|
2135
|
+
queue.push({
|
|
2136
|
+
absolute,
|
|
2137
|
+
target: child.target
|
|
2138
|
+
});
|
|
2139
|
+
continue;
|
|
2140
|
+
}
|
|
2141
|
+
if (child.type !== "file") continue;
|
|
2142
|
+
if (files.length >= ADD_UNCHANGED_CAP) return {
|
|
2143
|
+
files,
|
|
2144
|
+
truncated: true
|
|
2145
|
+
};
|
|
2146
|
+
files.push({
|
|
2147
|
+
path: absolute,
|
|
2148
|
+
content: await readTextOrNone(absolute, signal)
|
|
2149
|
+
});
|
|
2150
|
+
}
|
|
2151
|
+
}
|
|
2152
|
+
return {
|
|
2153
|
+
files,
|
|
2154
|
+
truncated: false
|
|
2155
|
+
};
|
|
2156
|
+
}
|
|
2157
|
+
/**
|
|
1106
2158
|
* The workspace whose session account holds `sessionId`. Web sessions are
|
|
1107
2159
|
* attached to a workspace at creation, so an unowned session is the
|
|
1108
2160
|
* memory-only edge (its entries never persist).
|
|
@@ -1690,66 +2742,19 @@ function apply(ctx, config) {
|
|
|
1690
2742
|
} catch (error) {
|
|
1691
2743
|
return rpcError(`import failed: ${errorMessage(error)}`);
|
|
1692
2744
|
}
|
|
1693
|
-
await ensureLoaded();
|
|
1694
|
-
const before = new Map(store.list(sessionId).map((entry) => [entry.path, entry]));
|
|
1695
|
-
let imported = 0;
|
|
1696
|
-
const changedPaths = [];
|
|
1697
|
-
for (const change of changes) {
|
|
1698
|
-
const entry = {
|
|
1699
|
-
id: change.path,
|
|
1700
|
-
sessionId,
|
|
1701
|
-
path: change.path,
|
|
1702
|
-
kind: change.kind,
|
|
1703
|
-
oldText: change.oldText,
|
|
1704
|
-
newText: change.newText,
|
|
1705
|
-
updatedAt: Date.now(),
|
|
1706
|
-
sessionIds: [sessionId]
|
|
1707
|
-
};
|
|
1708
|
-
if (store.fold(entry)) {
|
|
1709
|
-
imported += 1;
|
|
1710
|
-
changedPaths.push(change.path);
|
|
1711
|
-
}
|
|
1712
|
-
}
|
|
1713
|
-
if (imported > 0) {
|
|
1714
|
-
persistSession();
|
|
1715
|
-
const after = new Map(store.list(sessionId).map((entry) => [entry.path, entry]));
|
|
1716
|
-
const batchBefore = [];
|
|
1717
|
-
const batchAfter = [];
|
|
1718
|
-
for (const path of changedPaths) {
|
|
1719
|
-
const final = after.get(path);
|
|
1720
|
-
if (final === void 0) continue;
|
|
1721
|
-
const pre = before.get(path);
|
|
1722
|
-
batchAfter.push({
|
|
1723
|
-
id: final.id,
|
|
1724
|
-
path,
|
|
1725
|
-
entry: final,
|
|
1726
|
-
fileText: void 0
|
|
1727
|
-
});
|
|
1728
|
-
batchBefore.push({
|
|
1729
|
-
id: final.id,
|
|
1730
|
-
path,
|
|
1731
|
-
entry: pre,
|
|
1732
|
-
fileText: void 0
|
|
1733
|
-
});
|
|
1734
|
-
}
|
|
1735
|
-
if (batchBefore.length > 0) pushUndo(sessionId, {
|
|
1736
|
-
id: batchBefore[0].id,
|
|
1737
|
-
path: batchBefore[0].path,
|
|
1738
|
-
entry: void 0,
|
|
1739
|
-
fileText: void 0,
|
|
1740
|
-
batch: batchBefore
|
|
1741
|
-
}, {
|
|
1742
|
-
id: batchAfter[0].id,
|
|
1743
|
-
path: batchAfter[0].path,
|
|
1744
|
-
entry: void 0,
|
|
1745
|
-
fileText: void 0,
|
|
1746
|
-
batch: batchAfter
|
|
1747
|
-
});
|
|
1748
|
-
}
|
|
1749
2745
|
return {
|
|
1750
2746
|
ok: true,
|
|
1751
2747
|
value: {
|
|
1752
|
-
imported,
|
|
2748
|
+
imported: await foldBatch(sessionId, changes.map((change) => ({
|
|
2749
|
+
id: change.path,
|
|
2750
|
+
sessionId,
|
|
2751
|
+
path: change.path,
|
|
2752
|
+
kind: change.kind,
|
|
2753
|
+
oldText: change.oldText,
|
|
2754
|
+
newText: change.newText,
|
|
2755
|
+
updatedAt: Date.now(),
|
|
2756
|
+
sessionIds: [sessionId]
|
|
2757
|
+
}))),
|
|
1753
2758
|
detected: true
|
|
1754
2759
|
}
|
|
1755
2760
|
};
|
|
@@ -1787,8 +2792,7 @@ function apply(ctx, config) {
|
|
|
1787
2792
|
} catch (error) {
|
|
1788
2793
|
return rpcError(`refresh failed: ${errorMessage(error)}`);
|
|
1789
2794
|
}
|
|
1790
|
-
const
|
|
1791
|
-
const change = changes.find((candidate) => folded(candidate.path) === folded(entry.path));
|
|
2795
|
+
const change = changes.find((candidate) => pathIdentity(candidate.path) === pathIdentity(entry.path));
|
|
1792
2796
|
if (change === void 0) return {
|
|
1793
2797
|
ok: true,
|
|
1794
2798
|
value: { outcome: "no-change" }
|
|
@@ -1822,6 +2826,175 @@ function apply(ctx, config) {
|
|
|
1822
2826
|
value: { outcome: "refreshed" }
|
|
1823
2827
|
};
|
|
1824
2828
|
}
|
|
2829
|
+
case "list-path": {
|
|
2830
|
+
const sessionId = sessionOf(payload);
|
|
2831
|
+
if (sessionId === void 0) return rpcError("sessionId must be a non-empty string");
|
|
2832
|
+
const workspace = workspaceOf(sessionId);
|
|
2833
|
+
if (workspace === void 0) return rpcError("browse unavailable: the session has no workspace");
|
|
2834
|
+
const requested = pathFieldOf(payload) ?? "";
|
|
2835
|
+
const absolute = resolveInsideWorkspace(workspace.path, requested);
|
|
2836
|
+
if (absolute === void 0) return rpcError("browse failed: the path is outside the workspace");
|
|
2837
|
+
let children;
|
|
2838
|
+
try {
|
|
2839
|
+
const target = await ctx.fs.resolve(absolute, { signal });
|
|
2840
|
+
const info = await ctx.fs.stat(target, signal);
|
|
2841
|
+
if (info === void 0 || info.type !== "directory") return rpcError("browse failed: not a directory");
|
|
2842
|
+
children = await ctx.fs.listDir(target, signal);
|
|
2843
|
+
} catch (error) {
|
|
2844
|
+
return rpcError(`browse failed: ${errorMessage(error)}`);
|
|
2845
|
+
}
|
|
2846
|
+
const entries = [];
|
|
2847
|
+
for (const child of children) {
|
|
2848
|
+
if (BROWSE_HIDDEN_NAMES.has(child.name)) continue;
|
|
2849
|
+
const childAbsolute = resolve(absolute, child.name);
|
|
2850
|
+
if (workspaceRelativeOf(workspace.path, childAbsolute) === void 0) continue;
|
|
2851
|
+
entries.push({
|
|
2852
|
+
name: child.name,
|
|
2853
|
+
type: child.type === "directory" ? "directory" : child.type === "file" ? "file" : "other",
|
|
2854
|
+
path: childAbsolute,
|
|
2855
|
+
size: child.type === "file" ? child.size : void 0
|
|
2856
|
+
});
|
|
2857
|
+
}
|
|
2858
|
+
entries.sort((left, right) => {
|
|
2859
|
+
const rank = (value) => value.type === "directory" ? 0 : 1;
|
|
2860
|
+
const byKind = rank(left) - rank(right);
|
|
2861
|
+
return byKind !== 0 ? byKind : left.name.localeCompare(right.name, void 0, {
|
|
2862
|
+
numeric: true,
|
|
2863
|
+
sensitivity: "base"
|
|
2864
|
+
});
|
|
2865
|
+
});
|
|
2866
|
+
const truncated = entries.length > BROWSE_ENTRY_CAP;
|
|
2867
|
+
return {
|
|
2868
|
+
ok: true,
|
|
2869
|
+
value: {
|
|
2870
|
+
path: absolute,
|
|
2871
|
+
entries: truncated ? entries.slice(0, BROWSE_ENTRY_CAP) : entries,
|
|
2872
|
+
truncated
|
|
2873
|
+
}
|
|
2874
|
+
};
|
|
2875
|
+
}
|
|
2876
|
+
case "add-path": {
|
|
2877
|
+
const target = addTargetOf(payload);
|
|
2878
|
+
if (target === void 0) return rpcError("sessionId and path must be non-empty strings");
|
|
2879
|
+
const workspace = workspaceOf(target.sessionId);
|
|
2880
|
+
if (workspace === void 0) return rpcError("add unavailable: the session has no workspace");
|
|
2881
|
+
const absolute = resolveInsideWorkspace(workspace.path, target.path);
|
|
2882
|
+
if (absolute === void 0) return {
|
|
2883
|
+
ok: true,
|
|
2884
|
+
value: {
|
|
2885
|
+
outcome: "outside",
|
|
2886
|
+
added: 0,
|
|
2887
|
+
duplicates: 0
|
|
2888
|
+
}
|
|
2889
|
+
};
|
|
2890
|
+
await ensureLoaded();
|
|
2891
|
+
let info;
|
|
2892
|
+
try {
|
|
2893
|
+
const target = await ctx.fs.resolve(absolute, { signal });
|
|
2894
|
+
info = await ctx.fs.stat(target, signal);
|
|
2895
|
+
} catch (error) {
|
|
2896
|
+
return rpcError(`add failed: ${errorMessage(error)}`);
|
|
2897
|
+
}
|
|
2898
|
+
if (info === void 0 || info.type === "other") return {
|
|
2899
|
+
ok: true,
|
|
2900
|
+
value: {
|
|
2901
|
+
outcome: "missing",
|
|
2902
|
+
added: 0,
|
|
2903
|
+
duplicates: 0
|
|
2904
|
+
}
|
|
2905
|
+
};
|
|
2906
|
+
const isDirectory = info.type === "directory";
|
|
2907
|
+
const root = detectVcsRoot(workspace.path);
|
|
2908
|
+
if (root === void 0) return {
|
|
2909
|
+
ok: true,
|
|
2910
|
+
value: {
|
|
2911
|
+
outcome: "no-vcs",
|
|
2912
|
+
added: 0,
|
|
2913
|
+
duplicates: 0
|
|
2914
|
+
}
|
|
2915
|
+
};
|
|
2916
|
+
const shell = ctx.get("shell");
|
|
2917
|
+
if (shell === void 0) return rpcError("add unavailable: the deployment has no shell executor");
|
|
2918
|
+
let changes;
|
|
2919
|
+
try {
|
|
2920
|
+
changes = await listVcsChanges({
|
|
2921
|
+
kind: root.kind,
|
|
2922
|
+
root: root.root,
|
|
2923
|
+
workspaceRoot: workspace.path,
|
|
2924
|
+
includeUntracked: true,
|
|
2925
|
+
scope: absolute,
|
|
2926
|
+
shell,
|
|
2927
|
+
readText: (path) => readFile(path, "utf8").catch(() => void 0),
|
|
2928
|
+
signal
|
|
2929
|
+
});
|
|
2930
|
+
} catch (error) {
|
|
2931
|
+
return {
|
|
2932
|
+
ok: true,
|
|
2933
|
+
value: {
|
|
2934
|
+
outcome: "failed",
|
|
2935
|
+
added: 0,
|
|
2936
|
+
duplicates: 0,
|
|
2937
|
+
message: errorMessage(error)
|
|
2938
|
+
}
|
|
2939
|
+
};
|
|
2940
|
+
}
|
|
2941
|
+
const now = Date.now();
|
|
2942
|
+
const candidates = changes.map((change) => ({
|
|
2943
|
+
id: change.path,
|
|
2944
|
+
sessionId: target.sessionId,
|
|
2945
|
+
path: change.path,
|
|
2946
|
+
kind: change.kind,
|
|
2947
|
+
oldText: change.oldText,
|
|
2948
|
+
newText: change.newText,
|
|
2949
|
+
updatedAt: now,
|
|
2950
|
+
sessionIds: [target.sessionId]
|
|
2951
|
+
}));
|
|
2952
|
+
let truncated = false;
|
|
2953
|
+
if (target.includeUnchanged) {
|
|
2954
|
+
const scanned = new Set(candidates.map((entry) => pathIdentity(entry.path)));
|
|
2955
|
+
const found = isDirectory ? await collectFilesUnder(await ctx.fs.resolve(absolute, { signal }), absolute, signal) : {
|
|
2956
|
+
files: [{
|
|
2957
|
+
path: absolute,
|
|
2958
|
+
content: await readTextOrNone(absolute, signal)
|
|
2959
|
+
}],
|
|
2960
|
+
truncated: false
|
|
2961
|
+
};
|
|
2962
|
+
truncated = found.truncated;
|
|
2963
|
+
for (const file of found.files) {
|
|
2964
|
+
if (file.content === void 0) continue;
|
|
2965
|
+
if (scanned.has(pathIdentity(file.path))) continue;
|
|
2966
|
+
scanned.add(pathIdentity(file.path));
|
|
2967
|
+
candidates.push({
|
|
2968
|
+
id: file.path,
|
|
2969
|
+
sessionId: target.sessionId,
|
|
2970
|
+
path: file.path,
|
|
2971
|
+
kind: "edit",
|
|
2972
|
+
oldText: file.content,
|
|
2973
|
+
newText: file.content,
|
|
2974
|
+
updatedAt: now,
|
|
2975
|
+
sessionIds: [target.sessionId]
|
|
2976
|
+
});
|
|
2977
|
+
}
|
|
2978
|
+
}
|
|
2979
|
+
const listed = new Set(store.list(target.sessionId).map((entry) => pathIdentity(entry.path)));
|
|
2980
|
+
const fresh = candidates.filter((entry) => !listed.has(pathIdentity(entry.path)));
|
|
2981
|
+
const duplicates = candidates.length - fresh.length;
|
|
2982
|
+
const added = await foldBatch(target.sessionId, fresh, true);
|
|
2983
|
+
const outcome = added > 0 ? "added" : duplicates > 0 ? "duplicate" : isDirectory ? "empty" : "unchanged";
|
|
2984
|
+
return {
|
|
2985
|
+
ok: true,
|
|
2986
|
+
value: truncated ? {
|
|
2987
|
+
outcome,
|
|
2988
|
+
added,
|
|
2989
|
+
duplicates,
|
|
2990
|
+
truncated
|
|
2991
|
+
} : {
|
|
2992
|
+
outcome,
|
|
2993
|
+
added,
|
|
2994
|
+
duplicates
|
|
2995
|
+
}
|
|
2996
|
+
};
|
|
2997
|
+
}
|
|
1825
2998
|
case "open": {
|
|
1826
2999
|
const target = openTargetOf(payload);
|
|
1827
3000
|
if (target === void 0) return rpcError("sessionId, id, and action must be valid");
|
|
@@ -1980,6 +3153,24 @@ function previewImageTargetOf(payload) {
|
|
|
1980
3153
|
path
|
|
1981
3154
|
};
|
|
1982
3155
|
}
|
|
3156
|
+
/** One payload's optional `path` field; absent (or not a string) is undefined. */
|
|
3157
|
+
function pathFieldOf(payload) {
|
|
3158
|
+
if (typeof payload !== "object" || payload === null || Array.isArray(payload)) return void 0;
|
|
3159
|
+
const path = payload.path;
|
|
3160
|
+
return typeof path === "string" ? path : void 0;
|
|
3161
|
+
}
|
|
3162
|
+
/** Narrow a wire payload to one hand-added path. */
|
|
3163
|
+
function addTargetOf(payload) {
|
|
3164
|
+
const sessionId = sessionOf(payload);
|
|
3165
|
+
if (sessionId === void 0) return void 0;
|
|
3166
|
+
const path = pathFieldOf(payload)?.trim();
|
|
3167
|
+
if (path === void 0 || path === "") return void 0;
|
|
3168
|
+
return {
|
|
3169
|
+
sessionId,
|
|
3170
|
+
path,
|
|
3171
|
+
includeUnchanged: payload.includeUnchanged === true
|
|
3172
|
+
};
|
|
3173
|
+
}
|
|
1983
3174
|
/** Narrow a wire payload to one open target: the keep/revert pair plus the action. */
|
|
1984
3175
|
function openTargetOf(payload) {
|
|
1985
3176
|
const target = targetOf(payload);
|