vite-plugin-opencode-assistant 1.0.3 → 1.0.5
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/es/client/index.d.ts +1 -0
- package/es/client/index.js +328 -0
- package/es/core/api.d.ts +14 -0
- package/es/core/api.js +294 -0
- package/es/core/injector.d.ts +2 -0
- package/es/core/injector.js +11 -0
- package/es/core/service.d.ts +18 -0
- package/es/core/service.js +163 -0
- package/es/endpoints/context.d.ts +3 -0
- package/es/endpoints/context.js +114 -0
- package/es/endpoints/index.d.ts +4 -0
- package/es/endpoints/index.js +16 -0
- package/es/endpoints/sessions.d.ts +3 -0
- package/es/endpoints/sessions.js +79 -0
- package/es/endpoints/sse.d.ts +3 -0
- package/es/endpoints/sse.js +56 -0
- package/es/endpoints/start.d.ts +3 -0
- package/es/endpoints/start.js +35 -0
- package/es/endpoints/types.d.ts +13 -0
- package/es/endpoints/widget.d.ts +3 -0
- package/es/endpoints/widget.js +57 -0
- package/es/index.d.ts +3 -0
- package/es/index.js +168 -0
- package/es/utils/paths.d.ts +3 -0
- package/es/utils/paths.js +38 -0
- package/es/utils/system.js +241 -0
- package/lib/client/index.d.ts +1 -0
- package/lib/client/index.js +328 -0
- package/lib/client.js +5597 -0
- package/lib/core/api.d.ts +14 -0
- package/lib/core/api.js +321 -0
- package/lib/core/injector.d.ts +2 -0
- package/lib/core/injector.js +34 -0
- package/lib/core/service.d.ts +18 -0
- package/lib/core/service.js +180 -0
- package/lib/endpoints/context.d.ts +3 -0
- package/lib/endpoints/context.js +137 -0
- package/lib/endpoints/index.d.ts +4 -0
- package/lib/endpoints/index.js +41 -0
- package/lib/endpoints/sessions.d.ts +3 -0
- package/lib/endpoints/sessions.js +102 -0
- package/lib/endpoints/sse.d.ts +3 -0
- package/lib/endpoints/sse.js +79 -0
- package/lib/endpoints/start.d.ts +3 -0
- package/lib/endpoints/start.js +58 -0
- package/lib/endpoints/types.d.ts +13 -0
- package/lib/endpoints/types.js +15 -0
- package/lib/endpoints/widget.d.ts +3 -0
- package/lib/endpoints/widget.js +90 -0
- package/lib/index.d.ts +3 -0
- package/lib/index.js +190 -0
- package/lib/style.css +1 -0
- package/lib/utils/paths.d.ts +3 -0
- package/lib/utils/paths.js +73 -0
- package/lib/utils/system.d.ts +5 -0
- package/lib/utils/system.js +274 -0
- package/package.json +29 -31
- package/README.md +0 -282
- package/dist/constants.d.ts +0 -73
- package/dist/constants.js +0 -74
- package/dist/constants.js.map +0 -1
- package/dist/logger.d.ts +0 -64
- package/dist/logger.js +0 -311
- package/dist/logger.js.map +0 -1
- package/dist/opencode/plugins/page-context.d.ts +0 -7
- package/dist/opencode/plugins/page-context.js +0 -345
- package/dist/opencode/plugins/page-context.js.map +0 -1
- package/dist/opencode/web.d.ts +0 -3
- package/dist/opencode/web.js +0 -81
- package/dist/opencode/web.js.map +0 -1
- package/dist/types.d.ts +0 -124
- package/dist/types.js +0 -2
- package/dist/types.js.map +0 -1
- package/dist/vite/client.js +0 -2288
- package/dist/vite/client.js.map +0 -1
- package/dist/vite/index.d.ts +0 -3
- package/dist/vite/index.js +0 -520
- package/dist/vite/index.js.map +0 -1
- package/dist/vite/injector.d.ts +0 -2
- package/dist/vite/injector.js +0 -6
- package/dist/vite/injector.js.map +0 -1
- package/dist/vite/utils.js +0 -206
- package/dist/vite/utils.js.map +0 -1
- /package/{dist/vite/client.d.ts → es/endpoints/types.js} +0 -0
- /package/{dist/vite/utils.d.ts → es/utils/system.d.ts} +0 -0
|
@@ -1,345 +0,0 @@
|
|
|
1
|
-
const LOG_PREFIX = "[vite-plugin-opencode]";
|
|
2
|
-
const COLORS = {
|
|
3
|
-
reset: "\x1B[0m",
|
|
4
|
-
dim: "\x1B[2m",
|
|
5
|
-
bright: "\x1B[1m",
|
|
6
|
-
red: "\x1B[31m",
|
|
7
|
-
green: "\x1B[32m",
|
|
8
|
-
yellow: "\x1B[33m",
|
|
9
|
-
magenta: "\x1B[35m",
|
|
10
|
-
cyan: "\x1B[36m"
|
|
11
|
-
};
|
|
12
|
-
const LEVEL_COLORS = {
|
|
13
|
-
[
|
|
14
|
-
0
|
|
15
|
-
/* DEBUG */
|
|
16
|
-
]: COLORS.cyan,
|
|
17
|
-
[
|
|
18
|
-
1
|
|
19
|
-
/* INFO */
|
|
20
|
-
]: COLORS.green,
|
|
21
|
-
[
|
|
22
|
-
2
|
|
23
|
-
/* WARN */
|
|
24
|
-
]: COLORS.yellow,
|
|
25
|
-
[
|
|
26
|
-
3
|
|
27
|
-
/* ERROR */
|
|
28
|
-
]: COLORS.red,
|
|
29
|
-
[
|
|
30
|
-
4
|
|
31
|
-
/* NONE */
|
|
32
|
-
]: COLORS.reset
|
|
33
|
-
};
|
|
34
|
-
const LEVEL_NAMES = {
|
|
35
|
-
[
|
|
36
|
-
0
|
|
37
|
-
/* DEBUG */
|
|
38
|
-
]: "DEBUG",
|
|
39
|
-
[
|
|
40
|
-
1
|
|
41
|
-
/* INFO */
|
|
42
|
-
]: "INFO",
|
|
43
|
-
[
|
|
44
|
-
2
|
|
45
|
-
/* WARN */
|
|
46
|
-
]: "WARN",
|
|
47
|
-
[
|
|
48
|
-
3
|
|
49
|
-
/* ERROR */
|
|
50
|
-
]: "ERROR",
|
|
51
|
-
[
|
|
52
|
-
4
|
|
53
|
-
/* NONE */
|
|
54
|
-
]: "NONE"
|
|
55
|
-
};
|
|
56
|
-
let globalConfig = {
|
|
57
|
-
level: 1,
|
|
58
|
-
showTrace: false
|
|
59
|
-
};
|
|
60
|
-
function getTimestamp() {
|
|
61
|
-
const now = /* @__PURE__ */ new Date();
|
|
62
|
-
const hours = String(now.getHours()).padStart(2, "0");
|
|
63
|
-
const minutes = String(now.getMinutes()).padStart(2, "0");
|
|
64
|
-
const seconds = String(now.getSeconds()).padStart(2, "0");
|
|
65
|
-
const ms = String(now.getMilliseconds()).padStart(3, "0");
|
|
66
|
-
return `${hours}:${minutes}:${seconds}.${ms}`;
|
|
67
|
-
}
|
|
68
|
-
function getCallerInfo(depth = 3) {
|
|
69
|
-
const stack = new Error().stack;
|
|
70
|
-
if (!stack) return "";
|
|
71
|
-
const lines = stack.split("\n");
|
|
72
|
-
const targetLine = lines[depth];
|
|
73
|
-
if (!targetLine) return "";
|
|
74
|
-
const match = targetLine.match(/at\s+(?:(.+?)\s+\()?(.+?):(\d+):(\d+)\)?/);
|
|
75
|
-
if (!match) return "";
|
|
76
|
-
const [, funcName, filePath, line] = match;
|
|
77
|
-
const fileName = filePath.split("/").pop() || filePath;
|
|
78
|
-
const func = funcName || "<anonymous>";
|
|
79
|
-
return `${fileName}:${line} ${func}`;
|
|
80
|
-
}
|
|
81
|
-
function formatValue(value, depth = 0) {
|
|
82
|
-
if (depth > 3) return "...";
|
|
83
|
-
if (value === null) return "null";
|
|
84
|
-
if (value === void 0) return "undefined";
|
|
85
|
-
if (typeof value === "string") return depth > 0 ? `"${value}"` : value;
|
|
86
|
-
if (typeof value === "number" || typeof value === "boolean") return String(value);
|
|
87
|
-
if (value instanceof Error) {
|
|
88
|
-
return `${value.name}: ${value.message}${value.stack ? `
|
|
89
|
-
${value.stack}` : ""}`;
|
|
90
|
-
}
|
|
91
|
-
if (Array.isArray(value)) {
|
|
92
|
-
if (value.length === 0) return "[]";
|
|
93
|
-
if (value.length > 5) {
|
|
94
|
-
const items2 = value.slice(0, 3).map((v) => formatValue(v, depth + 1));
|
|
95
|
-
return `[${items2.join(", ")}, ... ${value.length - 3} more items]`;
|
|
96
|
-
}
|
|
97
|
-
const items = value.map((v) => formatValue(v, depth + 1));
|
|
98
|
-
return `[${items.join(", ")}]`;
|
|
99
|
-
}
|
|
100
|
-
if (typeof value === "object") {
|
|
101
|
-
const entries = Object.entries(value);
|
|
102
|
-
if (entries.length === 0) return "{}";
|
|
103
|
-
if (entries.length > 5) {
|
|
104
|
-
const shown = entries.slice(0, 3).map(([k, v]) => `${k}: ${formatValue(v, depth + 1)}`);
|
|
105
|
-
return `{${shown.join(", ")}, ... ${entries.length - 3} more keys}`;
|
|
106
|
-
}
|
|
107
|
-
const formatted = entries.map(([k, v]) => `${k}: ${formatValue(v, depth + 1)}`);
|
|
108
|
-
return `{${formatted.join(", ")}}`;
|
|
109
|
-
}
|
|
110
|
-
return String(value);
|
|
111
|
-
}
|
|
112
|
-
function formatContext(context) {
|
|
113
|
-
if (!context || Object.keys(context).length === 0) return "";
|
|
114
|
-
const parts = [];
|
|
115
|
-
if (context.module) parts.push(`[${context.module}]`);
|
|
116
|
-
if (context.operation) parts.push(`(${context.operation})`);
|
|
117
|
-
if (context.traceId) parts.push(`trace:${context.traceId}`);
|
|
118
|
-
if (context.duration !== void 0) parts.push(`${context.duration}ms`);
|
|
119
|
-
const extraKeys = Object.keys(context).filter(
|
|
120
|
-
(k) => !["module", "operation", "traceId", "duration", "error"].includes(k)
|
|
121
|
-
);
|
|
122
|
-
if (extraKeys.length > 0) {
|
|
123
|
-
const extra = {};
|
|
124
|
-
extraKeys.forEach((k) => extra[k] = context[k]);
|
|
125
|
-
parts.push(formatValue(extra));
|
|
126
|
-
}
|
|
127
|
-
return parts.join(" ");
|
|
128
|
-
}
|
|
129
|
-
function log$1(level, message, context, ...args) {
|
|
130
|
-
if (level < globalConfig.level) return;
|
|
131
|
-
const parts = [];
|
|
132
|
-
parts.push(`${COLORS.dim}[${process.pid}]${COLORS.reset}`);
|
|
133
|
-
{
|
|
134
|
-
parts.push(`${COLORS.dim}${getTimestamp()}${COLORS.reset}`);
|
|
135
|
-
}
|
|
136
|
-
const levelColor = LEVEL_COLORS[level];
|
|
137
|
-
const levelName = LEVEL_NAMES[level].padEnd(5);
|
|
138
|
-
parts.push(`${levelColor}${levelName}${COLORS.reset}`);
|
|
139
|
-
parts.push(`${COLORS.bright}${LOG_PREFIX}${COLORS.reset}`);
|
|
140
|
-
const contextStr = formatContext(context);
|
|
141
|
-
if (contextStr) {
|
|
142
|
-
parts.push(`${COLORS.magenta}${contextStr}${COLORS.reset}`);
|
|
143
|
-
}
|
|
144
|
-
parts.push(message);
|
|
145
|
-
if (level >= 2) {
|
|
146
|
-
const caller = getCallerInfo(4);
|
|
147
|
-
if (caller) {
|
|
148
|
-
parts.push(`${COLORS.dim}(${caller})${COLORS.reset}`);
|
|
149
|
-
}
|
|
150
|
-
}
|
|
151
|
-
const formattedArgs = args.map((a) => formatValue(a)).join(" ");
|
|
152
|
-
if (formattedArgs) {
|
|
153
|
-
parts.push(formattedArgs);
|
|
154
|
-
}
|
|
155
|
-
const output = parts.join(" ");
|
|
156
|
-
if (level >= 3) {
|
|
157
|
-
console.error(output);
|
|
158
|
-
} else if (level === 2) {
|
|
159
|
-
console.warn(output);
|
|
160
|
-
} else {
|
|
161
|
-
console.log(output);
|
|
162
|
-
}
|
|
163
|
-
if ((context == null ? void 0 : context.error) && level >= 3 && globalConfig.showTrace) ;
|
|
164
|
-
}
|
|
165
|
-
const logger = {
|
|
166
|
-
debug(message, context, ...args) {
|
|
167
|
-
log$1(0, message, context, ...args);
|
|
168
|
-
},
|
|
169
|
-
info(message, context, ...args) {
|
|
170
|
-
log$1(1, message, context, ...args);
|
|
171
|
-
},
|
|
172
|
-
warn(message, context, ...args) {
|
|
173
|
-
log$1(2, message, context, ...args);
|
|
174
|
-
},
|
|
175
|
-
error(message, context, ...args) {
|
|
176
|
-
log$1(3, message, context, ...args);
|
|
177
|
-
},
|
|
178
|
-
group(label, context) {
|
|
179
|
-
return;
|
|
180
|
-
},
|
|
181
|
-
groupEnd() {
|
|
182
|
-
return;
|
|
183
|
-
}
|
|
184
|
-
};
|
|
185
|
-
class PerformanceTimer {
|
|
186
|
-
constructor(operation, context) {
|
|
187
|
-
this.operation = operation;
|
|
188
|
-
this.context = context || {};
|
|
189
|
-
this.startTime = performance.now();
|
|
190
|
-
logger.debug(`⏱️ Starting: ${operation}`, this.context);
|
|
191
|
-
}
|
|
192
|
-
end(message) {
|
|
193
|
-
const duration = Math.round(performance.now() - this.startTime);
|
|
194
|
-
const msg = message || `✓ Completed: ${this.operation}`;
|
|
195
|
-
logger.debug(msg, { ...this.context, duration });
|
|
196
|
-
return duration;
|
|
197
|
-
}
|
|
198
|
-
checkpoint(label) {
|
|
199
|
-
const elapsed = Math.round(performance.now() - this.startTime);
|
|
200
|
-
logger.debug(` ↳ ${label}`, { ...this.context, duration: elapsed });
|
|
201
|
-
return elapsed;
|
|
202
|
-
}
|
|
203
|
-
}
|
|
204
|
-
function createLogger(module) {
|
|
205
|
-
return {
|
|
206
|
-
debug(message, context, ...args) {
|
|
207
|
-
logger.debug(message, { ...context, module }, ...args);
|
|
208
|
-
},
|
|
209
|
-
info(message, context, ...args) {
|
|
210
|
-
logger.info(message, { ...context, module }, ...args);
|
|
211
|
-
},
|
|
212
|
-
warn(message, context, ...args) {
|
|
213
|
-
logger.warn(message, { ...context, module }, ...args);
|
|
214
|
-
},
|
|
215
|
-
error(message, context, ...args) {
|
|
216
|
-
logger.error(message, { ...context, module }, ...args);
|
|
217
|
-
},
|
|
218
|
-
timer(operation, context) {
|
|
219
|
-
return new PerformanceTimer(operation, { ...context, module });
|
|
220
|
-
}
|
|
221
|
-
};
|
|
222
|
-
}
|
|
223
|
-
const MAX_TEXT_LENGTH = 1e4;
|
|
224
|
-
const CONTEXT_MARKER = "__OPENCODE_CONTEXT__";
|
|
225
|
-
const log = createLogger("OpenCodePluginPageContext");
|
|
226
|
-
const PageContextPlugin = async () => {
|
|
227
|
-
log.info("PageContextPlugin loading...");
|
|
228
|
-
const contextApiUrl = process.env.OPENCODE_CONTEXT_API_URL;
|
|
229
|
-
log.debug("Context API URL:", { contextApiUrl });
|
|
230
|
-
if (!contextApiUrl) {
|
|
231
|
-
log.warn("OPENCODE_CONTEXT_API_URL is not set, page context plugin will not work");
|
|
232
|
-
return {};
|
|
233
|
-
}
|
|
234
|
-
const apiUrl = contextApiUrl;
|
|
235
|
-
log.info("Plugin initialized successfully");
|
|
236
|
-
async function getPageContext() {
|
|
237
|
-
try {
|
|
238
|
-
log.debug("Fetching context...", { apiUrl });
|
|
239
|
-
const response = await fetch(apiUrl);
|
|
240
|
-
if (!response.ok) {
|
|
241
|
-
log.error("Context API returned error status", {
|
|
242
|
-
status: response.status,
|
|
243
|
-
statusText: response.statusText,
|
|
244
|
-
apiUrl
|
|
245
|
-
});
|
|
246
|
-
return null;
|
|
247
|
-
}
|
|
248
|
-
const data = await response.json();
|
|
249
|
-
log.debug("Context received", { url: data.url, title: data.title });
|
|
250
|
-
return {
|
|
251
|
-
url: data.url || "",
|
|
252
|
-
title: data.title || "",
|
|
253
|
-
selectedElements: data.selectedElements
|
|
254
|
-
};
|
|
255
|
-
} catch (error) {
|
|
256
|
-
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
257
|
-
const errorName = error instanceof Error ? error.name : "UnknownError";
|
|
258
|
-
log.error("Failed to get context", {
|
|
259
|
-
error: errorMessage,
|
|
260
|
-
errorType: errorName,
|
|
261
|
-
apiUrl
|
|
262
|
-
});
|
|
263
|
-
return null;
|
|
264
|
-
}
|
|
265
|
-
}
|
|
266
|
-
async function clearSelectedElements() {
|
|
267
|
-
try {
|
|
268
|
-
log.debug("Clearing selected elements", { apiUrl });
|
|
269
|
-
const response = await fetch(apiUrl, { method: "DELETE" });
|
|
270
|
-
log.debug("Clear response", { status: response.status });
|
|
271
|
-
} catch (error) {
|
|
272
|
-
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
273
|
-
const errorName = error instanceof Error ? error.name : "UnknownError";
|
|
274
|
-
log.error("Failed to clear selected elements", {
|
|
275
|
-
error: errorMessage,
|
|
276
|
-
errorType: errorName,
|
|
277
|
-
apiUrl
|
|
278
|
-
});
|
|
279
|
-
}
|
|
280
|
-
}
|
|
281
|
-
function formatSelectedElement(element) {
|
|
282
|
-
var _a;
|
|
283
|
-
const parts = [];
|
|
284
|
-
if (element.filePath) {
|
|
285
|
-
let location = `文件: ${element.filePath}`;
|
|
286
|
-
if (element.line) {
|
|
287
|
-
location += `:${element.line}`;
|
|
288
|
-
if (element.column) {
|
|
289
|
-
location += `:${element.column}`;
|
|
290
|
-
}
|
|
291
|
-
}
|
|
292
|
-
parts.push(location);
|
|
293
|
-
}
|
|
294
|
-
if ((_a = element.innerText) == null ? void 0 : _a.trim()) {
|
|
295
|
-
const text = element.innerText.trim().substring(0, MAX_TEXT_LENGTH);
|
|
296
|
-
const suffix = element.innerText.length > MAX_TEXT_LENGTH ? "..." : "";
|
|
297
|
-
parts.push(`节点文本: "${text}${suffix}"`);
|
|
298
|
-
}
|
|
299
|
-
return parts.join("\n") + "\n";
|
|
300
|
-
}
|
|
301
|
-
function buildContextPrefix(context) {
|
|
302
|
-
var _a;
|
|
303
|
-
let prefix = `我现在正在浏览项目中的这个页面:${context.url}
|
|
304
|
-
|
|
305
|
-
`;
|
|
306
|
-
if ((_a = context.selectedElements) == null ? void 0 : _a.length) {
|
|
307
|
-
prefix += `我选中了以下节点:
|
|
308
|
-
|
|
309
|
-
`;
|
|
310
|
-
context.selectedElements.forEach((element) => {
|
|
311
|
-
prefix += formatSelectedElement(element) + "\n";
|
|
312
|
-
});
|
|
313
|
-
}
|
|
314
|
-
prefix += `我的请求:
|
|
315
|
-
`;
|
|
316
|
-
prefix += `
|
|
317
|
-
`;
|
|
318
|
-
return prefix;
|
|
319
|
-
}
|
|
320
|
-
return {
|
|
321
|
-
"experimental.chat.messages.transform": async (_input, output) => {
|
|
322
|
-
var _a, _b;
|
|
323
|
-
log.debug("Message transform hook called");
|
|
324
|
-
const context = await getPageContext();
|
|
325
|
-
log.debug("Context data", { hasUrl: !!(context == null ? void 0 : context.url), hasElements: !!((_a = context == null ? void 0 : context.selectedElements) == null ? void 0 : _a.length) });
|
|
326
|
-
if (!(context == null ? void 0 : context.url)) return;
|
|
327
|
-
const lastUserMsg = [...output.messages].reverse().find((m) => m.info.role === "user");
|
|
328
|
-
if (!lastUserMsg) return;
|
|
329
|
-
const textPart = lastUserMsg.parts.find((p) => p.type === "text");
|
|
330
|
-
if (!textPart || !("text" in textPart)) return;
|
|
331
|
-
if (textPart.text.includes(CONTEXT_MARKER)) return;
|
|
332
|
-
const prefix = buildContextPrefix(context);
|
|
333
|
-
textPart.text = prefix + textPart.text;
|
|
334
|
-
if ((_b = context.selectedElements) == null ? void 0 : _b.length) {
|
|
335
|
-
log.debug("Selected elements found, clearing...");
|
|
336
|
-
await clearSelectedElements();
|
|
337
|
-
}
|
|
338
|
-
}
|
|
339
|
-
};
|
|
340
|
-
};
|
|
341
|
-
export {
|
|
342
|
-
PageContextPlugin,
|
|
343
|
-
PageContextPlugin as default
|
|
344
|
-
};
|
|
345
|
-
//# sourceMappingURL=page-context.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"page-context.js","sources":["../../../src/constants.ts","../../../src/logger.ts","../../../src/opencode/plugins/page-context.ts"],"sourcesContent":["/**\n * @fileoverview OpenCode 插件常量定义\n */\n\n/** ==================== 网络相关 ==================== */\n\n/** 默认主机名 */\nexport const DEFAULT_HOSTNAME = '127.0.0.1'\n\n/** 默认 Web 服务端口 */\nexport const DEFAULT_WEB_PORT = 4097\n\n/** 服务器启动超时时间(毫秒) */\nexport const SERVER_START_TIMEOUT = 15000\n\n/** 服务器检查间隔(毫秒) */\nexport const SERVER_CHECK_INTERVAL = 100\n\n/** ==================== 重试相关 ==================== */\n\n/** 默认重试次数 */\nexport const DEFAULT_RETRIES = 5\n\n/** 重试延迟(毫秒) */\nexport const RETRY_DELAY = 500\n\n/** ==================== 端口查找 ==================== */\n\n/** 最大端口尝试次数 */\nexport const MAX_PORT_TRIES = 10\n\n/** ==================== 日志相关 ==================== */\n\n/** 插件日志前缀 */\nexport const LOG_PREFIX = '[vite-plugin-opencode]'\n\n/** OpenCode Web 日志前缀 */\nexport const WEB_LOG_PREFIX = '[OpenCode Web]'\n\n/** OpenCode Web 错误日志前缀 */\nexport const WEB_ERROR_PREFIX = '[OpenCode Web Error]'\n\n/** ==================== 挂件相关 ==================== */\n\n/** 挂件脚本路径 */\nexport const WIDGET_SCRIPT_PATH = '/__opencode_widget__.js'\n\n/** 配置数据属性名 */\nexport const CONFIG_DATA_ATTR = 'data-opencode-config'\n\n/** 上下文 API 路径 */\nexport const CONTEXT_API_PATH = '/__opencode_context__'\n\n/** 启动 API 路径 */\nexport const START_API_PATH = '/__opencode_start__'\n\n/** 会话列表 API 路径 */\nexport const SESSIONS_API_PATH = '/__opencode_sessions__'\n\n/** SSE 事件流路径 */\nexport const SSE_EVENTS_PATH = '/__opencode_events__'\n\n/** 上下文更新间隔(毫秒) */\nexport const CONTEXT_UPDATE_INTERVAL = 500\n\n/** 服务器同步间隔(毫秒) */\nexport const SERVER_SYNC_INTERVAL = 2000\n\n/** Vue Inspector 检查间隔(毫秒) */\nexport const INSPECTOR_CHECK_INTERVAL = 500\n\n/** 自动打开延迟(毫秒) */\nexport const AUTO_OPEN_DELAY = 1000\n\n/** 通知显示时间(毫秒) */\nexport const NOTIFICATION_DURATION = 3000\n\n/** ==================== 存储相关 ==================== */\n\n/** 初始化标记 */\nexport const INIT_MARKER = '__OPENCODE_INITIALIZED__'\n\n/** 选中元素存储键 */\nexport const SELECTED_ELEMENTS_KEY = '__opencode_selected_elements__'\n\n/** ==================== 文本处理 ==================== */\n\n/** 元素文本最大显示长度 */\nexport const MAX_TEXT_LENGTH = 100\n\n/** 元素上下文标记 */\nexport const CONTEXT_MARKER = '[元素上下文]'\n\n/** ==================== 默认配置 ==================== */\n\n/** 默认插件配置 */\nexport const DEFAULT_CONFIG = {\n enabled: true,\n webPort: DEFAULT_WEB_PORT,\n hostname: DEFAULT_HOSTNAME,\n position: 'bottom-right' as const,\n theme: 'auto' as const,\n open: false,\n autoReload: true,\n verbose: false,\n hotkey: 'ctrl+k',\n}\n","import { LOG_PREFIX } from './constants.js'\n\nexport enum LogLevel {\n DEBUG = 0,\n INFO = 1,\n WARN = 2,\n ERROR = 3,\n NONE = 4,\n}\n\nexport interface LogContext {\n module?: string\n operation?: string\n traceId?: string\n duration?: number\n error?: Error | unknown\n [key: string]: unknown\n}\n\ninterface LoggerConfig {\n verbose: boolean\n level: LogLevel\n showTimestamp: boolean\n showCaller: boolean\n showTrace: boolean\n indent: string\n}\n\nconst COLORS = {\n reset: '\\x1b[0m',\n dim: '\\x1b[2m',\n bright: '\\x1b[1m',\n red: '\\x1b[31m',\n green: '\\x1b[32m',\n yellow: '\\x1b[33m',\n blue: '\\x1b[34m',\n magenta: '\\x1b[35m',\n cyan: '\\x1b[36m',\n white: '\\x1b[37m',\n}\n\nconst LEVEL_COLORS: Record<LogLevel, string> = {\n [LogLevel.DEBUG]: COLORS.cyan,\n [LogLevel.INFO]: COLORS.green,\n [LogLevel.WARN]: COLORS.yellow,\n [LogLevel.ERROR]: COLORS.red,\n [LogLevel.NONE]: COLORS.reset,\n}\n\nconst LEVEL_NAMES: Record<LogLevel, string> = {\n [LogLevel.DEBUG]: 'DEBUG',\n [LogLevel.INFO]: 'INFO',\n [LogLevel.WARN]: 'WARN',\n [LogLevel.ERROR]: 'ERROR',\n [LogLevel.NONE]: 'NONE',\n}\n\nlet globalConfig: LoggerConfig = {\n verbose: false,\n level: LogLevel.INFO,\n showTimestamp: true,\n showCaller: true,\n showTrace: false,\n indent: ' ',\n}\n\nlet traceCounter = 0\n\nexport function configureLogger(options: Partial<LoggerConfig>): void {\n globalConfig = { ...globalConfig, ...options }\n}\n\nexport function setVerbose(verbose: boolean): void {\n globalConfig.verbose = verbose\n globalConfig.level = verbose ? LogLevel.DEBUG : LogLevel.INFO\n}\n\nfunction getTimestamp(): string {\n const now = new Date()\n const hours = String(now.getHours()).padStart(2, '0')\n const minutes = String(now.getMinutes()).padStart(2, '0')\n const seconds = String(now.getSeconds()).padStart(2, '0')\n const ms = String(now.getMilliseconds()).padStart(3, '0')\n return `${hours}:${minutes}:${seconds}.${ms}`\n}\n\nfunction getCallerInfo(depth: number = 3): string {\n const stack = new Error().stack\n if (!stack) return ''\n\n const lines = stack.split('\\n')\n const targetLine = lines[depth]\n if (!targetLine) return ''\n\n const match = targetLine.match(/at\\s+(?:(.+?)\\s+\\()?(.+?):(\\d+):(\\d+)\\)?/)\n if (!match) return ''\n\n const [, funcName, filePath, line] = match\n const fileName = filePath.split('/').pop() || filePath\n const func = funcName || '<anonymous>'\n return `${fileName}:${line} ${func}`\n}\n\nfunction formatValue(value: unknown, depth: number = 0): string {\n if (depth > 3) return '...'\n \n if (value === null) return 'null'\n if (value === undefined) return 'undefined'\n if (typeof value === 'string') return depth > 0 ? `\"${value}\"` : value\n if (typeof value === 'number' || typeof value === 'boolean') return String(value)\n if (value instanceof Error) {\n return `${value.name}: ${value.message}${value.stack ? `\\n${value.stack}` : ''}`\n }\n if (Array.isArray(value)) {\n if (value.length === 0) return '[]'\n if (value.length > 5) {\n const items = value.slice(0, 3).map(v => formatValue(v, depth + 1))\n return `[${items.join(', ')}, ... ${value.length - 3} more items]`\n }\n const items = value.map(v => formatValue(v, depth + 1))\n return `[${items.join(', ')}]`\n }\n if (typeof value === 'object') {\n const entries = Object.entries(value as Record<string, unknown>)\n if (entries.length === 0) return '{}'\n if (entries.length > 5) {\n const shown = entries.slice(0, 3).map(([k, v]) => `${k}: ${formatValue(v, depth + 1)}`)\n return `{${shown.join(', ')}, ... ${entries.length - 3} more keys}`\n }\n const formatted = entries.map(([k, v]) => `${k}: ${formatValue(v, depth + 1)}`)\n return `{${formatted.join(', ')}}`\n }\n return String(value)\n}\n\nfunction formatContext(context?: LogContext): string {\n if (!context || Object.keys(context).length === 0) return ''\n \n const parts: string[] = []\n \n if (context.module) parts.push(`[${context.module}]`)\n if (context.operation) parts.push(`(${context.operation})`)\n if (context.traceId) parts.push(`trace:${context.traceId}`)\n if (context.duration !== undefined) parts.push(`${context.duration}ms`)\n \n const extraKeys = Object.keys(context).filter(\n k => !['module', 'operation', 'traceId', 'duration', 'error'].includes(k)\n )\n if (extraKeys.length > 0) {\n const extra: Record<string, unknown> = {}\n extraKeys.forEach(k => extra[k] = context[k])\n parts.push(formatValue(extra))\n }\n \n return parts.join(' ')\n}\n\nfunction log(level: LogLevel, message: string, context?: LogContext, ...args: unknown[]): void {\n if (level < globalConfig.level) return\n \n const parts: string[] = []\n \n parts.push(`${COLORS.dim}[${process.pid}]${COLORS.reset}`)\n \n if (globalConfig.showTimestamp) {\n parts.push(`${COLORS.dim}${getTimestamp()}${COLORS.reset}`)\n }\n \n const levelColor = LEVEL_COLORS[level]\n const levelName = LEVEL_NAMES[level].padEnd(5)\n parts.push(`${levelColor}${levelName}${COLORS.reset}`)\n \n parts.push(`${COLORS.bright}${LOG_PREFIX}${COLORS.reset}`)\n \n const contextStr = formatContext(context)\n if (contextStr) {\n parts.push(`${COLORS.magenta}${contextStr}${COLORS.reset}`)\n }\n \n parts.push(message)\n \n if (globalConfig.showCaller && level >= LogLevel.WARN) {\n const caller = getCallerInfo(4)\n if (caller) {\n parts.push(`${COLORS.dim}(${caller})${COLORS.reset}`)\n }\n }\n \n const formattedArgs = args.map(a => formatValue(a)).join(' ')\n if (formattedArgs) {\n parts.push(formattedArgs)\n }\n \n const output = parts.join(' ')\n \n if (level >= LogLevel.ERROR) {\n console.error(output)\n } else if (level === LogLevel.WARN) {\n console.warn(output)\n } else {\n console.log(output)\n }\n \n if (context?.error && level >= LogLevel.ERROR && globalConfig.showTrace) {\n const err = context.error\n if (err instanceof Error && err.stack) {\n console.error(`${COLORS.dim}${err.stack}${COLORS.reset}`)\n }\n }\n}\n\nexport const logger = {\n debug(message: string, context?: LogContext, ...args: unknown[]): void {\n log(LogLevel.DEBUG, message, context, ...args)\n },\n \n info(message: string, context?: LogContext, ...args: unknown[]): void {\n log(LogLevel.INFO, message, context, ...args)\n },\n \n warn(message: string, context?: LogContext, ...args: unknown[]): void {\n log(LogLevel.WARN, message, context, ...args)\n },\n \n error(message: string, context?: LogContext, ...args: unknown[]): void {\n log(LogLevel.ERROR, message, context, ...args)\n },\n \n group(label: string, context?: LogContext): void {\n if (!globalConfig.verbose) return\n const contextStr = formatContext(context)\n console.log(`${COLORS.dim}[${process.pid}]${COLORS.reset} ${COLORS.bright}${LOG_PREFIX}${COLORS.reset} ${COLORS.blue}▼${COLORS.reset} ${label}${contextStr ? ` ${contextStr}` : ''}`)\n },\n \n groupEnd(): void {\n if (!globalConfig.verbose) return\n },\n}\n\nexport function generateTraceId(): string {\n traceCounter++\n const timestamp = Date.now().toString(36)\n const counter = traceCounter.toString(36).padStart(4, '0')\n return `${timestamp}-${counter}`\n}\n\nexport class PerformanceTimer {\n private startTime: number\n private context: LogContext\n private operation: string\n \n constructor(operation: string, context?: LogContext) {\n this.operation = operation\n this.context = context || {}\n this.startTime = performance.now()\n \n logger.debug(`⏱️ Starting: ${operation}`, this.context)\n }\n \n end(message?: string): number {\n const duration = Math.round(performance.now() - this.startTime)\n const msg = message || `✓ Completed: ${this.operation}`\n logger.debug(msg, { ...this.context, duration })\n return duration\n }\n \n checkpoint(label: string): number {\n const elapsed = Math.round(performance.now() - this.startTime)\n logger.debug(` ↳ ${label}`, { ...this.context, duration: elapsed })\n return elapsed\n }\n}\n\nexport class RequestContext {\n traceId: string\n method: string\n path: string\n startTime: number\n private checkpoints: Array<{ time: number; label: string }> = []\n \n constructor(method: string, path: string) {\n this.traceId = generateTraceId()\n this.method = method\n this.path = path\n this.startTime = performance.now()\n \n logger.debug(`→ ${method} ${path}`, { traceId: this.traceId, module: 'HTTP' })\n }\n \n checkpoint(label: string): void {\n const elapsed = Math.round(performance.now() - this.startTime)\n this.checkpoints.push({ time: elapsed, label })\n logger.debug(` → ${label}`, { traceId: this.traceId, duration: elapsed })\n }\n \n end(statusCode: number): void {\n const duration = Math.round(performance.now() - this.startTime)\n const statusColor = statusCode < 400 ? COLORS.green : COLORS.red\n logger.debug(`← ${this.method} ${this.path} ${statusColor}${statusCode}${COLORS.reset}`, {\n traceId: this.traceId,\n duration,\n checkpoints: this.checkpoints.length,\n })\n }\n \n error(error: Error | unknown): void {\n const duration = Math.round(performance.now() - this.startTime)\n logger.error(`✗ ${this.method} ${this.path}`, {\n traceId: this.traceId,\n duration,\n error,\n })\n }\n}\n\nexport function createLogger(module: string) {\n return {\n debug(message: string, context?: Omit<LogContext, 'module'>, ...args: unknown[]): void {\n logger.debug(message, { ...context, module }, ...args)\n },\n \n info(message: string, context?: Omit<LogContext, 'module'>, ...args: unknown[]): void {\n logger.info(message, { ...context, module }, ...args)\n },\n \n warn(message: string, context?: Omit<LogContext, 'module'>, ...args: unknown[]): void {\n logger.warn(message, { ...context, module }, ...args)\n },\n \n error(message: string, context?: Omit<LogContext, 'module'>, ...args: unknown[]): void {\n logger.error(message, { ...context, module }, ...args)\n },\n \n timer(operation: string, context?: Omit<LogContext, 'module'>): PerformanceTimer {\n return new PerformanceTimer(operation, { ...context, module })\n },\n }\n}\n\nexport function logMethod(\n target: unknown,\n propertyKey: string,\n descriptor: PropertyDescriptor\n): PropertyDescriptor {\n const originalMethod = descriptor.value\n const className = (target as { constructor: { name: string } }).constructor.name\n \n descriptor.value = async function (...args: unknown[]) {\n const timer = new PerformanceTimer(`${className}.${propertyKey}`)\n try {\n const result = await originalMethod.apply(this, args)\n timer.end()\n return result\n } catch (error) {\n timer.end('❌ Failed')\n throw error\n }\n }\n \n return descriptor\n}\n\nexport function formatBytes(bytes: number): string {\n if (bytes === 0) return '0B'\n const k = 1024\n const sizes = ['B', 'KB', 'MB', 'GB']\n const i = Math.floor(Math.log(bytes) / Math.log(k))\n return `${parseFloat((bytes / Math.pow(k, i)).toFixed(2))}${sizes[i]}`\n}\n\nexport function formatDuration(ms: number): string {\n if (ms < 1000) return `${ms}ms`\n if (ms < 60000) return `${(ms / 1000).toFixed(2)}s`\n const minutes = Math.floor(ms / 60000)\n const seconds = Math.round((ms % 60000) / 1000)\n return `${minutes}m ${seconds}s`\n}\n","/**\n * @fileoverview OpenCode 页面上下文插件\n * @description 用于将页面上下文信息注入到 AI 对话中\n */\n\nimport type { Plugin, Hooks } from \"@opencode-ai/plugin\"\nimport { createLogger } from '../../logger.js'\n\nconst MAX_TEXT_LENGTH = 10000\n\nconst CONTEXT_MARKER = '__OPENCODE_CONTEXT__'\n\nconst log = createLogger('OpenCodePluginPageContext')\n\ninterface SelectedElement {\n filePath: string | null\n line: number | null\n column: number | null\n innerText: string\n}\n\ninterface PageContextData {\n url: string\n title: string\n selectedElements?: SelectedElement[]\n}\n\nexport const PageContextPlugin: Plugin = async (): Promise<Hooks> => {\n log.info('PageContextPlugin loading...')\n \n const contextApiUrl = process.env.OPENCODE_CONTEXT_API_URL\n log.debug('Context API URL:', { contextApiUrl })\n\n if (!contextApiUrl) {\n log.warn('OPENCODE_CONTEXT_API_URL is not set, page context plugin will not work')\n return {}\n }\n\n const apiUrl = contextApiUrl as string\n log.info('Plugin initialized successfully')\n\n async function getPageContext(): Promise<PageContextData | null> {\n try {\n log.debug('Fetching context...', { apiUrl })\n const response = await fetch(apiUrl)\n \n if (!response.ok) {\n log.error('Context API returned error status', { \n status: response.status, \n statusText: response.statusText,\n apiUrl \n })\n return null\n }\n \n const data = await response.json() as PageContextData\n log.debug('Context received', { url: data.url, title: data.title })\n return {\n url: data.url || \"\",\n title: data.title || \"\",\n selectedElements: data.selectedElements\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error)\n const errorName = error instanceof Error ? error.name : 'UnknownError'\n log.error('Failed to get context', { \n error: errorMessage,\n errorType: errorName,\n apiUrl \n })\n return null\n }\n }\n\n async function clearSelectedElements(): Promise<void> {\n try {\n log.debug('Clearing selected elements', { apiUrl })\n const response = await fetch(apiUrl, { method: 'DELETE' })\n log.debug('Clear response', { status: response.status })\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error)\n const errorName = error instanceof Error ? error.name : 'UnknownError'\n log.error('Failed to clear selected elements', { \n error: errorMessage,\n errorType: errorName,\n apiUrl \n })\n }\n }\n\n function formatSelectedElement(element: SelectedElement): string {\n const parts: string[] = []\n\n if (element.filePath) {\n let location = `文件: ${element.filePath}`\n if (element.line) {\n location += `:${element.line}`\n if (element.column) {\n location += `:${element.column}`\n }\n }\n parts.push(location)\n }\n\n if (element.innerText?.trim()) {\n const text = element.innerText.trim().substring(0, MAX_TEXT_LENGTH)\n const suffix = element.innerText.length > MAX_TEXT_LENGTH ? '...' : ''\n parts.push(`节点文本: \"${text}${suffix}\"`)\n }\n\n return parts.join('\\n') + '\\n'\n }\n\n function buildContextPrefix(context: PageContextData): string {\n let prefix = `我现在正在浏览项目中的这个页面:${context.url}\\n\\n`\n\n if (context.selectedElements?.length) {\n prefix += `我选中了以下节点:\\n\\n`\n context.selectedElements.forEach((element) => {\n prefix += formatSelectedElement(element) + \"\\n\"\n })\n }\n\n prefix += `我的请求:\\n`\n\n prefix += `\\n`\n return prefix\n }\n\n return {\n \"experimental.chat.messages.transform\": async (_input, output) => {\n log.debug('Message transform hook called')\n const context = await getPageContext()\n log.debug('Context data', { hasUrl: !!context?.url, hasElements: !!context?.selectedElements?.length })\n \n if (!context?.url) return\n\n const lastUserMsg = [...output.messages].reverse().find(m => m.info.role === \"user\")\n if (!lastUserMsg) return\n\n const textPart = lastUserMsg.parts.find(p => p.type === \"text\")\n if (!textPart || !(\"text\" in textPart)) return\n \n if (textPart.text.includes(CONTEXT_MARKER)) return\n\n const prefix = buildContextPrefix(context)\n textPart.text = prefix + textPart.text\n\n if (context.selectedElements?.length) {\n log.debug('Selected elements found, clearing...')\n await clearSelectedElements()\n }\n }\n }\n}\n\nexport default PageContextPlugin\n"],"names":["items","log"],"mappings":"AAkCO,MAAM,aAAa;ACN1B,MAAM,SAAS;AAAA,EACb,OAAO;AAAA,EACP,KAAK;AAAA,EACL,QAAQ;AAAA,EACR,KAAK;AAAA,EACL,OAAO;AAAA,EACP,QAAQ;AAAA,EAER,SAAS;AAAA,EACT,MAAM;AAER;AAEA,MAAM,eAAyC;AAAA,EAC7C;AAAA,IAAC;AAAA;AAAA,EAAA,GAAiB,OAAO;AAAA,EACzB;AAAA,IAAC;AAAA;AAAA,EAAA,GAAgB,OAAO;AAAA,EACxB;AAAA,IAAC;AAAA;AAAA,EAAA,GAAgB,OAAO;AAAA,EACxB;AAAA,IAAC;AAAA;AAAA,EAAA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cAAU;AAAA;AACV,WAAO;AAAA,EACT;AAEA,SAAO;AAAA,IACL,wCAAwC,OAAO,QAAQ,WAAW;AFhG/D;AEiGD,UAAI,MAAM,+BAA+B;AACzC,YAAM,UAAU,MAAM,eAAA;AACtB,UAAI,MAAM,gBAAgB,EAAE,QAAQ,CAAC,EAAC,mCAAS,MAAK,aAAa,CAAC,GAAC,wCAAS,qBAAT,mBAA2B,SAAQ;AAEtG,UAAI,EAAC,mCAAS,KAAK;AAEnB,YAAM,cAAc,CAAC,GAAG,OAAO,QAAQ,EAAE,QAAA,EAAU,KAAK,CAAA,MAAK,EAAE,KAAK,SAAS,MAAM;AACnF,UAAI,CAAC,YAAa;AAElB,YAAM,WAAW,YAAY,MAAM,KAAK,CAAA,MAAK,EAAE,SAAS,MAAM;AAC9D,UAAI,CAAC,YAAY,EAAE,UAAU,UAAW;AAExC,UAAI,SAAS,KAAK,SAAS,cAAc,EAAG;AAE5C,YAAM,SAAS,mBAAmB,OAAO;AACzC,eAAS,OAAO,SAAS,SAAS;AAElC,WAAI,aAAQ,qBAAR,mBAA0B,QAAQ;AACpC,YAAI,MAAM,sCAAsC;AAChD,cAAM,sBAAA;AAAA,MACR;AAAA,IACF;AAAA,EAAA;AAEJ;"}
|
package/dist/opencode/web.d.ts
DELETED
package/dist/opencode/web.js
DELETED
|
@@ -1,81 +0,0 @@
|
|
|
1
|
-
import { execa } from 'execa';
|
|
2
|
-
import { createLogger } from '../logger.js';
|
|
3
|
-
import path from 'path';
|
|
4
|
-
import fs from 'fs';
|
|
5
|
-
const log = createLogger('OpenCodeWeb');
|
|
6
|
-
export function startOpenCodeWeb(options) {
|
|
7
|
-
const { port, hostname, cwd, configDir, corsOrigins, contextApiUrl } = options;
|
|
8
|
-
log.debug('Creating state directory', { cwd });
|
|
9
|
-
const stateDir = createStateDirectory(cwd);
|
|
10
|
-
const pluginPath = path.join(stateDir, 'plugins', 'page-context.js');
|
|
11
|
-
log.debug('Building process environment', {
|
|
12
|
-
stateDir,
|
|
13
|
-
configDir,
|
|
14
|
-
contextApiUrl,
|
|
15
|
-
pluginPath
|
|
16
|
-
});
|
|
17
|
-
const env = buildProcessEnv(stateDir, configDir, contextApiUrl, pluginPath);
|
|
18
|
-
const args = [
|
|
19
|
-
'serve',
|
|
20
|
-
'--port', String(port),
|
|
21
|
-
'--hostname', hostname,
|
|
22
|
-
];
|
|
23
|
-
if (corsOrigins && corsOrigins.length > 0) {
|
|
24
|
-
corsOrigins.forEach(origin => {
|
|
25
|
-
args.push('--cors', origin);
|
|
26
|
-
});
|
|
27
|
-
log.debug('CORS origins added', { origins: corsOrigins });
|
|
28
|
-
}
|
|
29
|
-
log.debug('Spawning OpenCode process', {
|
|
30
|
-
command: 'opencode',
|
|
31
|
-
args: args.join(' '),
|
|
32
|
-
cwd
|
|
33
|
-
});
|
|
34
|
-
const proc = execa('opencode', args, {
|
|
35
|
-
cwd,
|
|
36
|
-
env,
|
|
37
|
-
reject: false,
|
|
38
|
-
cleanup: true,
|
|
39
|
-
});
|
|
40
|
-
proc.stdout?.on('data', (data) => {
|
|
41
|
-
const output = data.toString().trim();
|
|
42
|
-
if (output) {
|
|
43
|
-
log.debug('[OpenCode stdout]', { output });
|
|
44
|
-
}
|
|
45
|
-
});
|
|
46
|
-
proc.stderr?.on('data', (data) => {
|
|
47
|
-
const output = data.toString().trim();
|
|
48
|
-
if (output) {
|
|
49
|
-
log.warn('[OpenCode stderr]', { output });
|
|
50
|
-
}
|
|
51
|
-
});
|
|
52
|
-
return proc;
|
|
53
|
-
}
|
|
54
|
-
function createStateDirectory(cwd) {
|
|
55
|
-
const stateDir = path.join(cwd, 'node_modules', '.cache', 'opencode');
|
|
56
|
-
if (!fs.existsSync(stateDir)) {
|
|
57
|
-
fs.mkdirSync(stateDir, { recursive: true });
|
|
58
|
-
log.debug('Created state directory', { stateDir });
|
|
59
|
-
}
|
|
60
|
-
return stateDir;
|
|
61
|
-
}
|
|
62
|
-
function buildProcessEnv(stateDir, configDir, contextApiUrl, pluginPath) {
|
|
63
|
-
const env = {
|
|
64
|
-
...Object.fromEntries(Object.entries(process.env).filter(([, v]) => v !== undefined)),
|
|
65
|
-
XDG_STATE_HOME: stateDir,
|
|
66
|
-
};
|
|
67
|
-
if (configDir) {
|
|
68
|
-
env.OPENCODE_CONFIG_DIR = configDir;
|
|
69
|
-
log.debug('Set OPENCODE_CONFIG_DIR', { configDir });
|
|
70
|
-
}
|
|
71
|
-
if (contextApiUrl) {
|
|
72
|
-
env.OPENCODE_CONTEXT_API_URL = contextApiUrl;
|
|
73
|
-
log.debug('Set OPENCODE_CONTEXT_API_URL', { contextApiUrl });
|
|
74
|
-
}
|
|
75
|
-
if (pluginPath) {
|
|
76
|
-
env.OPENCODE_PLUGINS = pluginPath;
|
|
77
|
-
log.debug('Set OPENCODE_PLUGINS', { pluginPath });
|
|
78
|
-
}
|
|
79
|
-
return env;
|
|
80
|
-
}
|
|
81
|
-
//# sourceMappingURL=web.js.map
|
package/dist/opencode/web.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"web.js","sourceRoot":"","sources":["../../src/opencode/web.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,OAAO,CAAA;AAG7B,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAA;AAC3C,OAAO,IAAI,MAAM,MAAM,CAAA;AACvB,OAAO,EAAE,MAAM,IAAI,CAAA;AAEnB,MAAM,GAAG,GAAG,YAAY,CAAC,aAAa,CAAC,CAAA;AAEvC,MAAM,UAAU,gBAAgB,CAAC,OAAmB;IAClD,MAAM,EAAE,IAAI,EAAE,QAAQ,EAAE,GAAG,EAAE,SAAS,EAAE,WAAW,EAAE,aAAa,EAAE,GAAG,OAAO,CAAA;IAE9E,GAAG,CAAC,KAAK,CAAC,0BAA0B,EAAE,EAAE,GAAG,EAAE,CAAC,CAAA;IAC9C,MAAM,QAAQ,GAAG,oBAAoB,CAAC,GAAG,CAAC,CAAA;IA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AAE,EAAE,SAAS,EAAE,CAAC,CAAA;IACrD,CAAC;IAED,IAAI,aAAa,EAAE,CAAC;QAClB,GAAG,CAAC,wBAAwB,GAAG,aAAa,CAAA;QAC5C,GAAG,CAAC,KAAK,CAAC,8BAA8B,EAAE,EAAE,aAAa,EAAE,CAAC,CAAA;IAC9D,CAAC;IAED,IAAI,UAAU,EAAE,CAAC;QACf,GAAG,CAAC,gBAAgB,GAAG,UAAU,CAAA;QACjC,GAAG,CAAC,KAAK,CAAC,sBAAsB,EAAE,EAAE,UAAU,EAAE,CAAC,CAAA;IACnD,CAAC;IAED,OAAO,GAAG,CAAA;AACZ,CAAC","sourcesContent":["import { execa } from 'execa'\nimport type { ResultPromise } from 'execa'\nimport { WebOptions } from '../types.js'\nimport { createLogger } from '../logger.js'\nimport path from 'path'\nimport fs from 'fs'\n\nconst log = createLogger('OpenCodeWeb')\n\nexport function startOpenCodeWeb(options: WebOptions): ResultPromise {\n const { port, hostname, cwd, configDir, corsOrigins, contextApiUrl } = options\n\n log.debug('Creating state directory', { cwd })\n const stateDir = createStateDirectory(cwd)\n\n const pluginPath = path.join(stateDir, 'plugins', 'page-context.js')\n log.debug('Building process environment', { \n stateDir, \n configDir, \n contextApiUrl, \n pluginPath \n })\n const env = buildProcessEnv(stateDir, configDir, contextApiUrl, pluginPath)\n\n const args = [\n 'serve',\n '--port', String(port),\n '--hostname', hostname,\n ]\n\n if (corsOrigins && corsOrigins.length > 0) {\n corsOrigins.forEach(origin => {\n args.push('--cors', origin)\n })\n log.debug('CORS origins added', { origins: corsOrigins })\n }\n\n log.debug('Spawning OpenCode process', { \n command: 'opencode', \n args: args.join(' '),\n cwd \n })\n \n const proc = execa('opencode', args, {\n cwd,\n env,\n reject: false,\n cleanup: true,\n })\n\n proc.stdout?.on('data', (data) => {\n const output = data.toString().trim()\n if (output) {\n log.debug('[OpenCode stdout]', { output })\n }\n })\n\n proc.stderr?.on('data', (data) => {\n const output = data.toString().trim()\n if (output) {\n log.warn('[OpenCode stderr]', { output })\n }\n })\n\n return proc\n}\n\nfunction createStateDirectory(cwd: string): string {\n const stateDir = path.join(cwd, 'node_modules', '.cache', 'opencode')\n \n if (!fs.existsSync(stateDir)) {\n fs.mkdirSync(stateDir, { recursive: true })\n log.debug('Created state directory', { stateDir })\n }\n \n return stateDir\n}\n\nfunction buildProcessEnv(stateDir: string, configDir?: string, contextApiUrl?: string, pluginPath?: string): Record<string, string> {\n const env: Record<string, string> = {\n ...Object.fromEntries(\n Object.entries(process.env).filter(([, v]) => v !== undefined)\n ) as Record<string, string>,\n XDG_STATE_HOME: stateDir,\n }\n\n if (configDir) {\n env.OPENCODE_CONFIG_DIR = configDir\n log.debug('Set OPENCODE_CONFIG_DIR', { configDir })\n }\n\n if (contextApiUrl) {\n env.OPENCODE_CONTEXT_API_URL = contextApiUrl\n log.debug('Set OPENCODE_CONTEXT_API_URL', { contextApiUrl })\n }\n\n if (pluginPath) {\n env.OPENCODE_PLUGINS = pluginPath\n log.debug('Set OPENCODE_PLUGINS', { pluginPath })\n }\n\n return env\n}\n"]}
|
package/dist/types.d.ts
DELETED
|
@@ -1,124 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* OpenCode Vite 插件配置选项
|
|
3
|
-
*/
|
|
4
|
-
export interface OpenCodeOptions {
|
|
5
|
-
/** 是否启用插件,默认 true */
|
|
6
|
-
enabled?: boolean;
|
|
7
|
-
/** Web 服务端口,默认 4097 */
|
|
8
|
-
webPort?: number;
|
|
9
|
-
/** 服务主机名,默认 '127.0.0.1' */
|
|
10
|
-
hostname?: string;
|
|
11
|
-
/** 挂件位置,默认 'bottom-right' */
|
|
12
|
-
position?: 'bottom-right' | 'bottom-left' | 'top-right' | 'top-left';
|
|
13
|
-
/** 主题模式,默认 'auto' */
|
|
14
|
-
theme?: 'light' | 'dark' | 'auto';
|
|
15
|
-
/** 是否自动打开面板,默认 false */
|
|
16
|
-
open?: boolean;
|
|
17
|
-
/** 是否自动重载,默认 true */
|
|
18
|
-
autoReload?: boolean;
|
|
19
|
-
/** 是否输出详细日志,默认 false */
|
|
20
|
-
verbose?: boolean;
|
|
21
|
-
/** 快捷键配置,默认 'ctrl+k' */
|
|
22
|
-
hotkey?: string;
|
|
23
|
-
}
|
|
24
|
-
/**
|
|
25
|
-
* OpenCode Web 服务启动选项
|
|
26
|
-
*/
|
|
27
|
-
export interface WebOptions {
|
|
28
|
-
/** 服务端口 */
|
|
29
|
-
port: number;
|
|
30
|
-
/** 服务主机名 */
|
|
31
|
-
hostname: string;
|
|
32
|
-
/** 服务器 URL */
|
|
33
|
-
serverUrl: string;
|
|
34
|
-
/** 工作目录 */
|
|
35
|
-
cwd: string;
|
|
36
|
-
/** 配置目录路径 */
|
|
37
|
-
configDir?: string;
|
|
38
|
-
/** CORS 允许的源 */
|
|
39
|
-
corsOrigins?: string[];
|
|
40
|
-
/** 上下文 API URL */
|
|
41
|
-
contextApiUrl?: string;
|
|
42
|
-
}
|
|
43
|
-
/**
|
|
44
|
-
* 挂件注入配置选项
|
|
45
|
-
*/
|
|
46
|
-
export interface WidgetOptions {
|
|
47
|
-
/** Web 服务 URL */
|
|
48
|
-
webUrl: string;
|
|
49
|
-
/** 服务器 URL */
|
|
50
|
-
serverUrl: string;
|
|
51
|
-
/** 挂件位置 */
|
|
52
|
-
position: string;
|
|
53
|
-
/** 主题模式 */
|
|
54
|
-
theme: string;
|
|
55
|
-
/** 是否自动打开 */
|
|
56
|
-
open: boolean;
|
|
57
|
-
/** 是否自动重载 */
|
|
58
|
-
autoReload: boolean;
|
|
59
|
-
/** 工作目录 */
|
|
60
|
-
cwd: string;
|
|
61
|
-
/** 会话 URL */
|
|
62
|
-
sessionUrl?: string;
|
|
63
|
-
/** 快捷键配置 */
|
|
64
|
-
hotkey?: string;
|
|
65
|
-
}
|
|
66
|
-
/**
|
|
67
|
-
* OpenCode 会话信息
|
|
68
|
-
*/
|
|
69
|
-
export interface SessionInfo {
|
|
70
|
-
/** 会话 ID */
|
|
71
|
-
id: string;
|
|
72
|
-
/** 会话标识符 */
|
|
73
|
-
slug: string;
|
|
74
|
-
/** 项目 ID */
|
|
75
|
-
projectID: string;
|
|
76
|
-
/** 项目目录 */
|
|
77
|
-
directory: string;
|
|
78
|
-
/** 会话标题 */
|
|
79
|
-
title: string;
|
|
80
|
-
/** 版本号 */
|
|
81
|
-
version: string;
|
|
82
|
-
/** 代码变更统计 */
|
|
83
|
-
summary: {
|
|
84
|
-
/** 新增行数 */
|
|
85
|
-
additions: number;
|
|
86
|
-
/** 删除行数 */
|
|
87
|
-
deletions: number;
|
|
88
|
-
/** 修改文件数 */
|
|
89
|
-
files: number;
|
|
90
|
-
};
|
|
91
|
-
/** 时间信息 */
|
|
92
|
-
time: {
|
|
93
|
-
/** 创建时间戳 */
|
|
94
|
-
created: number;
|
|
95
|
-
/** 更新时间戳 */
|
|
96
|
-
updated: number;
|
|
97
|
-
};
|
|
98
|
-
}
|
|
99
|
-
/**
|
|
100
|
-
* 选中的元素信息
|
|
101
|
-
*/
|
|
102
|
-
export interface SelectedElement {
|
|
103
|
-
/** 文件路径 */
|
|
104
|
-
filePath: string | null;
|
|
105
|
-
/** 行号 */
|
|
106
|
-
line: number | null;
|
|
107
|
-
/** 列号 */
|
|
108
|
-
column: number | null;
|
|
109
|
-
/** 元素内部文本 */
|
|
110
|
-
innerText: string;
|
|
111
|
-
/** 元素描述(标签名+选择器) */
|
|
112
|
-
description?: string;
|
|
113
|
-
}
|
|
114
|
-
/**
|
|
115
|
-
* 页面上下文数据
|
|
116
|
-
*/
|
|
117
|
-
export interface PageContext {
|
|
118
|
-
/** 当前页面 URL */
|
|
119
|
-
url: string;
|
|
120
|
-
/** 当前页面标题 */
|
|
121
|
-
title: string;
|
|
122
|
-
/** 选中的元素列表 */
|
|
123
|
-
selectedElements?: SelectedElement[];
|
|
124
|
-
}
|
package/dist/types.js
DELETED
package/dist/types.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"","sourcesContent":["/**\n * OpenCode Vite 插件配置选项\n */\nexport interface OpenCodeOptions {\n /** 是否启用插件,默认 true */\n enabled?: boolean\n /** Web 服务端口,默认 4097 */\n webPort?: number\n /** 服务主机名,默认 '127.0.0.1' */\n hostname?: string\n /** 挂件位置,默认 'bottom-right' */\n position?: 'bottom-right' | 'bottom-left' | 'top-right' | 'top-left'\n /** 主题模式,默认 'auto' */\n theme?: 'light' | 'dark' | 'auto'\n /** 是否自动打开面板,默认 false */\n open?: boolean\n /** 是否自动重载,默认 true */\n autoReload?: boolean\n /** 是否输出详细日志,默认 false */\n verbose?: boolean\n /** 快捷键配置,默认 'ctrl+k' */\n hotkey?: string\n}\n\n/**\n * OpenCode Web 服务启动选项\n */\nexport interface WebOptions {\n /** 服务端口 */\n port: number\n /** 服务主机名 */\n hostname: string\n /** 服务器 URL */\n serverUrl: string\n /** 工作目录 */\n cwd: string\n /** 配置目录路径 */\n configDir?: string\n /** CORS 允许的源 */\n corsOrigins?: string[]\n /** 上下文 API URL */\n contextApiUrl?: string\n}\n\n/**\n * 挂件注入配置选项\n */\nexport interface WidgetOptions {\n /** Web 服务 URL */\n webUrl: string\n /** 服务器 URL */\n serverUrl: string\n /** 挂件位置 */\n position: string\n /** 主题模式 */\n theme: string\n /** 是否自动打开 */\n open: boolean\n /** 是否自动重载 */\n autoReload: boolean\n /** 工作目录 */\n cwd: string\n /** 会话 URL */\n sessionUrl?: string\n /** 快捷键配置 */\n hotkey?: string\n}\n\n/**\n * OpenCode 会话信息\n */\nexport interface SessionInfo {\n /** 会话 ID */\n id: string\n /** 会话标识符 */\n slug: string\n /** 项目 ID */\n projectID: string\n /** 项目目录 */\n directory: string\n /** 会话标题 */\n title: string\n /** 版本号 */\n version: string\n /** 代码变更统计 */\n summary: {\n /** 新增行数 */\n additions: number\n /** 删除行数 */\n deletions: number\n /** 修改文件数 */\n files: number\n }\n /** 时间信息 */\n time: {\n /** 创建时间戳 */\n created: number\n /** 更新时间戳 */\n updated: number\n }\n}\n\n/**\n * 选中的元素信息\n */\nexport interface SelectedElement {\n /** 文件路径 */\n filePath: string | null\n /** 行号 */\n line: number | null\n /** 列号 */\n column: number | null\n /** 元素内部文本 */\n innerText: string\n /** 元素描述(标签名+选择器) */\n description?: string\n}\n\n/**\n * 页面上下文数据\n */\nexport interface PageContext {\n /** 当前页面 URL */\n url: string\n /** 当前页面标题 */\n title: string\n /** 选中的元素列表 */\n selectedElements?: SelectedElement[]\n}\n"]}
|