@keyou007/agent-bot 0.1.27-alpha.1 → 0.1.27-alpha.3
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/CHANGELOG.md +28 -0
- package/README.md +55 -5
- package/README.zh.md +55 -5
- package/SECURITY.md +14 -0
- package/assets/workspace-sessions.js +648 -0
- package/assets/workspace.css +160 -0
- package/assets/workspace.js +1795 -0
- package/config.example.yaml +3 -2
- package/dist/codex/CodexEventMapper.js +35 -0
- package/dist/codex/CodexEventMapper.js.map +1 -1
- package/dist/codex/CodexRuntime.js +50 -4
- package/dist/codex/CodexRuntime.js.map +1 -1
- package/dist/codex/TraeTaskNotification.js +44 -0
- package/dist/codex/TraeTaskNotification.js.map +1 -0
- package/dist/config/SettingsStore.js +1 -1
- package/dist/config/SettingsStore.js.map +1 -1
- package/dist/config/loadConfig.js +3 -2
- package/dist/config/loadConfig.js.map +1 -1
- package/dist/config/paths.js +3 -0
- package/dist/config/paths.js.map +1 -1
- package/dist/feishu/CardRenderer.js +54 -10
- package/dist/feishu/CardRenderer.js.map +1 -1
- package/dist/feishu/FeishuMessageClient.js +2 -2
- package/dist/feishu/FeishuMessageClient.js.map +1 -1
- package/dist/feishu/FeishuTurnPresenter.js +103 -16
- package/dist/feishu/FeishuTurnPresenter.js.map +1 -1
- package/dist/index.js +61 -17
- package/dist/index.js.map +1 -1
- package/dist/local-files/DiagramPreview.js +1 -1
- package/dist/local-files/GitDiffPreview.js +11 -7
- package/dist/local-files/GitDiffPreview.js.map +1 -1
- package/dist/local-files/LocalFileViewerServer.js +359 -37
- package/dist/local-files/LocalFileViewerServer.js.map +1 -1
- package/dist/local-files/MarkdownFileLinks.js +5 -4
- package/dist/local-files/MarkdownFileLinks.js.map +1 -1
- package/dist/local-files/TurnPreviewPage.js +32 -10
- package/dist/local-files/TurnPreviewPage.js.map +1 -1
- package/dist/local-files/WebPageTitle.js +85 -0
- package/dist/local-files/WebPageTitle.js.map +1 -0
- package/dist/local-files/WorkspaceFiles.js +553 -0
- package/dist/local-files/WorkspaceFiles.js.map +1 -0
- package/dist/local-files/WorkspaceOrigin.js +38 -0
- package/dist/local-files/WorkspaceOrigin.js.map +1 -0
- package/dist/local-files/WorkspacePage.js +19 -0
- package/dist/local-files/WorkspacePage.js.map +1 -0
- package/dist/local-files/WorkspaceSessions.js +689 -0
- package/dist/local-files/WorkspaceSessions.js.map +1 -0
- package/dist/presentation/TurnStateReducer.js +74 -13
- package/dist/presentation/TurnStateReducer.js.map +1 -1
- package/dist/presentation/turnActivity.js +41 -0
- package/dist/presentation/turnActivity.js.map +1 -0
- package/dist/presentation/turnStatus.js +11 -0
- package/dist/presentation/turnStatus.js.map +1 -1
- package/dist/presentation/visibleTurnActivities.js +4 -2
- package/dist/presentation/visibleTurnActivities.js.map +1 -1
- package/dist/proxy/ProxySessionController.js +150 -14
- package/dist/proxy/ProxySessionController.js.map +1 -1
- package/dist/runtime/types.js +1 -1
- package/dist/runtime/types.js.map +1 -1
- package/dist/state/InboundMessageStore.js +54 -0
- package/dist/state/InboundMessageStore.js.map +1 -0
- package/dist/state/StateStore.js +71 -1
- package/dist/state/StateStore.js.map +1 -1
- package/dist/state/TurnPreviewJournal.js +4 -2
- package/dist/state/TurnPreviewJournal.js.map +1 -1
- package/dist/state/migrations.js +20 -0
- package/dist/state/migrations.js.map +1 -1
- package/dist/supervision/SafeRestartNotifier.js +1 -0
- package/dist/supervision/SafeRestartNotifier.js.map +1 -1
- package/dist/supervision/SafeRestartScheduler.js +33 -16
- package/dist/supervision/SafeRestartScheduler.js.map +1 -1
- package/dist/terminal/TerminalLinks.js +32 -0
- package/dist/terminal/TerminalLinks.js.map +1 -1
- package/dist/terminal/TerminalPage.js +44 -24
- package/dist/terminal/TerminalPage.js.map +1 -1
- package/dist/terminal/TerminalServer.js +103 -39
- package/dist/terminal/TerminalServer.js.map +1 -1
- package/docs/technical-reference.md +1 -1
- package/docs/technical-reference.zh.md +2 -2
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- package/skills/agent-bot/SKILL.md +3 -1
- package/src/codex/CodexEventMapper.ts +39 -1
- package/src/codex/CodexRuntime.ts +54 -4
- package/src/codex/TraeTaskNotification.ts +49 -0
- package/src/config/SettingsStore.ts +1 -1
- package/src/config/loadConfig.ts +3 -2
- package/src/config/paths.ts +4 -0
- package/src/feishu/CardRenderer.ts +45 -11
- package/src/feishu/FeishuMessageClient.ts +2 -2
- package/src/feishu/FeishuTurnPresenter.ts +110 -20
- package/src/index.ts +62 -17
- package/src/local-files/DiagramPreview.ts +1 -1
- package/src/local-files/GitDiffPreview.ts +10 -7
- package/src/local-files/LocalFileViewerServer.ts +330 -37
- package/src/local-files/MarkdownFileLinks.ts +5 -3
- package/src/local-files/TurnPreviewPage.ts +35 -9
- package/src/local-files/WebPageTitle.ts +59 -0
- package/src/local-files/WorkspaceFiles.ts +468 -0
- package/src/local-files/WorkspaceOrigin.ts +31 -0
- package/src/local-files/WorkspacePage.ts +21 -0
- package/src/local-files/WorkspaceSessions.ts +587 -0
- package/src/presentation/TurnStateReducer.ts +76 -14
- package/src/presentation/turnActivity.ts +43 -0
- package/src/presentation/turnStatus.ts +14 -0
- package/src/presentation/turnViewTypes.ts +10 -1
- package/src/presentation/visibleTurnActivities.ts +4 -2
- package/src/proxy/ProxySessionController.ts +149 -13
- package/src/runtime/types.ts +17 -0
- package/src/state/InboundMessageStore.ts +72 -0
- package/src/state/StateStore.ts +80 -1
- package/src/state/TurnPreviewJournal.ts +4 -2
- package/src/state/migrations.ts +20 -0
- package/src/supervision/SafeRestartNotifier.ts +1 -0
- package/src/supervision/SafeRestartScheduler.ts +42 -18
- package/src/terminal/TerminalLinks.ts +26 -0
- package/src/terminal/TerminalPage.ts +44 -24
- package/src/terminal/TerminalServer.ts +98 -36
|
@@ -5,6 +5,7 @@ import { createRequire } from "node:module";
|
|
|
5
5
|
import http, { type IncomingMessage, type ServerResponse } from "node:http";
|
|
6
6
|
import type { Duplex } from "node:stream";
|
|
7
7
|
import path from "node:path";
|
|
8
|
+
import { z } from "zod";
|
|
8
9
|
import hljs from "highlight.js/lib/common";
|
|
9
10
|
import dos from "highlight.js/lib/languages/dos";
|
|
10
11
|
import dockerfile from "highlight.js/lib/languages/dockerfile";
|
|
@@ -12,6 +13,10 @@ import powershell from "highlight.js/lib/languages/powershell";
|
|
|
12
13
|
import MarkdownIt from "markdown-it";
|
|
13
14
|
import { CSV_PREVIEW_CSS, renderCsvPreview, csvSourcePreview } from "./CsvPreview.js";
|
|
14
15
|
import { GIT_DIFF_PREVIEW_CSS, readGitFileDiff, renderGitFileDiff } from "./GitDiffPreview.js";
|
|
16
|
+
import { renderWorkspacePage, WORKSPACE_SCRIPT } from "./WorkspacePage.js";
|
|
17
|
+
import { directWorkspaceOrigin } from "./WorkspaceOrigin.js";
|
|
18
|
+
import { readWebPageTitle } from "./WebPageTitle.js";
|
|
19
|
+
import { WorkspaceError, readWorkspaceAddress, readWorkspaceEntries, readWorkspaceGitStatus, readWorkspaceChanges, readWorkspaceFileVersions, createWorkspaceDiff, renderWorkspaceDiff, resolveWorkspacePath, type WorkspaceChange } from "./WorkspaceFiles.js";
|
|
15
20
|
import { enableDiagramFences, DIAGRAM_PREVIEW_CLIENT_SCRIPT, DIAGRAM_PREVIEW_CSS } from "./DiagramPreview.js";
|
|
16
21
|
import { isFileUrl, rewriteMarkdownFileLinks } from "./MarkdownFileLinks.js";
|
|
17
22
|
import {
|
|
@@ -39,6 +44,13 @@ const MAX_TEXT_PREVIEW_BYTES = 2 * 1024 * 1024;
|
|
|
39
44
|
const MAX_CONTENT_SAMPLE_BYTES = 64 * 1024;
|
|
40
45
|
const MAX_SYNTAX_HIGHLIGHT_BYTES = 512 * 1024;
|
|
41
46
|
const DIRECTORY_PAGE_SIZE = 100;
|
|
47
|
+
const WORKSPACE_QUERY = z.object({
|
|
48
|
+
api: z.string().optional(), entry: z.string().default(""),
|
|
49
|
+
page: z.coerce.number().int().min(0).max(Number.MAX_SAFE_INTEGER).default(0),
|
|
50
|
+
mode: z.enum(["all", "staged", "unstaged"]).default("all"), original: z.string().optional(),
|
|
51
|
+
prefetch: z.enum(["0", "1"]).optional(), query: z.string().trim().max(160).optional(),
|
|
52
|
+
instance: z.string().regex(/^[a-f0-9]{16}$/u).optional(),
|
|
53
|
+
});
|
|
42
54
|
const MARKDOWN_EXTENSIONS = new Set([".markdown", ".md", ".mdown", ".mkd", ".mkdn"]);
|
|
43
55
|
const HTML_EXTENSIONS = new Set([".html", ".htm"]);
|
|
44
56
|
hljs.registerLanguage("dos", dos);
|
|
@@ -51,8 +63,8 @@ const MARKDOWN_RENDERER = new MarkdownIt({
|
|
|
51
63
|
linkify: true,
|
|
52
64
|
typographer: false,
|
|
53
65
|
highlight(value, language) {
|
|
54
|
-
const highlighted = language && hljs.getLanguage(language)
|
|
55
|
-
?
|
|
66
|
+
const highlighted = language && hljs.getLanguage(language) && Buffer.byteLength(value, "utf8") <= MAX_SYNTAX_HIGHLIGHT_BYTES
|
|
67
|
+
? highlightLines(value, language).join("\n")
|
|
56
68
|
: escapeHtml(value);
|
|
57
69
|
const languageAttribute = language && hljs.getLanguage(language)
|
|
58
70
|
? ` class="language-${escapeAttribute(language)}"`
|
|
@@ -91,6 +103,8 @@ const VIEWER_CLIENT_SCRIPT = DIAGRAM_PREVIEW_CLIENT_SCRIPT + `(() => {
|
|
|
91
103
|
const header = document.getElementById("viewer-header");
|
|
92
104
|
const title = document.getElementById("viewer-title");
|
|
93
105
|
const viewSwitch = document.getElementById("viewer-view-switch");
|
|
106
|
+
const diffPrevious = document.getElementById("diff-previous");
|
|
107
|
+
const diffNext = document.getElementById("diff-next");
|
|
94
108
|
const viewButtons = Array.from(document.querySelectorAll("[data-view-mode-button]"));
|
|
95
109
|
if (!content || !metadata || !header || !title) return;
|
|
96
110
|
const filePath = title.dataset.filePath || title.textContent || "";
|
|
@@ -126,29 +140,96 @@ const VIEWER_CLIENT_SCRIPT = DIAGRAM_PREVIEW_CLIENT_SCRIPT + `(() => {
|
|
|
126
140
|
selection.addRange(range);
|
|
127
141
|
});
|
|
128
142
|
|
|
143
|
+
const diffBlocks = [];
|
|
144
|
+
if (diffPrevious && diffNext) {
|
|
145
|
+
for (const line of content.querySelectorAll(".git-diff .diff-addition, .git-diff .diff-deletion")) {
|
|
146
|
+
const previous = diffBlocks.at(-1);
|
|
147
|
+
if (previous && line.previousElementSibling === previous.last) previous.last = line;
|
|
148
|
+
else diffBlocks.push({ first: line, last: line, hash: "#diff-" + line.id });
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
let diffPositions = [], selectedDiff = -1;
|
|
152
|
+
const updateDiffNavigation = () => {
|
|
153
|
+
let previous = -1, next = -1;
|
|
154
|
+
const top = window.scrollY;
|
|
155
|
+
// Adjacent blocks can share a scroll position near the ends of the file.
|
|
156
|
+
const current = Math.abs(diffPositions[selectedDiff] - top) <= 1
|
|
157
|
+
? selectedDiff : diffPositions.findIndex(position => Math.abs(position - top) <= 1);
|
|
158
|
+
if (current >= 0) {
|
|
159
|
+
previous = current - 1;
|
|
160
|
+
next = current + 1 < diffPositions.length ? current + 1 : -1;
|
|
161
|
+
} else {
|
|
162
|
+
for (let i = 0; i < diffPositions.length; i++) {
|
|
163
|
+
if (diffPositions[i] < top) previous = i;
|
|
164
|
+
else { next = i; break; }
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
if (diffPrevious && diffNext) {
|
|
168
|
+
diffPrevious.disabled = previous < 0;
|
|
169
|
+
diffNext.disabled = next < 0;
|
|
170
|
+
}
|
|
171
|
+
return { previous, next };
|
|
172
|
+
};
|
|
173
|
+
const measureDiffPositions = () => {
|
|
174
|
+
if (!diffBlocks.length) return;
|
|
175
|
+
const height = window.innerHeight;
|
|
176
|
+
const readerCenter = (header.getBoundingClientRect().height + height) / 2;
|
|
177
|
+
const maxTop = Math.max(0, document.documentElement.scrollHeight - height);
|
|
178
|
+
diffPositions = diffBlocks.map(({ first, last }) => {
|
|
179
|
+
const center = (first.getBoundingClientRect().top + last.getBoundingClientRect().bottom) / 2;
|
|
180
|
+
return Math.min(maxTop, Math.max(0, window.scrollY + center - readerCenter));
|
|
181
|
+
});
|
|
182
|
+
updateDiffNavigation();
|
|
183
|
+
};
|
|
129
184
|
const updateHeaderOffset = () => {
|
|
130
185
|
const offset = Math.ceil(header.getBoundingClientRect().height) + 8;
|
|
131
186
|
document.documentElement.style.setProperty("--viewer-header-offset", offset + "px");
|
|
187
|
+
measureDiffPositions();
|
|
132
188
|
};
|
|
133
189
|
const highlightHashTarget = () => {
|
|
134
|
-
|
|
190
|
+
content.querySelector(".line.is-target-line")?.classList.remove("is-target-line");
|
|
191
|
+
const hash = window.location.hash;
|
|
192
|
+
selectedDiff = hash ? diffBlocks.findIndex(block => block.hash === hash) : (diffBlocks.length ? 0 : -1);
|
|
135
193
|
let id;
|
|
136
|
-
try {
|
|
137
|
-
id = decodeURIComponent(window.location.hash.slice(1));
|
|
138
|
-
} catch {
|
|
139
|
-
title.textContent = filePath;
|
|
140
|
-
return null;
|
|
141
|
-
}
|
|
194
|
+
try { id = decodeURIComponent(hash.slice(1)); } catch { id = ""; }
|
|
142
195
|
const lineNumber = /^L(\\d+)$/.exec(id)?.[1];
|
|
143
196
|
title.textContent = lineNumber ? filePath + ":" + lineNumber : filePath;
|
|
144
|
-
|
|
145
|
-
const target = document.getElementById(id);
|
|
197
|
+
const target = diffBlocks[selectedDiff]?.first ?? (lineNumber ? document.getElementById(id) : null);
|
|
146
198
|
target?.classList.add("is-target-line");
|
|
147
199
|
return target;
|
|
148
200
|
};
|
|
201
|
+
const centerDiffBlock = () => {
|
|
202
|
+
measureDiffPositions();
|
|
203
|
+
const top = diffPositions[selectedDiff];
|
|
204
|
+
if (top !== undefined) window.scrollTo(window.scrollX, top);
|
|
205
|
+
updateDiffNavigation();
|
|
206
|
+
};
|
|
149
207
|
const positionHashTarget = () => {
|
|
150
|
-
|
|
208
|
+
const target = highlightHashTarget();
|
|
209
|
+
if (window.location.hash && selectedDiff >= 0) centerDiffBlock();
|
|
210
|
+
else if (selectedDiff < 0) target?.scrollIntoView({ block: "start" });
|
|
211
|
+
if (diffBlocks.length) updateDiffNavigation();
|
|
212
|
+
};
|
|
213
|
+
const positionInitialContent = () => {
|
|
214
|
+
if (!diffBlocks.length) return positionHashTarget();
|
|
215
|
+
if (["reload", "back_forward"].includes(performance.getEntriesByType("navigation")[0]?.type)) {
|
|
216
|
+
highlightHashTarget();
|
|
217
|
+
updateDiffNavigation();
|
|
218
|
+
} else if (window.location.hash) positionHashTarget();
|
|
219
|
+
else { highlightHashTarget(); centerDiffBlock(); }
|
|
220
|
+
};
|
|
221
|
+
const jumpDiff = (direction) => {
|
|
222
|
+
const index = updateDiffNavigation()[direction];
|
|
223
|
+
if (index < 0) return;
|
|
224
|
+
window.history.pushState(null, "", diffBlocks[index].hash);
|
|
225
|
+
positionHashTarget();
|
|
151
226
|
};
|
|
227
|
+
if (diffBlocks.length) {
|
|
228
|
+
diffPrevious.addEventListener("click", () => jumpDiff("previous"));
|
|
229
|
+
diffNext.addEventListener("click", () => jumpDiff("next"));
|
|
230
|
+
window.addEventListener("scroll", updateDiffNavigation, { passive: true });
|
|
231
|
+
window.addEventListener("resize", measureDiffPositions);
|
|
232
|
+
}
|
|
152
233
|
if (/^#L\\d+$/u.test(window.location.hash)) document.body.dataset.viewMode = "code";
|
|
153
234
|
syncViewMode();
|
|
154
235
|
updateHeaderOffset();
|
|
@@ -159,7 +240,7 @@ const VIEWER_CLIENT_SCRIPT = DIAGRAM_PREVIEW_CLIENT_SCRIPT + `(() => {
|
|
|
159
240
|
if (/^#L\\d+$/u.test(window.location.hash)) setViewMode("code");
|
|
160
241
|
else requestAnimationFrame(positionHashTarget);
|
|
161
242
|
});
|
|
162
|
-
requestAnimationFrame(
|
|
243
|
+
requestAnimationFrame(positionInitialContent);
|
|
163
244
|
if (!eventsUrl || typeof EventSource !== "function") return;
|
|
164
245
|
|
|
165
246
|
const restoreScroll = (top, left, atBottom, codeScrollLeft, tablePositions) => {
|
|
@@ -275,6 +356,7 @@ export interface LocalFileViewerServerOptions {
|
|
|
275
356
|
getTurnSnapshot?: (turnId: string) => unknown;
|
|
276
357
|
loadTurnSnapshot?: (turnId: string) => Promise<unknown>;
|
|
277
358
|
turnPreviewPollIntervalMs?: number;
|
|
359
|
+
createWorkspaceTerminalUrl?: (root: string, instance: string, request: IncomingMessage) => string;
|
|
278
360
|
}
|
|
279
361
|
|
|
280
362
|
export interface LocalFileViewerAddress {
|
|
@@ -297,6 +379,13 @@ export class LocalFileViewerServer {
|
|
|
297
379
|
private address?: LocalFileViewerAddress;
|
|
298
380
|
private basePath = "";
|
|
299
381
|
private readonly services = new Map<string, LocalFileViewerService>();
|
|
382
|
+
private workspaceAppBase?: string;
|
|
383
|
+
|
|
384
|
+
enableWorkspaceApp(base: string): void { this.workspaceAppBase = base; }
|
|
385
|
+
|
|
386
|
+
serveWorkspaceAppPage(response: ServerResponse, url: URL, headOnly: boolean): void {
|
|
387
|
+
this.sendHtml(response, 200, renderWorkspacePage("", url.toString(), this.basePath + "/assets/workspace.js", this.workspaceAppBase), headOnly, true);
|
|
388
|
+
}
|
|
300
389
|
|
|
301
390
|
constructor(private readonly options: LocalFileViewerServerOptions) {}
|
|
302
391
|
|
|
@@ -424,6 +513,27 @@ export class LocalFileViewerServer {
|
|
|
424
513
|
return url.toString();
|
|
425
514
|
}
|
|
426
515
|
|
|
516
|
+
createWorkspaceUrl(directory: string, origin?: string): string | undefined {
|
|
517
|
+
if (!this.address || !this.secret) return undefined;
|
|
518
|
+
try {
|
|
519
|
+
const root = fs.realpathSync(directory);
|
|
520
|
+
if (!fs.statSync(root).isDirectory()) return undefined;
|
|
521
|
+
const url = new URL(origin ?? this.address.publicBaseUrl);
|
|
522
|
+
url.pathname = this.basePath + "/workspace/" + this.createShortToken("workspace:" + root);
|
|
523
|
+
url.searchParams.set("path", root);
|
|
524
|
+
return url.toString();
|
|
525
|
+
} catch { return undefined; }
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
serveWorkspaceChatImage(request: IncomingMessage, response: ServerResponse, root: string, entry: string): void {
|
|
529
|
+
const file = resolveWorkspacePath(root, entry);
|
|
530
|
+
const stat = fs.statSync(file);
|
|
531
|
+
if (!stat.isFile() || !contentTypeFor(path.extname(file).toLowerCase()).startsWith("image/")) {
|
|
532
|
+
throw new WorkspaceError("图片格式不可预览。", 404);
|
|
533
|
+
}
|
|
534
|
+
this.serveRawFile(request, response, file, stat, false);
|
|
535
|
+
}
|
|
536
|
+
|
|
427
537
|
createTurnPreviewUrl(turnId: string): string | undefined {
|
|
428
538
|
const normalizedTurnId = normalizeTurnId(turnId);
|
|
429
539
|
if (!this.address || !this.secret || !this.options.getTurnSnapshot || !normalizedTurnId) return undefined;
|
|
@@ -447,6 +557,26 @@ export class LocalFileViewerServer {
|
|
|
447
557
|
|
|
448
558
|
const requestUrl = new URL(request.url ?? "/", "http://127.0.0.1");
|
|
449
559
|
const route = routeWithinBasePath(requestUrl.pathname, this.basePath);
|
|
560
|
+
if (route === "/assets/workspace.js") {
|
|
561
|
+
this.sendJavascript(response, request.method === "HEAD", WORKSPACE_SCRIPT);
|
|
562
|
+
return;
|
|
563
|
+
}
|
|
564
|
+
const workspaceMatch = new RegExp("^/workspace/([A-Za-z0-9_-]{" + SHORT_TOKEN_LENGTH + "})$", "u").exec(route);
|
|
565
|
+
if (workspaceMatch) {
|
|
566
|
+
const root = normalizeAbsolutePath(requestUrl.searchParams.get("path") ?? "");
|
|
567
|
+
const expected = root ? this.createShortToken("workspace:" + root) : "";
|
|
568
|
+
if (!root || !timingSafeEqual(Buffer.from(expected), Buffer.from(workspaceMatch[1]!))) {
|
|
569
|
+
this.sendWorkspaceJson(response, 403, { error: "工作台链接无效,项目签名校验失败。" }, request.method === "HEAD");
|
|
570
|
+
return;
|
|
571
|
+
}
|
|
572
|
+
try { await this.handleWorkspace(request, response, requestUrl, root); }
|
|
573
|
+
catch (error) {
|
|
574
|
+
const code = (error as NodeJS.ErrnoException).code;
|
|
575
|
+
this.sendWorkspaceJson(response, error instanceof WorkspaceError ? error.status : code === "ENOENT" ? 404 : code === "EACCES" || code === "EPERM" ? 403 : 500,
|
|
576
|
+
{ error: error instanceof Error ? error.message : String(error) }, request.method === "HEAD");
|
|
577
|
+
}
|
|
578
|
+
return;
|
|
579
|
+
}
|
|
450
580
|
if (!route.startsWith("/")) {
|
|
451
581
|
this.sendHtml(response, 404, errorPage("文件链接无效", "请从 Agent Bot 的回答中重新打开文件链接。"), request.method === "HEAD");
|
|
452
582
|
return;
|
|
@@ -532,8 +662,13 @@ export class LocalFileViewerServer {
|
|
|
532
662
|
eventsUrl.searchParams.set("events", "1");
|
|
533
663
|
if (snapshot.previewCursor !== undefined) eventsUrl.searchParams.set("after", String(snapshot.previewCursor));
|
|
534
664
|
const language = detectTurnPreviewLanguage(request.headers["accept-language"]);
|
|
665
|
+
const projectWorkspaceUrl = snapshot.projectCwd ? this.createWorkspaceUrl(snapshot.projectCwd) : undefined;
|
|
666
|
+
const workspaceUrl = projectWorkspaceUrl ? new URL(projectWorkspaceUrl) : undefined;
|
|
667
|
+
workspaceUrl?.searchParams.set("list", "changes");
|
|
668
|
+
if (this.workspaceAppBase && snapshot.sessionId) workspaceUrl?.searchParams.set("task", snapshot.sessionId);
|
|
535
669
|
const html = renderTurnPreviewPage({
|
|
536
670
|
state: snapshot,
|
|
671
|
+
workspaceUrl: workspaceUrl?.toString(),
|
|
537
672
|
eventsUrl: eventsUrl.toString(),
|
|
538
673
|
scriptPath: `${this.basePath}/assets/turn-preview.js`.replace(/\/{2,}/gu, "/"),
|
|
539
674
|
localFileUrl: (filePath, options) => this.createFileUrl(filePath, undefined, options),
|
|
@@ -574,7 +709,8 @@ export class LocalFileViewerServer {
|
|
|
574
709
|
actions.push({ href: original, label: "查看文件" }, { href: raw.toString(), label: "打开原始文件" }, { href: download.toString(), label: "下载" });
|
|
575
710
|
}
|
|
576
711
|
this.sendHtml(response, 200, renderViewerPage({ title: path.basename(filePath), filePath,
|
|
577
|
-
metadata: ["Git diff", "完整文件", "当前工作区"], actions, content
|
|
712
|
+
metadata: ["Git diff", "完整文件", "当前工作区"], actions, content, gitDiff: true,
|
|
713
|
+
scriptPath: `${this.basePath}/assets/viewer.js`.replace(/\/{2,}/gu, "/") }), request.method === "HEAD");
|
|
578
714
|
return;
|
|
579
715
|
}
|
|
580
716
|
}
|
|
@@ -706,10 +842,8 @@ export class LocalFileViewerServer {
|
|
|
706
842
|
content: snapshot.content,
|
|
707
843
|
viewMode: snapshot.viewMode,
|
|
708
844
|
diagramScriptPath: isMarkdownFile(filePath) ? `${this.basePath}/assets/mermaid.js`.replace(/\/{2,}/gu, "/") : undefined,
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
scriptPath: `${this.basePath}/assets/viewer.js`.replace(/\/{2,}/gu, "/"),
|
|
712
|
-
},
|
|
845
|
+
eventsUrl: eventsUrl.toString(),
|
|
846
|
+
scriptPath: `${this.basePath}/assets/viewer.js`.replace(/\/{2,}/gu, "/"),
|
|
713
847
|
});
|
|
714
848
|
}
|
|
715
849
|
|
|
@@ -961,6 +1095,128 @@ export class LocalFileViewerServer {
|
|
|
961
1095
|
response.once("close", cleanup);
|
|
962
1096
|
}
|
|
963
1097
|
|
|
1098
|
+
private sendWorkspaceJson(response: ServerResponse, status: number, value: unknown, headOnly: boolean): void {
|
|
1099
|
+
const body = Buffer.from(JSON.stringify(value), "utf8");
|
|
1100
|
+
setSecurityHeaders(response);
|
|
1101
|
+
response.writeHead(status, { "Content-Type": "application/json; charset=utf-8", "Cache-Control": "no-store", "Content-Length": body.length });
|
|
1102
|
+
response.end(headOnly ? undefined : body);
|
|
1103
|
+
}
|
|
1104
|
+
|
|
1105
|
+
private async handleWorkspace(request: IncomingMessage, response: ServerResponse, url: URL, root: string): Promise<void> {
|
|
1106
|
+
resolveWorkspacePath(root);
|
|
1107
|
+
const headOnly = request.method === "HEAD";
|
|
1108
|
+
const published = new URL(this.address!.publicBaseUrl);
|
|
1109
|
+
const origin = request.headers.host === published.host ? published.origin : directWorkspaceOrigin(request);
|
|
1110
|
+
const workspaceUrl = this.createWorkspaceUrl(root, origin)!;
|
|
1111
|
+
if (!url.searchParams.has("api")) {
|
|
1112
|
+
this.sendHtml(response, 200, renderWorkspacePage(root, workspaceUrl, this.basePath + "/assets/workspace.js", this.workspaceAppBase), headOnly, true);
|
|
1113
|
+
return;
|
|
1114
|
+
}
|
|
1115
|
+
const parsed = WORKSPACE_QUERY.safeParse(Object.fromEntries(url.searchParams));
|
|
1116
|
+
if (!parsed.success) throw new WorkspaceError("工作台参数无效:" + parsed.error.issues.map((issue) => issue.message).join(";"));
|
|
1117
|
+
const { api, entry, page, mode, original, prefetch, query, instance } = parsed.data;
|
|
1118
|
+
if (!api) {
|
|
1119
|
+
this.sendHtml(response, 200, renderWorkspacePage(root, workspaceUrl, this.basePath + "/assets/workspace.js", this.workspaceAppBase), headOnly, true);
|
|
1120
|
+
return;
|
|
1121
|
+
}
|
|
1122
|
+
if (api === "tree") {
|
|
1123
|
+
this.sendWorkspaceJson(response, 200, await readWorkspaceEntries(root, entry, page, { prefetch: prefetch === "1", query }), headOnly);
|
|
1124
|
+
return;
|
|
1125
|
+
}
|
|
1126
|
+
if (api === "address") {
|
|
1127
|
+
this.sendWorkspaceJson(response, 200, await readWorkspaceAddress(root, entry, query), headOnly);
|
|
1128
|
+
return;
|
|
1129
|
+
}
|
|
1130
|
+
if (api === "web-title") {
|
|
1131
|
+
this.sendWorkspaceJson(response, 200, headOnly ? {} : await readWebPageTitle(entry), headOnly);
|
|
1132
|
+
return;
|
|
1133
|
+
}
|
|
1134
|
+
if (api === "changes") {
|
|
1135
|
+
this.sendWorkspaceJson(response, 200, await readWorkspaceChanges(root, entry, page, { prefetch: prefetch === "1", query }), headOnly);
|
|
1136
|
+
return;
|
|
1137
|
+
}
|
|
1138
|
+
if (api === "terminal") {
|
|
1139
|
+
if (!instance) throw new WorkspaceError("终端标签标识无效。");
|
|
1140
|
+
if (!this.options.createWorkspaceTerminalUrl) throw new WorkspaceError("网页终端服务未启用。", 503);
|
|
1141
|
+
if (!headOnly) this.sendWorkspaceJson(response, 200, { url: this.options.createWorkspaceTerminalUrl(root, instance, request) }, false);
|
|
1142
|
+
else this.sendWorkspaceJson(response, 200, {}, true);
|
|
1143
|
+
return;
|
|
1144
|
+
}
|
|
1145
|
+
if (api === "diff") {
|
|
1146
|
+
const versions = await readWorkspaceFileVersions(root, entry, mode, original);
|
|
1147
|
+
const file = resolveWorkspacePath(root, entry, true);
|
|
1148
|
+
const before = classifyContentSample(versions.before, true), after = classifyContentSample(versions.after, true);
|
|
1149
|
+
let html: string;
|
|
1150
|
+
if (before.kind === "binary" || after.kind === "binary") html = '<div class="workspace-notice">这个文件是二进制格式,无法显示文本 Diff;可以查看文件预览或下载。</div>';
|
|
1151
|
+
else {
|
|
1152
|
+
const previous = decodeText(versions.before, before.encoding, true), current = decodeText(versions.after, after.encoding, true);
|
|
1153
|
+
html = renderWorkspaceDiff(await createWorkspaceDiff(root, previous, current), current, (value) => highlightTextLines(value, file));
|
|
1154
|
+
}
|
|
1155
|
+
this.sendWorkspaceJson(response, 200, { html, canViewFile: versions.canViewFile }, headOnly);
|
|
1156
|
+
return;
|
|
1157
|
+
}
|
|
1158
|
+
if (api !== "file" && api !== "raw") throw new WorkspaceError("工作台接口不存在。", 404);
|
|
1159
|
+
const file = resolveWorkspacePath(root, entry);
|
|
1160
|
+
const stat = fs.statSync(file);
|
|
1161
|
+
if (!stat.isFile()) throw new WorkspaceError("这不是普通文件,未读取内容。");
|
|
1162
|
+
if (api === "raw") {
|
|
1163
|
+
this.serveRawFile(request, response, file, stat, url.searchParams.get("download") === "1");
|
|
1164
|
+
return;
|
|
1165
|
+
}
|
|
1166
|
+
const raw = new URL(workspaceUrl);
|
|
1167
|
+
raw.searchParams.set("api", "raw"); raw.searchParams.set("entry", entry);
|
|
1168
|
+
const classification = classifyFileContent(file, stat.size);
|
|
1169
|
+
const type = binaryContentTypeFor(path.extname(file).toLowerCase());
|
|
1170
|
+
let html: string;
|
|
1171
|
+
if (classification.kind === "text") {
|
|
1172
|
+
const preview = readTextPreview(file, stat.size, classification.encoding);
|
|
1173
|
+
const lines = preview.text.split(/\r\n?|\n/u);
|
|
1174
|
+
html = (preview.truncated || lines.length > 10_000 ? '<div class="workspace-notice">文件较大,仅显示前 2 MiB 或 10000 行;可下载完整文件。</div>' : "")
|
|
1175
|
+
+ (isMarkdownFile(file) ? this.renderWorkspaceMarkdown(root, file, lines.slice(0, 10_000).join("\n"), workspaceUrl) : renderText(lines.slice(0, 10_000).join("\n"), file));
|
|
1176
|
+
} else if (type.startsWith("image/")) {
|
|
1177
|
+
html = '<div class="workspace-media"><img src="' + escapeAttribute(raw.toString()) + '" alt="' + escapeAttribute(path.basename(file)) + '"></div>';
|
|
1178
|
+
} else if (type === "application/pdf") {
|
|
1179
|
+
html = '<object class="workspace-pdf" type="application/pdf" data="' + escapeAttribute(raw.toString()) + '">浏览器不支持 PDF 预览,请下载文件。</object>';
|
|
1180
|
+
} else {
|
|
1181
|
+
html = '<div class="workspace-notice">这个文件是二进制格式,无法显示文本内容;可下载到本地查看。</div>';
|
|
1182
|
+
}
|
|
1183
|
+
let change: WorkspaceChange | undefined, gitError: string | undefined;
|
|
1184
|
+
try {
|
|
1185
|
+
const relative = path.relative(root, file).split(path.sep).join("/");
|
|
1186
|
+
const normalize = (value: string) => process.platform === "win32" ? value.toLowerCase() : value;
|
|
1187
|
+
change = (await readWorkspaceGitStatus(root)).changes.find(item => normalize(item.path) === normalize(relative));
|
|
1188
|
+
} catch (error) { gitError = error instanceof Error ? error.message : String(error); }
|
|
1189
|
+
this.sendWorkspaceJson(response, 200, { html, rawUrl: raw.toString(), change, gitError }, headOnly);
|
|
1190
|
+
}
|
|
1191
|
+
|
|
1192
|
+
private renderWorkspaceMarkdown(root: string, file: string, value: string, workspaceUrl: string): string {
|
|
1193
|
+
const environment = {}, tokens = MARKDOWN_RENDERER.parse(value, environment), targets = new Map<string, string>();
|
|
1194
|
+
rewriteMarkdownFileLinks(tokens, file, (target) => {
|
|
1195
|
+
const entry = path.relative(root, target).split(path.sep).join("/");
|
|
1196
|
+
try {
|
|
1197
|
+
const resolved = resolveWorkspacePath(root, entry);
|
|
1198
|
+
if (!fs.statSync(resolved).isFile()) return undefined;
|
|
1199
|
+
} catch { return undefined; }
|
|
1200
|
+
const url = new URL(workspaceUrl); url.searchParams.set("api", "raw"); url.searchParams.set("entry", entry);
|
|
1201
|
+
targets.set(url.toString(), entry); return url;
|
|
1202
|
+
});
|
|
1203
|
+
const rewriteLinks = (items: typeof tokens): void => {
|
|
1204
|
+
for (const token of items) {
|
|
1205
|
+
const href = token.type === "link_open" ? token.attrGet("href") : null;
|
|
1206
|
+
if (typeof href === "string" && href) {
|
|
1207
|
+
const entry = targets.get(href.split("#")[0]!);
|
|
1208
|
+
if (entry !== undefined) {
|
|
1209
|
+
const url = new URL(href); url.searchParams.delete("api");
|
|
1210
|
+
token.attrSet("href", url.toString()); token.attrSet("data-workspace-entry", entry);
|
|
1211
|
+
}
|
|
1212
|
+
}
|
|
1213
|
+
if (token.children) rewriteLinks(token.children);
|
|
1214
|
+
}
|
|
1215
|
+
};
|
|
1216
|
+
rewriteLinks(tokens);
|
|
1217
|
+
return '<article class="markdown-body">' + MARKDOWN_RENDERER.renderer.render(tokens, MARKDOWN_RENDERER.options, environment) + '</article>';
|
|
1218
|
+
}
|
|
1219
|
+
|
|
964
1220
|
private renderDirectoryViewer(directory: string, stat: fs.Stats, requestedPage: number): string {
|
|
965
1221
|
const entries = fs.readdirSync(directory, { withFileTypes: true })
|
|
966
1222
|
.flatMap((entry): DirectoryViewerEntry[] => {
|
|
@@ -998,7 +1254,7 @@ export class LocalFileViewerServer {
|
|
|
998
1254
|
title,
|
|
999
1255
|
filePath: directory,
|
|
1000
1256
|
metadata: [`${entries.length} 项`, stat.mtime.toLocaleString()],
|
|
1001
|
-
actions: [],
|
|
1257
|
+
actions: [{ href: this.createWorkspaceUrl(directory)!, label: "打开项目工作台" }],
|
|
1002
1258
|
content: `<div class="directory-list">${rows}</div>${pagination}`,
|
|
1003
1259
|
});
|
|
1004
1260
|
}
|
|
@@ -1059,9 +1315,13 @@ export class LocalFileViewerServer {
|
|
|
1059
1315
|
stream.pipe(response);
|
|
1060
1316
|
}
|
|
1061
1317
|
|
|
1062
|
-
private sendHtml(response: ServerResponse, status: number, html: string, headOnly = false): void {
|
|
1318
|
+
private sendHtml(response: ServerResponse, status: number, html: string, headOnly = false, workspace = false): void {
|
|
1063
1319
|
const body = Buffer.from(html, "utf8");
|
|
1064
1320
|
setSecurityHeaders(response);
|
|
1321
|
+
// External frame redirects must not expose privileged viewer documents.
|
|
1322
|
+
response.setHeader("X-Frame-Options", "DENY");
|
|
1323
|
+
if (workspace) response.setHeader("Content-Security-Policy", "default-src 'none'; img-src 'self' data:; media-src 'self'; object-src 'self'; frame-src 'self' http: https:; script-src 'self'; connect-src 'self'; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'");
|
|
1324
|
+
else response.setHeader("Content-Security-Policy", String(response.getHeader("Content-Security-Policy")).replace("frame-ancestors 'self'", "frame-ancestors 'none'"));
|
|
1065
1325
|
response.statusCode = status;
|
|
1066
1326
|
response.setHeader("Cache-Control", "no-store");
|
|
1067
1327
|
response.setHeader("Content-Type", "text/html; charset=utf-8");
|
|
@@ -1086,9 +1346,11 @@ function renderViewerPage(input: {
|
|
|
1086
1346
|
metadata: string[];
|
|
1087
1347
|
actions: Array<{ href: string; label: string }>;
|
|
1088
1348
|
content: string;
|
|
1349
|
+
gitDiff?: boolean;
|
|
1089
1350
|
viewMode?: RenderedFileSnapshot["viewMode"];
|
|
1090
1351
|
diagramScriptPath?: string;
|
|
1091
|
-
|
|
1352
|
+
eventsUrl?: string;
|
|
1353
|
+
scriptPath?: string;
|
|
1092
1354
|
}): string {
|
|
1093
1355
|
const metadata = renderMetadata(input.metadata);
|
|
1094
1356
|
const actions = input.actions.length > 0
|
|
@@ -1097,14 +1359,17 @@ function renderViewerPage(input: {
|
|
|
1097
1359
|
const viewSwitch = input.viewMode
|
|
1098
1360
|
? '<div class="view-switch" id="viewer-view-switch" role="tablist" aria-label="预览模式"><button class="is-active" type="button" role="tab" aria-selected="true" data-view-mode-button="rendered">预览</button><button type="button" role="tab" aria-selected="false" data-view-mode-button="code">代码</button></div>'
|
|
1099
1361
|
: "";
|
|
1100
|
-
const
|
|
1101
|
-
|
|
1362
|
+
const diffNavigation = input.gitDiff ? `<div class="diff-navigation" role="group" aria-label="Git Diff 导航">${[
|
|
1363
|
+
["previous", "上一处改动", "M12 20V4m-6 6 6-6 6 6"], ["next", "下一处改动", "M12 4v16m-6-6 6 6 6-6"],
|
|
1364
|
+
].map(([direction, label, arrow]) => `<button type="button" id="diff-${direction}" title="${label}" aria-label="${label}" disabled><svg aria-hidden="true" focusable="false" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"><path d="${arrow}"/></svg></button>`).join("")}</div>` : "";
|
|
1365
|
+
const toolbar = viewSwitch || actions || diffNavigation
|
|
1366
|
+
? `<div class="toolbar">${viewSwitch}${diffNavigation}${actions}</div>`
|
|
1102
1367
|
: "";
|
|
1103
|
-
const liveAttributes = input.
|
|
1104
|
-
? ` data-events-url="${escapeAttribute(input.
|
|
1368
|
+
const liveAttributes = input.eventsUrl
|
|
1369
|
+
? ` data-events-url="${escapeAttribute(input.eventsUrl)}"`
|
|
1105
1370
|
: "";
|
|
1106
|
-
const
|
|
1107
|
-
? `<script src="${escapeAttribute(input.
|
|
1371
|
+
const clientScript = input.scriptPath
|
|
1372
|
+
? `<script src="${escapeAttribute(input.scriptPath)}" defer></script>`
|
|
1108
1373
|
: "";
|
|
1109
1374
|
return `<!doctype html>
|
|
1110
1375
|
<html lang="zh-CN">
|
|
@@ -1123,6 +1388,12 @@ function renderViewerPage(input: {
|
|
|
1123
1388
|
.toolbar { margin-left: auto; display: flex; gap: 8px; align-items: center; }
|
|
1124
1389
|
.actions { display: flex; gap: 8px; }
|
|
1125
1390
|
.actions a { color: #1456f0; text-decoration: none; padding: 3px 7px; border: 1px solid #c9d0db; border-radius: 4px; background: #fff; }
|
|
1391
|
+
.diff-navigation { display: inline-flex; gap: 4px; }
|
|
1392
|
+
.diff-navigation button { display: grid; place-items: center; width: 28px; height: 28px; padding: 0; border: 1px solid #c9d0db; border-radius: 4px; background: transparent; color: inherit; cursor: pointer; }
|
|
1393
|
+
.diff-navigation button:disabled { opacity: .4; cursor: default; }
|
|
1394
|
+
.diff-navigation button:not(:disabled):hover { background: #f0f4ff; color: #1456f0; }
|
|
1395
|
+
.diff-navigation button:focus-visible { outline: 2px solid currentColor; outline-offset: 1px; }
|
|
1396
|
+
.diff-navigation svg { width: 16px; height: 16px; }
|
|
1126
1397
|
.view-switch { display: inline-flex; padding: 2px; border: 1px solid #c9d0db; border-radius: 5px; background: #f2f3f5; }
|
|
1127
1398
|
.view-switch[hidden] { display: none; }
|
|
1128
1399
|
.view-switch button { min-width: 46px; padding: 2px 8px; border: 0; border-radius: 3px; background: transparent; color: #646a73; cursor: pointer; font: inherit; }
|
|
@@ -1195,6 +1466,8 @@ function renderViewerPage(input: {
|
|
|
1195
1466
|
.meta, .pagination { color: #a6a9ad; }
|
|
1196
1467
|
.actions a, .pagination a { color: #8ab4ff; }
|
|
1197
1468
|
.actions a { border-color: #55585c; background: #292a2d; }
|
|
1469
|
+
.diff-navigation button { border-color: #55585c; }
|
|
1470
|
+
.diff-navigation button:not(:disabled):hover { background: #292f3d; color: #8ab4ff; }
|
|
1198
1471
|
.view-switch { border-color: #55585c; background: #292a2d; }
|
|
1199
1472
|
.view-switch button { color: #a6a9ad; }
|
|
1200
1473
|
.view-switch button.is-active { background: #3a3b3d; color: #8ab4ff; box-shadow: none; }
|
|
@@ -1230,7 +1503,7 @@ function renderViewerPage(input: {
|
|
|
1230
1503
|
<div class="meta"><span class="metadata-values" id="viewer-metadata">${metadata}</span>${toolbar}</div>
|
|
1231
1504
|
</header>
|
|
1232
1505
|
<main id="viewer-content">${input.content}</main>
|
|
1233
|
-
${
|
|
1506
|
+
${clientScript}
|
|
1234
1507
|
</body>
|
|
1235
1508
|
</html>`;
|
|
1236
1509
|
}
|
|
@@ -1385,11 +1658,26 @@ async function readGitDiffPreview(filePath: string): Promise<string | undefined>
|
|
|
1385
1658
|
text = preview.text;
|
|
1386
1659
|
}
|
|
1387
1660
|
const diff = await readGitFileDiff(filePath);
|
|
1388
|
-
|
|
1661
|
+
let content = diff ? renderGitFileDiff(diff, text, (value) => highlightTextLines(value, filePath)) : undefined;
|
|
1662
|
+
if (!content && !fs.lstatSync(filePath, { throwIfNoEntry: false })?.isSymbolicLink()) {
|
|
1663
|
+
let directory = path.dirname(filePath);
|
|
1664
|
+
while (!fs.existsSync(directory)) {
|
|
1665
|
+
const parent = path.dirname(directory); if (parent === directory) return undefined; directory = parent;
|
|
1666
|
+
}
|
|
1667
|
+
const root = fs.realpathSync(directory), entry = path.relative(directory, filePath).split(path.sep).join("/");
|
|
1668
|
+
const versions = await readWorkspaceFileVersions(root, entry, "all");
|
|
1669
|
+
if (!versions.beforeExists) return undefined;
|
|
1670
|
+
const previous = classifyContentSample(versions.before, true), current = classifyContentSample(versions.after, true);
|
|
1671
|
+
if (previous.kind !== "text" || current.kind !== "text") return undefined;
|
|
1672
|
+
const previousText = decodeText(versions.before, previous.encoding, true), currentText = decodeText(versions.after, current.encoding, true);
|
|
1673
|
+
const patch = await createWorkspaceDiff(root, previousText, currentText);
|
|
1674
|
+
if (!patch) return undefined;
|
|
1675
|
+
content = renderGitFileDiff(patch, currentText, (value) => highlightTextLines(value, filePath));
|
|
1676
|
+
}
|
|
1389
1677
|
const after = fs.statSync(filePath, { throwIfNoEntry: false });
|
|
1390
1678
|
if (before?.size !== after?.size || before?.mtimeMs !== after?.mtimeMs || before?.ctimeMs !== after?.ctimeMs
|
|
1391
1679
|
|| before?.ino !== after?.ino || before?.dev !== after?.dev) return undefined;
|
|
1392
|
-
return
|
|
1680
|
+
return content;
|
|
1393
1681
|
} catch {
|
|
1394
1682
|
return undefined;
|
|
1395
1683
|
}
|
|
@@ -1491,11 +1779,7 @@ function hasTextLikeCharacters(value: string): boolean {
|
|
|
1491
1779
|
}
|
|
1492
1780
|
|
|
1493
1781
|
function renderText(value: string, filePath: string): string {
|
|
1494
|
-
const
|
|
1495
|
-
const language = syntaxLanguageFor(filePath);
|
|
1496
|
-
const lines = language && Buffer.byteLength(normalized, "utf8") <= MAX_SYNTAX_HIGHLIGHT_BYTES
|
|
1497
|
-
? highlightLines(normalized, language)
|
|
1498
|
-
: normalized.split("\n").map(escapeHtml);
|
|
1782
|
+
const language = syntaxLanguageFor(filePath), lines = highlightTextLines(value, filePath);
|
|
1499
1783
|
const languageClass = language ? ` class="language-${escapeAttribute(language)}"` : "";
|
|
1500
1784
|
return `<pre class="code hljs"><code${languageClass}>${lines.map((line, index) => {
|
|
1501
1785
|
const lineNumber = index + 1;
|
|
@@ -1503,6 +1787,14 @@ function renderText(value: string, filePath: string): string {
|
|
|
1503
1787
|
}).join("")}</code></pre>`;
|
|
1504
1788
|
}
|
|
1505
1789
|
|
|
1790
|
+
function highlightTextLines(value: string, filePath: string): string[] {
|
|
1791
|
+
const normalized = value.replace(/\r\n?/gu, "\n");
|
|
1792
|
+
const language = syntaxLanguageFor(filePath);
|
|
1793
|
+
return language && Buffer.byteLength(normalized, "utf8") <= MAX_SYNTAX_HIGHLIGHT_BYTES
|
|
1794
|
+
? highlightLines(normalized, language)
|
|
1795
|
+
: normalized.split("\n").map(escapeHtml);
|
|
1796
|
+
}
|
|
1797
|
+
|
|
1506
1798
|
function renderMarkdownDocument(value: string, filePath: string, createPreviewUrl: (filePath: string) => URL): string {
|
|
1507
1799
|
const environment = {};
|
|
1508
1800
|
const tokens = MARKDOWN_RENDERER.parse(value, environment);
|
|
@@ -1516,9 +1808,10 @@ function isMarkdownFile(filePath: string): boolean {
|
|
|
1516
1808
|
}
|
|
1517
1809
|
|
|
1518
1810
|
function syntaxLanguageFor(filePath: string): string | undefined {
|
|
1811
|
+
if (isMarkdownFile(filePath)) return "markdown";
|
|
1519
1812
|
const fileName = path.basename(filePath).toLowerCase();
|
|
1520
|
-
return HIGHLIGHT_LANGUAGE_BY_FILENAME[fileName]
|
|
1521
|
-
|
|
1813
|
+
return Object.hasOwn(HIGHLIGHT_LANGUAGE_BY_FILENAME, fileName) ? HIGHLIGHT_LANGUAGE_BY_FILENAME[fileName]
|
|
1814
|
+
: HIGHLIGHT_LANGUAGE_BY_EXTENSION[path.extname(fileName)];
|
|
1522
1815
|
}
|
|
1523
1816
|
|
|
1524
1817
|
function highlightLines(value: string, language: string): string[] {
|
|
@@ -10,6 +10,7 @@ export function rewriteMarkdownFileLinks(
|
|
|
10
10
|
tokens: Token[],
|
|
11
11
|
markdownPath: string | undefined,
|
|
12
12
|
createPreviewUrl: (filePath: string) => URL | undefined,
|
|
13
|
+
createImageUrl?: (filePath: string) => URL | undefined,
|
|
13
14
|
): void {
|
|
14
15
|
for (const token of tokens) {
|
|
15
16
|
const attribute = token.type === "link_open" ? "href" : token.type === "image" ? "src" : undefined;
|
|
@@ -17,10 +18,11 @@ export function rewriteMarkdownFileLinks(
|
|
|
17
18
|
if (attribute && typeof target === "string" && target) {
|
|
18
19
|
const local = resolveLocalTarget(target, markdownPath);
|
|
19
20
|
if (local) {
|
|
20
|
-
const
|
|
21
|
+
const image = token.type === "image";
|
|
22
|
+
const url = image && createImageUrl ? createImageUrl(local.filePath) : createPreviewUrl(local.filePath);
|
|
21
23
|
if (url) {
|
|
22
24
|
url.hash = local.hash;
|
|
23
|
-
if (
|
|
25
|
+
if (image && !createImageUrl) url.searchParams.set("raw", "1");
|
|
24
26
|
token.attrSet(attribute, url.toString());
|
|
25
27
|
} else {
|
|
26
28
|
token.attrs = token.attrs?.filter(([name]) => name !== attribute) ?? null;
|
|
@@ -30,7 +32,7 @@ export function rewriteMarkdownFileLinks(
|
|
|
30
32
|
token.attrs = token.attrs?.filter(([name]) => name !== attribute) ?? null;
|
|
31
33
|
}
|
|
32
34
|
}
|
|
33
|
-
if (token.children) rewriteMarkdownFileLinks(token.children, markdownPath, createPreviewUrl);
|
|
35
|
+
if (token.children) rewriteMarkdownFileLinks(token.children, markdownPath, createPreviewUrl, createImageUrl);
|
|
34
36
|
}
|
|
35
37
|
}
|
|
36
38
|
|