@spotpatch/vite 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +43 -0
- package/dist/index.cjs +2268 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +59 -0
- package/dist/index.d.ts +59 -0
- package/dist/index.js +2269 -0
- package/dist/index.js.map +1 -0
- package/dist/runtime-client.d.ts +2 -0
- package/dist/runtime-client.js +786 -0
- package/dist/runtime-react-adapter.js +16 -0
- package/package.json +68 -0
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,2268 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __export = (target, all) => {
|
|
9
|
+
for (var name in all)
|
|
10
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
11
|
+
};
|
|
12
|
+
var __copyProps = (to, from, except, desc) => {
|
|
13
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
14
|
+
for (let key of __getOwnPropNames(from))
|
|
15
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
16
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
17
|
+
}
|
|
18
|
+
return to;
|
|
19
|
+
};
|
|
20
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
25
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
26
|
+
mod
|
|
27
|
+
));
|
|
28
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
29
|
+
|
|
30
|
+
// src/index.ts
|
|
31
|
+
var index_exports = {};
|
|
32
|
+
__export(index_exports, {
|
|
33
|
+
DEFAULT_AGENT_LIMITS: () => import_shared12.DEFAULT_AGENT_LIMITS,
|
|
34
|
+
DEFAULT_OPTIONS: () => DEFAULT_OPTIONS,
|
|
35
|
+
resolveOptions: () => resolveOptions,
|
|
36
|
+
spotPatch: () => spotPatch
|
|
37
|
+
});
|
|
38
|
+
module.exports = __toCommonJS(index_exports);
|
|
39
|
+
|
|
40
|
+
// src/options.ts
|
|
41
|
+
var import_shared = require("@spotpatch/shared");
|
|
42
|
+
var import_zod = require("zod");
|
|
43
|
+
var DEFAULT_EXCLUDE = Object.freeze([
|
|
44
|
+
/node_modules/,
|
|
45
|
+
/\.test\.[jt]sx$/,
|
|
46
|
+
/\.spec\.[jt]sx$/,
|
|
47
|
+
/\.stories\.[jt]sx$/,
|
|
48
|
+
/(?:^|\/)dist(?:\/|$)/,
|
|
49
|
+
/(?:^|\/)coverage(?:\/|$)/
|
|
50
|
+
]);
|
|
51
|
+
var DEFAULT_INCLUDE = Object.freeze([/(?:^|[/\\])src[/\\].+\.(?:jsx|tsx)$/]);
|
|
52
|
+
var DEFAULT_BUDGET = Object.freeze({
|
|
53
|
+
totalCharacters: 16e3,
|
|
54
|
+
domCharacters: 3e3,
|
|
55
|
+
cssCharacters: 4e3,
|
|
56
|
+
codeCharacters: 7e3,
|
|
57
|
+
maxCodeLines: 80,
|
|
58
|
+
maxComponentDepth: 8
|
|
59
|
+
});
|
|
60
|
+
var DEFAULT_OPTIONS = Object.freeze({
|
|
61
|
+
enabled: true,
|
|
62
|
+
include: DEFAULT_INCLUDE,
|
|
63
|
+
exclude: DEFAULT_EXCLUDE,
|
|
64
|
+
editor: "vscode",
|
|
65
|
+
redact: true,
|
|
66
|
+
budget: DEFAULT_BUDGET,
|
|
67
|
+
shortcut: "Mod+Shift+S",
|
|
68
|
+
allowLan: false,
|
|
69
|
+
debug: false,
|
|
70
|
+
locale: "auto",
|
|
71
|
+
maxTargets: 8,
|
|
72
|
+
ai: false
|
|
73
|
+
});
|
|
74
|
+
var PROFILE_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
|
|
75
|
+
var ENV_NAME_PATTERN = /^[A-Z][A-Z0-9_]{1,127}$/;
|
|
76
|
+
var agentLimitsSchema = import_zod.z.strictObject({
|
|
77
|
+
maxTurns: import_zod.z.number().optional(),
|
|
78
|
+
maxToolCalls: import_zod.z.number().optional(),
|
|
79
|
+
maxChangedFiles: import_zod.z.number().optional(),
|
|
80
|
+
maxDiffBytes: import_zod.z.number().optional(),
|
|
81
|
+
maxReadBytesPerFile: import_zod.z.number().optional(),
|
|
82
|
+
maxToolOutputCharacters: import_zod.z.number().optional(),
|
|
83
|
+
maxProviderResponseBytes: import_zod.z.number().optional(),
|
|
84
|
+
providerConnectTimeoutMs: import_zod.z.number().optional(),
|
|
85
|
+
providerFirstByteTimeoutMs: import_zod.z.number().optional(),
|
|
86
|
+
providerIdleTimeoutMs: import_zod.z.number().optional(),
|
|
87
|
+
checkTimeoutMs: import_zod.z.number().optional(),
|
|
88
|
+
jobTimeoutMs: import_zod.z.number().optional()
|
|
89
|
+
}).optional();
|
|
90
|
+
var agentCheckSchema = import_zod.z.strictObject({
|
|
91
|
+
label: import_zod.z.string(),
|
|
92
|
+
command: import_zod.z.string(),
|
|
93
|
+
args: import_zod.z.array(import_zod.z.string()).optional(),
|
|
94
|
+
required: import_zod.z.boolean().optional(),
|
|
95
|
+
timeoutMs: import_zod.z.number().optional()
|
|
96
|
+
});
|
|
97
|
+
var aiOptionsSchema = import_zod.z.strictObject({
|
|
98
|
+
providers: import_zod.z.record(
|
|
99
|
+
import_zod.z.string(),
|
|
100
|
+
import_zod.z.strictObject({
|
|
101
|
+
type: import_zod.z.literal("openai-compatible"),
|
|
102
|
+
label: import_zod.z.string(),
|
|
103
|
+
protocol: import_zod.z.enum(["responses", "chat-completions"]),
|
|
104
|
+
baseURL: import_zod.z.string(),
|
|
105
|
+
apiKeyEnv: import_zod.z.string(),
|
|
106
|
+
models: import_zod.z.record(
|
|
107
|
+
import_zod.z.string(),
|
|
108
|
+
import_zod.z.strictObject({ label: import_zod.z.string(), model: import_zod.z.string() })
|
|
109
|
+
),
|
|
110
|
+
defaultModel: import_zod.z.string()
|
|
111
|
+
})
|
|
112
|
+
),
|
|
113
|
+
defaultProvider: import_zod.z.string(),
|
|
114
|
+
execution: import_zod.z.strictObject({
|
|
115
|
+
isolation: import_zod.z.literal("git-worktree").optional(),
|
|
116
|
+
applyMode: import_zod.z.enum(["review", "auto"]).optional(),
|
|
117
|
+
checks: import_zod.z.record(import_zod.z.string(), agentCheckSchema).optional(),
|
|
118
|
+
limits: agentLimitsSchema
|
|
119
|
+
}).optional()
|
|
120
|
+
});
|
|
121
|
+
function assertIdentifier(value, label) {
|
|
122
|
+
if (!PROFILE_ID_PATTERN.test(value)) {
|
|
123
|
+
throw new RangeError(
|
|
124
|
+
`SpotPatch ${label} must contain only letters, numbers, dot, underscore, or hyphen.`
|
|
125
|
+
);
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
function nonEmpty(value, label, maximum = 256) {
|
|
129
|
+
const normalized = value.trim();
|
|
130
|
+
if (normalized.length === 0 || normalized.length > maximum || value.includes("\0")) {
|
|
131
|
+
throw new RangeError(`SpotPatch ${label} is invalid.`);
|
|
132
|
+
}
|
|
133
|
+
return normalized;
|
|
134
|
+
}
|
|
135
|
+
function normalizeProviderBaseURL(value) {
|
|
136
|
+
let url;
|
|
137
|
+
try {
|
|
138
|
+
url = new URL(value);
|
|
139
|
+
} catch {
|
|
140
|
+
throw new RangeError("SpotPatch AI provider baseURL must be a valid URL.");
|
|
141
|
+
}
|
|
142
|
+
const loopbackHosts = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "[::1]"]);
|
|
143
|
+
const allowedProtocol = url.protocol === "https:" || url.protocol === "http:" && loopbackHosts.has(url.hostname);
|
|
144
|
+
if (!allowedProtocol || url.username.length > 0 || url.password.length > 0 || url.search.length > 0 || url.hash.length > 0) {
|
|
145
|
+
throw new RangeError("SpotPatch AI provider baseURL violates URL policy.");
|
|
146
|
+
}
|
|
147
|
+
url.pathname = url.pathname.replace(/\/{2,}/g, "/").replace(/\/$/, "");
|
|
148
|
+
return url.toString().replace(/\/$/, "");
|
|
149
|
+
}
|
|
150
|
+
function resolveLimits(limits) {
|
|
151
|
+
const resolved = Object.freeze({
|
|
152
|
+
maxTurns: limits?.maxTurns ?? import_shared.DEFAULT_AGENT_LIMITS.maxTurns,
|
|
153
|
+
maxToolCalls: limits?.maxToolCalls ?? import_shared.DEFAULT_AGENT_LIMITS.maxToolCalls,
|
|
154
|
+
maxChangedFiles: limits?.maxChangedFiles ?? import_shared.DEFAULT_AGENT_LIMITS.maxChangedFiles,
|
|
155
|
+
maxDiffBytes: limits?.maxDiffBytes ?? import_shared.DEFAULT_AGENT_LIMITS.maxDiffBytes,
|
|
156
|
+
maxReadBytesPerFile: limits?.maxReadBytesPerFile ?? import_shared.DEFAULT_AGENT_LIMITS.maxReadBytesPerFile,
|
|
157
|
+
maxToolOutputCharacters: limits?.maxToolOutputCharacters ?? import_shared.DEFAULT_AGENT_LIMITS.maxToolOutputCharacters,
|
|
158
|
+
maxProviderResponseBytes: limits?.maxProviderResponseBytes ?? import_shared.DEFAULT_AGENT_LIMITS.maxProviderResponseBytes,
|
|
159
|
+
providerConnectTimeoutMs: limits?.providerConnectTimeoutMs ?? import_shared.DEFAULT_AGENT_LIMITS.providerConnectTimeoutMs,
|
|
160
|
+
providerFirstByteTimeoutMs: limits?.providerFirstByteTimeoutMs ?? import_shared.DEFAULT_AGENT_LIMITS.providerFirstByteTimeoutMs,
|
|
161
|
+
providerIdleTimeoutMs: limits?.providerIdleTimeoutMs ?? import_shared.DEFAULT_AGENT_LIMITS.providerIdleTimeoutMs,
|
|
162
|
+
checkTimeoutMs: limits?.checkTimeoutMs ?? import_shared.DEFAULT_AGENT_LIMITS.checkTimeoutMs,
|
|
163
|
+
jobTimeoutMs: limits?.jobTimeoutMs ?? import_shared.DEFAULT_AGENT_LIMITS.jobTimeoutMs
|
|
164
|
+
});
|
|
165
|
+
for (const [name, value] of Object.entries(resolved)) {
|
|
166
|
+
if (!Number.isSafeInteger(value) || value <= 0) {
|
|
167
|
+
throw new RangeError(`SpotPatch AI limit ${name} must be a positive integer.`);
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
return resolved;
|
|
171
|
+
}
|
|
172
|
+
function resolveModels(models) {
|
|
173
|
+
const entries = Object.entries(models);
|
|
174
|
+
if (entries.length === 0) {
|
|
175
|
+
throw new RangeError("SpotPatch AI provider must declare at least one model.");
|
|
176
|
+
}
|
|
177
|
+
return Object.freeze(
|
|
178
|
+
Object.fromEntries(
|
|
179
|
+
entries.map(([id, model]) => {
|
|
180
|
+
assertIdentifier(id, "model profile id");
|
|
181
|
+
return [
|
|
182
|
+
id,
|
|
183
|
+
Object.freeze({
|
|
184
|
+
id,
|
|
185
|
+
label: nonEmpty(model.label, "model label", 100),
|
|
186
|
+
model: nonEmpty(model.model, "provider model name")
|
|
187
|
+
})
|
|
188
|
+
];
|
|
189
|
+
})
|
|
190
|
+
)
|
|
191
|
+
);
|
|
192
|
+
}
|
|
193
|
+
function resolveProviders(providers) {
|
|
194
|
+
const entries = Object.entries(providers);
|
|
195
|
+
if (entries.length === 0) {
|
|
196
|
+
throw new RangeError("SpotPatch AI must declare at least one provider.");
|
|
197
|
+
}
|
|
198
|
+
return Object.freeze(
|
|
199
|
+
Object.fromEntries(
|
|
200
|
+
entries.map(([id, provider]) => {
|
|
201
|
+
assertIdentifier(id, "provider profile id");
|
|
202
|
+
if (!ENV_NAME_PATTERN.test(provider.apiKeyEnv) || provider.apiKeyEnv.startsWith("VITE_")) {
|
|
203
|
+
throw new RangeError(
|
|
204
|
+
"SpotPatch AI apiKeyEnv must be an uppercase non-VITE environment name."
|
|
205
|
+
);
|
|
206
|
+
}
|
|
207
|
+
const models = resolveModels(provider.models);
|
|
208
|
+
if (!(provider.defaultModel in models)) {
|
|
209
|
+
throw new RangeError(
|
|
210
|
+
"SpotPatch AI provider defaultModel must reference a configured model."
|
|
211
|
+
);
|
|
212
|
+
}
|
|
213
|
+
return [
|
|
214
|
+
id,
|
|
215
|
+
Object.freeze({
|
|
216
|
+
id,
|
|
217
|
+
type: provider.type,
|
|
218
|
+
label: nonEmpty(provider.label, "provider label", 100),
|
|
219
|
+
protocol: provider.protocol,
|
|
220
|
+
baseURL: normalizeProviderBaseURL(provider.baseURL),
|
|
221
|
+
apiKeyEnv: provider.apiKeyEnv,
|
|
222
|
+
models,
|
|
223
|
+
defaultModel: provider.defaultModel
|
|
224
|
+
})
|
|
225
|
+
];
|
|
226
|
+
})
|
|
227
|
+
)
|
|
228
|
+
);
|
|
229
|
+
}
|
|
230
|
+
function resolveChecks(checks, defaultTimeoutMs) {
|
|
231
|
+
return Object.freeze(
|
|
232
|
+
Object.fromEntries(
|
|
233
|
+
Object.entries(checks ?? {}).map(([id, check]) => {
|
|
234
|
+
assertIdentifier(id, "check id");
|
|
235
|
+
const timeoutMs = check.timeoutMs ?? defaultTimeoutMs;
|
|
236
|
+
if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0) {
|
|
237
|
+
throw new RangeError("SpotPatch AI check timeout must be positive.");
|
|
238
|
+
}
|
|
239
|
+
const args = Object.freeze(
|
|
240
|
+
[...check.args ?? []].map(
|
|
241
|
+
(argument) => nonEmpty(argument, "check argument", 4096)
|
|
242
|
+
)
|
|
243
|
+
);
|
|
244
|
+
return [
|
|
245
|
+
id,
|
|
246
|
+
Object.freeze({
|
|
247
|
+
id,
|
|
248
|
+
label: nonEmpty(check.label, "check label", 100),
|
|
249
|
+
command: nonEmpty(check.command, "check command", 1024),
|
|
250
|
+
args,
|
|
251
|
+
required: check.required ?? true,
|
|
252
|
+
timeoutMs
|
|
253
|
+
})
|
|
254
|
+
];
|
|
255
|
+
})
|
|
256
|
+
)
|
|
257
|
+
);
|
|
258
|
+
}
|
|
259
|
+
function resolveAiOptions(options) {
|
|
260
|
+
if (options === void 0 || options === false) {
|
|
261
|
+
return false;
|
|
262
|
+
}
|
|
263
|
+
const parsed = aiOptionsSchema.safeParse(options);
|
|
264
|
+
if (!parsed.success) {
|
|
265
|
+
throw new RangeError("SpotPatch AI configuration is invalid.");
|
|
266
|
+
}
|
|
267
|
+
const validated = parsed.data;
|
|
268
|
+
const limits = resolveLimits(validated.execution?.limits);
|
|
269
|
+
const checks = resolveChecks(validated.execution?.checks, limits.checkTimeoutMs);
|
|
270
|
+
const applyMode = validated.execution?.applyMode ?? "review";
|
|
271
|
+
if (applyMode === "auto" && !Object.values(checks).some((check) => check.required)) {
|
|
272
|
+
throw new RangeError("SpotPatch AI auto mode requires a required check.");
|
|
273
|
+
}
|
|
274
|
+
const providers = resolveProviders(validated.providers);
|
|
275
|
+
if (!(validated.defaultProvider in providers)) {
|
|
276
|
+
throw new RangeError(
|
|
277
|
+
"SpotPatch AI defaultProvider must reference a configured provider."
|
|
278
|
+
);
|
|
279
|
+
}
|
|
280
|
+
return Object.freeze({
|
|
281
|
+
providers,
|
|
282
|
+
defaultProvider: validated.defaultProvider,
|
|
283
|
+
execution: Object.freeze({
|
|
284
|
+
isolation: "git-worktree",
|
|
285
|
+
applyMode,
|
|
286
|
+
checks,
|
|
287
|
+
limits
|
|
288
|
+
})
|
|
289
|
+
});
|
|
290
|
+
}
|
|
291
|
+
function createRuntimeAiConfig(options) {
|
|
292
|
+
if (options === false) {
|
|
293
|
+
return Object.freeze({ enabled: false });
|
|
294
|
+
}
|
|
295
|
+
return Object.freeze({
|
|
296
|
+
enabled: true,
|
|
297
|
+
defaultProvider: options.defaultProvider,
|
|
298
|
+
applyMode: options.execution.applyMode,
|
|
299
|
+
providers: Object.freeze(
|
|
300
|
+
Object.values(options.providers).map(
|
|
301
|
+
(provider) => Object.freeze({
|
|
302
|
+
id: provider.id,
|
|
303
|
+
label: provider.label,
|
|
304
|
+
protocol: provider.protocol,
|
|
305
|
+
defaultModel: provider.defaultModel,
|
|
306
|
+
models: Object.freeze(
|
|
307
|
+
Object.values(provider.models).map(
|
|
308
|
+
(model) => Object.freeze({ id: model.id, label: model.label })
|
|
309
|
+
)
|
|
310
|
+
)
|
|
311
|
+
})
|
|
312
|
+
)
|
|
313
|
+
)
|
|
314
|
+
});
|
|
315
|
+
}
|
|
316
|
+
function assertPositiveBudget(budget) {
|
|
317
|
+
for (const [name, value] of Object.entries(budget)) {
|
|
318
|
+
if (!Number.isSafeInteger(value) || value <= 0) {
|
|
319
|
+
throw new RangeError(`SpotPatch budget ${name} must be a positive integer.`);
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
function resolveOptions(options = {}) {
|
|
324
|
+
const budget = Object.freeze({
|
|
325
|
+
...DEFAULT_OPTIONS.budget,
|
|
326
|
+
...options.budget
|
|
327
|
+
});
|
|
328
|
+
assertPositiveBudget(budget);
|
|
329
|
+
const maxTargets = options.maxTargets ?? DEFAULT_OPTIONS.maxTargets;
|
|
330
|
+
const locale = options.locale ?? DEFAULT_OPTIONS.locale;
|
|
331
|
+
if (!import_shared.SPOTPATCH_LOCALE_PREFERENCES.includes(locale)) {
|
|
332
|
+
throw new RangeError("SpotPatch locale must be auto, en-US, or zh-CN.");
|
|
333
|
+
}
|
|
334
|
+
if (!Number.isSafeInteger(maxTargets) || maxTargets < 1 || maxTargets > import_shared.MAX_ANNOTATION_TARGETS) {
|
|
335
|
+
throw new RangeError(
|
|
336
|
+
`SpotPatch maxTargets must be an integer between 1 and ${String(import_shared.MAX_ANNOTATION_TARGETS)}.`
|
|
337
|
+
);
|
|
338
|
+
}
|
|
339
|
+
const resolved = {
|
|
340
|
+
enabled: options.enabled ?? DEFAULT_OPTIONS.enabled,
|
|
341
|
+
include: Object.freeze([...options.include ?? DEFAULT_OPTIONS.include]),
|
|
342
|
+
exclude: Object.freeze([...options.exclude ?? DEFAULT_OPTIONS.exclude]),
|
|
343
|
+
editor: options.editor ?? DEFAULT_OPTIONS.editor,
|
|
344
|
+
redact: options.redact ?? DEFAULT_OPTIONS.redact,
|
|
345
|
+
budget,
|
|
346
|
+
shortcut: options.shortcut ?? DEFAULT_OPTIONS.shortcut,
|
|
347
|
+
allowLan: options.allowLan ?? DEFAULT_OPTIONS.allowLan,
|
|
348
|
+
debug: options.debug ?? DEFAULT_OPTIONS.debug,
|
|
349
|
+
locale,
|
|
350
|
+
maxTargets,
|
|
351
|
+
ai: resolveAiOptions(options.ai)
|
|
352
|
+
};
|
|
353
|
+
if (resolved.shortcut.trim().length === 0) {
|
|
354
|
+
throw new RangeError("SpotPatch shortcut cannot be empty.");
|
|
355
|
+
}
|
|
356
|
+
return Object.freeze(resolved);
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
// src/registry/source-registry.ts
|
|
360
|
+
var import_node_path = __toESM(require("path"), 1);
|
|
361
|
+
|
|
362
|
+
// src/registry/source-id.ts
|
|
363
|
+
var import_node_crypto = require("crypto");
|
|
364
|
+
var SOURCE_ID_BYTES = 8;
|
|
365
|
+
var createRandomSourceId = () => (0, import_node_crypto.randomBytes)(SOURCE_ID_BYTES).toString("base64url");
|
|
366
|
+
|
|
367
|
+
// src/registry/source-registry.ts
|
|
368
|
+
function normalizeAbsolutePath(absolutePath) {
|
|
369
|
+
return import_node_path.default.normalize(import_node_path.default.resolve(absolutePath));
|
|
370
|
+
}
|
|
371
|
+
function createSourceRegistry(options = {}) {
|
|
372
|
+
const createId = options.createId ?? createRandomSourceId;
|
|
373
|
+
const pathToId = /* @__PURE__ */ new Map();
|
|
374
|
+
const idToPath = /* @__PURE__ */ new Map();
|
|
375
|
+
return Object.freeze({
|
|
376
|
+
register(absolutePath) {
|
|
377
|
+
const normalizedPath = normalizeAbsolutePath(absolutePath);
|
|
378
|
+
const existingId = pathToId.get(normalizedPath);
|
|
379
|
+
if (existingId !== void 0) {
|
|
380
|
+
return existingId;
|
|
381
|
+
}
|
|
382
|
+
let fileId = createId();
|
|
383
|
+
while (idToPath.has(fileId)) {
|
|
384
|
+
fileId = createId();
|
|
385
|
+
}
|
|
386
|
+
pathToId.set(normalizedPath, fileId);
|
|
387
|
+
idToPath.set(fileId, normalizedPath);
|
|
388
|
+
return fileId;
|
|
389
|
+
},
|
|
390
|
+
resolve(fileId) {
|
|
391
|
+
return idToPath.get(fileId);
|
|
392
|
+
},
|
|
393
|
+
clear() {
|
|
394
|
+
pathToId.clear();
|
|
395
|
+
idToPath.clear();
|
|
396
|
+
}
|
|
397
|
+
});
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
// src/runtime/runtime-injection-plugin.ts
|
|
401
|
+
var import_node_module = require("module");
|
|
402
|
+
var import_node_fs = require("fs");
|
|
403
|
+
var import_node_path2 = __toESM(require("path"), 1);
|
|
404
|
+
|
|
405
|
+
// package.json
|
|
406
|
+
var package_default = {
|
|
407
|
+
name: "@spotpatch/vite",
|
|
408
|
+
version: "1.0.0",
|
|
409
|
+
description: "Vite development plugin for SpotPatch.",
|
|
410
|
+
license: "MIT",
|
|
411
|
+
repository: {
|
|
412
|
+
type: "git",
|
|
413
|
+
url: "git+https://github.com/huanglvjing/spotpatch.git",
|
|
414
|
+
directory: "packages/vite"
|
|
415
|
+
},
|
|
416
|
+
homepage: "https://github.com/huanglvjing/spotpatch#readme",
|
|
417
|
+
bugs: {
|
|
418
|
+
url: "https://github.com/huanglvjing/spotpatch/issues"
|
|
419
|
+
},
|
|
420
|
+
keywords: [
|
|
421
|
+
"spotpatch",
|
|
422
|
+
"vite",
|
|
423
|
+
"react",
|
|
424
|
+
"developer-tools",
|
|
425
|
+
"ai-agent"
|
|
426
|
+
],
|
|
427
|
+
type: "module",
|
|
428
|
+
sideEffects: false,
|
|
429
|
+
engines: {
|
|
430
|
+
node: ">=20.19.0"
|
|
431
|
+
},
|
|
432
|
+
files: [
|
|
433
|
+
"dist"
|
|
434
|
+
],
|
|
435
|
+
main: "./dist/index.cjs",
|
|
436
|
+
module: "./dist/index.js",
|
|
437
|
+
types: "./dist/index.d.ts",
|
|
438
|
+
exports: {
|
|
439
|
+
".": {
|
|
440
|
+
import: {
|
|
441
|
+
types: "./dist/index.d.ts",
|
|
442
|
+
default: "./dist/index.js"
|
|
443
|
+
},
|
|
444
|
+
require: {
|
|
445
|
+
types: "./dist/index.d.cts",
|
|
446
|
+
default: "./dist/index.cjs"
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
},
|
|
450
|
+
scripts: {
|
|
451
|
+
build: "tsup src/index.ts --format esm,cjs --dts --sourcemap --clean && tsup --config tsup.runtime-client.config.ts && tsup --config tsup.runtime-react-adapter.config.ts",
|
|
452
|
+
clean: `node --input-type=module -e "import { rmSync } from 'node:fs'; rmSync('dist', { recursive: true, force: true })"`,
|
|
453
|
+
typecheck: "tsc --noEmit -p tsconfig.json"
|
|
454
|
+
},
|
|
455
|
+
dependencies: {
|
|
456
|
+
"@rollup/pluginutils": "5.4.0",
|
|
457
|
+
"@spotpatch/agent": "workspace:^",
|
|
458
|
+
"@spotpatch/react-adapter": "workspace:^",
|
|
459
|
+
"@spotpatch/runtime": "workspace:^",
|
|
460
|
+
"@spotpatch/shared": "workspace:^",
|
|
461
|
+
"launch-editor": "2.14.1",
|
|
462
|
+
"magic-string": "1.1.0",
|
|
463
|
+
"oxc-parser": "0.143.0",
|
|
464
|
+
zod: "4.4.3"
|
|
465
|
+
},
|
|
466
|
+
peerDependencies: {
|
|
467
|
+
vite: "^5.0.0 || ^6.0.0 || ^7.0.0"
|
|
468
|
+
},
|
|
469
|
+
publishConfig: {
|
|
470
|
+
access: "public",
|
|
471
|
+
registry: "https://registry.npmjs.org/"
|
|
472
|
+
}
|
|
473
|
+
};
|
|
474
|
+
|
|
475
|
+
// src/runtime/runtime-injection-plugin.ts
|
|
476
|
+
var import_vite = require("vite");
|
|
477
|
+
var SPOTPATCH_CLIENT_MODULE_ID = "virtual:spotpatch/client";
|
|
478
|
+
var RESOLVED_SPOTPATCH_CLIENT_MODULE_ID = `\0${SPOTPATCH_CLIENT_MODULE_ID}`;
|
|
479
|
+
var SPOTPATCH_REACT_ADAPTER_MODULE_ID = "virtual:spotpatch/react-adapter";
|
|
480
|
+
var RESOLVED_SPOTPATCH_REACT_ADAPTER_MODULE_ID = `\0${SPOTPATCH_REACT_ADAPTER_MODULE_ID}`;
|
|
481
|
+
function readRuntimeBundle(root, fileName) {
|
|
482
|
+
const resolveFromProject = (0, import_node_module.createRequire)(import_node_path2.default.join(root, "package.json"));
|
|
483
|
+
const packageEntry = resolveFromProject.resolve("@spotpatch/vite");
|
|
484
|
+
const bundlePath = import_node_path2.default.join(import_node_path2.default.dirname(packageEntry), fileName);
|
|
485
|
+
return (0, import_node_fs.readFileSync)(bundlePath, "utf8");
|
|
486
|
+
}
|
|
487
|
+
function readConsumerViteVersion(root) {
|
|
488
|
+
try {
|
|
489
|
+
const resolveFromProject = (0, import_node_module.createRequire)(import_node_path2.default.join(root, "package.json"));
|
|
490
|
+
const manifestPath = resolveFromProject.resolve("vite/package.json");
|
|
491
|
+
const manifest = JSON.parse((0, import_node_fs.readFileSync)(manifestPath, "utf8"));
|
|
492
|
+
if (typeof manifest === "object" && manifest !== null && "version" in manifest && typeof manifest.version === "string") {
|
|
493
|
+
return manifest.version;
|
|
494
|
+
}
|
|
495
|
+
} catch {
|
|
496
|
+
}
|
|
497
|
+
return import_vite.version;
|
|
498
|
+
}
|
|
499
|
+
function createClientModule(input, clientBundle, viteVersion) {
|
|
500
|
+
const runtimeConfig = {
|
|
501
|
+
ai: createRuntimeAiConfig(input.options.ai),
|
|
502
|
+
budget: input.options.budget,
|
|
503
|
+
debug: input.options.debug,
|
|
504
|
+
locale: input.options.locale,
|
|
505
|
+
maxTargets: input.options.maxTargets,
|
|
506
|
+
redact: input.options.redact,
|
|
507
|
+
sessionToken: input.session.token,
|
|
508
|
+
shortcut: input.options.shortcut,
|
|
509
|
+
spotPatchVersion: package_default.version,
|
|
510
|
+
viteVersion
|
|
511
|
+
};
|
|
512
|
+
return [
|
|
513
|
+
`const __SPOTPATCH_RUNTIME_CONFIG__ = ${JSON.stringify(runtimeConfig)};`,
|
|
514
|
+
clientBundle
|
|
515
|
+
].join("\n");
|
|
516
|
+
}
|
|
517
|
+
function createRuntimeInjectionPlugin(input) {
|
|
518
|
+
let root = process.cwd();
|
|
519
|
+
let clientBundle = input.clientBundle;
|
|
520
|
+
let viteVersion = import_vite.version;
|
|
521
|
+
return {
|
|
522
|
+
name: "spotpatch:runtime-injection",
|
|
523
|
+
apply: "serve",
|
|
524
|
+
enforce: "pre",
|
|
525
|
+
configResolved(config) {
|
|
526
|
+
root = import_node_path2.default.resolve(config.root);
|
|
527
|
+
viteVersion = readConsumerViteVersion(root);
|
|
528
|
+
},
|
|
529
|
+
resolveId(id, importer) {
|
|
530
|
+
if (id === SPOTPATCH_CLIENT_MODULE_ID) {
|
|
531
|
+
return RESOLVED_SPOTPATCH_CLIENT_MODULE_ID;
|
|
532
|
+
}
|
|
533
|
+
if (id === "@spotpatch/react-adapter" && importer === RESOLVED_SPOTPATCH_CLIENT_MODULE_ID) {
|
|
534
|
+
return RESOLVED_SPOTPATCH_REACT_ADAPTER_MODULE_ID;
|
|
535
|
+
}
|
|
536
|
+
return null;
|
|
537
|
+
},
|
|
538
|
+
load(id) {
|
|
539
|
+
if (id === RESOLVED_SPOTPATCH_CLIENT_MODULE_ID) {
|
|
540
|
+
clientBundle ??= readRuntimeBundle(root, "runtime-client.js");
|
|
541
|
+
return createClientModule(input, clientBundle, viteVersion);
|
|
542
|
+
}
|
|
543
|
+
if (id === RESOLVED_SPOTPATCH_REACT_ADAPTER_MODULE_ID) {
|
|
544
|
+
return input.reactAdapterBundle ?? readRuntimeBundle(root, "runtime-react-adapter.js");
|
|
545
|
+
}
|
|
546
|
+
return null;
|
|
547
|
+
},
|
|
548
|
+
transformIndexHtml() {
|
|
549
|
+
return [
|
|
550
|
+
{
|
|
551
|
+
tag: "script",
|
|
552
|
+
attrs: {
|
|
553
|
+
type: "module",
|
|
554
|
+
src: `/@id/${SPOTPATCH_CLIENT_MODULE_ID}`
|
|
555
|
+
},
|
|
556
|
+
injectTo: "head"
|
|
557
|
+
}
|
|
558
|
+
];
|
|
559
|
+
}
|
|
560
|
+
};
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
// src/server/server-plugin.ts
|
|
564
|
+
var import_node_path6 = __toESM(require("path"), 1);
|
|
565
|
+
|
|
566
|
+
// src/agent/job-manager.ts
|
|
567
|
+
var import_node_crypto2 = require("crypto");
|
|
568
|
+
var import_agent = require("@spotpatch/agent");
|
|
569
|
+
var import_shared2 = require("@spotpatch/shared");
|
|
570
|
+
var MAX_RETAINED_JOBS = 32;
|
|
571
|
+
var MAX_RETAINED_EVENTS = 512;
|
|
572
|
+
var JOB_ID_PATTERN = /^[A-Za-z0-9_-]{22,128}$/;
|
|
573
|
+
var ACTIVE_JOB_STATUSES = /* @__PURE__ */ new Set([
|
|
574
|
+
"queued",
|
|
575
|
+
"preparing",
|
|
576
|
+
"running",
|
|
577
|
+
"validating",
|
|
578
|
+
"awaiting-review",
|
|
579
|
+
"applying",
|
|
580
|
+
"cancelling",
|
|
581
|
+
"reverting"
|
|
582
|
+
]);
|
|
583
|
+
var CANCELLABLE_JOB_STATUSES = /* @__PURE__ */ new Set([
|
|
584
|
+
"queued",
|
|
585
|
+
"preparing",
|
|
586
|
+
"running",
|
|
587
|
+
"validating",
|
|
588
|
+
"awaiting-review"
|
|
589
|
+
]);
|
|
590
|
+
var PRUNABLE_JOB_STATUSES = /* @__PURE__ */ new Set([
|
|
591
|
+
"completed",
|
|
592
|
+
"cancelled",
|
|
593
|
+
"reverted",
|
|
594
|
+
"failed"
|
|
595
|
+
]);
|
|
596
|
+
var DEFAULT_DEPENDENCIES = Object.freeze({
|
|
597
|
+
applyChange: import_agent.applyPreparedAgentChange,
|
|
598
|
+
createJobId: () => (0, import_node_crypto2.randomBytes)(16).toString("base64url"),
|
|
599
|
+
executeChange: import_agent.executeAgentChange,
|
|
600
|
+
now: () => (/* @__PURE__ */ new Date()).toISOString(),
|
|
601
|
+
probeCapability: import_agent.probeProviderCapability,
|
|
602
|
+
resolveCredential: import_agent.resolveProviderCredential,
|
|
603
|
+
revertChange: import_agent.revertPreparedAgentChange
|
|
604
|
+
});
|
|
605
|
+
function normalizeError(error) {
|
|
606
|
+
return error instanceof import_shared2.SpotPatchError ? error : new import_shared2.SpotPatchError(import_shared2.ERROR_CODES.INTERNAL_ERROR, void 0, { cause: error });
|
|
607
|
+
}
|
|
608
|
+
function isActive(status) {
|
|
609
|
+
return ACTIVE_JOB_STATUSES.has(status);
|
|
610
|
+
}
|
|
611
|
+
function snapshot(job) {
|
|
612
|
+
const base = {
|
|
613
|
+
jobId: job.id,
|
|
614
|
+
status: job.status,
|
|
615
|
+
providerProfileId: job.provider.id,
|
|
616
|
+
providerLabel: job.provider.label,
|
|
617
|
+
modelProfileId: job.model.id,
|
|
618
|
+
modelLabel: job.model.label,
|
|
619
|
+
phaseMessage: job.phaseMessage,
|
|
620
|
+
createdAt: job.createdAt,
|
|
621
|
+
updatedAt: job.updatedAt,
|
|
622
|
+
canCancel: CANCELLABLE_JOB_STATUSES.has(job.status),
|
|
623
|
+
canApply: job.status === "awaiting-review" && job.preparedChange?.validationPassed === true && job.result !== void 0 && job.result.diff.length > 0,
|
|
624
|
+
canRevert: job.status === "applied"
|
|
625
|
+
};
|
|
626
|
+
return Object.freeze(
|
|
627
|
+
job.errorCode === void 0 ? base : { ...base, errorCode: job.errorCode }
|
|
628
|
+
);
|
|
629
|
+
}
|
|
630
|
+
function capabilityCacheKey(provider, model) {
|
|
631
|
+
const configurationDigest = (0, import_node_crypto2.createHash)("sha256").update(provider.baseURL).update("\0").update(provider.protocol).digest("hex");
|
|
632
|
+
return `${provider.id}:${model.id}:${configurationDigest}`;
|
|
633
|
+
}
|
|
634
|
+
function freezeEvent(event) {
|
|
635
|
+
return Object.freeze(event);
|
|
636
|
+
}
|
|
637
|
+
function createAgentJobManager(options) {
|
|
638
|
+
const dependencies = Object.freeze({
|
|
639
|
+
...DEFAULT_DEPENDENCIES,
|
|
640
|
+
...options.dependencies
|
|
641
|
+
});
|
|
642
|
+
const jobs = /* @__PURE__ */ new Map();
|
|
643
|
+
const capabilityCache = /* @__PURE__ */ new Map();
|
|
644
|
+
const providerConsents = /* @__PURE__ */ new Set();
|
|
645
|
+
let closed = false;
|
|
646
|
+
const resolveSelection = (providerProfileId, modelProfileId) => {
|
|
647
|
+
const provider = options.ai.providers[providerProfileId];
|
|
648
|
+
if (provider === void 0) {
|
|
649
|
+
throw new import_shared2.SpotPatchError(import_shared2.ERROR_CODES.PROVIDER_NOT_CONFIGURED);
|
|
650
|
+
}
|
|
651
|
+
const model = provider.models[modelProfileId];
|
|
652
|
+
if (model === void 0) {
|
|
653
|
+
throw new import_shared2.SpotPatchError(import_shared2.ERROR_CODES.MODEL_NOT_ALLOWED);
|
|
654
|
+
}
|
|
655
|
+
const credential = dependencies.resolveCredential(
|
|
656
|
+
provider.apiKeyEnv,
|
|
657
|
+
options.environment
|
|
658
|
+
);
|
|
659
|
+
return Object.freeze({ credential, model, provider });
|
|
660
|
+
};
|
|
661
|
+
const requireJob = (jobId) => {
|
|
662
|
+
if (!JOB_ID_PATTERN.test(jobId)) {
|
|
663
|
+
throw new import_shared2.SpotPatchError(import_shared2.ERROR_CODES.INVALID_REQUEST);
|
|
664
|
+
}
|
|
665
|
+
const job = jobs.get(jobId);
|
|
666
|
+
if (job === void 0) {
|
|
667
|
+
throw new import_shared2.SpotPatchError(import_shared2.ERROR_CODES.INVALID_REQUEST);
|
|
668
|
+
}
|
|
669
|
+
return job;
|
|
670
|
+
};
|
|
671
|
+
const appendEvent = (job, event) => {
|
|
672
|
+
job.events.push(event);
|
|
673
|
+
if (job.events.length > MAX_RETAINED_EVENTS) {
|
|
674
|
+
job.events.splice(0, job.events.length - MAX_RETAINED_EVENTS);
|
|
675
|
+
}
|
|
676
|
+
for (const listener of job.listeners) {
|
|
677
|
+
listener(event);
|
|
678
|
+
}
|
|
679
|
+
};
|
|
680
|
+
const eventBase = (job) => {
|
|
681
|
+
job.sequence += 1;
|
|
682
|
+
return {
|
|
683
|
+
schemaVersion: 1,
|
|
684
|
+
sequence: job.sequence,
|
|
685
|
+
jobId: job.id,
|
|
686
|
+
status: job.status,
|
|
687
|
+
timestamp: dependencies.now()
|
|
688
|
+
};
|
|
689
|
+
};
|
|
690
|
+
const emitSnapshot = (job) => {
|
|
691
|
+
appendEvent(
|
|
692
|
+
job,
|
|
693
|
+
freezeEvent({
|
|
694
|
+
...eventBase(job),
|
|
695
|
+
type: "snapshot",
|
|
696
|
+
data: Object.freeze({ snapshot: snapshot(job) })
|
|
697
|
+
})
|
|
698
|
+
);
|
|
699
|
+
};
|
|
700
|
+
const emitPhase = (job, message) => {
|
|
701
|
+
appendEvent(
|
|
702
|
+
job,
|
|
703
|
+
freezeEvent({
|
|
704
|
+
...eventBase(job),
|
|
705
|
+
type: "phase",
|
|
706
|
+
data: Object.freeze({ message })
|
|
707
|
+
})
|
|
708
|
+
);
|
|
709
|
+
};
|
|
710
|
+
const emitError = (job, code) => {
|
|
711
|
+
appendEvent(
|
|
712
|
+
job,
|
|
713
|
+
freezeEvent({
|
|
714
|
+
...eventBase(job),
|
|
715
|
+
type: "error",
|
|
716
|
+
data: Object.freeze({ code, message: "The Agent job failed." })
|
|
717
|
+
})
|
|
718
|
+
);
|
|
719
|
+
};
|
|
720
|
+
const transition = (job, status, phaseMessage, errorCode) => {
|
|
721
|
+
job.status = status;
|
|
722
|
+
job.phaseMessage = phaseMessage;
|
|
723
|
+
job.errorCode = errorCode;
|
|
724
|
+
job.updatedAt = dependencies.now();
|
|
725
|
+
emitSnapshot(job);
|
|
726
|
+
emitPhase(job, phaseMessage);
|
|
727
|
+
};
|
|
728
|
+
const probeResolved = async (selection, signal) => {
|
|
729
|
+
const key = capabilityCacheKey(selection.provider, selection.model);
|
|
730
|
+
const cached = capabilityCache.get(key);
|
|
731
|
+
if (cached !== void 0) {
|
|
732
|
+
return cached;
|
|
733
|
+
}
|
|
734
|
+
const capability = await dependencies.probeCapability({
|
|
735
|
+
provider: selection.provider,
|
|
736
|
+
modelProfileId: selection.model.id,
|
|
737
|
+
limits: options.ai.execution.limits,
|
|
738
|
+
credential: selection.credential,
|
|
739
|
+
signal,
|
|
740
|
+
...options.fetch === void 0 ? {} : { fetch: options.fetch }
|
|
741
|
+
});
|
|
742
|
+
if (capability.state !== "agent-ready") {
|
|
743
|
+
throw new import_shared2.SpotPatchError(import_shared2.ERROR_CODES.MODEL_TOOL_CALL_UNSUPPORTED);
|
|
744
|
+
}
|
|
745
|
+
capabilityCache.set(key, capability);
|
|
746
|
+
return capability;
|
|
747
|
+
};
|
|
748
|
+
const finishWithError = (job, error) => {
|
|
749
|
+
const normalized = normalizeError(error);
|
|
750
|
+
const cancelled = job.controller.signal.aborted || normalized.code === import_shared2.ERROR_CODES.AGENT_CANCELLED;
|
|
751
|
+
transition(
|
|
752
|
+
job,
|
|
753
|
+
cancelled ? "cancelled" : "failed",
|
|
754
|
+
cancelled ? "Agent job cancelled." : "Agent job failed.",
|
|
755
|
+
cancelled ? import_shared2.ERROR_CODES.AGENT_CANCELLED : normalized.code
|
|
756
|
+
);
|
|
757
|
+
if (!cancelled) {
|
|
758
|
+
emitError(job, normalized.code);
|
|
759
|
+
}
|
|
760
|
+
};
|
|
761
|
+
const applyChange = async (job, preparedChange) => {
|
|
762
|
+
transition(job, "applying", "Applying validated changes to the project.");
|
|
763
|
+
try {
|
|
764
|
+
await dependencies.applyChange(preparedChange);
|
|
765
|
+
transition(job, "applied", "Changes were applied to local project files.");
|
|
766
|
+
} catch (error) {
|
|
767
|
+
const normalized = normalizeError(error);
|
|
768
|
+
transition(job, "failed", "Agent change could not be applied.", normalized.code);
|
|
769
|
+
emitError(job, normalized.code);
|
|
770
|
+
throw normalized;
|
|
771
|
+
}
|
|
772
|
+
};
|
|
773
|
+
const runJob = async (job) => {
|
|
774
|
+
try {
|
|
775
|
+
transition(job, "preparing", "Verifying provider and model capabilities.");
|
|
776
|
+
await probeResolved(
|
|
777
|
+
Object.freeze({
|
|
778
|
+
credential: job.credential,
|
|
779
|
+
model: job.model,
|
|
780
|
+
provider: job.provider
|
|
781
|
+
}),
|
|
782
|
+
job.controller.signal
|
|
783
|
+
);
|
|
784
|
+
const callbacks = {
|
|
785
|
+
onCheck(result) {
|
|
786
|
+
appendEvent(
|
|
787
|
+
job,
|
|
788
|
+
freezeEvent({
|
|
789
|
+
...eventBase(job),
|
|
790
|
+
type: "check",
|
|
791
|
+
data: Object.freeze({ result })
|
|
792
|
+
})
|
|
793
|
+
);
|
|
794
|
+
},
|
|
795
|
+
onPhase(event) {
|
|
796
|
+
transition(job, event.phase, event.message);
|
|
797
|
+
},
|
|
798
|
+
onTool(event) {
|
|
799
|
+
appendEvent(
|
|
800
|
+
job,
|
|
801
|
+
freezeEvent({
|
|
802
|
+
...eventBase(job),
|
|
803
|
+
type: "tool",
|
|
804
|
+
data: Object.freeze({ ...event })
|
|
805
|
+
})
|
|
806
|
+
);
|
|
807
|
+
}
|
|
808
|
+
};
|
|
809
|
+
const preparedChange = await dependencies.executeChange({
|
|
810
|
+
annotation: job.annotation,
|
|
811
|
+
callbacks,
|
|
812
|
+
credential: job.credential,
|
|
813
|
+
execution: options.ai.execution,
|
|
814
|
+
jobId: job.id,
|
|
815
|
+
model: job.model,
|
|
816
|
+
provider: job.provider,
|
|
817
|
+
root: options.root,
|
|
818
|
+
signal: job.controller.signal,
|
|
819
|
+
...options.fetch === void 0 ? {} : { fetch: options.fetch }
|
|
820
|
+
});
|
|
821
|
+
job.preparedChange = preparedChange;
|
|
822
|
+
job.result = preparedChange.result;
|
|
823
|
+
appendEvent(
|
|
824
|
+
job,
|
|
825
|
+
freezeEvent({
|
|
826
|
+
...eventBase(job),
|
|
827
|
+
type: "result-ready",
|
|
828
|
+
data: Object.freeze({ hasResult: true })
|
|
829
|
+
})
|
|
830
|
+
);
|
|
831
|
+
if (!preparedChange.validationPassed) {
|
|
832
|
+
transition(
|
|
833
|
+
job,
|
|
834
|
+
"failed",
|
|
835
|
+
"Required validation checks failed.",
|
|
836
|
+
import_shared2.ERROR_CODES.VALIDATION_FAILED
|
|
837
|
+
);
|
|
838
|
+
emitError(job, import_shared2.ERROR_CODES.VALIDATION_FAILED);
|
|
839
|
+
return;
|
|
840
|
+
}
|
|
841
|
+
if (preparedChange.result.diff.length === 0) {
|
|
842
|
+
transition(job, "completed", "No source changes were proposed.");
|
|
843
|
+
return;
|
|
844
|
+
}
|
|
845
|
+
if (options.ai.execution.applyMode === "auto" && preparedChange.autoApplyEligible) {
|
|
846
|
+
try {
|
|
847
|
+
await applyChange(job, preparedChange);
|
|
848
|
+
} catch {
|
|
849
|
+
}
|
|
850
|
+
return;
|
|
851
|
+
}
|
|
852
|
+
transition(job, "awaiting-review", "Validated changes are ready for review.");
|
|
853
|
+
} catch (error) {
|
|
854
|
+
finishWithError(job, error);
|
|
855
|
+
}
|
|
856
|
+
};
|
|
857
|
+
const hasActiveJob = (excludedJobId) => [...jobs.values()].some((job) => job.id !== excludedJobId && isActive(job.status));
|
|
858
|
+
const pruneJobs = () => {
|
|
859
|
+
if (jobs.size < MAX_RETAINED_JOBS) {
|
|
860
|
+
return;
|
|
861
|
+
}
|
|
862
|
+
for (const [jobId, job] of jobs) {
|
|
863
|
+
if (PRUNABLE_JOB_STATUSES.has(job.status)) {
|
|
864
|
+
jobs.delete(jobId);
|
|
865
|
+
}
|
|
866
|
+
if (jobs.size < MAX_RETAINED_JOBS) {
|
|
867
|
+
return;
|
|
868
|
+
}
|
|
869
|
+
}
|
|
870
|
+
};
|
|
871
|
+
return Object.freeze({
|
|
872
|
+
async apply(jobId) {
|
|
873
|
+
const job = requireJob(jobId);
|
|
874
|
+
if (job.status !== "awaiting-review" || job.preparedChange === void 0 || !job.preparedChange.validationPassed || job.result?.diff.length === 0) {
|
|
875
|
+
throw new import_shared2.SpotPatchError(import_shared2.ERROR_CODES.PATCH_REJECTED);
|
|
876
|
+
}
|
|
877
|
+
await applyChange(job, job.preparedChange);
|
|
878
|
+
return snapshot(job);
|
|
879
|
+
},
|
|
880
|
+
cancel(jobId) {
|
|
881
|
+
const job = requireJob(jobId);
|
|
882
|
+
if (!CANCELLABLE_JOB_STATUSES.has(job.status)) {
|
|
883
|
+
return snapshot(job);
|
|
884
|
+
}
|
|
885
|
+
if (job.status === "awaiting-review") {
|
|
886
|
+
job.preparedChange = void 0;
|
|
887
|
+
job.controller.abort("agent-review-cancelled");
|
|
888
|
+
transition(
|
|
889
|
+
job,
|
|
890
|
+
"cancelled",
|
|
891
|
+
"Agent review was closed without applying changes.",
|
|
892
|
+
import_shared2.ERROR_CODES.AGENT_CANCELLED
|
|
893
|
+
);
|
|
894
|
+
return snapshot(job);
|
|
895
|
+
}
|
|
896
|
+
transition(job, "cancelling", "Cancelling Agent job.");
|
|
897
|
+
job.controller.abort("agent-job-cancelled");
|
|
898
|
+
return snapshot(job);
|
|
899
|
+
},
|
|
900
|
+
async close() {
|
|
901
|
+
if (closed) {
|
|
902
|
+
return;
|
|
903
|
+
}
|
|
904
|
+
closed = true;
|
|
905
|
+
for (const job of jobs.values()) {
|
|
906
|
+
if (CANCELLABLE_JOB_STATUSES.has(job.status)) {
|
|
907
|
+
job.controller.abort("vite-server-closed");
|
|
908
|
+
}
|
|
909
|
+
}
|
|
910
|
+
await Promise.allSettled(
|
|
911
|
+
[...jobs.values()].map((job) => job.runPromise).filter((promise) => promise !== void 0)
|
|
912
|
+
);
|
|
913
|
+
capabilityCache.clear();
|
|
914
|
+
providerConsents.clear();
|
|
915
|
+
jobs.clear();
|
|
916
|
+
},
|
|
917
|
+
create(request) {
|
|
918
|
+
if (closed) {
|
|
919
|
+
throw new import_shared2.SpotPatchError(import_shared2.ERROR_CODES.AI_DISABLED);
|
|
920
|
+
}
|
|
921
|
+
if (hasActiveJob()) {
|
|
922
|
+
throw new import_shared2.SpotPatchError(import_shared2.ERROR_CODES.AGENT_BUSY);
|
|
923
|
+
}
|
|
924
|
+
pruneJobs();
|
|
925
|
+
if (jobs.size >= MAX_RETAINED_JOBS) {
|
|
926
|
+
throw new import_shared2.SpotPatchError(import_shared2.ERROR_CODES.AGENT_BUSY);
|
|
927
|
+
}
|
|
928
|
+
const selection = resolveSelection(
|
|
929
|
+
request.providerProfileId,
|
|
930
|
+
request.modelProfileId
|
|
931
|
+
);
|
|
932
|
+
providerConsents.add(selection.provider.id);
|
|
933
|
+
const id = dependencies.createJobId();
|
|
934
|
+
if (!JOB_ID_PATTERN.test(id) || jobs.has(id)) {
|
|
935
|
+
throw new import_shared2.SpotPatchError(import_shared2.ERROR_CODES.INTERNAL_ERROR);
|
|
936
|
+
}
|
|
937
|
+
const timestamp = dependencies.now();
|
|
938
|
+
const job = {
|
|
939
|
+
annotation: request.annotation,
|
|
940
|
+
controller: new AbortController(),
|
|
941
|
+
createdAt: timestamp,
|
|
942
|
+
credential: selection.credential,
|
|
943
|
+
errorCode: void 0,
|
|
944
|
+
events: [],
|
|
945
|
+
id,
|
|
946
|
+
listeners: /* @__PURE__ */ new Set(),
|
|
947
|
+
model: selection.model,
|
|
948
|
+
phaseMessage: "Agent job queued.",
|
|
949
|
+
preparedChange: void 0,
|
|
950
|
+
provider: selection.provider,
|
|
951
|
+
result: void 0,
|
|
952
|
+
runPromise: void 0,
|
|
953
|
+
sequence: 0,
|
|
954
|
+
status: "queued",
|
|
955
|
+
updatedAt: timestamp
|
|
956
|
+
};
|
|
957
|
+
jobs.set(id, job);
|
|
958
|
+
emitSnapshot(job);
|
|
959
|
+
emitPhase(job, job.phaseMessage);
|
|
960
|
+
job.runPromise = Promise.resolve().then(async () => runJob(job));
|
|
961
|
+
return snapshot(job);
|
|
962
|
+
},
|
|
963
|
+
events(jobId) {
|
|
964
|
+
return Object.freeze([...requireJob(jobId).events]);
|
|
965
|
+
},
|
|
966
|
+
async probe(request, signal) {
|
|
967
|
+
if (closed) {
|
|
968
|
+
throw new import_shared2.SpotPatchError(import_shared2.ERROR_CODES.AI_DISABLED);
|
|
969
|
+
}
|
|
970
|
+
return probeResolved(
|
|
971
|
+
resolveSelection(request.providerProfileId, request.modelProfileId),
|
|
972
|
+
signal
|
|
973
|
+
);
|
|
974
|
+
},
|
|
975
|
+
result(jobId) {
|
|
976
|
+
const job = requireJob(jobId);
|
|
977
|
+
const response = job.result === void 0 ? { snapshot: snapshot(job) } : { snapshot: snapshot(job), result: job.result };
|
|
978
|
+
return Object.freeze(response);
|
|
979
|
+
},
|
|
980
|
+
async revert(jobId) {
|
|
981
|
+
const job = requireJob(jobId);
|
|
982
|
+
if (job.status !== "applied" || job.preparedChange === void 0 || hasActiveJob(job.id)) {
|
|
983
|
+
throw new import_shared2.SpotPatchError(
|
|
984
|
+
hasActiveJob(job.id) ? import_shared2.ERROR_CODES.AGENT_BUSY : import_shared2.ERROR_CODES.APPLY_CONFLICT
|
|
985
|
+
);
|
|
986
|
+
}
|
|
987
|
+
transition(job, "reverting", "Reverting the applied Agent change.");
|
|
988
|
+
try {
|
|
989
|
+
await dependencies.revertChange(job.preparedChange);
|
|
990
|
+
transition(job, "reverted", "The Agent change was safely reverted.");
|
|
991
|
+
} catch (error) {
|
|
992
|
+
const normalized = normalizeError(error);
|
|
993
|
+
transition(
|
|
994
|
+
job,
|
|
995
|
+
"applied",
|
|
996
|
+
"Revert was rejected because project files changed.",
|
|
997
|
+
normalized.code
|
|
998
|
+
);
|
|
999
|
+
emitError(job, normalized.code);
|
|
1000
|
+
throw normalized;
|
|
1001
|
+
}
|
|
1002
|
+
return snapshot(job);
|
|
1003
|
+
},
|
|
1004
|
+
subscribe(jobId, listener) {
|
|
1005
|
+
const job = requireJob(jobId);
|
|
1006
|
+
job.listeners.add(listener);
|
|
1007
|
+
return () => {
|
|
1008
|
+
job.listeners.delete(listener);
|
|
1009
|
+
};
|
|
1010
|
+
}
|
|
1011
|
+
});
|
|
1012
|
+
}
|
|
1013
|
+
|
|
1014
|
+
// src/server/middleware.ts
|
|
1015
|
+
var import_shared9 = require("@spotpatch/shared");
|
|
1016
|
+
|
|
1017
|
+
// src/server/agent-http.ts
|
|
1018
|
+
var import_shared7 = require("@spotpatch/shared");
|
|
1019
|
+
|
|
1020
|
+
// src/server/agent-request.ts
|
|
1021
|
+
var import_promises3 = require("fs/promises");
|
|
1022
|
+
var import_node_path5 = __toESM(require("path"), 1);
|
|
1023
|
+
var import_shared5 = require("@spotpatch/shared");
|
|
1024
|
+
|
|
1025
|
+
// src/server/source-context.ts
|
|
1026
|
+
var import_promises2 = require("fs/promises");
|
|
1027
|
+
var import_node_path4 = __toESM(require("path"), 1);
|
|
1028
|
+
var import_shared4 = require("@spotpatch/shared");
|
|
1029
|
+
|
|
1030
|
+
// src/server/extract-code-context.ts
|
|
1031
|
+
var import_oxc_parser = require("oxc-parser");
|
|
1032
|
+
function isComponentName(name) {
|
|
1033
|
+
return /^[A-Z]/u.test(name);
|
|
1034
|
+
}
|
|
1035
|
+
function unwrapTypeExpression(expression) {
|
|
1036
|
+
switch (expression.type) {
|
|
1037
|
+
case "TSAsExpression":
|
|
1038
|
+
case "TSSatisfiesExpression":
|
|
1039
|
+
case "TSTypeAssertion":
|
|
1040
|
+
case "TSNonNullExpression":
|
|
1041
|
+
case "TSInstantiationExpression":
|
|
1042
|
+
return unwrapTypeExpression(expression.expression);
|
|
1043
|
+
default:
|
|
1044
|
+
return expression;
|
|
1045
|
+
}
|
|
1046
|
+
}
|
|
1047
|
+
function calleeName(expression) {
|
|
1048
|
+
const unwrapped = unwrapTypeExpression(expression);
|
|
1049
|
+
if (unwrapped.type === "Identifier") {
|
|
1050
|
+
return unwrapped.name;
|
|
1051
|
+
}
|
|
1052
|
+
if (unwrapped.type === "MemberExpression" && !unwrapped.computed) {
|
|
1053
|
+
return unwrapped.property.type === "Identifier" ? unwrapped.property.name : void 0;
|
|
1054
|
+
}
|
|
1055
|
+
return void 0;
|
|
1056
|
+
}
|
|
1057
|
+
function isFunctionExpression(expression) {
|
|
1058
|
+
const unwrapped = unwrapTypeExpression(expression);
|
|
1059
|
+
return unwrapped.type === "ArrowFunctionExpression" || unwrapped.type === "FunctionExpression";
|
|
1060
|
+
}
|
|
1061
|
+
function isSupportedComponentInitializer(expression) {
|
|
1062
|
+
const unwrapped = unwrapTypeExpression(expression);
|
|
1063
|
+
if (isFunctionExpression(unwrapped)) {
|
|
1064
|
+
return true;
|
|
1065
|
+
}
|
|
1066
|
+
if (unwrapped.type !== "CallExpression") {
|
|
1067
|
+
return false;
|
|
1068
|
+
}
|
|
1069
|
+
const name = calleeName(unwrapped.callee);
|
|
1070
|
+
if (name !== "memo" && name !== "forwardRef") {
|
|
1071
|
+
return false;
|
|
1072
|
+
}
|
|
1073
|
+
const firstArgument = unwrapped.arguments[0];
|
|
1074
|
+
return firstArgument !== void 0 && firstArgument.type !== "SpreadElement" && (isFunctionExpression(firstArgument) || isSupportedComponentInitializer(firstArgument));
|
|
1075
|
+
}
|
|
1076
|
+
function variableComponent(node) {
|
|
1077
|
+
if (node.id.type !== "Identifier" || !isComponentName(node.id.name) || node.init === null || !isSupportedComponentInitializer(node.init)) {
|
|
1078
|
+
return void 0;
|
|
1079
|
+
}
|
|
1080
|
+
return Object.freeze({ start: node.start, end: node.end, name: node.id.name });
|
|
1081
|
+
}
|
|
1082
|
+
function functionComponent(node) {
|
|
1083
|
+
return node.id !== null && isComponentName(node.id.name) && node.body !== null ? Object.freeze({ start: node.start, end: node.end, name: node.id.name }) : void 0;
|
|
1084
|
+
}
|
|
1085
|
+
function isReactComponentSuperclass(expression) {
|
|
1086
|
+
if (expression === null) {
|
|
1087
|
+
return false;
|
|
1088
|
+
}
|
|
1089
|
+
const unwrapped = unwrapTypeExpression(expression);
|
|
1090
|
+
if (unwrapped.type === "Identifier") {
|
|
1091
|
+
return unwrapped.name === "Component" || unwrapped.name === "PureComponent";
|
|
1092
|
+
}
|
|
1093
|
+
return unwrapped.type === "MemberExpression" && !unwrapped.computed && unwrapped.object.type === "Identifier" && unwrapped.object.name === "React" && (unwrapped.property.name === "Component" || unwrapped.property.name === "PureComponent");
|
|
1094
|
+
}
|
|
1095
|
+
function classComponent(node) {
|
|
1096
|
+
return node.id !== null && isComponentName(node.id.name) && isReactComponentSuperclass(node.superClass) ? Object.freeze({ start: node.start, end: node.end, name: node.id.name }) : void 0;
|
|
1097
|
+
}
|
|
1098
|
+
function selectedOffset(source, line, column) {
|
|
1099
|
+
const lines = source.split(/\r?\n/u);
|
|
1100
|
+
if (line < 1 || line > lines.length) {
|
|
1101
|
+
return void 0;
|
|
1102
|
+
}
|
|
1103
|
+
const lineStart = lines.slice(0, line - 1).reduce((total, value) => total + value.length + 1, 0);
|
|
1104
|
+
const lineLength = lines[line - 1]?.length ?? 0;
|
|
1105
|
+
return lineStart + Math.min(Math.max(0, column - 1), lineLength);
|
|
1106
|
+
}
|
|
1107
|
+
function findComponentSpan(options) {
|
|
1108
|
+
const offset = selectedOffset(options.source, options.line, options.column);
|
|
1109
|
+
if (offset === void 0) {
|
|
1110
|
+
return void 0;
|
|
1111
|
+
}
|
|
1112
|
+
let parseResult;
|
|
1113
|
+
try {
|
|
1114
|
+
parseResult = (0, import_oxc_parser.parseSync)(options.sourcePath, options.source, {
|
|
1115
|
+
sourceType: "module"
|
|
1116
|
+
});
|
|
1117
|
+
} catch {
|
|
1118
|
+
return void 0;
|
|
1119
|
+
}
|
|
1120
|
+
if (parseResult.errors.length > 0) {
|
|
1121
|
+
return void 0;
|
|
1122
|
+
}
|
|
1123
|
+
const jsxNodes = [];
|
|
1124
|
+
const components = [];
|
|
1125
|
+
const visitor = new import_oxc_parser.Visitor({
|
|
1126
|
+
JSXElement(node) {
|
|
1127
|
+
jsxNodes.push(node);
|
|
1128
|
+
},
|
|
1129
|
+
JSXFragment(node) {
|
|
1130
|
+
jsxNodes.push(node);
|
|
1131
|
+
},
|
|
1132
|
+
FunctionDeclaration(node) {
|
|
1133
|
+
const candidate = functionComponent(node);
|
|
1134
|
+
if (candidate !== void 0) {
|
|
1135
|
+
components.push(candidate);
|
|
1136
|
+
}
|
|
1137
|
+
},
|
|
1138
|
+
VariableDeclarator(node) {
|
|
1139
|
+
const candidate = variableComponent(node);
|
|
1140
|
+
if (candidate !== void 0) {
|
|
1141
|
+
components.push(candidate);
|
|
1142
|
+
}
|
|
1143
|
+
},
|
|
1144
|
+
ClassDeclaration(node) {
|
|
1145
|
+
const candidate = classComponent(node);
|
|
1146
|
+
if (candidate !== void 0) {
|
|
1147
|
+
components.push(candidate);
|
|
1148
|
+
}
|
|
1149
|
+
}
|
|
1150
|
+
});
|
|
1151
|
+
visitor.visit(parseResult.program);
|
|
1152
|
+
const selectedJsx = jsxNodes.filter((node) => node.start <= offset && node.end >= offset).sort((left, right) => left.end - left.start - (right.end - right.start))[0];
|
|
1153
|
+
if (selectedJsx === void 0) {
|
|
1154
|
+
return void 0;
|
|
1155
|
+
}
|
|
1156
|
+
return components.filter(
|
|
1157
|
+
(component) => component.start <= selectedJsx.start && component.end >= selectedJsx.end
|
|
1158
|
+
).sort((left, right) => left.end - left.start - (right.end - right.start))[0];
|
|
1159
|
+
}
|
|
1160
|
+
function lineAtOffset(source, offset) {
|
|
1161
|
+
let line = 1;
|
|
1162
|
+
for (let index = 0; index < offset; index += 1) {
|
|
1163
|
+
if (source[index] === "\n") {
|
|
1164
|
+
line += 1;
|
|
1165
|
+
}
|
|
1166
|
+
}
|
|
1167
|
+
return line;
|
|
1168
|
+
}
|
|
1169
|
+
function componentRange(source, component) {
|
|
1170
|
+
return Object.freeze({
|
|
1171
|
+
startLine: lineAtOffset(source, component.start),
|
|
1172
|
+
endLine: lineAtOffset(source, Math.max(component.start, component.end - 1))
|
|
1173
|
+
});
|
|
1174
|
+
}
|
|
1175
|
+
function truncateSelectedLine(line, column, maxCharacters) {
|
|
1176
|
+
if (line.length <= maxCharacters) {
|
|
1177
|
+
return line;
|
|
1178
|
+
}
|
|
1179
|
+
if (maxCharacters === 1) {
|
|
1180
|
+
return "\u2026";
|
|
1181
|
+
}
|
|
1182
|
+
const contentCharacters = maxCharacters - 2;
|
|
1183
|
+
const desiredStart = Math.max(0, column - 1 - Math.floor(contentCharacters / 2));
|
|
1184
|
+
const start = Math.min(desiredStart, line.length - contentCharacters);
|
|
1185
|
+
const end = start + contentCharacters;
|
|
1186
|
+
return `${start > 0 ? "\u2026" : ""}${line.slice(start, end)}${end < line.length ? "\u2026" : ""}`.slice(
|
|
1187
|
+
0,
|
|
1188
|
+
maxCharacters
|
|
1189
|
+
);
|
|
1190
|
+
}
|
|
1191
|
+
function boundedRange(lines, selectedLine, column, initialStart, initialEnd, maxCharacters) {
|
|
1192
|
+
let startLine = initialStart;
|
|
1193
|
+
let endLine = initialEnd;
|
|
1194
|
+
let excerpt = lines.slice(startLine - 1, endLine).join("\n");
|
|
1195
|
+
while (excerpt.length > maxCharacters && startLine < endLine) {
|
|
1196
|
+
if (endLine - selectedLine >= selectedLine - startLine) {
|
|
1197
|
+
endLine -= 1;
|
|
1198
|
+
} else {
|
|
1199
|
+
startLine += 1;
|
|
1200
|
+
}
|
|
1201
|
+
excerpt = lines.slice(startLine - 1, endLine).join("\n");
|
|
1202
|
+
}
|
|
1203
|
+
if (excerpt.length > maxCharacters) {
|
|
1204
|
+
startLine = selectedLine;
|
|
1205
|
+
endLine = selectedLine;
|
|
1206
|
+
excerpt = truncateSelectedLine(
|
|
1207
|
+
lines[selectedLine - 1] ?? "",
|
|
1208
|
+
column,
|
|
1209
|
+
maxCharacters
|
|
1210
|
+
);
|
|
1211
|
+
}
|
|
1212
|
+
return Object.freeze({ startLine, endLine, excerpt });
|
|
1213
|
+
}
|
|
1214
|
+
function nearbyContext(options) {
|
|
1215
|
+
const lines = options.source.split(/\r?\n/u);
|
|
1216
|
+
const initialStart = Math.max(1, options.line - Math.floor(options.maxLines / 2));
|
|
1217
|
+
const initialEnd = Math.min(lines.length, initialStart + options.maxLines - 1);
|
|
1218
|
+
const startLine = Math.max(1, initialEnd - options.maxLines + 1);
|
|
1219
|
+
const bounded = boundedRange(
|
|
1220
|
+
lines,
|
|
1221
|
+
options.line,
|
|
1222
|
+
options.column,
|
|
1223
|
+
startLine,
|
|
1224
|
+
initialEnd,
|
|
1225
|
+
options.maxCharacters
|
|
1226
|
+
);
|
|
1227
|
+
return Object.freeze({
|
|
1228
|
+
relativePath: options.relativePath,
|
|
1229
|
+
language: options.language,
|
|
1230
|
+
startLine: bounded.startLine,
|
|
1231
|
+
endLine: bounded.endLine,
|
|
1232
|
+
excerpt: bounded.excerpt,
|
|
1233
|
+
boundary: "nearby-lines"
|
|
1234
|
+
});
|
|
1235
|
+
}
|
|
1236
|
+
function extractCodeContext(options) {
|
|
1237
|
+
const component = findComponentSpan(options);
|
|
1238
|
+
if (component !== void 0) {
|
|
1239
|
+
const range = componentRange(options.source, component);
|
|
1240
|
+
const lineCount = range.endLine - range.startLine + 1;
|
|
1241
|
+
const excerpt = options.source.split(/\r?\n/u).slice(range.startLine - 1, range.endLine).join("\n");
|
|
1242
|
+
if (lineCount <= options.maxLines && excerpt.length <= options.maxCharacters) {
|
|
1243
|
+
return Object.freeze({
|
|
1244
|
+
relativePath: options.relativePath,
|
|
1245
|
+
language: options.language,
|
|
1246
|
+
startLine: range.startLine,
|
|
1247
|
+
endLine: range.endLine,
|
|
1248
|
+
excerpt,
|
|
1249
|
+
boundary: "component"
|
|
1250
|
+
});
|
|
1251
|
+
}
|
|
1252
|
+
}
|
|
1253
|
+
return nearbyContext(options);
|
|
1254
|
+
}
|
|
1255
|
+
|
|
1256
|
+
// src/server/source-file.ts
|
|
1257
|
+
var import_promises = require("fs/promises");
|
|
1258
|
+
var import_node_path3 = __toESM(require("path"), 1);
|
|
1259
|
+
var import_shared3 = require("@spotpatch/shared");
|
|
1260
|
+
|
|
1261
|
+
// src/server/constants.ts
|
|
1262
|
+
var MAX_REQUEST_BODY_BYTES = 32 * 1024;
|
|
1263
|
+
var MAX_AGENT_REQUEST_BODY_BYTES = 256 * 1024;
|
|
1264
|
+
var MAX_SOURCE_FILE_BYTES = 1024 * 1024;
|
|
1265
|
+
|
|
1266
|
+
// src/server/source-file.ts
|
|
1267
|
+
var ALLOWED_EXTENSIONS = /* @__PURE__ */ new Set([".jsx", ".tsx"]);
|
|
1268
|
+
function isMissingFileError(error) {
|
|
1269
|
+
return error instanceof Error && "code" in error && (error.code === "ENOENT" || error.code === "ENOTDIR");
|
|
1270
|
+
}
|
|
1271
|
+
async function assertInsideRoot(root, candidate) {
|
|
1272
|
+
let realRoot;
|
|
1273
|
+
let realCandidate;
|
|
1274
|
+
try {
|
|
1275
|
+
[realRoot, realCandidate] = await Promise.all([
|
|
1276
|
+
(0, import_promises.realpath)(root),
|
|
1277
|
+
(0, import_promises.realpath)(candidate)
|
|
1278
|
+
]);
|
|
1279
|
+
} catch (error) {
|
|
1280
|
+
if (isMissingFileError(error)) {
|
|
1281
|
+
throw new import_shared3.SpotPatchError(import_shared3.ERROR_CODES.SOURCE_NOT_FOUND, void 0, {
|
|
1282
|
+
cause: error
|
|
1283
|
+
});
|
|
1284
|
+
}
|
|
1285
|
+
throw error;
|
|
1286
|
+
}
|
|
1287
|
+
const relative = import_node_path3.default.relative(realRoot, realCandidate);
|
|
1288
|
+
const outside = relative.startsWith(`..${import_node_path3.default.sep}`) || relative === ".." || import_node_path3.default.isAbsolute(relative);
|
|
1289
|
+
if (outside) {
|
|
1290
|
+
throw new import_shared3.SpotPatchError(import_shared3.ERROR_CODES.SOURCE_OUTSIDE_ROOT);
|
|
1291
|
+
}
|
|
1292
|
+
return realCandidate;
|
|
1293
|
+
}
|
|
1294
|
+
async function resolveSourceFile(options) {
|
|
1295
|
+
const registeredPath = options.registry.resolve(options.fileId);
|
|
1296
|
+
if (registeredPath === void 0) {
|
|
1297
|
+
throw new import_shared3.SpotPatchError(import_shared3.ERROR_CODES.SOURCE_NOT_FOUND);
|
|
1298
|
+
}
|
|
1299
|
+
const sourcePath = await assertInsideRoot(options.root, registeredPath);
|
|
1300
|
+
if (!ALLOWED_EXTENSIONS.has(import_node_path3.default.extname(sourcePath).toLowerCase())) {
|
|
1301
|
+
throw new import_shared3.SpotPatchError(import_shared3.ERROR_CODES.SOURCE_NOT_FOUND);
|
|
1302
|
+
}
|
|
1303
|
+
let sourceStat;
|
|
1304
|
+
try {
|
|
1305
|
+
sourceStat = await (0, import_promises.stat)(sourcePath);
|
|
1306
|
+
} catch (error) {
|
|
1307
|
+
if (isMissingFileError(error)) {
|
|
1308
|
+
throw new import_shared3.SpotPatchError(import_shared3.ERROR_CODES.SOURCE_NOT_FOUND, void 0, {
|
|
1309
|
+
cause: error
|
|
1310
|
+
});
|
|
1311
|
+
}
|
|
1312
|
+
throw error;
|
|
1313
|
+
}
|
|
1314
|
+
if (!sourceStat.isFile()) {
|
|
1315
|
+
throw new import_shared3.SpotPatchError(import_shared3.ERROR_CODES.SOURCE_NOT_FOUND);
|
|
1316
|
+
}
|
|
1317
|
+
if (sourceStat.size > MAX_SOURCE_FILE_BYTES) {
|
|
1318
|
+
throw new import_shared3.SpotPatchError(import_shared3.ERROR_CODES.SOURCE_TOO_LARGE);
|
|
1319
|
+
}
|
|
1320
|
+
return sourcePath;
|
|
1321
|
+
}
|
|
1322
|
+
|
|
1323
|
+
// src/server/source-context.ts
|
|
1324
|
+
function toDisplayPath(root, sourcePath) {
|
|
1325
|
+
return import_node_path4.default.relative(root, sourcePath).split(import_node_path4.default.sep).join("/");
|
|
1326
|
+
}
|
|
1327
|
+
async function readSourceContext(options) {
|
|
1328
|
+
const sourcePath = await resolveSourceFile({
|
|
1329
|
+
fileId: options.request.fileId,
|
|
1330
|
+
registry: options.registry,
|
|
1331
|
+
root: options.root
|
|
1332
|
+
});
|
|
1333
|
+
let source;
|
|
1334
|
+
try {
|
|
1335
|
+
source = await (0, import_promises2.readFile)(sourcePath, "utf8");
|
|
1336
|
+
} catch (error) {
|
|
1337
|
+
if (error instanceof Error && "code" in error && (error.code === "ENOENT" || error.code === "ENOTDIR")) {
|
|
1338
|
+
throw new import_shared4.SpotPatchError(import_shared4.ERROR_CODES.SOURCE_NOT_FOUND, void 0, {
|
|
1339
|
+
cause: error
|
|
1340
|
+
});
|
|
1341
|
+
}
|
|
1342
|
+
throw error;
|
|
1343
|
+
}
|
|
1344
|
+
const lines = source.split(/\r?\n/);
|
|
1345
|
+
if (options.request.line > lines.length) {
|
|
1346
|
+
throw new import_shared4.SpotPatchError(import_shared4.ERROR_CODES.INVALID_REQUEST);
|
|
1347
|
+
}
|
|
1348
|
+
const extension = import_node_path4.default.extname(sourcePath).toLowerCase();
|
|
1349
|
+
return extractCodeContext({
|
|
1350
|
+
source,
|
|
1351
|
+
sourcePath,
|
|
1352
|
+
relativePath: toDisplayPath(await (0, import_promises2.realpath)(options.root), sourcePath),
|
|
1353
|
+
language: extension === ".tsx" ? "tsx" : "jsx",
|
|
1354
|
+
line: options.request.line,
|
|
1355
|
+
column: options.request.column,
|
|
1356
|
+
maxLines: Math.min(options.request.maxLines, options.maxLines),
|
|
1357
|
+
maxCharacters: options.maxCharacters
|
|
1358
|
+
});
|
|
1359
|
+
}
|
|
1360
|
+
|
|
1361
|
+
// src/server/agent-request.ts
|
|
1362
|
+
function compactSourceRef(source) {
|
|
1363
|
+
return Object.freeze({
|
|
1364
|
+
origin: source.origin,
|
|
1365
|
+
confidence: source.confidence,
|
|
1366
|
+
...source.fileId === void 0 ? {} : { fileId: source.fileId },
|
|
1367
|
+
...source.relativePath === void 0 ? {} : { relativePath: source.relativePath },
|
|
1368
|
+
...source.line === void 0 ? {} : { line: source.line },
|
|
1369
|
+
...source.column === void 0 ? {} : { column: source.column }
|
|
1370
|
+
});
|
|
1371
|
+
}
|
|
1372
|
+
async function authorizeSourceRef(source, registry, root) {
|
|
1373
|
+
const markerOrigin = source.origin === "jsx-host" || source.origin === "dom-ancestor";
|
|
1374
|
+
if (markerOrigin && (source.fileId === void 0 || source.line === void 0 || source.column === void 0)) {
|
|
1375
|
+
throw new import_shared5.SpotPatchError(import_shared5.ERROR_CODES.INVALID_REQUEST);
|
|
1376
|
+
}
|
|
1377
|
+
if (source.fileId === void 0) {
|
|
1378
|
+
if (source.origin === "none" && source.relativePath !== void 0) {
|
|
1379
|
+
throw new import_shared5.SpotPatchError(import_shared5.ERROR_CODES.INVALID_REQUEST);
|
|
1380
|
+
}
|
|
1381
|
+
return compactSourceRef(source);
|
|
1382
|
+
}
|
|
1383
|
+
const sourcePath = await resolveSourceFile({
|
|
1384
|
+
fileId: source.fileId,
|
|
1385
|
+
registry,
|
|
1386
|
+
root
|
|
1387
|
+
});
|
|
1388
|
+
const relativePath = import_node_path5.default.relative(await (0, import_promises3.realpath)(root), sourcePath).split(import_node_path5.default.sep).join("/");
|
|
1389
|
+
if (source.relativePath !== void 0 && source.relativePath !== relativePath) {
|
|
1390
|
+
throw new import_shared5.SpotPatchError(import_shared5.ERROR_CODES.INVALID_REQUEST);
|
|
1391
|
+
}
|
|
1392
|
+
return Object.freeze({
|
|
1393
|
+
...compactSourceRef(source),
|
|
1394
|
+
relativePath
|
|
1395
|
+
});
|
|
1396
|
+
}
|
|
1397
|
+
function freezeMatchedRule(rule) {
|
|
1398
|
+
return Object.freeze({
|
|
1399
|
+
selector: rule.selector,
|
|
1400
|
+
declarations: rule.declarations,
|
|
1401
|
+
...rule.source === void 0 ? {} : { source: rule.source },
|
|
1402
|
+
...rule.media === void 0 ? {} : { media: rule.media }
|
|
1403
|
+
});
|
|
1404
|
+
}
|
|
1405
|
+
function targetIdentity(target) {
|
|
1406
|
+
const source = target.source;
|
|
1407
|
+
if (source.fileId !== void 0 && source.line !== void 0 && source.column !== void 0) {
|
|
1408
|
+
return `source:${source.fileId}:${String(source.line)}:${String(source.column)}`;
|
|
1409
|
+
}
|
|
1410
|
+
return [
|
|
1411
|
+
"element",
|
|
1412
|
+
source.origin,
|
|
1413
|
+
source.relativePath ?? "",
|
|
1414
|
+
target.element.selector,
|
|
1415
|
+
target.element.sanitizedHtml
|
|
1416
|
+
].join("\0");
|
|
1417
|
+
}
|
|
1418
|
+
async function authorizeTarget(target, input) {
|
|
1419
|
+
const source = await authorizeSourceRef(target.source, input.registry, input.root);
|
|
1420
|
+
const reactSourceInput = target.react.source;
|
|
1421
|
+
const reactSource = reactSourceInput === void 0 ? void 0 : await authorizeSourceRef(reactSourceInput, input.registry, input.root);
|
|
1422
|
+
const marker = source.fileId === void 0 || source.line === void 0 || source.column === void 0 ? void 0 : Object.freeze({
|
|
1423
|
+
fileId: source.fileId,
|
|
1424
|
+
line: source.line,
|
|
1425
|
+
column: source.column,
|
|
1426
|
+
maxLines: input.options.budget.maxCodeLines
|
|
1427
|
+
});
|
|
1428
|
+
if (marker === void 0 && target.code !== void 0) {
|
|
1429
|
+
throw new import_shared5.SpotPatchError(import_shared5.ERROR_CODES.INVALID_REQUEST);
|
|
1430
|
+
}
|
|
1431
|
+
const code = marker === void 0 ? void 0 : await readSourceContext({
|
|
1432
|
+
request: marker,
|
|
1433
|
+
registry: input.registry,
|
|
1434
|
+
root: input.root,
|
|
1435
|
+
maxCharacters: input.options.budget.codeCharacters,
|
|
1436
|
+
maxLines: input.options.budget.maxCodeLines
|
|
1437
|
+
});
|
|
1438
|
+
if (target.code !== void 0 && target.code.relativePath !== code?.relativePath) {
|
|
1439
|
+
throw new import_shared5.SpotPatchError(import_shared5.ERROR_CODES.INVALID_REQUEST);
|
|
1440
|
+
}
|
|
1441
|
+
return Object.freeze({
|
|
1442
|
+
instruction: target.instruction,
|
|
1443
|
+
source,
|
|
1444
|
+
react: Object.freeze({
|
|
1445
|
+
supported: target.react.supported,
|
|
1446
|
+
...target.react.version === void 0 ? {} : { version: target.react.version },
|
|
1447
|
+
...target.react.componentName === void 0 ? {} : { componentName: target.react.componentName },
|
|
1448
|
+
componentStack: Object.freeze([...target.react.componentStack]),
|
|
1449
|
+
...reactSource === void 0 ? {} : { source: reactSource }
|
|
1450
|
+
}),
|
|
1451
|
+
element: Object.freeze({
|
|
1452
|
+
tagName: target.element.tagName,
|
|
1453
|
+
selector: target.element.selector,
|
|
1454
|
+
sanitizedHtml: target.element.sanitizedHtml,
|
|
1455
|
+
...target.element.textPreview === void 0 ? {} : { textPreview: target.element.textPreview },
|
|
1456
|
+
...target.element.role === void 0 ? {} : { role: target.element.role },
|
|
1457
|
+
rect: Object.freeze({ ...target.element.rect })
|
|
1458
|
+
}),
|
|
1459
|
+
styles: Object.freeze({
|
|
1460
|
+
classNames: Object.freeze([...target.styles.classNames]),
|
|
1461
|
+
...target.styles.inlineStyle === void 0 ? {} : { inlineStyle: target.styles.inlineStyle },
|
|
1462
|
+
matchedRules: Object.freeze(target.styles.matchedRules.map(freezeMatchedRule)),
|
|
1463
|
+
computed: Object.freeze({ ...target.styles.computed }),
|
|
1464
|
+
warnings: Object.freeze([...target.styles.warnings])
|
|
1465
|
+
}),
|
|
1466
|
+
...code === void 0 ? {} : { code: Object.freeze({ ...code }) },
|
|
1467
|
+
warnings: Object.freeze([...target.warnings])
|
|
1468
|
+
});
|
|
1469
|
+
}
|
|
1470
|
+
async function authorizeAgentJobRequest(input) {
|
|
1471
|
+
const requestedTargets = input.request.annotation.targets;
|
|
1472
|
+
if (requestedTargets.length > input.options.maxTargets) {
|
|
1473
|
+
throw new import_shared5.SpotPatchError(import_shared5.ERROR_CODES.INVALID_REQUEST);
|
|
1474
|
+
}
|
|
1475
|
+
const identities = requestedTargets.map(targetIdentity);
|
|
1476
|
+
if (new Set(identities).size !== identities.length) {
|
|
1477
|
+
throw new import_shared5.SpotPatchError(import_shared5.ERROR_CODES.INVALID_REQUEST);
|
|
1478
|
+
}
|
|
1479
|
+
const targets = Object.freeze(
|
|
1480
|
+
await Promise.all(requestedTargets.map((target) => authorizeTarget(target, input)))
|
|
1481
|
+
);
|
|
1482
|
+
const annotation = Object.freeze({
|
|
1483
|
+
schemaVersion: 3,
|
|
1484
|
+
id: input.request.annotation.id,
|
|
1485
|
+
locale: input.request.annotation.locale,
|
|
1486
|
+
page: Object.freeze({ ...input.request.annotation.page }),
|
|
1487
|
+
targets,
|
|
1488
|
+
createdAt: input.request.annotation.createdAt
|
|
1489
|
+
});
|
|
1490
|
+
return Object.freeze({
|
|
1491
|
+
annotation,
|
|
1492
|
+
providerProfileId: input.request.providerProfileId,
|
|
1493
|
+
modelProfileId: input.request.modelProfileId,
|
|
1494
|
+
providerDataConsent: true
|
|
1495
|
+
});
|
|
1496
|
+
}
|
|
1497
|
+
|
|
1498
|
+
// src/server/request-body.ts
|
|
1499
|
+
var import_shared6 = require("@spotpatch/shared");
|
|
1500
|
+
function isJsonContentType(value) {
|
|
1501
|
+
return value?.split(";", 1)[0]?.trim().toLowerCase() === "application/json";
|
|
1502
|
+
}
|
|
1503
|
+
async function readJsonRequestBody(request, maximumBytes = MAX_REQUEST_BODY_BYTES) {
|
|
1504
|
+
if (!isJsonContentType(request.headers["content-type"])) {
|
|
1505
|
+
throw new import_shared6.SpotPatchError(import_shared6.ERROR_CODES.INVALID_REQUEST);
|
|
1506
|
+
}
|
|
1507
|
+
const declaredLength = Number(request.headers["content-length"]);
|
|
1508
|
+
if (Number.isFinite(declaredLength) && declaredLength > maximumBytes) {
|
|
1509
|
+
throw new import_shared6.SpotPatchError(import_shared6.ERROR_CODES.INVALID_REQUEST);
|
|
1510
|
+
}
|
|
1511
|
+
const chunks = [];
|
|
1512
|
+
let byteLength = 0;
|
|
1513
|
+
let exceededLimit = false;
|
|
1514
|
+
for await (const rawChunk of request) {
|
|
1515
|
+
const chunk = rawChunk;
|
|
1516
|
+
if (typeof chunk !== "string" && !(chunk instanceof Uint8Array)) {
|
|
1517
|
+
throw new import_shared6.SpotPatchError(import_shared6.ERROR_CODES.INVALID_REQUEST);
|
|
1518
|
+
}
|
|
1519
|
+
const buffer = Buffer.from(chunk);
|
|
1520
|
+
byteLength += buffer.byteLength;
|
|
1521
|
+
if (byteLength > maximumBytes) {
|
|
1522
|
+
exceededLimit = true;
|
|
1523
|
+
continue;
|
|
1524
|
+
}
|
|
1525
|
+
chunks.push(buffer);
|
|
1526
|
+
}
|
|
1527
|
+
if (exceededLimit || byteLength === 0) {
|
|
1528
|
+
throw new import_shared6.SpotPatchError(import_shared6.ERROR_CODES.INVALID_REQUEST);
|
|
1529
|
+
}
|
|
1530
|
+
try {
|
|
1531
|
+
return JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
1532
|
+
} catch (error) {
|
|
1533
|
+
throw new import_shared6.SpotPatchError(import_shared6.ERROR_CODES.INVALID_REQUEST, void 0, {
|
|
1534
|
+
cause: error
|
|
1535
|
+
});
|
|
1536
|
+
}
|
|
1537
|
+
}
|
|
1538
|
+
|
|
1539
|
+
// src/server/agent-http.ts
|
|
1540
|
+
var AGENT_JOB_ID_PATTERN = /^[A-Za-z0-9_-]{22,128}$/;
|
|
1541
|
+
var AGENT_JOB_ACTIONS = /* @__PURE__ */ new Set([
|
|
1542
|
+
"events",
|
|
1543
|
+
"result",
|
|
1544
|
+
"cancel",
|
|
1545
|
+
"apply",
|
|
1546
|
+
"revert"
|
|
1547
|
+
]);
|
|
1548
|
+
var EVENT_STREAM_END_STATUSES = /* @__PURE__ */ new Set([
|
|
1549
|
+
"awaiting-review",
|
|
1550
|
+
"applied",
|
|
1551
|
+
"completed",
|
|
1552
|
+
"cancelled",
|
|
1553
|
+
"reverted",
|
|
1554
|
+
"failed"
|
|
1555
|
+
]);
|
|
1556
|
+
function matchAgentRequestPath(path10) {
|
|
1557
|
+
if (path10 === import_shared7.SPOTPATCH_ENDPOINTS.agentCapability) {
|
|
1558
|
+
return Object.freeze({ kind: "capability" });
|
|
1559
|
+
}
|
|
1560
|
+
if (path10 === import_shared7.SPOTPATCH_ENDPOINTS.agentJobs) {
|
|
1561
|
+
return Object.freeze({ kind: "create-job" });
|
|
1562
|
+
}
|
|
1563
|
+
const prefix = `${import_shared7.SPOTPATCH_ENDPOINTS.agentJobs}/`;
|
|
1564
|
+
if (!path10.startsWith(prefix)) {
|
|
1565
|
+
return void 0;
|
|
1566
|
+
}
|
|
1567
|
+
const segments = path10.slice(prefix.length).split("/");
|
|
1568
|
+
const jobId = segments[0];
|
|
1569
|
+
const action = segments[1];
|
|
1570
|
+
if (segments.length !== 2 || jobId === void 0 || !AGENT_JOB_ID_PATTERN.test(jobId) || action === void 0 || !AGENT_JOB_ACTIONS.has(action)) {
|
|
1571
|
+
return void 0;
|
|
1572
|
+
}
|
|
1573
|
+
return Object.freeze({
|
|
1574
|
+
kind: "job-action",
|
|
1575
|
+
action,
|
|
1576
|
+
jobId
|
|
1577
|
+
});
|
|
1578
|
+
}
|
|
1579
|
+
function requireAgentManager(options) {
|
|
1580
|
+
if (options.agentManager === void 0 || options.options.ai === false) {
|
|
1581
|
+
throw new import_shared7.SpotPatchError(import_shared7.ERROR_CODES.AI_DISABLED);
|
|
1582
|
+
}
|
|
1583
|
+
return options.agentManager;
|
|
1584
|
+
}
|
|
1585
|
+
function writeNdjsonEvent(response, event) {
|
|
1586
|
+
response.write(`${JSON.stringify(event)}
|
|
1587
|
+
`);
|
|
1588
|
+
}
|
|
1589
|
+
function streamAgentJobEvents(response, manager, jobId) {
|
|
1590
|
+
const events = manager.events(jobId);
|
|
1591
|
+
const current = manager.result(jobId).snapshot;
|
|
1592
|
+
response.statusCode = 200;
|
|
1593
|
+
response.setHeader("Cache-Control", "no-store");
|
|
1594
|
+
response.setHeader("Content-Type", "application/x-ndjson; charset=utf-8");
|
|
1595
|
+
response.setHeader("X-Content-Type-Options", "nosniff");
|
|
1596
|
+
for (const event of events) {
|
|
1597
|
+
writeNdjsonEvent(response, event);
|
|
1598
|
+
}
|
|
1599
|
+
if (EVENT_STREAM_END_STATUSES.has(current.status)) {
|
|
1600
|
+
response.end();
|
|
1601
|
+
return;
|
|
1602
|
+
}
|
|
1603
|
+
let settled = false;
|
|
1604
|
+
let unsubscribe = () => void 0;
|
|
1605
|
+
const heartbeat = setInterval(() => {
|
|
1606
|
+
if (!settled) {
|
|
1607
|
+
response.write("\n");
|
|
1608
|
+
}
|
|
1609
|
+
}, 15e3);
|
|
1610
|
+
heartbeat.unref();
|
|
1611
|
+
const cleanup = () => {
|
|
1612
|
+
if (settled) {
|
|
1613
|
+
return;
|
|
1614
|
+
}
|
|
1615
|
+
settled = true;
|
|
1616
|
+
clearInterval(heartbeat);
|
|
1617
|
+
unsubscribe();
|
|
1618
|
+
};
|
|
1619
|
+
unsubscribe = manager.subscribe(jobId, (event) => {
|
|
1620
|
+
if (settled) {
|
|
1621
|
+
return;
|
|
1622
|
+
}
|
|
1623
|
+
writeNdjsonEvent(response, event);
|
|
1624
|
+
if (event.type === "snapshot" && EVENT_STREAM_END_STATUSES.has(event.data.snapshot.status)) {
|
|
1625
|
+
cleanup();
|
|
1626
|
+
response.end();
|
|
1627
|
+
}
|
|
1628
|
+
});
|
|
1629
|
+
response.once("close", cleanup);
|
|
1630
|
+
response.once("error", cleanup);
|
|
1631
|
+
}
|
|
1632
|
+
async function handleCapability(request, response, options, writeSuccess) {
|
|
1633
|
+
if (request.method !== "POST") {
|
|
1634
|
+
throw new import_shared7.SpotPatchError(import_shared7.ERROR_CODES.INVALID_REQUEST);
|
|
1635
|
+
}
|
|
1636
|
+
const parsed = import_shared7.agentCapabilityRequestSchema.safeParse(
|
|
1637
|
+
await readJsonRequestBody(request)
|
|
1638
|
+
);
|
|
1639
|
+
if (!parsed.success) {
|
|
1640
|
+
throw new import_shared7.SpotPatchError(import_shared7.ERROR_CODES.INVALID_REQUEST);
|
|
1641
|
+
}
|
|
1642
|
+
const controller = new AbortController();
|
|
1643
|
+
const abort = () => {
|
|
1644
|
+
controller.abort("agent-capability-client-disconnected");
|
|
1645
|
+
};
|
|
1646
|
+
response.once("close", abort);
|
|
1647
|
+
try {
|
|
1648
|
+
const data = await requireAgentManager(options).probe(
|
|
1649
|
+
parsed.data,
|
|
1650
|
+
controller.signal
|
|
1651
|
+
);
|
|
1652
|
+
writeSuccess(response, 200, data);
|
|
1653
|
+
} finally {
|
|
1654
|
+
response.removeListener("close", abort);
|
|
1655
|
+
}
|
|
1656
|
+
}
|
|
1657
|
+
async function handleCreateJob(request, response, options, writeSuccess) {
|
|
1658
|
+
if (request.method !== "POST") {
|
|
1659
|
+
throw new import_shared7.SpotPatchError(import_shared7.ERROR_CODES.INVALID_REQUEST);
|
|
1660
|
+
}
|
|
1661
|
+
const parsed = import_shared7.agentJobCreateRequestSchema.safeParse(
|
|
1662
|
+
await readJsonRequestBody(request, MAX_AGENT_REQUEST_BODY_BYTES)
|
|
1663
|
+
);
|
|
1664
|
+
if (!parsed.success) {
|
|
1665
|
+
throw new import_shared7.SpotPatchError(import_shared7.ERROR_CODES.INVALID_REQUEST);
|
|
1666
|
+
}
|
|
1667
|
+
const authorizedRequest = await authorizeAgentJobRequest({
|
|
1668
|
+
request: parsed.data,
|
|
1669
|
+
options: options.options,
|
|
1670
|
+
registry: options.registry,
|
|
1671
|
+
root: options.root
|
|
1672
|
+
});
|
|
1673
|
+
const data = requireAgentManager(options).create(authorizedRequest);
|
|
1674
|
+
writeSuccess(response, 202, data);
|
|
1675
|
+
}
|
|
1676
|
+
async function handleJobAction(request, response, options, route, writeSuccess) {
|
|
1677
|
+
const manager = requireAgentManager(options);
|
|
1678
|
+
if (request.method !== "POST") {
|
|
1679
|
+
throw new import_shared7.SpotPatchError(import_shared7.ERROR_CODES.INVALID_REQUEST);
|
|
1680
|
+
}
|
|
1681
|
+
const parsed = import_shared7.agentJobActionRequestSchema.safeParse(
|
|
1682
|
+
await readJsonRequestBody(request)
|
|
1683
|
+
);
|
|
1684
|
+
if (!parsed.success) {
|
|
1685
|
+
throw new import_shared7.SpotPatchError(import_shared7.ERROR_CODES.INVALID_REQUEST);
|
|
1686
|
+
}
|
|
1687
|
+
if (route.action === "events") {
|
|
1688
|
+
streamAgentJobEvents(response, manager, route.jobId);
|
|
1689
|
+
return;
|
|
1690
|
+
}
|
|
1691
|
+
if (route.action === "result") {
|
|
1692
|
+
writeSuccess(response, 200, manager.result(route.jobId));
|
|
1693
|
+
return;
|
|
1694
|
+
}
|
|
1695
|
+
const data = route.action === "cancel" ? manager.cancel(route.jobId) : route.action === "apply" ? await manager.apply(route.jobId) : await manager.revert(route.jobId);
|
|
1696
|
+
writeSuccess(response, 200, data);
|
|
1697
|
+
}
|
|
1698
|
+
async function handleAgentRequest(request, response, options, route, writeSuccess) {
|
|
1699
|
+
if (route.kind === "capability") {
|
|
1700
|
+
await handleCapability(request, response, options, writeSuccess);
|
|
1701
|
+
return;
|
|
1702
|
+
}
|
|
1703
|
+
if (route.kind === "create-job") {
|
|
1704
|
+
await handleCreateJob(request, response, options, writeSuccess);
|
|
1705
|
+
return;
|
|
1706
|
+
}
|
|
1707
|
+
await handleJobAction(request, response, options, route, writeSuccess);
|
|
1708
|
+
}
|
|
1709
|
+
|
|
1710
|
+
// src/server/editor.ts
|
|
1711
|
+
var import_launch_editor = __toESM(require("launch-editor"), 1);
|
|
1712
|
+
var launchVSCode = (target, onError) => {
|
|
1713
|
+
(0, import_launch_editor.default)(target, "code", onError);
|
|
1714
|
+
};
|
|
1715
|
+
|
|
1716
|
+
// src/server/request-security.ts
|
|
1717
|
+
var import_node_crypto3 = require("crypto");
|
|
1718
|
+
var import_node_net = require("net");
|
|
1719
|
+
var import_shared8 = require("@spotpatch/shared");
|
|
1720
|
+
function getSingleHeader(request, name) {
|
|
1721
|
+
const value = request.headers[name.toLowerCase()];
|
|
1722
|
+
return Array.isArray(value) ? value[0] : value;
|
|
1723
|
+
}
|
|
1724
|
+
function tokensMatch(actual, expected) {
|
|
1725
|
+
if (actual === void 0) {
|
|
1726
|
+
return false;
|
|
1727
|
+
}
|
|
1728
|
+
const actualBytes = Buffer.from(actual);
|
|
1729
|
+
const expectedBytes = Buffer.from(expected);
|
|
1730
|
+
return actualBytes.byteLength === expectedBytes.byteLength && (0, import_node_crypto3.timingSafeEqual)(actualBytes, expectedBytes);
|
|
1731
|
+
}
|
|
1732
|
+
function isLoopbackHostname(hostname) {
|
|
1733
|
+
const normalized = hostname.toLowerCase().replace(/^\[|\]$/g, "");
|
|
1734
|
+
if (normalized === "localhost" || normalized.endsWith(".localhost")) {
|
|
1735
|
+
return true;
|
|
1736
|
+
}
|
|
1737
|
+
if (normalized === "::1") {
|
|
1738
|
+
return true;
|
|
1739
|
+
}
|
|
1740
|
+
if ((0, import_node_net.isIP)(normalized) === 4) {
|
|
1741
|
+
return normalized.split(".")[0] === "127";
|
|
1742
|
+
}
|
|
1743
|
+
return normalized.startsWith("::ffff:127.");
|
|
1744
|
+
}
|
|
1745
|
+
function parseHost(value) {
|
|
1746
|
+
try {
|
|
1747
|
+
return new URL(`http://${value}`);
|
|
1748
|
+
} catch {
|
|
1749
|
+
return void 0;
|
|
1750
|
+
}
|
|
1751
|
+
}
|
|
1752
|
+
function parseOrigin(value) {
|
|
1753
|
+
try {
|
|
1754
|
+
const origin = new URL(value);
|
|
1755
|
+
if (origin.protocol !== "http:" && origin.protocol !== "https:" || origin.username.length > 0 || origin.password.length > 0 || origin.origin === "null") {
|
|
1756
|
+
return void 0;
|
|
1757
|
+
}
|
|
1758
|
+
return origin;
|
|
1759
|
+
} catch {
|
|
1760
|
+
return void 0;
|
|
1761
|
+
}
|
|
1762
|
+
}
|
|
1763
|
+
function assertRequestAuthorized(request, options) {
|
|
1764
|
+
const actualToken = getSingleHeader(request, import_shared8.SPOTPATCH_TOKEN_HEADER);
|
|
1765
|
+
if (!tokensMatch(actualToken, options.sessionToken)) {
|
|
1766
|
+
throw new import_shared8.SpotPatchError(import_shared8.ERROR_CODES.INVALID_TOKEN);
|
|
1767
|
+
}
|
|
1768
|
+
const hostHeader = getSingleHeader(request, "host");
|
|
1769
|
+
const originHeader = getSingleHeader(request, "origin");
|
|
1770
|
+
const host = hostHeader === void 0 ? void 0 : parseHost(hostHeader);
|
|
1771
|
+
const origin = originHeader === void 0 ? void 0 : parseOrigin(originHeader);
|
|
1772
|
+
if (host === void 0 || origin === void 0) {
|
|
1773
|
+
throw new import_shared8.SpotPatchError(import_shared8.ERROR_CODES.ORIGIN_NOT_ALLOWED);
|
|
1774
|
+
}
|
|
1775
|
+
const hostIsLoopback = isLoopbackHostname(host.hostname);
|
|
1776
|
+
const originIsLoopback = isLoopbackHostname(origin.hostname);
|
|
1777
|
+
if (!options.allowLan) {
|
|
1778
|
+
if (!hostIsLoopback || !originIsLoopback) {
|
|
1779
|
+
throw new import_shared8.SpotPatchError(import_shared8.ERROR_CODES.ORIGIN_NOT_ALLOWED);
|
|
1780
|
+
}
|
|
1781
|
+
return;
|
|
1782
|
+
}
|
|
1783
|
+
if (!originIsLoopback && origin.host.toLowerCase() !== host.host.toLowerCase()) {
|
|
1784
|
+
throw new import_shared8.SpotPatchError(import_shared8.ERROR_CODES.ORIGIN_NOT_ALLOWED);
|
|
1785
|
+
}
|
|
1786
|
+
}
|
|
1787
|
+
|
|
1788
|
+
// src/server/middleware.ts
|
|
1789
|
+
var STATUS_BY_ERROR = Object.freeze({
|
|
1790
|
+
[import_shared9.ERROR_CODES.INVALID_REQUEST]: 400,
|
|
1791
|
+
[import_shared9.ERROR_CODES.INVALID_TOKEN]: 401,
|
|
1792
|
+
[import_shared9.ERROR_CODES.ORIGIN_NOT_ALLOWED]: 403,
|
|
1793
|
+
[import_shared9.ERROR_CODES.SOURCE_NOT_FOUND]: 404,
|
|
1794
|
+
[import_shared9.ERROR_CODES.SOURCE_OUTSIDE_ROOT]: 403,
|
|
1795
|
+
[import_shared9.ERROR_CODES.SOURCE_TOO_LARGE]: 413,
|
|
1796
|
+
[import_shared9.ERROR_CODES.EDITOR_OPEN_FAILED]: 500,
|
|
1797
|
+
[import_shared9.ERROR_CODES.AI_DISABLED]: 404,
|
|
1798
|
+
[import_shared9.ERROR_CODES.PROVIDER_NOT_CONFIGURED]: 503,
|
|
1799
|
+
[import_shared9.ERROR_CODES.PROVIDER_AUTH_FAILED]: 502,
|
|
1800
|
+
[import_shared9.ERROR_CODES.PROVIDER_PROTOCOL_UNSUPPORTED]: 502,
|
|
1801
|
+
[import_shared9.ERROR_CODES.MODEL_NOT_ALLOWED]: 400,
|
|
1802
|
+
[import_shared9.ERROR_CODES.MODEL_TOOL_CALL_UNSUPPORTED]: 422,
|
|
1803
|
+
[import_shared9.ERROR_CODES.PROVIDER_RATE_LIMITED]: 429,
|
|
1804
|
+
[import_shared9.ERROR_CODES.AGENT_BUSY]: 409,
|
|
1805
|
+
[import_shared9.ERROR_CODES.AGENT_LIMIT_EXCEEDED]: 413,
|
|
1806
|
+
[import_shared9.ERROR_CODES.AGENT_CANCELLED]: 409,
|
|
1807
|
+
[import_shared9.ERROR_CODES.WORKTREE_DIRTY]: 409,
|
|
1808
|
+
[import_shared9.ERROR_CODES.TOOL_DENIED]: 403,
|
|
1809
|
+
[import_shared9.ERROR_CODES.PATCH_REJECTED]: 422,
|
|
1810
|
+
[import_shared9.ERROR_CODES.VALIDATION_FAILED]: 422,
|
|
1811
|
+
[import_shared9.ERROR_CODES.APPLY_CONFLICT]: 409,
|
|
1812
|
+
[import_shared9.ERROR_CODES.INTERNAL_ERROR]: 500
|
|
1813
|
+
});
|
|
1814
|
+
var PUBLIC_MESSAGES = Object.freeze({
|
|
1815
|
+
[import_shared9.ERROR_CODES.INVALID_REQUEST]: "The request is invalid.",
|
|
1816
|
+
[import_shared9.ERROR_CODES.INVALID_TOKEN]: "The session token is invalid.",
|
|
1817
|
+
[import_shared9.ERROR_CODES.ORIGIN_NOT_ALLOWED]: "The request origin is not allowed.",
|
|
1818
|
+
[import_shared9.ERROR_CODES.SOURCE_NOT_FOUND]: "The source file is unavailable.",
|
|
1819
|
+
[import_shared9.ERROR_CODES.SOURCE_OUTSIDE_ROOT]: "The source file is outside the project root.",
|
|
1820
|
+
[import_shared9.ERROR_CODES.SOURCE_TOO_LARGE]: "The source file exceeds the size limit.",
|
|
1821
|
+
[import_shared9.ERROR_CODES.EDITOR_OPEN_FAILED]: "The editor request could not be started.",
|
|
1822
|
+
[import_shared9.ERROR_CODES.AI_DISABLED]: "AI execution is not enabled.",
|
|
1823
|
+
[import_shared9.ERROR_CODES.PROVIDER_NOT_CONFIGURED]: "The AI provider is unavailable.",
|
|
1824
|
+
[import_shared9.ERROR_CODES.PROVIDER_AUTH_FAILED]: "The AI provider rejected authentication.",
|
|
1825
|
+
[import_shared9.ERROR_CODES.PROVIDER_PROTOCOL_UNSUPPORTED]: "The AI provider protocol is unsupported.",
|
|
1826
|
+
[import_shared9.ERROR_CODES.MODEL_NOT_ALLOWED]: "The selected model is not allowed.",
|
|
1827
|
+
[import_shared9.ERROR_CODES.MODEL_TOOL_CALL_UNSUPPORTED]: "The selected model cannot run SpotPatch tools.",
|
|
1828
|
+
[import_shared9.ERROR_CODES.PROVIDER_RATE_LIMITED]: "The AI provider is rate limited.",
|
|
1829
|
+
[import_shared9.ERROR_CODES.AGENT_BUSY]: "Another Agent job is already running.",
|
|
1830
|
+
[import_shared9.ERROR_CODES.AGENT_LIMIT_EXCEEDED]: "The Agent job exceeded a safety limit.",
|
|
1831
|
+
[import_shared9.ERROR_CODES.AGENT_CANCELLED]: "The Agent job was cancelled.",
|
|
1832
|
+
[import_shared9.ERROR_CODES.WORKTREE_DIRTY]: "The project worktree must be clean.",
|
|
1833
|
+
[import_shared9.ERROR_CODES.TOOL_DENIED]: "The Agent tool request was denied.",
|
|
1834
|
+
[import_shared9.ERROR_CODES.PATCH_REJECTED]: "The proposed patch was rejected.",
|
|
1835
|
+
[import_shared9.ERROR_CODES.VALIDATION_FAILED]: "The proposed change failed validation.",
|
|
1836
|
+
[import_shared9.ERROR_CODES.APPLY_CONFLICT]: "The change conflicts with the current worktree.",
|
|
1837
|
+
[import_shared9.ERROR_CODES.INTERNAL_ERROR]: "The request could not be completed."
|
|
1838
|
+
});
|
|
1839
|
+
function writeJson(response, status, payload) {
|
|
1840
|
+
response.statusCode = status;
|
|
1841
|
+
response.setHeader("Cache-Control", "no-store");
|
|
1842
|
+
response.setHeader("Content-Type", "application/json; charset=utf-8");
|
|
1843
|
+
response.end(JSON.stringify(payload));
|
|
1844
|
+
}
|
|
1845
|
+
function asSpotPatchError(error) {
|
|
1846
|
+
return error instanceof import_shared9.SpotPatchError ? error : new import_shared9.SpotPatchError(import_shared9.ERROR_CODES.INTERNAL_ERROR, void 0, { cause: error });
|
|
1847
|
+
}
|
|
1848
|
+
function writeError(response, error, logger) {
|
|
1849
|
+
const normalized = asSpotPatchError(error);
|
|
1850
|
+
if (normalized.code === import_shared9.ERROR_CODES.INTERNAL_ERROR) {
|
|
1851
|
+
logger?.warn("[spotpatch:server] Internal request failure.");
|
|
1852
|
+
}
|
|
1853
|
+
writeJson(response, STATUS_BY_ERROR[normalized.code], {
|
|
1854
|
+
ok: false,
|
|
1855
|
+
error: {
|
|
1856
|
+
code: normalized.code,
|
|
1857
|
+
message: PUBLIC_MESSAGES[normalized.code]
|
|
1858
|
+
}
|
|
1859
|
+
});
|
|
1860
|
+
}
|
|
1861
|
+
function requestPath(request) {
|
|
1862
|
+
try {
|
|
1863
|
+
return new URL(request.url ?? "/", "http://spotpatch.invalid").pathname;
|
|
1864
|
+
} catch {
|
|
1865
|
+
return "";
|
|
1866
|
+
}
|
|
1867
|
+
}
|
|
1868
|
+
async function handleSourceContext(request, options) {
|
|
1869
|
+
const parsed = import_shared9.sourceContextRequestSchema.safeParse(
|
|
1870
|
+
await readJsonRequestBody(request)
|
|
1871
|
+
);
|
|
1872
|
+
if (!parsed.success) {
|
|
1873
|
+
throw new import_shared9.SpotPatchError(import_shared9.ERROR_CODES.INVALID_REQUEST);
|
|
1874
|
+
}
|
|
1875
|
+
return readSourceContext({
|
|
1876
|
+
request: parsed.data,
|
|
1877
|
+
registry: options.registry,
|
|
1878
|
+
root: options.root,
|
|
1879
|
+
maxCharacters: options.options.budget.codeCharacters,
|
|
1880
|
+
maxLines: options.options.budget.maxCodeLines
|
|
1881
|
+
});
|
|
1882
|
+
}
|
|
1883
|
+
async function handleOpenEditor(request, options) {
|
|
1884
|
+
const parsed = import_shared9.openEditorRequestSchema.safeParse(await readJsonRequestBody(request));
|
|
1885
|
+
if (!parsed.success) {
|
|
1886
|
+
throw new import_shared9.SpotPatchError(import_shared9.ERROR_CODES.INVALID_REQUEST);
|
|
1887
|
+
}
|
|
1888
|
+
const body = parsed.data;
|
|
1889
|
+
const sourcePath = await resolveSourceFile({
|
|
1890
|
+
fileId: body.fileId,
|
|
1891
|
+
registry: options.registry,
|
|
1892
|
+
root: options.root
|
|
1893
|
+
});
|
|
1894
|
+
const target = `${sourcePath}:${String(body.line)}:${String(body.column)}`;
|
|
1895
|
+
const editorLauncher = options.editorLauncher ?? launchVSCode;
|
|
1896
|
+
try {
|
|
1897
|
+
editorLauncher(target, () => {
|
|
1898
|
+
options.logger?.warn("[spotpatch:server] VS Code rejected an editor request.");
|
|
1899
|
+
});
|
|
1900
|
+
} catch (error) {
|
|
1901
|
+
throw new import_shared9.SpotPatchError(import_shared9.ERROR_CODES.EDITOR_OPEN_FAILED, void 0, {
|
|
1902
|
+
cause: error
|
|
1903
|
+
});
|
|
1904
|
+
}
|
|
1905
|
+
return Object.freeze({});
|
|
1906
|
+
}
|
|
1907
|
+
function createSpotPatchMiddleware(options) {
|
|
1908
|
+
return (request, response, next) => {
|
|
1909
|
+
const path10 = requestPath(request);
|
|
1910
|
+
const agentRoute = matchAgentRequestPath(path10);
|
|
1911
|
+
if (path10 !== import_shared9.SPOTPATCH_ENDPOINTS.sourceContext && path10 !== import_shared9.SPOTPATCH_ENDPOINTS.openEditor && agentRoute === void 0 && !path10.startsWith(`${import_shared9.SPOTPATCH_API_BASE}/`)) {
|
|
1912
|
+
next();
|
|
1913
|
+
return;
|
|
1914
|
+
}
|
|
1915
|
+
const handle = async () => {
|
|
1916
|
+
assertRequestAuthorized(request, {
|
|
1917
|
+
allowLan: options.options.allowLan,
|
|
1918
|
+
sessionToken: options.session.token
|
|
1919
|
+
});
|
|
1920
|
+
if (path10 === import_shared9.SPOTPATCH_ENDPOINTS.sourceContext) {
|
|
1921
|
+
if (request.method !== "POST") {
|
|
1922
|
+
throw new import_shared9.SpotPatchError(import_shared9.ERROR_CODES.INVALID_REQUEST);
|
|
1923
|
+
}
|
|
1924
|
+
const data = await handleSourceContext(request, options);
|
|
1925
|
+
writeJson(response, 200, { ok: true, data });
|
|
1926
|
+
return;
|
|
1927
|
+
}
|
|
1928
|
+
if (path10 === import_shared9.SPOTPATCH_ENDPOINTS.openEditor) {
|
|
1929
|
+
if (request.method !== "POST") {
|
|
1930
|
+
throw new import_shared9.SpotPatchError(import_shared9.ERROR_CODES.INVALID_REQUEST);
|
|
1931
|
+
}
|
|
1932
|
+
const data = await handleOpenEditor(request, options);
|
|
1933
|
+
writeJson(response, 200, { ok: true, data });
|
|
1934
|
+
return;
|
|
1935
|
+
}
|
|
1936
|
+
if (agentRoute === void 0) {
|
|
1937
|
+
throw new import_shared9.SpotPatchError(import_shared9.ERROR_CODES.INVALID_REQUEST);
|
|
1938
|
+
}
|
|
1939
|
+
await handleAgentRequest(
|
|
1940
|
+
request,
|
|
1941
|
+
response,
|
|
1942
|
+
options,
|
|
1943
|
+
agentRoute,
|
|
1944
|
+
(target, status, data) => {
|
|
1945
|
+
writeJson(target, status, { ok: true, data });
|
|
1946
|
+
}
|
|
1947
|
+
);
|
|
1948
|
+
};
|
|
1949
|
+
void handle().catch((error) => {
|
|
1950
|
+
writeError(response, error, options.logger);
|
|
1951
|
+
});
|
|
1952
|
+
};
|
|
1953
|
+
}
|
|
1954
|
+
|
|
1955
|
+
// src/server/server-plugin.ts
|
|
1956
|
+
function createServerPlugin(input) {
|
|
1957
|
+
let agentManager;
|
|
1958
|
+
let config;
|
|
1959
|
+
const closeResources = async () => {
|
|
1960
|
+
input.registry.clear();
|
|
1961
|
+
await agentManager?.close();
|
|
1962
|
+
agentManager = void 0;
|
|
1963
|
+
};
|
|
1964
|
+
return {
|
|
1965
|
+
name: "spotpatch:server",
|
|
1966
|
+
apply: "serve",
|
|
1967
|
+
enforce: "pre",
|
|
1968
|
+
configResolved(resolvedConfig) {
|
|
1969
|
+
config = resolvedConfig;
|
|
1970
|
+
},
|
|
1971
|
+
configureServer(server) {
|
|
1972
|
+
if (config === void 0) {
|
|
1973
|
+
throw new Error("SpotPatch server initialized before Vite config resolution.");
|
|
1974
|
+
}
|
|
1975
|
+
const root = import_node_path6.default.resolve(config.root);
|
|
1976
|
+
agentManager = input.options.ai === false ? void 0 : createAgentJobManager({ ai: input.options.ai, root });
|
|
1977
|
+
server.middlewares.use(
|
|
1978
|
+
createSpotPatchMiddleware({
|
|
1979
|
+
...agentManager === void 0 ? {} : { agentManager },
|
|
1980
|
+
options: input.options,
|
|
1981
|
+
registry: input.registry,
|
|
1982
|
+
root,
|
|
1983
|
+
session: input.session,
|
|
1984
|
+
logger: config.logger
|
|
1985
|
+
})
|
|
1986
|
+
);
|
|
1987
|
+
server.httpServer?.once("close", () => {
|
|
1988
|
+
void closeResources();
|
|
1989
|
+
});
|
|
1990
|
+
config.logger.info(
|
|
1991
|
+
`[spotpatch:vite] Ready. Toggle picker with ${input.options.shortcut}.`
|
|
1992
|
+
);
|
|
1993
|
+
},
|
|
1994
|
+
async closeBundle() {
|
|
1995
|
+
await closeResources();
|
|
1996
|
+
}
|
|
1997
|
+
};
|
|
1998
|
+
}
|
|
1999
|
+
|
|
2000
|
+
// src/session/session.ts
|
|
2001
|
+
var import_node_crypto4 = require("crypto");
|
|
2002
|
+
function createSession() {
|
|
2003
|
+
return Object.freeze({
|
|
2004
|
+
token: (0, import_node_crypto4.randomBytes)(16).toString("base64url")
|
|
2005
|
+
});
|
|
2006
|
+
}
|
|
2007
|
+
|
|
2008
|
+
// src/transform/transform-plugin.ts
|
|
2009
|
+
var import_node_crypto5 = require("crypto");
|
|
2010
|
+
var import_node_path9 = __toESM(require("path"), 1);
|
|
2011
|
+
|
|
2012
|
+
// src/transform/inject-source-markers.ts
|
|
2013
|
+
var import_node_path7 = __toESM(require("path"), 1);
|
|
2014
|
+
var import_shared11 = require("@spotpatch/shared");
|
|
2015
|
+
var import_magic_string = __toESM(require("magic-string"), 1);
|
|
2016
|
+
var import_oxc_parser2 = require("oxc-parser");
|
|
2017
|
+
|
|
2018
|
+
// src/transform/intrinsic-element.ts
|
|
2019
|
+
var import_shared10 = require("@spotpatch/shared");
|
|
2020
|
+
function isIntrinsicOpeningElement(node) {
|
|
2021
|
+
if (node.name.type !== "JSXIdentifier") {
|
|
2022
|
+
return false;
|
|
2023
|
+
}
|
|
2024
|
+
const { name } = node.name;
|
|
2025
|
+
const firstCharacter = name[0];
|
|
2026
|
+
return name.includes("-") || firstCharacter?.toLowerCase() === firstCharacter;
|
|
2027
|
+
}
|
|
2028
|
+
function hasSourceMarkerAttribute(node) {
|
|
2029
|
+
return node.attributes.some(
|
|
2030
|
+
(attribute) => attribute.type === "JSXAttribute" && attribute.name.type === "JSXIdentifier" && attribute.name.name === import_shared10.SOURCE_MARKER_ATTRIBUTE
|
|
2031
|
+
);
|
|
2032
|
+
}
|
|
2033
|
+
|
|
2034
|
+
// src/transform/source-position.ts
|
|
2035
|
+
function createLineStarts(code) {
|
|
2036
|
+
const starts = [0];
|
|
2037
|
+
for (let index = 0; index < code.length; index += 1) {
|
|
2038
|
+
if (code.charCodeAt(index) === 10) {
|
|
2039
|
+
starts.push(index + 1);
|
|
2040
|
+
}
|
|
2041
|
+
}
|
|
2042
|
+
return starts;
|
|
2043
|
+
}
|
|
2044
|
+
function getSourcePosition(lineStarts, offset) {
|
|
2045
|
+
let lower = 0;
|
|
2046
|
+
let upper = lineStarts.length - 1;
|
|
2047
|
+
while (lower <= upper) {
|
|
2048
|
+
const middle = Math.floor((lower + upper) / 2);
|
|
2049
|
+
const start = lineStarts[middle];
|
|
2050
|
+
if (start === void 0) {
|
|
2051
|
+
break;
|
|
2052
|
+
}
|
|
2053
|
+
if (start <= offset) {
|
|
2054
|
+
lower = middle + 1;
|
|
2055
|
+
} else {
|
|
2056
|
+
upper = middle - 1;
|
|
2057
|
+
}
|
|
2058
|
+
}
|
|
2059
|
+
const lineIndex = Math.max(0, upper);
|
|
2060
|
+
const lineStart = lineStarts[lineIndex] ?? 0;
|
|
2061
|
+
return Object.freeze({
|
|
2062
|
+
line: lineIndex + 1,
|
|
2063
|
+
column: offset - lineStart + 1
|
|
2064
|
+
});
|
|
2065
|
+
}
|
|
2066
|
+
|
|
2067
|
+
// src/transform/inject-source-markers.ts
|
|
2068
|
+
function findAttributeInsertionOffset(code, node) {
|
|
2069
|
+
let cursor = node.end - 2;
|
|
2070
|
+
while (cursor >= node.start && /\s/u.test(code[cursor] ?? "")) {
|
|
2071
|
+
cursor -= 1;
|
|
2072
|
+
}
|
|
2073
|
+
if (code[cursor] === "/") {
|
|
2074
|
+
cursor -= 1;
|
|
2075
|
+
while (cursor >= node.start && /\s/u.test(code[cursor] ?? "")) {
|
|
2076
|
+
cursor -= 1;
|
|
2077
|
+
}
|
|
2078
|
+
}
|
|
2079
|
+
return cursor + 1;
|
|
2080
|
+
}
|
|
2081
|
+
function normalizeRelativePath(root, absolutePath) {
|
|
2082
|
+
return import_node_path7.default.relative(root, absolutePath).split(import_node_path7.default.sep).join("/");
|
|
2083
|
+
}
|
|
2084
|
+
function createMarker(fileId, line, column) {
|
|
2085
|
+
return Object.freeze({ fileId, line, column });
|
|
2086
|
+
}
|
|
2087
|
+
function injectSourceMarkers(input) {
|
|
2088
|
+
const parseResult = (0, import_oxc_parser2.parseSync)(input.absolutePath, input.code, {
|
|
2089
|
+
sourceType: "module"
|
|
2090
|
+
});
|
|
2091
|
+
const parseError = parseResult.errors[0];
|
|
2092
|
+
if (parseError !== void 0) {
|
|
2093
|
+
throw new SyntaxError(parseError.message);
|
|
2094
|
+
}
|
|
2095
|
+
const magicString = new import_magic_string.default(input.code);
|
|
2096
|
+
const lineStarts = createLineStarts(input.code);
|
|
2097
|
+
let markerCount = 0;
|
|
2098
|
+
const visitor = new import_oxc_parser2.Visitor({
|
|
2099
|
+
JSXOpeningElement(node) {
|
|
2100
|
+
if (!isIntrinsicOpeningElement(node)) {
|
|
2101
|
+
return;
|
|
2102
|
+
}
|
|
2103
|
+
const position = getSourcePosition(lineStarts, node.start);
|
|
2104
|
+
if (hasSourceMarkerAttribute(node)) {
|
|
2105
|
+
input.onWarning?.({
|
|
2106
|
+
code: "EXISTING_SOURCE_MARKER",
|
|
2107
|
+
line: position.line,
|
|
2108
|
+
column: position.column
|
|
2109
|
+
});
|
|
2110
|
+
return;
|
|
2111
|
+
}
|
|
2112
|
+
const value = (0, import_shared11.formatSourceMarker)(
|
|
2113
|
+
createMarker(input.fileId, position.line, position.column)
|
|
2114
|
+
);
|
|
2115
|
+
const insertionOffset = findAttributeInsertionOffset(input.code, node);
|
|
2116
|
+
magicString.appendLeft(
|
|
2117
|
+
insertionOffset,
|
|
2118
|
+
` ${import_shared11.SOURCE_MARKER_ATTRIBUTE}=${JSON.stringify(value)}`
|
|
2119
|
+
);
|
|
2120
|
+
markerCount += 1;
|
|
2121
|
+
}
|
|
2122
|
+
});
|
|
2123
|
+
visitor.visit(parseResult.program);
|
|
2124
|
+
if (markerCount === 0) {
|
|
2125
|
+
return void 0;
|
|
2126
|
+
}
|
|
2127
|
+
return Object.freeze({
|
|
2128
|
+
code: magicString.toString(),
|
|
2129
|
+
map: magicString.generateMap({
|
|
2130
|
+
hires: true,
|
|
2131
|
+
includeContent: true,
|
|
2132
|
+
source: normalizeRelativePath(input.root, input.absolutePath)
|
|
2133
|
+
}),
|
|
2134
|
+
markerCount
|
|
2135
|
+
});
|
|
2136
|
+
}
|
|
2137
|
+
|
|
2138
|
+
// src/transform/transform-filter.ts
|
|
2139
|
+
var import_node_path8 = __toESM(require("path"), 1);
|
|
2140
|
+
var import_pluginutils = require("@rollup/pluginutils");
|
|
2141
|
+
var SUPPORTED_EXTENSIONS = /* @__PURE__ */ new Set([".jsx", ".tsx"]);
|
|
2142
|
+
function stripViteQuery(id) {
|
|
2143
|
+
const queryIndex = id.indexOf("?");
|
|
2144
|
+
return queryIndex === -1 ? id : id.slice(0, queryIndex);
|
|
2145
|
+
}
|
|
2146
|
+
function isInsideRoot(root, candidate, pathApi = import_node_path8.default) {
|
|
2147
|
+
const relative = pathApi.relative(pathApi.resolve(root), pathApi.resolve(candidate));
|
|
2148
|
+
return relative === "" || !relative.startsWith(`..${pathApi.sep}`) && relative !== ".." && !pathApi.isAbsolute(relative);
|
|
2149
|
+
}
|
|
2150
|
+
function createTransformFilter(root, options) {
|
|
2151
|
+
const matchesConfiguredFilter = (0, import_pluginutils.createFilter)(options.include, options.exclude);
|
|
2152
|
+
return Object.freeze({
|
|
2153
|
+
shouldTransform(id, code) {
|
|
2154
|
+
if (id.startsWith("\0") || id.includes("virtual:spotpatch")) {
|
|
2155
|
+
return false;
|
|
2156
|
+
}
|
|
2157
|
+
const cleanId = stripViteQuery(id);
|
|
2158
|
+
if (!SUPPORTED_EXTENSIONS.has(import_node_path8.default.extname(cleanId).toLowerCase())) {
|
|
2159
|
+
return false;
|
|
2160
|
+
}
|
|
2161
|
+
if (cleanId.includes("/node_modules/") || cleanId.includes("\\node_modules\\") || cleanId.includes("/packages/vite/") || cleanId.includes("\\packages\\vite\\")) {
|
|
2162
|
+
return false;
|
|
2163
|
+
}
|
|
2164
|
+
if (!isInsideRoot(root, cleanId) || !matchesConfiguredFilter(cleanId)) {
|
|
2165
|
+
return false;
|
|
2166
|
+
}
|
|
2167
|
+
return code.includes("<");
|
|
2168
|
+
}
|
|
2169
|
+
});
|
|
2170
|
+
}
|
|
2171
|
+
|
|
2172
|
+
// src/transform/transform-plugin.ts
|
|
2173
|
+
function createCacheKey(id, code) {
|
|
2174
|
+
const hash = (0, import_node_crypto5.createHash)("sha256").update(code).digest("base64url");
|
|
2175
|
+
return `${id}\0${hash}`;
|
|
2176
|
+
}
|
|
2177
|
+
function getDisplayPath(root, id) {
|
|
2178
|
+
const relative = import_node_path9.default.relative(root, stripViteQuery(id));
|
|
2179
|
+
return relative.split(import_node_path9.default.sep).join("/");
|
|
2180
|
+
}
|
|
2181
|
+
function createTransformPlugin(input) {
|
|
2182
|
+
let root = process.cwd();
|
|
2183
|
+
let filter = createTransformFilter(root, input.options);
|
|
2184
|
+
let logger;
|
|
2185
|
+
const warnedFiles = /* @__PURE__ */ new Set();
|
|
2186
|
+
const cache = /* @__PURE__ */ new Map();
|
|
2187
|
+
return {
|
|
2188
|
+
name: "spotpatch:transform",
|
|
2189
|
+
apply: "serve",
|
|
2190
|
+
enforce: "pre",
|
|
2191
|
+
configResolved(config) {
|
|
2192
|
+
root = import_node_path9.default.resolve(config.root);
|
|
2193
|
+
filter = createTransformFilter(root, input.options);
|
|
2194
|
+
logger = config.logger;
|
|
2195
|
+
},
|
|
2196
|
+
transform(code, id) {
|
|
2197
|
+
if (!filter.shouldTransform(id, code)) {
|
|
2198
|
+
return null;
|
|
2199
|
+
}
|
|
2200
|
+
const cleanId = import_node_path9.default.resolve(stripViteQuery(id));
|
|
2201
|
+
const cacheKey = createCacheKey(cleanId, code);
|
|
2202
|
+
if (cache.has(cacheKey)) {
|
|
2203
|
+
return cache.get(cacheKey) ?? null;
|
|
2204
|
+
}
|
|
2205
|
+
const startedAt = performance.now();
|
|
2206
|
+
try {
|
|
2207
|
+
const result = injectSourceMarkers({
|
|
2208
|
+
code,
|
|
2209
|
+
absolutePath: cleanId,
|
|
2210
|
+
root,
|
|
2211
|
+
fileId: input.registry.register(cleanId),
|
|
2212
|
+
onWarning(warning) {
|
|
2213
|
+
logger?.warn(
|
|
2214
|
+
`[spotpatch:transform] Existing source marker at ${getDisplayPath(root, id)}:${String(warning.line)}:${String(warning.column)}; preserving application value.`
|
|
2215
|
+
);
|
|
2216
|
+
}
|
|
2217
|
+
});
|
|
2218
|
+
const output = result === void 0 ? null : Object.freeze({
|
|
2219
|
+
code: result.code,
|
|
2220
|
+
map: result.map.toString()
|
|
2221
|
+
});
|
|
2222
|
+
cache.set(cacheKey, output);
|
|
2223
|
+
if (input.options.debug) {
|
|
2224
|
+
const elapsed = performance.now() - startedAt;
|
|
2225
|
+
logger?.info(
|
|
2226
|
+
`[spotpatch:transform] ${getDisplayPath(root, id)} ${elapsed.toFixed(2)}ms`
|
|
2227
|
+
);
|
|
2228
|
+
}
|
|
2229
|
+
return output;
|
|
2230
|
+
} catch (error) {
|
|
2231
|
+
if (!warnedFiles.has(cleanId)) {
|
|
2232
|
+
warnedFiles.add(cleanId);
|
|
2233
|
+
const detail = input.options.debug && error instanceof Error ? `: ${error.message}` : "";
|
|
2234
|
+
logger?.warn(
|
|
2235
|
+
`[spotpatch:transform] Failed to transform ${getDisplayPath(root, id)}; using original module${detail}`
|
|
2236
|
+
);
|
|
2237
|
+
}
|
|
2238
|
+
return null;
|
|
2239
|
+
}
|
|
2240
|
+
}
|
|
2241
|
+
};
|
|
2242
|
+
}
|
|
2243
|
+
|
|
2244
|
+
// src/plugin.ts
|
|
2245
|
+
function spotPatch(userOptions = {}) {
|
|
2246
|
+
const options = resolveOptions(userOptions);
|
|
2247
|
+
if (!options.enabled) {
|
|
2248
|
+
return [];
|
|
2249
|
+
}
|
|
2250
|
+
const registry = createSourceRegistry();
|
|
2251
|
+
const session = createSession();
|
|
2252
|
+
return [
|
|
2253
|
+
createTransformPlugin({ options, registry }),
|
|
2254
|
+
createRuntimeInjectionPlugin({ options, session }),
|
|
2255
|
+
createServerPlugin({ options, registry, session })
|
|
2256
|
+
];
|
|
2257
|
+
}
|
|
2258
|
+
|
|
2259
|
+
// src/index.ts
|
|
2260
|
+
var import_shared12 = require("@spotpatch/shared");
|
|
2261
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
2262
|
+
0 && (module.exports = {
|
|
2263
|
+
DEFAULT_AGENT_LIMITS,
|
|
2264
|
+
DEFAULT_OPTIONS,
|
|
2265
|
+
resolveOptions,
|
|
2266
|
+
spotPatch
|
|
2267
|
+
});
|
|
2268
|
+
//# sourceMappingURL=index.cjs.map
|