@keyou007/agent-bot 0.1.27-alpha.3 → 0.1.27-alpha.4
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 +18 -0
- package/README.md +77 -12
- package/README.zh.md +77 -12
- package/assets/agent-bot.ico +0 -0
- package/assets/roboto-mono-OFL.txt +93 -0
- package/assets/roboto-mono-latin.woff2 +0 -0
- package/assets/workspace-drafts.js +88 -0
- package/assets/workspace-sessions.js +1935 -232
- package/assets/workspace.css +360 -35
- package/assets/workspace.js +2115 -249
- package/dist/cli/SelfUpdateObserver.js +124 -0
- package/dist/cli/SelfUpdateObserver.js.map +1 -0
- package/dist/cli/SelfUpdateRunner.js +267 -70
- package/dist/cli/SelfUpdateRunner.js.map +1 -1
- package/dist/cli/SelfUpdater.js +54 -15
- package/dist/cli/SelfUpdater.js.map +1 -1
- package/dist/cli/controlProtocol.js.map +1 -1
- package/dist/cli/help.js +6 -0
- package/dist/cli/help.js.map +1 -1
- package/dist/cli.js +85 -6
- package/dist/cli.js.map +1 -1
- package/dist/codex/CodexEventMapper.js +29 -5
- package/dist/codex/CodexEventMapper.js.map +1 -1
- package/dist/codex/CodexRuntime.js +3 -0
- package/dist/codex/CodexRuntime.js.map +1 -1
- package/dist/feishu/CardRenderer.js +45 -13
- package/dist/feishu/CardRenderer.js.map +1 -1
- package/dist/feishu/ConsoleFeishuClient.js +4 -0
- package/dist/feishu/ConsoleFeishuClient.js.map +1 -1
- package/dist/feishu/FeishuMarkdown.js +2 -14
- package/dist/feishu/FeishuMarkdown.js.map +1 -1
- package/dist/feishu/FeishuMessageClient.js +9 -0
- package/dist/feishu/FeishuMessageClient.js.map +1 -1
- package/dist/feishu/FeishuTurnPresenter.js +26 -14
- package/dist/feishu/FeishuTurnPresenter.js.map +1 -1
- package/dist/index.js +47 -12
- package/dist/index.js.map +1 -1
- package/dist/local-files/DiagramPreview.js +11 -6
- package/dist/local-files/DiagramPreview.js.map +1 -1
- package/dist/local-files/GitDiffPreview.js +40 -10
- package/dist/local-files/GitDiffPreview.js.map +1 -1
- package/dist/local-files/LiveMarkup.js +104 -0
- package/dist/local-files/LiveMarkup.js.map +1 -0
- package/dist/local-files/LocalFileViewerServer.js +133 -117
- package/dist/local-files/LocalFileViewerServer.js.map +1 -1
- package/dist/local-files/MarkdownExport.js +54 -0
- package/dist/local-files/MarkdownExport.js.map +1 -0
- package/dist/local-files/PreviewCodeFont.js +11 -0
- package/dist/local-files/PreviewCodeFont.js.map +1 -0
- package/dist/local-files/PreviewSyntaxHighlight.js +73 -0
- package/dist/local-files/PreviewSyntaxHighlight.js.map +1 -1
- package/dist/local-files/ToolCommandDisplay.js +111 -0
- package/dist/local-files/ToolCommandDisplay.js.map +1 -0
- package/dist/local-files/TurnPreviewPage.js +23 -269
- package/dist/local-files/TurnPreviewPage.js.map +1 -1
- package/dist/local-files/WorkspaceFileEvents.js +206 -0
- package/dist/local-files/WorkspaceFileEvents.js.map +1 -0
- package/dist/local-files/WorkspaceFiles.js +79 -3
- package/dist/local-files/WorkspaceFiles.js.map +1 -1
- package/dist/local-files/WorkspaceImages.js +15 -0
- package/dist/local-files/WorkspaceImages.js.map +1 -0
- package/dist/local-files/WorkspacePage.js +20 -5
- package/dist/local-files/WorkspacePage.js.map +1 -1
- package/dist/local-files/WorkspaceSessions.js +881 -79
- package/dist/local-files/WorkspaceSessions.js.map +1 -1
- package/dist/local-files/WorkspaceTimeline.js +105 -0
- package/dist/local-files/WorkspaceTimeline.js.map +1 -0
- package/dist/presentation/OutboundRouter.js +13 -6
- package/dist/presentation/OutboundRouter.js.map +1 -1
- package/dist/presentation/TurnStateReducer.js +28 -21
- package/dist/presentation/TurnStateReducer.js.map +1 -1
- package/dist/proxy/ProxySessionController.js +229 -92
- package/dist/proxy/ProxySessionController.js.map +1 -1
- package/dist/proxy/TaskMetadata.js +86 -0
- package/dist/proxy/TaskMetadata.js.map +1 -0
- package/dist/scheduling/ScheduleCards.js +10 -4
- package/dist/scheduling/ScheduleCards.js.map +1 -1
- package/dist/scheduling/ScheduleCommand.js +4 -0
- package/dist/scheduling/ScheduleCommand.js.map +1 -1
- package/dist/scheduling/ScheduledTaskStore.js +51 -12
- package/dist/scheduling/ScheduledTaskStore.js.map +1 -1
- package/dist/scheduling/types.js +18 -4
- package/dist/scheduling/types.js.map +1 -1
- package/dist/state/StateStore.js +145 -19
- package/dist/state/StateStore.js.map +1 -1
- package/dist/state/TurnPreviewJournal.js +143 -36
- package/dist/state/TurnPreviewJournal.js.map +1 -1
- package/dist/state/TurnToolText.js +172 -0
- package/dist/state/TurnToolText.js.map +1 -0
- package/dist/state/migrations.js +4 -0
- package/dist/state/migrations.js.map +1 -1
- package/dist/supervision/SafeRestartNotifier.js +9 -6
- package/dist/supervision/SafeRestartNotifier.js.map +1 -1
- package/dist/terminal/TerminalPage.js +5 -0
- package/dist/terminal/TerminalPage.js.map +1 -1
- package/dist/updates/AutomaticUpdatePreparer.js +63 -12
- package/dist/updates/AutomaticUpdatePreparer.js.map +1 -1
- package/dist/updates/ManualUpdateController.js +7 -2
- package/dist/updates/ManualUpdateController.js.map +1 -1
- package/dist/utils/promptAttachments.js +20 -0
- package/dist/utils/promptAttachments.js.map +1 -0
- package/dist/utils/toolTimestamp.js +6 -0
- package/dist/utils/toolTimestamp.js.map +1 -0
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- package/skills/agent-bot/SKILL.md +23 -2
- package/src/cli/SelfUpdateObserver.ts +111 -0
- package/src/cli/SelfUpdateRunner.ts +271 -85
- package/src/cli/SelfUpdater.ts +53 -16
- package/src/cli/controlProtocol.ts +1 -0
- package/src/cli/help.ts +6 -0
- package/src/cli.ts +71 -5
- package/src/codex/CodexEventMapper.ts +25 -5
- package/src/codex/CodexRuntime.ts +4 -0
- package/src/feishu/CardRenderer.ts +48 -13
- package/src/feishu/ConsoleFeishuClient.ts +6 -1
- package/src/feishu/FeishuMarkdown.ts +2 -14
- package/src/feishu/FeishuMessageClient.ts +10 -0
- package/src/feishu/FeishuTurnPresenter.ts +22 -8
- package/src/feishu/types.ts +1 -0
- package/src/index.ts +47 -12
- package/src/local-files/DiagramPreview.ts +11 -6
- package/src/local-files/GitDiffPreview.ts +38 -10
- package/src/local-files/LiveMarkup.ts +103 -0
- package/src/local-files/LocalFileViewerServer.ts +120 -120
- package/src/local-files/MarkdownExport.ts +54 -0
- package/src/local-files/PreviewCodeFont.ts +12 -0
- package/src/local-files/PreviewSyntaxHighlight.ts +75 -0
- package/src/local-files/ToolCommandDisplay.ts +104 -0
- package/src/local-files/TurnPreviewPage.ts +23 -254
- package/src/local-files/WorkspaceFileEvents.ts +186 -0
- package/src/local-files/WorkspaceFiles.ts +72 -5
- package/src/local-files/WorkspaceImages.ts +10 -0
- package/src/local-files/WorkspacePage.ts +20 -5
- package/src/local-files/WorkspaceSessions.ts +811 -82
- package/src/local-files/WorkspaceTimeline.ts +109 -0
- package/src/presentation/OutboundRouter.ts +15 -4
- package/src/presentation/TurnStateReducer.ts +27 -18
- package/src/presentation/turnViewTypes.ts +2 -0
- package/src/proxy/ProxySessionController.ts +226 -77
- package/src/proxy/TaskMetadata.ts +81 -0
- package/src/runtime/types.ts +2 -1
- package/src/scheduling/ScheduleCards.ts +10 -4
- package/src/scheduling/ScheduleCommand.ts +4 -0
- package/src/scheduling/ScheduledTaskStore.ts +54 -9
- package/src/scheduling/types.ts +24 -4
- package/src/state/StateStore.ts +157 -20
- package/src/state/TurnPreviewJournal.ts +138 -34
- package/src/state/TurnToolText.ts +156 -0
- package/src/state/migrations.ts +4 -0
- package/src/supervision/SafeRestartNotifier.ts +9 -6
- package/src/terminal/TerminalPage.ts +5 -0
- package/src/updates/AutomaticUpdatePreparer.ts +52 -11
- package/src/updates/ManualUpdateController.ts +8 -3
- package/src/utils/promptAttachments.ts +24 -0
- package/src/utils/toolTimestamp.ts +5 -0
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
export const LIVE_MARKUP_CLIENT_SCRIPT = `(() => {
|
|
2
|
+
const nodeKey = (node) => {
|
|
3
|
+
if (node.nodeType !== 1) return undefined;
|
|
4
|
+
for (const attribute of ["data-preview-key", "data-activity", "data-activity-id", "data-scroll-id", "data-reasoning-field", "data-reasoning-part"]) {
|
|
5
|
+
if (node.hasAttribute(attribute)) return attribute + ":" + node.getAttribute(attribute);
|
|
6
|
+
}
|
|
7
|
+
if (node.tagName === "IMG") return "image:" + node.getAttribute("src");
|
|
8
|
+
// Keep Markdown image paragraphs/links anchored when text is inserted before them.
|
|
9
|
+
if (["P", "A", "FIGURE", "PICTURE"].includes(node.tagName)) {
|
|
10
|
+
const image = node.querySelector("img");
|
|
11
|
+
if (image) return node.tagName + ":image:" + image.getAttribute("src");
|
|
12
|
+
}
|
|
13
|
+
for (const name of ["markdown", "tool-command", "tool-image", "files", "tool-header", "tool-body", "tool-footer"]) {
|
|
14
|
+
if (node.classList.contains(name)) return node.tagName + ":" + name;
|
|
15
|
+
}
|
|
16
|
+
return undefined;
|
|
17
|
+
};
|
|
18
|
+
const compatible = (current, next) => current.nodeType === next.nodeType && current.nodeName === next.nodeName;
|
|
19
|
+
const patchNode = (current, next) => {
|
|
20
|
+
if (!compatible(current, next)) {
|
|
21
|
+
current.replaceWith(next.cloneNode(true));
|
|
22
|
+
return;
|
|
23
|
+
}
|
|
24
|
+
// Summary snapshots never own a detail body that has already been fetched.
|
|
25
|
+
if (current.nodeType === 1 && current.hasAttribute("data-detail-body") && next.hasAttribute("data-detail-body")) return;
|
|
26
|
+
if (current.isEqualNode(next)) return;
|
|
27
|
+
if (current.nodeType !== 1) {
|
|
28
|
+
if (current.nodeValue !== next.nodeValue) current.nodeValue = next.nodeValue;
|
|
29
|
+
return;
|
|
30
|
+
}
|
|
31
|
+
if (current.hasAttribute("data-diagram") && next.hasAttribute("data-diagram")) {
|
|
32
|
+
const code = current.querySelector(".diagram-source code");
|
|
33
|
+
const nextCode = next.querySelector(".diagram-source code");
|
|
34
|
+
if (code && nextCode && code.textContent !== nextCode.textContent) {
|
|
35
|
+
code.textContent = nextCode.textContent;
|
|
36
|
+
window.agentBotDiagrams.refresh(current);
|
|
37
|
+
}
|
|
38
|
+
return;
|
|
39
|
+
}
|
|
40
|
+
const preserveOpen = current.tagName === "DETAILS";
|
|
41
|
+
for (const attribute of Array.from(current.attributes)) {
|
|
42
|
+
if (preserveOpen && attribute.name === "open") continue;
|
|
43
|
+
if (!next.hasAttribute(attribute.name)) current.removeAttribute(attribute.name);
|
|
44
|
+
}
|
|
45
|
+
for (const attribute of Array.from(next.attributes)) {
|
|
46
|
+
if (preserveOpen && attribute.name === "open") continue;
|
|
47
|
+
if (current.getAttribute(attribute.name) !== attribute.value) current.setAttribute(attribute.name, attribute.value);
|
|
48
|
+
}
|
|
49
|
+
patchChildren(current, next);
|
|
50
|
+
};
|
|
51
|
+
const patchChildren = (parent, next) => {
|
|
52
|
+
const nextChildren = Array.from(next.childNodes);
|
|
53
|
+
const nextKeys = new Set(nextChildren.map(nodeKey).filter((key) => key !== undefined));
|
|
54
|
+
const remaining = new Set(Array.from(parent.childNodes));
|
|
55
|
+
const keyed = new Map();
|
|
56
|
+
for (const child of remaining) {
|
|
57
|
+
const key = nodeKey(child);
|
|
58
|
+
if (key === undefined) continue;
|
|
59
|
+
if (!nextKeys.has(key)) {
|
|
60
|
+
child.remove();
|
|
61
|
+
remaining.delete(child);
|
|
62
|
+
continue;
|
|
63
|
+
}
|
|
64
|
+
const matches = keyed.get(key) || [];
|
|
65
|
+
matches.push(child);
|
|
66
|
+
keyed.set(key, matches);
|
|
67
|
+
}
|
|
68
|
+
let cursor = parent.firstChild;
|
|
69
|
+
for (const child of nextChildren) {
|
|
70
|
+
const key = nodeKey(child);
|
|
71
|
+
const matches = key === undefined ? undefined : keyed.get(key);
|
|
72
|
+
const current = key === undefined
|
|
73
|
+
? cursor && nodeKey(cursor) === undefined && compatible(cursor, child) ? cursor : undefined
|
|
74
|
+
: matches?.find((candidate) => remaining.has(candidate) && compatible(candidate, child));
|
|
75
|
+
if (current) {
|
|
76
|
+
remaining.delete(current);
|
|
77
|
+
// Drop obsolete text/markup before a retained block without detaching that block.
|
|
78
|
+
while (cursor && cursor !== current && nodeKey(cursor) === undefined) {
|
|
79
|
+
const obsolete = cursor;
|
|
80
|
+
cursor = cursor.nextSibling;
|
|
81
|
+
remaining.delete(obsolete);
|
|
82
|
+
obsolete.remove();
|
|
83
|
+
}
|
|
84
|
+
if (current !== cursor) {
|
|
85
|
+
if (typeof parent.moveBefore === "function" && current.isConnected) parent.moveBefore(current, cursor);
|
|
86
|
+
else parent.insertBefore(current, cursor);
|
|
87
|
+
}
|
|
88
|
+
patchNode(current, child);
|
|
89
|
+
cursor = current.nextSibling;
|
|
90
|
+
} else {
|
|
91
|
+
const added = child.cloneNode(true);
|
|
92
|
+
parent.insertBefore(added, cursor);
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
for (const child of remaining) child.remove();
|
|
96
|
+
};
|
|
97
|
+
const patchMarkup = (element, markup) => {
|
|
98
|
+
const template = document.createElement("template");
|
|
99
|
+
template.innerHTML = markup;
|
|
100
|
+
patchChildren(element, template.content);
|
|
101
|
+
};
|
|
102
|
+
window.agentBotLiveMarkup = { nodeKey, patchMarkup, patchNode };
|
|
103
|
+
})();\n`;
|
|
104
|
+
//# sourceMappingURL=LiveMarkup.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"LiveMarkup.js","sourceRoot":"","sources":["../../src/local-files/LiveMarkup.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,yBAAyB,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;QAsGjC,CAAC"}
|
|
@@ -1,19 +1,19 @@
|
|
|
1
1
|
import { TurnPreviewProjection } from "../state/TurnPreviewJournal.js";
|
|
2
|
-
import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
|
|
2
|
+
import { createHash, createHmac, randomBytes, timingSafeEqual } from "node:crypto";
|
|
3
3
|
import fs from "node:fs";
|
|
4
4
|
import { createRequire } from "node:module";
|
|
5
5
|
import http from "node:http";
|
|
6
6
|
import path from "node:path";
|
|
7
7
|
import { z } from "zod";
|
|
8
8
|
import hljs from "highlight.js/lib/common";
|
|
9
|
-
import dos from "highlight.js/lib/languages/dos";
|
|
10
|
-
import dockerfile from "highlight.js/lib/languages/dockerfile";
|
|
11
|
-
import powershell from "highlight.js/lib/languages/powershell";
|
|
12
9
|
import MarkdownIt from "markdown-it";
|
|
13
10
|
import { CSV_PREVIEW_CSS, renderCsvPreview, csvSourcePreview } from "./CsvPreview.js";
|
|
14
11
|
import { GIT_DIFF_PREVIEW_CSS, readGitFileDiff, renderGitFileDiff } from "./GitDiffPreview.js";
|
|
15
|
-
import { renderWorkspacePage, WORKSPACE_SCRIPT } from "./WorkspacePage.js";
|
|
12
|
+
import { renderWorkspacePage, WORKSPACE_ICON, WORKSPACE_ICON_NAME, WORKSPACE_INSTANCE, WORKSPACE_INSTANCE_HEADER, WORKSPACE_REVISION, WORKSPACE_REVISION_HEADER, WORKSPACE_SCRIPT } from "./WorkspacePage.js";
|
|
13
|
+
import { PREVIEW_CODE_FONT, PREVIEW_CODE_FONT_NAME, previewCodeFontCss } from "./PreviewCodeFont.js";
|
|
14
|
+
import { highlightLines, highlightTextLines, MAX_SYNTAX_HIGHLIGHT_BYTES, syntaxLanguageFor } from "./PreviewSyntaxHighlight.js";
|
|
16
15
|
import { directWorkspaceOrigin } from "./WorkspaceOrigin.js";
|
|
16
|
+
import { WorkspaceFileEvents } from "./WorkspaceFileEvents.js";
|
|
17
17
|
import { readWebPageTitle } from "./WebPageTitle.js";
|
|
18
18
|
import { WorkspaceError, readWorkspaceAddress, readWorkspaceEntries, readWorkspaceGitStatus, readWorkspaceChanges, readWorkspaceFileVersions, createWorkspaceDiff, renderWorkspaceDiff, resolveWorkspacePath } from "./WorkspaceFiles.js";
|
|
19
19
|
import { enableDiagramFences, DIAGRAM_PREVIEW_CLIENT_SCRIPT, DIAGRAM_PREVIEW_CSS } from "./DiagramPreview.js";
|
|
@@ -28,20 +28,17 @@ const SHORT_TOKEN_BYTES = 12;
|
|
|
28
28
|
const SHORT_TOKEN_LENGTH = 16;
|
|
29
29
|
const MAX_TEXT_PREVIEW_BYTES = 2 * 1024 * 1024;
|
|
30
30
|
const MAX_CONTENT_SAMPLE_BYTES = 64 * 1024;
|
|
31
|
-
const MAX_SYNTAX_HIGHLIGHT_BYTES = 512 * 1024;
|
|
32
31
|
const DIRECTORY_PAGE_SIZE = 100;
|
|
33
32
|
const WORKSPACE_QUERY = z.object({
|
|
34
33
|
api: z.string().optional(), entry: z.string().default(""),
|
|
35
34
|
page: z.coerce.number().int().min(0).max(Number.MAX_SAFE_INTEGER).default(0),
|
|
36
35
|
mode: z.enum(["all", "staged", "unstaged"]).default("all"), original: z.string().optional(),
|
|
37
36
|
prefetch: z.enum(["0", "1"]).optional(), query: z.string().trim().max(160).optional(),
|
|
37
|
+
refresh: z.enum(["1"]).optional(),
|
|
38
38
|
instance: z.string().regex(/^[a-f0-9]{16}$/u).optional(),
|
|
39
39
|
});
|
|
40
40
|
const MARKDOWN_EXTENSIONS = new Set([".markdown", ".md", ".mdown", ".mkd", ".mkdn"]);
|
|
41
41
|
const HTML_EXTENSIONS = new Set([".html", ".htm"]);
|
|
42
|
-
hljs.registerLanguage("dos", dos);
|
|
43
|
-
hljs.registerLanguage("dockerfile", dockerfile);
|
|
44
|
-
hljs.registerLanguage("powershell", powershell);
|
|
45
42
|
const MARKDOWN_RENDERER = new MarkdownIt({
|
|
46
43
|
breaks: false,
|
|
47
44
|
html: false,
|
|
@@ -58,27 +55,18 @@ const MARKDOWN_RENDERER = new MarkdownIt({
|
|
|
58
55
|
},
|
|
59
56
|
});
|
|
60
57
|
enableDiagramFences(MARKDOWN_RENDERER);
|
|
61
|
-
MARKDOWN_RENDERER.renderer.rules.table_open = () => '<div class="markdown-table-scroll" role="region" aria-label="Markdown 表格" tabindex="0"><table>\n';
|
|
58
|
+
MARKDOWN_RENDERER.renderer.rules.table_open = (tokens, index, _options, _env, renderer) => '<div class="markdown-table-scroll" role="region" aria-label="Markdown 表格" tabindex="0"><table' + renderer.renderAttrs(tokens[index]) + '>\n';
|
|
62
59
|
MARKDOWN_RENDERER.renderer.rules.table_close = () => '</table></div>\n';
|
|
60
|
+
for (const kind of ["fence", "code_block"]) {
|
|
61
|
+
const render = MARKDOWN_RENDERER.renderer.rules[kind];
|
|
62
|
+
MARKDOWN_RENDERER.renderer.rules[kind] = (tokens, index, options, env, renderer) => {
|
|
63
|
+
const html = render(tokens, index, options, env, renderer), token = tokens[index];
|
|
64
|
+
const start = token.attrGet("data-source-start"), end = token.attrGet("data-source-end");
|
|
65
|
+
return start === null ? html : `<div data-source-start="${start}" data-source-end="${end}">${html}</div>\n`;
|
|
66
|
+
};
|
|
67
|
+
}
|
|
63
68
|
const validateMarkdownLink = MARKDOWN_RENDERER.validateLink.bind(MARKDOWN_RENDERER);
|
|
64
69
|
MARKDOWN_RENDERER.validateLink = (url) => isFileUrl(url) || validateMarkdownLink(url);
|
|
65
|
-
const HIGHLIGHT_LANGUAGE_BY_EXTENSION = {
|
|
66
|
-
".bash": "bash", ".bat": "dos", ".c": "c", ".cc": "cpp", ".cmd": "dos", ".cpp": "cpp",
|
|
67
|
-
".cs": "csharp", ".css": "css", ".cxx": "cpp", ".diff": "diff", ".go": "go", ".h": "cpp",
|
|
68
|
-
".hpp": "cpp", ".htm": "xml", ".html": "xml", ".ini": "ini", ".ipynb": "json", ".java": "java",
|
|
69
|
-
".js": "javascript", ".json": "json", ".jsonl": "json", ".jsx": "javascript", ".kt": "kotlin",
|
|
70
|
-
".kts": "kotlin", ".less": "less", ".lua": "lua", ".markdown": "markdown", ".md": "markdown",
|
|
71
|
-
".mjs": "javascript", ".patch": "diff", ".php": "php", ".pl": "perl", ".ps1": "powershell",
|
|
72
|
-
".py": "python", ".r": "r", ".rb": "ruby", ".rs": "rust", ".scss": "scss", ".sh": "bash",
|
|
73
|
-
".sql": "sql", ".swift": "swift", ".toml": "ini", ".ts": "typescript", ".tsx": "typescript",
|
|
74
|
-
".vue": "xml", ".xml": "xml", ".yaml": "yaml", ".yml": "yaml", ".zsh": "bash",
|
|
75
|
-
};
|
|
76
|
-
const HIGHLIGHT_LANGUAGE_BY_FILENAME = {
|
|
77
|
-
".env": "ini",
|
|
78
|
-
".gitignore": "ini",
|
|
79
|
-
"dockerfile": "dockerfile",
|
|
80
|
-
"makefile": "makefile",
|
|
81
|
-
};
|
|
82
70
|
const VIEWER_CLIENT_SCRIPT = DIAGRAM_PREVIEW_CLIENT_SCRIPT + `(() => {
|
|
83
71
|
const eventsUrl = document.body.dataset.eventsUrl;
|
|
84
72
|
const content = document.getElementById("viewer-content");
|
|
@@ -126,9 +114,9 @@ const VIEWER_CLIENT_SCRIPT = DIAGRAM_PREVIEW_CLIENT_SCRIPT + `(() => {
|
|
|
126
114
|
const diffBlocks = [];
|
|
127
115
|
if (diffPrevious && diffNext) {
|
|
128
116
|
for (const line of content.querySelectorAll(".git-diff .diff-addition, .git-diff .diff-deletion")) {
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
117
|
+
if (!line.previousElementSibling?.matches(".diff-addition, .diff-deletion")) {
|
|
118
|
+
diffBlocks.push({ first: line, hash: "#diff-" + line.id });
|
|
119
|
+
}
|
|
132
120
|
}
|
|
133
121
|
}
|
|
134
122
|
let diffPositions = [], selectedDiff = -1;
|
|
@@ -158,8 +146,9 @@ const VIEWER_CLIENT_SCRIPT = DIAGRAM_PREVIEW_CLIENT_SCRIPT + `(() => {
|
|
|
158
146
|
const height = window.innerHeight;
|
|
159
147
|
const readerCenter = (header.getBoundingClientRect().height + height) / 2;
|
|
160
148
|
const maxTop = Math.max(0, document.documentElement.scrollHeight - height);
|
|
161
|
-
diffPositions = diffBlocks.map(({ first
|
|
162
|
-
const
|
|
149
|
+
diffPositions = diffBlocks.map(({ first }) => {
|
|
150
|
+
const line = first.getBoundingClientRect();
|
|
151
|
+
const center = (line.top + line.bottom) / 2;
|
|
163
152
|
return Math.min(maxTop, Math.max(0, window.scrollY + center - readerCenter));
|
|
164
153
|
});
|
|
165
154
|
updateDiffNavigation();
|
|
@@ -315,6 +304,7 @@ export class LocalFileViewerServer {
|
|
|
315
304
|
address;
|
|
316
305
|
basePath = "";
|
|
317
306
|
services = new Map();
|
|
307
|
+
workspaceFileEvents = new WorkspaceFileEvents();
|
|
318
308
|
workspaceAppBase;
|
|
319
309
|
enableWorkspaceApp(base) { this.workspaceAppBase = base; }
|
|
320
310
|
serveWorkspaceAppPage(response, url, headOnly) {
|
|
@@ -400,6 +390,7 @@ export class LocalFileViewerServer {
|
|
|
400
390
|
async close() {
|
|
401
391
|
await Promise.all([...this.services.values()].map((service) => service.close()));
|
|
402
392
|
this.services.clear();
|
|
393
|
+
this.workspaceFileEvents.close();
|
|
403
394
|
const server = this.server;
|
|
404
395
|
this.server = undefined;
|
|
405
396
|
this.address = undefined;
|
|
@@ -506,7 +497,20 @@ export class LocalFileViewerServer {
|
|
|
506
497
|
}
|
|
507
498
|
const requestUrl = new URL(request.url ?? "/", "http://127.0.0.1");
|
|
508
499
|
const route = routeWithinBasePath(requestUrl.pathname, this.basePath);
|
|
500
|
+
const workspaceIcon = route === "/assets/" + WORKSPACE_ICON_NAME;
|
|
501
|
+
if (workspaceIcon || route === "/assets/" + PREVIEW_CODE_FONT_NAME) {
|
|
502
|
+
const asset = workspaceIcon ? WORKSPACE_ICON : PREVIEW_CODE_FONT;
|
|
503
|
+
setSecurityHeaders(response);
|
|
504
|
+
response.statusCode = 200;
|
|
505
|
+
response.setHeader("Content-Type", workspaceIcon ? "image/x-icon" : "font/woff2");
|
|
506
|
+
response.setHeader("Cache-Control", "public, max-age=86400");
|
|
507
|
+
response.setHeader("Content-Length", asset.length);
|
|
508
|
+
response.end(request.method === "HEAD" ? undefined : asset);
|
|
509
|
+
return;
|
|
510
|
+
}
|
|
509
511
|
if (route === "/assets/workspace.js") {
|
|
512
|
+
response.setHeader(WORKSPACE_REVISION_HEADER, WORKSPACE_REVISION);
|
|
513
|
+
response.setHeader(WORKSPACE_INSTANCE_HEADER, WORKSPACE_INSTANCE);
|
|
510
514
|
this.sendJavascript(response, request.method === "HEAD", WORKSPACE_SCRIPT);
|
|
511
515
|
return;
|
|
512
516
|
}
|
|
@@ -522,8 +526,7 @@ export class LocalFileViewerServer {
|
|
|
522
526
|
await this.handleWorkspace(request, response, requestUrl, root);
|
|
523
527
|
}
|
|
524
528
|
catch (error) {
|
|
525
|
-
|
|
526
|
-
this.sendWorkspaceJson(response, error instanceof WorkspaceError ? error.status : code === "ENOENT" ? 404 : code === "EACCES" || code === "EPERM" ? 403 : 500, { error: error instanceof Error ? error.message : String(error) }, request.method === "HEAD");
|
|
529
|
+
this.sendWorkspaceJson(response, this.workspaceErrorStatus(error), { error: error instanceof Error ? error.message : String(error) }, request.method === "HEAD");
|
|
527
530
|
}
|
|
528
531
|
return;
|
|
529
532
|
}
|
|
@@ -561,7 +564,7 @@ export class LocalFileViewerServer {
|
|
|
561
564
|
}
|
|
562
565
|
const detailKey = requestUrl.searchParams.get("detail");
|
|
563
566
|
let snapshot = recorded
|
|
564
|
-
? journal.
|
|
567
|
+
? await journal.loadAsync(journalId, detailKey ?? false)
|
|
565
568
|
: this.options.getTurnSnapshot?.(turnId);
|
|
566
569
|
if (!recorded && this.options.loadTurnSnapshot && request.method !== "HEAD"
|
|
567
570
|
&& requestUrl.searchParams.get("events") !== "1" && !requestUrl.searchParams.has("detail")) {
|
|
@@ -940,14 +943,19 @@ export class LocalFileViewerServer {
|
|
|
940
943
|
}
|
|
941
944
|
response.flushHeaders();
|
|
942
945
|
const language = detectTurnPreviewLanguage(request.headers["accept-language"]);
|
|
943
|
-
|
|
946
|
+
let projection = new TurnPreviewProjection(false);
|
|
944
947
|
let offset = 0;
|
|
945
948
|
let closed = false;
|
|
946
949
|
let initial = true;
|
|
947
950
|
const cursor = request.headers["last-event-id"] ?? new URL(request.url, "http://localhost").searchParams.get("after");
|
|
948
951
|
if (typeof cursor === "string" && /^\d+$/u.test(cursor) && Number.isSafeInteger(Number(cursor)) && Number(cursor) > 0
|
|
949
952
|
&& Number(cursor) <= fs.statSync(journal.file(turnId)).size) {
|
|
950
|
-
|
|
953
|
+
const cached = journal.cachedProjection(turnId, Number(cursor));
|
|
954
|
+
if (cached) {
|
|
955
|
+
projection = cached;
|
|
956
|
+
offset = Number(cursor);
|
|
957
|
+
}
|
|
958
|
+
while (!cached && offset < Number(cursor)) {
|
|
951
959
|
const batch = journal.read(turnId, offset, 256 * 1024, Number(cursor));
|
|
952
960
|
for (const record of batch.records)
|
|
953
961
|
projection.apply(record, ++projection.revision);
|
|
@@ -1061,32 +1069,89 @@ export class LocalFileViewerServer {
|
|
|
1061
1069
|
request.once("aborted", cleanup);
|
|
1062
1070
|
response.once("close", cleanup);
|
|
1063
1071
|
}
|
|
1064
|
-
sendWorkspaceJson(response, status, value, headOnly) {
|
|
1072
|
+
sendWorkspaceJson(response, status, value, headOnly, request) {
|
|
1065
1073
|
const body = Buffer.from(JSON.stringify(value), "utf8");
|
|
1066
1074
|
setSecurityHeaders(response);
|
|
1075
|
+
if (request) {
|
|
1076
|
+
const etag = '"' + createHash("sha256").update(body).digest("base64url") + '"';
|
|
1077
|
+
response.setHeader("ETag", etag);
|
|
1078
|
+
if (request.headers["if-none-match"] === etag) {
|
|
1079
|
+
response.writeHead(304, { "Cache-Control": "no-store" });
|
|
1080
|
+
response.end();
|
|
1081
|
+
return;
|
|
1082
|
+
}
|
|
1083
|
+
}
|
|
1067
1084
|
response.writeHead(status, { "Content-Type": "application/json; charset=utf-8", "Cache-Control": "no-store", "Content-Length": body.length });
|
|
1068
1085
|
response.end(headOnly ? undefined : body);
|
|
1069
1086
|
}
|
|
1070
|
-
async
|
|
1071
|
-
|
|
1087
|
+
async serveTaskDirectory(request, response, url, root, base) {
|
|
1088
|
+
try {
|
|
1089
|
+
await this.handleWorkspace(request, response, url, root, base);
|
|
1090
|
+
}
|
|
1091
|
+
catch (error) {
|
|
1092
|
+
if (response.headersSent)
|
|
1093
|
+
throw error;
|
|
1094
|
+
const status = this.workspaceErrorStatus(error);
|
|
1095
|
+
const message = status < 500 && error instanceof Error ? error.message : "暂时无法打开此目录,请重试。";
|
|
1096
|
+
if (url.searchParams.has("api"))
|
|
1097
|
+
this.sendWorkspaceJson(response, status, { error: message }, request.method === "HEAD");
|
|
1098
|
+
else
|
|
1099
|
+
this.sendHtml(response, status, errorPage("无法打开任务目录", message), request.method === "HEAD", "embedded");
|
|
1100
|
+
}
|
|
1101
|
+
}
|
|
1102
|
+
workspaceErrorStatus(error) {
|
|
1103
|
+
if (error instanceof WorkspaceError)
|
|
1104
|
+
return error.status;
|
|
1105
|
+
const code = error?.code;
|
|
1106
|
+
return code === "ENOENT" || code === "ENOTDIR" ? 404 : code === "EACCES" || code === "EPERM" ? 403 : 500;
|
|
1107
|
+
}
|
|
1108
|
+
async handleWorkspace(request, response, url, root, scopedBase) {
|
|
1109
|
+
if (!fs.statSync(resolveWorkspacePath(root)).isDirectory())
|
|
1110
|
+
throw new WorkspaceError("目录已不可用。", 404);
|
|
1072
1111
|
const headOnly = request.method === "HEAD";
|
|
1073
1112
|
const published = new URL(this.address.publicBaseUrl);
|
|
1074
|
-
const origin = request.headers.host === published.host ? published.origin : directWorkspaceOrigin(request);
|
|
1075
|
-
const workspaceUrl = this.createWorkspaceUrl(root, origin);
|
|
1076
|
-
if (!url.searchParams.
|
|
1077
|
-
this.sendHtml(response, 200, renderWorkspacePage(root, workspaceUrl, this.basePath + "/assets/workspace.js", this.workspaceAppBase), headOnly, true);
|
|
1113
|
+
const origin = scopedBase?.origin ?? (request.headers.host === published.host ? published.origin : directWorkspaceOrigin(request));
|
|
1114
|
+
const workspaceUrl = scopedBase?.href ?? this.createWorkspaceUrl(root, origin);
|
|
1115
|
+
if (!url.searchParams.get("api")) {
|
|
1116
|
+
this.sendHtml(response, 200, renderWorkspacePage(root, workspaceUrl, this.basePath + "/assets/workspace.js", scopedBase ? undefined : this.workspaceAppBase, Boolean(scopedBase)), headOnly, scopedBase ? "embedded" : true);
|
|
1078
1117
|
return;
|
|
1079
1118
|
}
|
|
1080
1119
|
const parsed = WORKSPACE_QUERY.safeParse(Object.fromEntries(url.searchParams));
|
|
1081
1120
|
if (!parsed.success)
|
|
1082
1121
|
throw new WorkspaceError("工作台参数无效:" + parsed.error.issues.map((issue) => issue.message).join(";"));
|
|
1083
|
-
const { api, entry, page, mode, original, prefetch, query, instance } = parsed.data;
|
|
1084
|
-
if (
|
|
1085
|
-
|
|
1122
|
+
const { api, entry, page, mode, original, prefetch, query, instance, refresh } = parsed.data;
|
|
1123
|
+
if (scopedBase && (api === "terminal" || api === "web-title"))
|
|
1124
|
+
throw new WorkspaceError("该目录只支持文件浏览。", 404);
|
|
1125
|
+
if (api === "events") {
|
|
1126
|
+
if (request.headers["sec-fetch-site"] === "cross-site" || (request.headers.origin && request.headers.origin !== origin)) {
|
|
1127
|
+
throw new WorkspaceError("项目实时连接来源不受信任。", 403);
|
|
1128
|
+
}
|
|
1129
|
+
if (headOnly)
|
|
1130
|
+
this.sendWorkspaceJson(response, 200, {}, true);
|
|
1131
|
+
else
|
|
1132
|
+
this.workspaceFileEvents.subscribe(root, response);
|
|
1086
1133
|
return;
|
|
1087
1134
|
}
|
|
1088
|
-
if (api === "tree") {
|
|
1089
|
-
|
|
1135
|
+
if (api === "tree" || api === "changes") {
|
|
1136
|
+
if (refresh)
|
|
1137
|
+
this.workspaceFileEvents.invalidateGit(root);
|
|
1138
|
+
const read = api === "tree" ? readWorkspaceEntries : readWorkspaceChanges;
|
|
1139
|
+
const data = await read(root, entry, page, {
|
|
1140
|
+
prefetch: prefetch === "1" && request.headers["save-data"] !== "on", query, readGitStatus: () => this.workspaceFileEvents.gitStatus(root),
|
|
1141
|
+
});
|
|
1142
|
+
if (!headOnly && !query && page === 0) {
|
|
1143
|
+
this.workspaceFileEvents.watchDirectory(root, entry);
|
|
1144
|
+
if ("preloaded" in data && data.preloaded)
|
|
1145
|
+
for (const item of data.preloaded)
|
|
1146
|
+
if (item.directory)
|
|
1147
|
+
this.workspaceFileEvents.watchDirectory(root, item.path);
|
|
1148
|
+
}
|
|
1149
|
+
this.sendWorkspaceJson(response, 200, data, headOnly, request);
|
|
1150
|
+
return;
|
|
1151
|
+
}
|
|
1152
|
+
if (api === "changes-summary") {
|
|
1153
|
+
const { changes, repository, branch, notice } = await this.workspaceFileEvents.gitStatus(root);
|
|
1154
|
+
this.sendWorkspaceJson(response, 200, { totalChanges: changes.length, repository, branch, notice }, headOnly, request);
|
|
1090
1155
|
return;
|
|
1091
1156
|
}
|
|
1092
1157
|
if (api === "address") {
|
|
@@ -1097,10 +1162,6 @@ export class LocalFileViewerServer {
|
|
|
1097
1162
|
this.sendWorkspaceJson(response, 200, headOnly ? {} : await readWebPageTitle(entry), headOnly);
|
|
1098
1163
|
return;
|
|
1099
1164
|
}
|
|
1100
|
-
if (api === "changes") {
|
|
1101
|
-
this.sendWorkspaceJson(response, 200, await readWorkspaceChanges(root, entry, page, { prefetch: prefetch === "1", query }), headOnly);
|
|
1102
|
-
return;
|
|
1103
|
-
}
|
|
1104
1165
|
if (api === "terminal") {
|
|
1105
1166
|
if (!instance)
|
|
1106
1167
|
throw new WorkspaceError("终端标签标识无效。");
|
|
@@ -1123,7 +1184,7 @@ export class LocalFileViewerServer {
|
|
|
1123
1184
|
const previous = decodeText(versions.before, before.encoding, true), current = decodeText(versions.after, after.encoding, true);
|
|
1124
1185
|
html = renderWorkspaceDiff(await createWorkspaceDiff(root, previous, current), current, (value) => highlightTextLines(value, file));
|
|
1125
1186
|
}
|
|
1126
|
-
this.sendWorkspaceJson(response, 200, { html, canViewFile: versions.canViewFile }, headOnly);
|
|
1187
|
+
this.sendWorkspaceJson(response, 200, { html, canViewFile: versions.canViewFile }, headOnly, request);
|
|
1127
1188
|
return;
|
|
1128
1189
|
}
|
|
1129
1190
|
if (api !== "file" && api !== "raw")
|
|
@@ -1166,10 +1227,16 @@ export class LocalFileViewerServer {
|
|
|
1166
1227
|
catch (error) {
|
|
1167
1228
|
gitError = error instanceof Error ? error.message : String(error);
|
|
1168
1229
|
}
|
|
1169
|
-
this.sendWorkspaceJson(response, 200, { html, rawUrl: raw.toString(), change, gitError }, headOnly);
|
|
1230
|
+
this.sendWorkspaceJson(response, 200, { html, rawUrl: raw.toString(), change, gitError }, headOnly, request);
|
|
1170
1231
|
}
|
|
1171
1232
|
renderWorkspaceMarkdown(root, file, value, workspaceUrl) {
|
|
1172
1233
|
const environment = {}, tokens = MARKDOWN_RENDERER.parse(value, environment), targets = new Map();
|
|
1234
|
+
for (const token of tokens) {
|
|
1235
|
+
if (token.map && !token.hidden && token.tag && token.nesting >= 0) {
|
|
1236
|
+
token.attrSet("data-source-start", String(token.map[0] + 1));
|
|
1237
|
+
token.attrSet("data-source-end", String(token.map[1]));
|
|
1238
|
+
}
|
|
1239
|
+
}
|
|
1173
1240
|
rewriteMarkdownFileLinks(tokens, file, (target) => {
|
|
1174
1241
|
const entry = path.relative(root, target).split(path.sep).join("/");
|
|
1175
1242
|
try {
|
|
@@ -1299,9 +1366,9 @@ export class LocalFileViewerServer {
|
|
|
1299
1366
|
const body = Buffer.from(html, "utf8");
|
|
1300
1367
|
setSecurityHeaders(response);
|
|
1301
1368
|
// External frame redirects must not expose privileged viewer documents.
|
|
1302
|
-
response.setHeader("X-Frame-Options", "DENY");
|
|
1369
|
+
response.setHeader("X-Frame-Options", workspace === "embedded" ? "SAMEORIGIN" : "DENY");
|
|
1303
1370
|
if (workspace)
|
|
1304
|
-
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'");
|
|
1371
|
+
response.setHeader("Content-Security-Policy", "default-src 'none'; img-src 'self' data: blob:; media-src 'self'; object-src 'self'; frame-src 'self' http: https:; script-src 'self'; connect-src 'self'; font-src 'self'; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'; frame-ancestors " + (workspace === "embedded" ? "'self'" : "'none'"));
|
|
1305
1372
|
else
|
|
1306
1373
|
response.setHeader("Content-Security-Policy", String(response.getHeader("Content-Security-Policy")).replace("frame-ancestors 'self'", "frame-ancestors 'none'"));
|
|
1307
1374
|
response.statusCode = status;
|
|
@@ -1346,8 +1413,8 @@ function renderViewerPage(input) {
|
|
|
1346
1413
|
<meta charset="utf-8">
|
|
1347
1414
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
1348
1415
|
<title>${escapeHtml(input.title)} · Agent Bot</title>
|
|
1349
|
-
<style>${input.diagramScriptPath ? DIAGRAM_PREVIEW_CSS : ""}
|
|
1350
|
-
:root { --viewer-header-offset: 56px;
|
|
1416
|
+
<style>${input.scriptPath ? previewCodeFontCss(input.scriptPath) : ""}${input.diagramScriptPath ? DIAGRAM_PREVIEW_CSS : ""}
|
|
1417
|
+
:root { --viewer-header-offset: 56px; color-scheme: light dark; font-family: Inter, "Segoe UI", system-ui, sans-serif; }
|
|
1351
1418
|
* { box-sizing: border-box; }
|
|
1352
1419
|
body { margin: 0; background: #f5f7fa; color: #1f2329; }
|
|
1353
1420
|
header { position: sticky; top: 0; z-index: 2; padding: 7px 12px; background: rgba(255,255,255,.96); border-bottom: 1px solid #dfe3e8; }
|
|
@@ -1370,10 +1437,10 @@ function renderViewerPage(input) {
|
|
|
1370
1437
|
main { padding: 0; }
|
|
1371
1438
|
.notice, .unsupported { margin: 8px; padding: 10px 12px; border: 1px solid #f3cf8f; background: #fff7e6; border-radius: 5px; }
|
|
1372
1439
|
.code { margin: 0; padding: 6px 0; overflow: auto; border: 0; border-radius: 0; background: #fff; color: #1f2329; font-size: 13px; line-height: 1.5; tab-size: 2; }
|
|
1373
|
-
.code, .code code, .code .line, .code .line * { font-family: var(--
|
|
1440
|
+
.code, .code code, .code .line, .code .line * { font-family: var(--preview-code-font); font-variant-ligatures: none; }
|
|
1374
1441
|
.line { display: block; min-height: 1.55em; padding-right: 16px; scroll-margin-top: var(--viewer-header-offset); }
|
|
1375
1442
|
.line:target, .line.is-target-line { background: #fff1b8; box-shadow: inset 4px 0 #e6a700; }
|
|
1376
|
-
.line-number { display: inline-block; width:
|
|
1443
|
+
.line-number { display: inline-block; box-sizing: content-box; width: var(--line-number-width, 2ch); margin-right: 8px; padding: 0 6px; text-align: right; color: #8f959e; border-right: 1px solid #eceff3; text-decoration: none; user-select: none; }
|
|
1377
1444
|
.hljs-comment, .hljs-quote { color: #6a737d; font-style: italic; }
|
|
1378
1445
|
.hljs-keyword, .hljs-selector-tag, .hljs-literal, .hljs-section, .hljs-link { color: #a626a4; }
|
|
1379
1446
|
.hljs-string, .hljs-regexp, .hljs-title, .hljs-name, .hljs-type, .hljs-attribute, .hljs-symbol, .hljs-bullet, .hljs-addition, .hljs-variable, .hljs-template-tag, .hljs-template-variable { color: #087f5b; }
|
|
@@ -1397,7 +1464,7 @@ function renderViewerPage(input) {
|
|
|
1397
1464
|
.markdown-body blockquote { margin-left: 0; padding: .15em 1em; border-left: 4px solid #c9d0db; color: #646a73; }
|
|
1398
1465
|
.markdown-body a { color: #1456f0; text-decoration: none; }
|
|
1399
1466
|
.markdown-body a:hover { text-decoration: underline; }
|
|
1400
|
-
.markdown-body code { padding: .14em .35em; border-radius: 4px; background: #f2f3f5; font-family: var(--
|
|
1467
|
+
.markdown-body code { padding: .14em .35em; border-radius: 4px; background: #f2f3f5; font-family: var(--preview-code-font); font-size: .9em; }
|
|
1401
1468
|
.markdown-body .markdown-code-block { margin: 0 0 1em; padding: 14px 16px; overflow: auto; border-radius: 6px; background: #f6f8fa; line-height: 1.55; }
|
|
1402
1469
|
.markdown-body .markdown-code-block code { padding: 0; background: transparent; font-size: 13px; }
|
|
1403
1470
|
.markdown-body .diagram-source { padding: 14px 16px; }
|
|
@@ -1743,18 +1810,12 @@ function hasTextLikeCharacters(value) {
|
|
|
1743
1810
|
function renderText(value, filePath) {
|
|
1744
1811
|
const language = syntaxLanguageFor(filePath), lines = highlightTextLines(value, filePath);
|
|
1745
1812
|
const languageClass = language ? ` class="language-${escapeAttribute(language)}"` : "";
|
|
1746
|
-
|
|
1813
|
+
const numberWidth = Math.max(2, String(lines.length).length);
|
|
1814
|
+
return `<pre class="code hljs" style="--line-number-width:${numberWidth}ch"><code${languageClass}>${lines.map((line, index) => {
|
|
1747
1815
|
const lineNumber = index + 1;
|
|
1748
|
-
return `<span class="line" id="L${lineNumber}"><a class="line-number" href="#L${lineNumber}">${lineNumber}</a>${line}</span>`;
|
|
1816
|
+
return `<span class="line" id="L${lineNumber}"><a class="line-number" href="#L${lineNumber}">${lineNumber}</a><span class="line-text">${line}</span></span>`;
|
|
1749
1817
|
}).join("")}</code></pre>`;
|
|
1750
1818
|
}
|
|
1751
|
-
function highlightTextLines(value, filePath) {
|
|
1752
|
-
const normalized = value.replace(/\r\n?/gu, "\n");
|
|
1753
|
-
const language = syntaxLanguageFor(filePath);
|
|
1754
|
-
return language && Buffer.byteLength(normalized, "utf8") <= MAX_SYNTAX_HIGHLIGHT_BYTES
|
|
1755
|
-
? highlightLines(normalized, language)
|
|
1756
|
-
: normalized.split("\n").map(escapeHtml);
|
|
1757
|
-
}
|
|
1758
1819
|
function renderMarkdownDocument(value, filePath, createPreviewUrl) {
|
|
1759
1820
|
const environment = {};
|
|
1760
1821
|
const tokens = MARKDOWN_RENDERER.parse(value, environment);
|
|
@@ -1765,51 +1826,6 @@ function renderMarkdownDocument(value, filePath, createPreviewUrl) {
|
|
|
1765
1826
|
function isMarkdownFile(filePath) {
|
|
1766
1827
|
return MARKDOWN_EXTENSIONS.has(path.extname(filePath).toLowerCase());
|
|
1767
1828
|
}
|
|
1768
|
-
function syntaxLanguageFor(filePath) {
|
|
1769
|
-
if (isMarkdownFile(filePath))
|
|
1770
|
-
return "markdown";
|
|
1771
|
-
const fileName = path.basename(filePath).toLowerCase();
|
|
1772
|
-
return Object.hasOwn(HIGHLIGHT_LANGUAGE_BY_FILENAME, fileName) ? HIGHLIGHT_LANGUAGE_BY_FILENAME[fileName]
|
|
1773
|
-
: HIGHLIGHT_LANGUAGE_BY_EXTENSION[path.extname(fileName)];
|
|
1774
|
-
}
|
|
1775
|
-
function highlightLines(value, language) {
|
|
1776
|
-
try {
|
|
1777
|
-
return splitHighlightedLines(hljs.highlight(value, { language, ignoreIllegals: true }).value);
|
|
1778
|
-
}
|
|
1779
|
-
catch {
|
|
1780
|
-
return value.split("\n").map(escapeHtml);
|
|
1781
|
-
}
|
|
1782
|
-
}
|
|
1783
|
-
function splitHighlightedLines(value) {
|
|
1784
|
-
const lines = [];
|
|
1785
|
-
const openTags = [];
|
|
1786
|
-
const tokenPattern = /<span class="[^"]+">|<\/span>|\n/gu;
|
|
1787
|
-
let current = "";
|
|
1788
|
-
let offset = 0;
|
|
1789
|
-
for (const match of value.matchAll(tokenPattern)) {
|
|
1790
|
-
const token = match[0];
|
|
1791
|
-
const index = match.index ?? offset;
|
|
1792
|
-
current += value.slice(offset, index);
|
|
1793
|
-
offset = index + token.length;
|
|
1794
|
-
if (token === "\n") {
|
|
1795
|
-
current += "</span>".repeat(openTags.length);
|
|
1796
|
-
lines.push(current);
|
|
1797
|
-
current = openTags.join("");
|
|
1798
|
-
}
|
|
1799
|
-
else if (token === "</span>") {
|
|
1800
|
-
current += token;
|
|
1801
|
-
openTags.pop();
|
|
1802
|
-
}
|
|
1803
|
-
else {
|
|
1804
|
-
current += token;
|
|
1805
|
-
openTags.push(token);
|
|
1806
|
-
}
|
|
1807
|
-
}
|
|
1808
|
-
current += value.slice(offset);
|
|
1809
|
-
current += "</span>".repeat(openTags.length);
|
|
1810
|
-
lines.push(current);
|
|
1811
|
-
return lines;
|
|
1812
|
-
}
|
|
1813
1829
|
function contentTypeFor(extension) {
|
|
1814
1830
|
const known = {
|
|
1815
1831
|
".aac": "audio/aac", ".avi": "video/x-msvideo", ".bmp": "image/bmp", ".css": "text/css; charset=utf-8",
|
|
@@ -1889,7 +1905,7 @@ function writeServerSentEvent(response, event, data) {
|
|
|
1889
1905
|
response.write("\n");
|
|
1890
1906
|
}
|
|
1891
1907
|
function setSecurityHeaders(response) {
|
|
1892
|
-
response.setHeader("Content-Security-Policy", "default-src 'none'; img-src 'self' data:; media-src 'self'; object-src 'self'; frame-src 'self'; script-src 'self'; connect-src 'self'; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'; frame-ancestors 'self'");
|
|
1908
|
+
response.setHeader("Content-Security-Policy", "default-src 'none'; img-src 'self' data:; media-src 'self'; object-src 'self'; frame-src 'self'; script-src 'self'; connect-src 'self'; font-src 'self'; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'; frame-ancestors 'self'");
|
|
1893
1909
|
response.setHeader("Cross-Origin-Resource-Policy", "same-origin");
|
|
1894
1910
|
response.setHeader("Referrer-Policy", "no-referrer");
|
|
1895
1911
|
response.setHeader("X-Content-Type-Options", "nosniff");
|