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