@andorra-labs/code 0.1.16 → 0.1.17
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/src/acp-agent.d.ts +6 -0
- package/dist/src/acp-agent.js +15 -4
- package/dist/src/agent-execution.js +11 -8
- package/dist/src/agent-mcp-catalog.js +1 -0
- package/dist/src/agent-mcp.d.ts +3 -0
- package/dist/src/agent-mcp.js +33 -1
- package/dist/src/andorra/entry.d.ts +10 -0
- package/dist/src/andorra/entry.js +18 -4
- package/dist/src/andorra/hosted.d.ts +2 -1
- package/dist/src/andorra/hosted.js +2 -1
- package/dist/src/andorra/notices.d.ts +5 -0
- package/dist/src/andorra/notices.js +7 -0
- package/dist/src/andorra/state.d.ts +3 -2
- package/dist/src/andorra/state.js +4 -4
- package/dist/src/andorra/terminal.js +7 -2
- package/dist/src/anthropic-credentials.js +2 -0
- package/dist/src/app-server/error.d.ts +5 -0
- package/dist/src/app-server/error.js +7 -0
- package/dist/src/app-server/protocol.d.ts +19 -44
- package/dist/src/app-server/protocol.js +5 -1
- package/dist/src/app-server/workspace.d.ts +89 -0
- package/dist/src/app-server/workspace.js +457 -11
- package/dist/src/app-server.d.ts +358 -32
- package/dist/src/app-server.js +2429 -509
- package/dist/src/bridge/cloud.d.ts +27 -0
- package/dist/src/bridge/cloud.js +187 -0
- package/dist/src/bridge/command.d.ts +30 -0
- package/dist/src/bridge/command.js +347 -0
- package/dist/src/bridge/control.d.ts +68 -0
- package/dist/src/bridge/control.js +233 -0
- package/dist/src/bridge/engines.d.ts +90 -0
- package/dist/src/bridge/engines.js +601 -0
- package/dist/src/bridge/host-ops.d.ts +9 -0
- package/dist/src/bridge/host-ops.js +129 -0
- package/dist/src/bridge/host.d.ts +47 -0
- package/dist/src/bridge/host.js +540 -0
- package/dist/src/bridge/link.d.ts +38 -0
- package/dist/src/bridge/link.js +508 -0
- package/dist/src/bridge/login-link.d.ts +29 -0
- package/dist/src/bridge/login-link.js +54 -0
- package/dist/src/bridge/protocol.d.ts +136 -0
- package/dist/src/bridge/protocol.js +11 -0
- package/dist/src/bridge/store.d.ts +12 -0
- package/dist/src/bridge/store.js +61 -0
- package/dist/src/bridge/wording.d.ts +6 -0
- package/dist/src/bridge/wording.js +10 -0
- package/dist/src/browser-server.js +7 -1
- package/dist/src/browser-ui/tokens.css +1 -1
- package/dist/src/change-authors.d.ts +41 -0
- package/dist/src/change-authors.js +146 -0
- package/dist/src/cli.js +182 -32
- package/dist/src/coding-tools.js +15 -15
- package/dist/src/command-screens.d.ts +6 -0
- package/dist/src/command-screens.js +14 -11
- package/dist/src/commands.d.ts +14 -2
- package/dist/src/compaction-phrases.js +1 -1
- package/dist/src/completion.js +82 -5
- package/dist/src/config.d.ts +71 -3
- package/dist/src/config.js +202 -77
- package/dist/src/deadline.js +13 -1
- package/dist/src/decision/checks.js +1 -1
- package/dist/src/decision/requestPhrases.js +0 -1
- package/dist/src/default-graph.js +1 -1
- package/dist/src/file-diff.d.ts +4 -0
- package/dist/src/file-diff.js +2 -1
- package/dist/src/github-app/agent-writes.d.ts +102 -0
- package/dist/src/github-app/agent-writes.js +320 -0
- package/dist/src/github-app/client.d.ts +349 -0
- package/dist/src/github-app/client.js +810 -0
- package/dist/src/github-app/event-source.d.ts +208 -0
- package/dist/src/github-app/event-source.js +684 -0
- package/dist/src/github-app/metrics.d.ts +32 -0
- package/dist/src/github-app/metrics.js +49 -0
- package/dist/src/github-app/review-loop.d.ts +274 -0
- package/dist/src/github-app/review-loop.js +1177 -0
- package/dist/src/github-app/review-node.d.ts +81 -0
- package/dist/src/github-app/review-node.js +205 -0
- package/dist/src/github-app/review-post.d.ts +73 -0
- package/dist/src/github-app/review-post.js +139 -0
- package/dist/src/github-app/review-text.d.ts +107 -0
- package/dist/src/github-app/review-text.js +1133 -0
- package/dist/src/github-app/review-threads.d.ts +47 -0
- package/dist/src/github-app/review-threads.js +107 -0
- package/dist/src/github-app/reviewer.d.ts +121 -0
- package/dist/src/github-app/reviewer.js +598 -0
- package/dist/src/github-app/store.d.ts +59 -0
- package/dist/src/github-app/store.js +148 -0
- package/dist/src/github-app/triggers.d.ts +141 -0
- package/dist/src/github-app/triggers.js +441 -0
- package/dist/src/github-names.d.ts +8 -0
- package/dist/src/github-names.js +8 -0
- package/dist/src/glob-search.d.ts +61 -0
- package/dist/src/glob-search.js +180 -0
- package/dist/src/graph-health.js +6 -1
- package/dist/src/graph-manager-chat.js +1 -1
- package/dist/src/graph-preview.d.ts +46 -0
- package/dist/src/graph-preview.js +55 -0
- package/dist/src/graph-provider-portability.js +2 -1
- package/dist/src/graph-runner.js +64 -3
- package/dist/src/graph-server.js +3 -3
- package/dist/src/graph-sync.js +3 -3
- package/dist/src/graph-ui/app.js +91 -7
- package/dist/src/graph-ui/icons.js +2 -1
- package/dist/src/graph-ui/studio.js +15 -1
- package/dist/src/graph-ui/tokens.css +1 -1
- package/dist/src/graphs.d.ts +34 -1
- package/dist/src/graphs.js +158 -14
- package/dist/src/image-input.d.ts +16 -0
- package/dist/src/image-input.js +41 -0
- package/dist/src/membership.d.ts +10 -0
- package/dist/src/membership.js +19 -4
- package/dist/src/model-health-cache.js +1 -1
- package/dist/src/model-metadata.d.ts +6 -0
- package/dist/src/model-metadata.js +35 -15
- package/dist/src/model-relay/local.d.ts +116 -0
- package/dist/src/model-relay/local.js +468 -0
- package/dist/src/model-relay/remote.d.ts +129 -0
- package/dist/src/model-relay/remote.js +252 -0
- package/dist/src/model-relay/runs.d.ts +34 -0
- package/dist/src/model-relay/runs.js +146 -0
- package/dist/src/model-relay/wire.d.ts +5 -0
- package/dist/src/model-relay/wire.js +5 -0
- package/dist/src/project-registry.d.ts +21 -0
- package/dist/src/project-registry.js +74 -0
- package/dist/src/provider-import.d.ts +0 -12
- package/dist/src/provider-import.js +7 -195
- package/dist/src/providers.d.ts +23 -2
- package/dist/src/providers.js +25 -4
- package/dist/src/pull-request-logs.d.ts +12 -1
- package/dist/src/pull-request-logs.js +14 -3
- package/dist/src/pull-requests.d.ts +327 -7
- package/dist/src/pull-requests.js +429 -51
- package/dist/src/react-runtime.js +1 -1
- package/dist/src/remote/engine-pool.d.ts +88 -4
- package/dist/src/remote/engine-pool.js +366 -89
- package/dist/src/remote/roots.d.ts +19 -0
- package/dist/src/remote/roots.js +45 -7
- package/dist/src/remote/types.d.ts +0 -44
- package/dist/src/run-control.d.ts +7 -0
- package/dist/src/run-control.js +23 -0
- package/dist/src/run-records.d.ts +7 -2
- package/dist/src/run-records.js +71 -6
- package/dist/src/runtime.d.ts +5 -1
- package/dist/src/runtime.js +10 -2
- package/dist/src/session-changes.d.ts +35 -0
- package/dist/src/session-changes.js +194 -6
- package/dist/src/session-monitor.js +2 -1
- package/dist/src/session-reaper.d.ts +1 -1
- package/dist/src/session-reaper.js +6 -1
- package/dist/src/session-summary.d.ts +2 -1
- package/dist/src/session-summary.js +2 -1
- package/dist/src/sessions.d.ts +11 -1
- package/dist/src/sessions.js +17 -4
- package/dist/src/skills/bundled/diagram/SKILL.md +5 -3
- package/dist/src/skills/bundled/graph-manager/SKILL.md +7 -4
- package/dist/src/skills/bundled/provenance.json +2 -2
- package/dist/src/skills/runtime-skills.js +1 -1
- package/dist/src/telemetry/emitter.d.ts +15 -0
- package/dist/src/telemetry/emitter.js +35 -1
- package/dist/src/telemetry/schema.d.ts +25 -2
- package/dist/src/telemetry/schema.js +52 -4
- package/dist/src/telemetry/surface.d.ts +2 -1
- package/dist/src/telemetry/surface.js +4 -1
- package/dist/src/terminal-ui.d.ts +1 -0
- package/dist/src/terminal-ui.js +10 -3
- package/dist/src/test-edit-guard.d.ts +7 -0
- package/dist/src/test-edit-guard.js +49 -1
- package/dist/src/timers.d.ts +2 -0
- package/dist/src/tools.js +59 -9
- package/package.json +6 -1
- package/dist/src/remote/cert.d.ts +0 -11
- package/dist/src/remote/cert.js +0 -87
- package/dist/src/remote/client.d.ts +0 -119
- package/dist/src/remote/client.js +0 -544
- package/dist/src/remote/command.d.ts +0 -4
- package/dist/src/remote/command.js +0 -194
- package/dist/src/remote/errors.d.ts +0 -11
- package/dist/src/remote/errors.js +0 -14
- package/dist/src/remote/network.d.ts +0 -22
- package/dist/src/remote/network.js +0 -102
- package/dist/src/remote/pairing.d.ts +0 -63
- package/dist/src/remote/pairing.js +0 -299
- package/dist/src/remote/pem.d.ts +0 -2
- package/dist/src/remote/pem.js +0 -7
- package/dist/src/remote/serve.d.ts +0 -68
- package/dist/src/remote/serve.js +0 -244
- package/dist/src/remote/server.d.ts +0 -21
- package/dist/src/remote/server.js +0 -406
|
@@ -0,0 +1,1133 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The text of an Andorra review (`design/specs/andorra-review-loop.md`): the reviewer's output checked ("The
|
|
3
|
+
* reviewer"), the diff's hunks indexed so that a finding goes inline only where GitHub takes it ("A round",
|
|
4
|
+
* step 2), every text the reviewer wrote sanitised before it reaches the service ("Sanitising what the bot
|
|
5
|
+
* posts", R16), and the review cut to the service's sizes ("Limits"). Pure functions: no I/O.
|
|
6
|
+
*
|
|
7
|
+
* The sanitiser keeps one invariant: whatever it leaves untouched as code, GitHub reads as code too. Where it
|
|
8
|
+
* cannot tell how GitHub will read a line, it reads the line as text and neutralises it; at worst an escape then
|
|
9
|
+
* shows inside a code block. So that GitHub opens no fence, pairs no backtick and makes no link the sanitiser did
|
|
10
|
+
* not, it escapes every unpaired backtick run, every run of three tildes and every bracket it does not keep.
|
|
11
|
+
*/
|
|
12
|
+
/** The service's limit on a review's summary (its `BODY_BYTES`). */
|
|
13
|
+
export const REVIEW_SUMMARY_BYTES = 16_384;
|
|
14
|
+
/** The service's limit on one inline comment. */
|
|
15
|
+
export const REVIEW_COMMENT_BYTES = 4_096;
|
|
16
|
+
/** The most inline comments the service takes in one review. */
|
|
17
|
+
export const REVIEW_COMMENTS = 30;
|
|
18
|
+
/** The most findings the reviewer is asked for. */
|
|
19
|
+
export const REVIEWER_FINDINGS = 20;
|
|
20
|
+
/** The service's limit on a whole write request (`WRITE_REQUEST_BYTES`). */
|
|
21
|
+
export const REVIEW_REQUEST_BYTES = 163_840;
|
|
22
|
+
/** Room left in a request for its other fields: request id, owner, repo, number, commit, loop, rounds. */
|
|
23
|
+
const OTHER_FIELDS_BYTES = 4_096;
|
|
24
|
+
/** The most findings kept from one reviewer output, however many it wrote. */
|
|
25
|
+
const PARSED_FINDINGS = 50;
|
|
26
|
+
const PATH_BYTES = 1_024;
|
|
27
|
+
const LINE_CEILING = 10_000_000;
|
|
28
|
+
/** How much of a finding's body the summary shows. */
|
|
29
|
+
const ITEM_BODY_CHARS = 600;
|
|
30
|
+
const TITLE_CHARS = 200;
|
|
31
|
+
const PATH_CHARS = 300;
|
|
32
|
+
/** The reviewer's own summary is cut to this, so that the findings always have room in the review's summary. */
|
|
33
|
+
const REVIEWER_SUMMARY_BYTES = 8_192;
|
|
34
|
+
/** No more than this much of any one text is ever sanitised. */
|
|
35
|
+
const RAW_CHARS = 32_768;
|
|
36
|
+
/** A link longer than these is not taken for a link: its brackets are escaped, so GitHub does not take it either. */
|
|
37
|
+
const LINK_TEXT_CHARS = 500;
|
|
38
|
+
const DEST_CHARS = 1_000;
|
|
39
|
+
const WORD_JOINER = '\u2060';
|
|
40
|
+
const ELLIPSIS = '\u2026';
|
|
41
|
+
/** Lone surrogates as U+FFFD: the service encodes every text as UTF-8 and refuses one it cannot. */
|
|
42
|
+
const wellFormed = (text) => text.replace(/[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/g, '\ufffd');
|
|
43
|
+
/** Blank as Python's `str.strip()` sees it, which also strips U+001C to U+001F and U+0085. */
|
|
44
|
+
const isBlankText = (text) => /^[\s\x1c-\x1f\x85]*$/.test(text);
|
|
45
|
+
// ---- the reviewer's output -------------------------------------------------------------------------------------
|
|
46
|
+
/** Validates the reviewer's structured output ({summary, findings[]}); drops malformed findings; keeps at most 50. Undefined when the value is not an object with a string summary and a findings array. */
|
|
47
|
+
export function parseReviewerOutput(value) {
|
|
48
|
+
return readReviewerOutput(value)?.output;
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* The same, with how many findings it dropped as malformed (those past the 50 kept are not counted). The loop reads a
|
|
52
|
+
* dropped finding as a failed reviewer run: a P1 without a line must not turn into "No findings".
|
|
53
|
+
*/
|
|
54
|
+
export function readReviewerOutput(value) {
|
|
55
|
+
const output = typeof value === 'string' ? jsonText(value) : value;
|
|
56
|
+
if (!isRecord(output) || typeof output.summary !== 'string' || !Array.isArray(output.findings))
|
|
57
|
+
return undefined;
|
|
58
|
+
const findings = [];
|
|
59
|
+
let dropped = 0;
|
|
60
|
+
for (const item of output.findings) {
|
|
61
|
+
if (findings.length === PARSED_FINDINGS)
|
|
62
|
+
break;
|
|
63
|
+
const finding = parseFinding(item);
|
|
64
|
+
if (finding)
|
|
65
|
+
findings.push(finding);
|
|
66
|
+
else
|
|
67
|
+
dropped++;
|
|
68
|
+
}
|
|
69
|
+
return { output: { summary: output.summary, findings }, dropped };
|
|
70
|
+
}
|
|
71
|
+
/** A result that arrives as JSON text, bare or in one ```json fence. */
|
|
72
|
+
function jsonText(text) {
|
|
73
|
+
const fenced = /^\s*```(?:json)?[ \t]*\r?\n([\s\S]*?)\r?\n[ \t]*```\s*$/i.exec(text);
|
|
74
|
+
try {
|
|
75
|
+
return JSON.parse(fenced ? fenced[1] : text);
|
|
76
|
+
}
|
|
77
|
+
catch {
|
|
78
|
+
return undefined;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
function isRecord(value) {
|
|
82
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
83
|
+
}
|
|
84
|
+
function lineNumber(value) {
|
|
85
|
+
const number = typeof value === 'string' && /^\s*\d{1,8}\s*$/.test(value) ? Number(value) : value;
|
|
86
|
+
return typeof number === 'number' && Number.isInteger(number) && number > 0 && number < LINE_CEILING ? number : undefined;
|
|
87
|
+
}
|
|
88
|
+
function parseFinding(item) {
|
|
89
|
+
if (!isRecord(item))
|
|
90
|
+
return undefined;
|
|
91
|
+
const priority = typeof item.priority === 'string' ? item.priority.trim().toUpperCase() : '';
|
|
92
|
+
if (priority !== 'P1' && priority !== 'P2' && priority !== 'P3')
|
|
93
|
+
return undefined;
|
|
94
|
+
if (typeof item.title !== 'string' || item.title.trim() === '')
|
|
95
|
+
return undefined;
|
|
96
|
+
if (typeof item.path !== 'string')
|
|
97
|
+
return undefined;
|
|
98
|
+
const path = item.path.trim().replace(/^(?:\.\/)+/, '');
|
|
99
|
+
if (path === '')
|
|
100
|
+
return undefined;
|
|
101
|
+
const line = lineNumber(item.line);
|
|
102
|
+
if (line === undefined || typeof item.body !== 'string')
|
|
103
|
+
return undefined;
|
|
104
|
+
const finding = { priority, title: item.title.trim(), path, line, body: item.body };
|
|
105
|
+
if (item.startLine !== undefined && item.startLine !== null) {
|
|
106
|
+
const startLine = lineNumber(item.startLine);
|
|
107
|
+
if (startLine === undefined)
|
|
108
|
+
return undefined;
|
|
109
|
+
// A range that starts on or after its own line is one line: models write startLine = line often.
|
|
110
|
+
if (startLine < line)
|
|
111
|
+
finding.startLine = startLine;
|
|
112
|
+
}
|
|
113
|
+
if (item.side !== undefined && item.side !== null) {
|
|
114
|
+
const side = typeof item.side === 'string' ? item.side.trim().toUpperCase() : '';
|
|
115
|
+
if (side !== 'LEFT' && side !== 'RIGHT')
|
|
116
|
+
return undefined;
|
|
117
|
+
finding.side = side;
|
|
118
|
+
}
|
|
119
|
+
return finding;
|
|
120
|
+
}
|
|
121
|
+
// ---- the marker ------------------------------------------------------------------------------------------------
|
|
122
|
+
/**
|
|
123
|
+
* The marker's opening as the service finds it (`MARKER` in `github_app.py`, `<!--\s*andorra-review` in any
|
|
124
|
+
* case): Python's `\s` also takes U+001C to U+001F and U+0085, and its IGNORECASE takes U+0130 and U+0131 for `i`.
|
|
125
|
+
*/
|
|
126
|
+
const MARKER_OPENING = /<(?=!--[\s\x1c-\x1f\x85]*andorra-rev[i\u0130\u0131]ew)/gi;
|
|
127
|
+
/** The marker's opening `<!-- andorra-review` (any case, any whitespace after `<!--`) broken everywhere, code included, with U+2060 WORD JOINER after the `<`. */
|
|
128
|
+
export function breakMarker(text) {
|
|
129
|
+
return text.replace(MARKER_OPENING, `<${WORD_JOINER}`);
|
|
130
|
+
}
|
|
131
|
+
const isBlank = (line) => /^[ \t]*\r?$/.test(line);
|
|
132
|
+
/** Columns of leading whitespace, tabs to the next multiple of 4. */
|
|
133
|
+
function indentOf(line) {
|
|
134
|
+
let width = 0;
|
|
135
|
+
for (const ch of line) {
|
|
136
|
+
if (ch === ' ')
|
|
137
|
+
width++;
|
|
138
|
+
else if (ch === '\t')
|
|
139
|
+
width += 4 - (width % 4);
|
|
140
|
+
else
|
|
141
|
+
break;
|
|
142
|
+
}
|
|
143
|
+
return width;
|
|
144
|
+
}
|
|
145
|
+
function fenceOpening(line) {
|
|
146
|
+
const match = /^( {0,3})(`{3,}|~{3,})([^\r\n]*)\r?$/.exec(line);
|
|
147
|
+
if (!match || (match[2][0] === '`' && match[3].includes('`')))
|
|
148
|
+
return undefined;
|
|
149
|
+
return { indent: match[1].length, char: match[2][0], length: match[2].length };
|
|
150
|
+
}
|
|
151
|
+
function fenceCloses(line, fence) {
|
|
152
|
+
const match = /^[ \t]*(`+|~+)[ \t]*\r?$/.exec(line);
|
|
153
|
+
return match !== null && match[1][0] === fence.char && match[1].length >= fence.length;
|
|
154
|
+
}
|
|
155
|
+
/** Block quote and list markers at a line's start, with the whitespace around them. */
|
|
156
|
+
const CONTAINERS = /^(?:[ \t]*(?:>|[-+*](?=[ \t])|\d{1,9}[.)](?=[ \t])))*[ \t]*/;
|
|
157
|
+
const afterContainers = (line) => line.slice(CONTAINERS.exec(line)[0].length);
|
|
158
|
+
/**
|
|
159
|
+
* The fenced code blocks GitHub surely sees, and the text between them.
|
|
160
|
+
*
|
|
161
|
+
* - A fence opened at the margin is GitHub's top-level fence: it ends at a closing fence indented at most 3
|
|
162
|
+
* columns, or at the end.
|
|
163
|
+
* - A fence opened 1 to 3 columns in may belong to a list item, which GitHub closes, with its fence, at the first
|
|
164
|
+
* line indented less than the item. Its lines are code while they are indented at least as far as the opening,
|
|
165
|
+
* and a closing fence counts only when it is indented 3 columns at most. A line indented less, or a closing
|
|
166
|
+
* fence indented further, could be read either way: from there on everything is text.
|
|
167
|
+
* - `strict` (for text that is not neutralised) also takes everything from the first fence or HTML block GitHub
|
|
168
|
+
* might see, and the sanitiser does not, as text.
|
|
169
|
+
*/
|
|
170
|
+
function splitFences(lines, strict) {
|
|
171
|
+
const regions = [];
|
|
172
|
+
let text = [];
|
|
173
|
+
const flush = () => {
|
|
174
|
+
if (text.length)
|
|
175
|
+
regions.push({ code: false, lines: text });
|
|
176
|
+
text = [];
|
|
177
|
+
};
|
|
178
|
+
let i = 0;
|
|
179
|
+
while (i < lines.length) {
|
|
180
|
+
const fence = fenceOpening(lines[i]);
|
|
181
|
+
if (!fence) {
|
|
182
|
+
if (strict && /^(?:`{3,}|~{3,}|<)/.test(afterContainers(lines[i]))) {
|
|
183
|
+
text.push(...lines.slice(i));
|
|
184
|
+
break;
|
|
185
|
+
}
|
|
186
|
+
text.push(lines[i++]);
|
|
187
|
+
continue;
|
|
188
|
+
}
|
|
189
|
+
const block = [lines[i]];
|
|
190
|
+
let j = i + 1;
|
|
191
|
+
let closed = false;
|
|
192
|
+
let unsure = false;
|
|
193
|
+
for (; j < lines.length; j++) {
|
|
194
|
+
const line = lines[j];
|
|
195
|
+
if (isBlank(line)) {
|
|
196
|
+
block.push(line);
|
|
197
|
+
continue;
|
|
198
|
+
}
|
|
199
|
+
const width = indentOf(line);
|
|
200
|
+
if (width < fence.indent) {
|
|
201
|
+
unsure = true;
|
|
202
|
+
break;
|
|
203
|
+
}
|
|
204
|
+
if (fenceCloses(line, fence)) {
|
|
205
|
+
if (width <= 3) {
|
|
206
|
+
block.push(line);
|
|
207
|
+
closed = true;
|
|
208
|
+
j++;
|
|
209
|
+
break;
|
|
210
|
+
}
|
|
211
|
+
if (fence.indent > 0) {
|
|
212
|
+
unsure = true;
|
|
213
|
+
break;
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
block.push(line);
|
|
217
|
+
}
|
|
218
|
+
if (unsure) {
|
|
219
|
+
text.push(...lines.slice(i));
|
|
220
|
+
break;
|
|
221
|
+
}
|
|
222
|
+
flush();
|
|
223
|
+
regions.push(closed ? { code: true, lines: block } : { code: true, lines: block, close: ' '.repeat(fence.indent) + fence.char.repeat(fence.length) });
|
|
224
|
+
i = j;
|
|
225
|
+
}
|
|
226
|
+
flush();
|
|
227
|
+
return regions;
|
|
228
|
+
}
|
|
229
|
+
/** A table's delimiter row (`|---|:--:|`), after any block quote or list markers. */
|
|
230
|
+
const DELIMITER_ROW = /^\|?[ \t]*:?-+:?[ \t]*(?:\|[ \t]*:?-+:?[ \t]*)*\|?[ \t]*\r?$/;
|
|
231
|
+
/**
|
|
232
|
+
* The lines GitHub may read as table rows, where a `|` splits cells before code spans are found: in each
|
|
233
|
+
* paragraph, the line before the first delimiter row and every line after it.
|
|
234
|
+
*/
|
|
235
|
+
function tableLines(lines) {
|
|
236
|
+
const marks = lines.map(() => false);
|
|
237
|
+
let start = 0;
|
|
238
|
+
for (let k = 0; k <= lines.length; k++) {
|
|
239
|
+
if (k < lines.length && !isBlank(lines[k]))
|
|
240
|
+
continue;
|
|
241
|
+
for (let row = start; row < k; row++) {
|
|
242
|
+
if (DELIMITER_ROW.test(afterContainers(lines[row]))) {
|
|
243
|
+
for (let m = Math.max(start, row - 1); m < k; m++)
|
|
244
|
+
marks[m] = true;
|
|
245
|
+
break;
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
start = k + 1;
|
|
249
|
+
}
|
|
250
|
+
return marks;
|
|
251
|
+
}
|
|
252
|
+
// ---- inlines -------------------------------------------------------------------------------------------------
|
|
253
|
+
const PUNCTUATION = /^[\x21-\x2f\x3a-\x40\x5b-\x60\x7b-\x7e]$/;
|
|
254
|
+
const isPunctuation = (ch) => ch !== undefined && PUNCTUATION.test(ch);
|
|
255
|
+
const isAlphanumeric = (ch) => ch !== undefined && /^[A-Za-z0-9]$/.test(ch);
|
|
256
|
+
function backtickRun(line, p) {
|
|
257
|
+
let q = p;
|
|
258
|
+
while (line[q] === '`')
|
|
259
|
+
q++;
|
|
260
|
+
return q - p;
|
|
261
|
+
}
|
|
262
|
+
/** Where a code span opened by a run of `length` backticks closes on this line, or -1. */
|
|
263
|
+
function spanCloser(line, from, length) {
|
|
264
|
+
for (let q = line.indexOf('`', from); q >= 0; q = line.indexOf('`', q)) {
|
|
265
|
+
const run = backtickRun(line, q);
|
|
266
|
+
if (run === length)
|
|
267
|
+
return q;
|
|
268
|
+
q += run;
|
|
269
|
+
}
|
|
270
|
+
return -1;
|
|
271
|
+
}
|
|
272
|
+
/** `content` as one inline code span: a fence longer than any backtick run in it, padded where it starts or ends with one. */
|
|
273
|
+
function codeSpan(content, table = false) {
|
|
274
|
+
let text = content.replace(/[\r\n]+/g, ' ');
|
|
275
|
+
// In a table row GitHub splits cells at every `|` before it finds code spans.
|
|
276
|
+
if (table)
|
|
277
|
+
text = text.replace(/\|/g, '%7C');
|
|
278
|
+
let longest = 0;
|
|
279
|
+
for (const run of text.match(/`+/g) ?? [])
|
|
280
|
+
longest = Math.max(longest, run.length);
|
|
281
|
+
const fence = '`'.repeat(longest + 1);
|
|
282
|
+
const pad = text.startsWith('`') || text.endsWith('`') || (text.length > 1 && text.startsWith(' ') && text.endsWith(' ') && text.trim() !== '') ? ' ' : '';
|
|
283
|
+
return `${fence}${pad}${text}${pad}${fence}`;
|
|
284
|
+
}
|
|
285
|
+
/**
|
|
286
|
+
* A line's output, part by part. Where two parts would run together into other Markdown, a word joiner goes
|
|
287
|
+
* between them: two backtick runs that would merge, a `!` that would make an image of a link, a backslash that
|
|
288
|
+
* would escape the next part's first character, and a `$` touching a code span (GitHub's inline math is
|
|
289
|
+
* `` $`\u2026`$ ``, and renders its content as text, where a mention or reference is live).
|
|
290
|
+
*/
|
|
291
|
+
class Output {
|
|
292
|
+
parts = [];
|
|
293
|
+
last = '';
|
|
294
|
+
oddBackslashes = false;
|
|
295
|
+
get lastChar() {
|
|
296
|
+
return this.last;
|
|
297
|
+
}
|
|
298
|
+
push(part) {
|
|
299
|
+
if (!part)
|
|
300
|
+
return;
|
|
301
|
+
const first = part[0];
|
|
302
|
+
if ((this.last === '`' && (first === '`' || first === '$')) || (this.last === '$' && first === '`') || (this.last === '!' && first === '[')
|
|
303
|
+
|| (this.oddBackslashes && isPunctuation(first)))
|
|
304
|
+
this.add(WORD_JOINER);
|
|
305
|
+
this.add(part);
|
|
306
|
+
}
|
|
307
|
+
add(part) {
|
|
308
|
+
this.parts.push(part);
|
|
309
|
+
let k = part.length;
|
|
310
|
+
while (k > 0 && part[k - 1] === '\\')
|
|
311
|
+
k--;
|
|
312
|
+
const odd = (part.length - k) % 2 === 1;
|
|
313
|
+
this.oddBackslashes = k === 0 ? this.oddBackslashes !== odd : odd;
|
|
314
|
+
this.last = part[part.length - 1];
|
|
315
|
+
}
|
|
316
|
+
toString() {
|
|
317
|
+
return this.parts.join('');
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
/** Letters GitHub's case-insensitive matching also takes for an ASCII letter: K for k, long s for s, dotted and dotless i. */
|
|
321
|
+
const FOLDS = { k: 'kK\\u212a', s: 'sS\\u017f', i: 'iI\\u0130\\u0131' };
|
|
322
|
+
function contextFor(repo, labels = new Set()) {
|
|
323
|
+
const owner = Array.from(repo.owner).map(ch => {
|
|
324
|
+
const lower = ch.toLowerCase();
|
|
325
|
+
if (FOLDS[lower])
|
|
326
|
+
return `[${FOLDS[lower]}]`;
|
|
327
|
+
return /^[a-z]$/.test(lower) ? `[${lower}${lower.toUpperCase()}]` : ch.replace(/[\\^$.*+?()[\]{}|\/-]/g, '\\$&');
|
|
328
|
+
}).join('');
|
|
329
|
+
return { repo, labels, table: false, link: false, ...(owner ? { ownerReference: new RegExp(`${owner}(?:#\\d+|[gG][hH]-\\d+)`, 'y') } : {}) };
|
|
330
|
+
}
|
|
331
|
+
/** Link or image text left as plain text, with a word joiner on each side, so that nothing outside joins it into a mention or reference. */
|
|
332
|
+
const dissolved = (text) => (text ? `${WORD_JOINER}${text}${WORD_JOINER}` : WORD_JOINER);
|
|
333
|
+
/** The index of the `]` that closes the bracket at `p`, skipping escapes and code spans, or -1. */
|
|
334
|
+
function bracketEnd(line, p) {
|
|
335
|
+
let depth = 0;
|
|
336
|
+
const limit = Math.min(line.length, p + LINK_TEXT_CHARS);
|
|
337
|
+
for (let q = p; q < limit;) {
|
|
338
|
+
const ch = line[q];
|
|
339
|
+
if (ch === '\\' && isPunctuation(line[q + 1])) {
|
|
340
|
+
q += 2;
|
|
341
|
+
continue;
|
|
342
|
+
}
|
|
343
|
+
if (ch === '`') {
|
|
344
|
+
const length = backtickRun(line, q);
|
|
345
|
+
const close = spanCloser(line, q + length, length);
|
|
346
|
+
q = close >= 0 ? close + length : q + length;
|
|
347
|
+
continue;
|
|
348
|
+
}
|
|
349
|
+
if (ch === '[')
|
|
350
|
+
depth++;
|
|
351
|
+
else if (ch === ']' && --depth === 0)
|
|
352
|
+
return q;
|
|
353
|
+
q++;
|
|
354
|
+
}
|
|
355
|
+
return -1;
|
|
356
|
+
}
|
|
357
|
+
/** An inline link's `(destination "title")` starting at `q`, as CommonMark reads it on one line. */
|
|
358
|
+
function linkTail(line, q) {
|
|
359
|
+
if (line[q] !== '(')
|
|
360
|
+
return undefined;
|
|
361
|
+
let i = q + 1;
|
|
362
|
+
while (line[i] === ' ' || line[i] === '\t')
|
|
363
|
+
i++;
|
|
364
|
+
let dest;
|
|
365
|
+
if (line[i] === '<') {
|
|
366
|
+
let j = i + 1;
|
|
367
|
+
for (; j < line.length && j - i < DEST_CHARS; j++) {
|
|
368
|
+
if (line[j] === '\\' && isPunctuation(line[j + 1]))
|
|
369
|
+
j++;
|
|
370
|
+
else if (line[j] === '<')
|
|
371
|
+
return undefined;
|
|
372
|
+
else if (line[j] === '>')
|
|
373
|
+
break;
|
|
374
|
+
}
|
|
375
|
+
if (line[j] !== '>')
|
|
376
|
+
return undefined;
|
|
377
|
+
dest = line.slice(i, j + 1);
|
|
378
|
+
i = j + 1;
|
|
379
|
+
}
|
|
380
|
+
else {
|
|
381
|
+
let j = i;
|
|
382
|
+
let depth = 0;
|
|
383
|
+
for (; j < line.length; j++) {
|
|
384
|
+
if (j - i >= DEST_CHARS)
|
|
385
|
+
return undefined;
|
|
386
|
+
const ch = line[j];
|
|
387
|
+
if (ch === '\\' && isPunctuation(line[j + 1])) {
|
|
388
|
+
j++;
|
|
389
|
+
continue;
|
|
390
|
+
}
|
|
391
|
+
if (ch <= ' ' || ch === '\x7f')
|
|
392
|
+
break;
|
|
393
|
+
if (ch === '(')
|
|
394
|
+
depth++;
|
|
395
|
+
else if (ch === ')') {
|
|
396
|
+
if (depth === 0)
|
|
397
|
+
break;
|
|
398
|
+
depth--;
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
if (depth !== 0)
|
|
402
|
+
return undefined;
|
|
403
|
+
dest = line.slice(i, j);
|
|
404
|
+
i = j;
|
|
405
|
+
}
|
|
406
|
+
const afterDest = i;
|
|
407
|
+
while (line[i] === ' ' || line[i] === '\t')
|
|
408
|
+
i++;
|
|
409
|
+
if (i > afterDest && (line[i] === '"' || line[i] === "'" || line[i] === '(')) {
|
|
410
|
+
const open = line[i];
|
|
411
|
+
const close = open === '(' ? ')' : open;
|
|
412
|
+
let j = i + 1;
|
|
413
|
+
for (; j < line.length && j - i < DEST_CHARS; j++) {
|
|
414
|
+
if (line[j] === '\\' && isPunctuation(line[j + 1]))
|
|
415
|
+
j++;
|
|
416
|
+
else if (open === '(' && line[j] === '(')
|
|
417
|
+
return undefined;
|
|
418
|
+
else if (line[j] === close)
|
|
419
|
+
break;
|
|
420
|
+
}
|
|
421
|
+
if (j >= line.length || line[j] !== close)
|
|
422
|
+
return undefined;
|
|
423
|
+
i = j + 1;
|
|
424
|
+
while (line[i] === ' ' || line[i] === '\t')
|
|
425
|
+
i++;
|
|
426
|
+
}
|
|
427
|
+
if (line[i] !== ')')
|
|
428
|
+
return undefined;
|
|
429
|
+
return { dest, end: i + 1 };
|
|
430
|
+
}
|
|
431
|
+
/** Whether `url` is this repository on GitHub: `https://github.com/<owner>/<repo>` or below it, in plain characters only. */
|
|
432
|
+
function repoUrl(url, repo) {
|
|
433
|
+
const prefix = `https://github.com/${repo.owner}/${repo.repo}`;
|
|
434
|
+
if (url.length < prefix.length || url.slice(0, prefix.length).toLowerCase() !== prefix.toLowerCase())
|
|
435
|
+
return false;
|
|
436
|
+
const path = url.slice(prefix.length);
|
|
437
|
+
if (path !== '' && !path.startsWith('/'))
|
|
438
|
+
return false;
|
|
439
|
+
// No encoded dot, slash or backslash, and no `..` segment: nothing that could leave the repository.
|
|
440
|
+
return /^[A-Za-z0-9\-._~!$'+,;=:@%/?#]*$/.test(path) && !/%2e|%2f|%5c/i.test(path) && !/(?:^|\/)\.\.(?:[/?#]|$)/.test(path);
|
|
441
|
+
}
|
|
442
|
+
const normalizeLabel = (label) => label.trim().replace(/\s+/g, ' ').toLowerCase();
|
|
443
|
+
function linkAt(line, p, ctx) {
|
|
444
|
+
const close = bracketEnd(line, p);
|
|
445
|
+
if (close < 0)
|
|
446
|
+
return undefined;
|
|
447
|
+
const tail = linkTail(line, close + 1);
|
|
448
|
+
if (!tail)
|
|
449
|
+
return undefined;
|
|
450
|
+
const label = sanitizeInline(line.slice(p + 1, close), { ...ctx, link: true });
|
|
451
|
+
const url = tail.dest.startsWith('<') ? tail.dest.slice(1, -1) : tail.dest;
|
|
452
|
+
if (!ctx.link && repoUrl(url, ctx.repo))
|
|
453
|
+
return { text: `[${isBlankText(label) ? url : label}](${url})`, end: tail.end };
|
|
454
|
+
if (!url)
|
|
455
|
+
return { text: dissolved(label), end: tail.end };
|
|
456
|
+
return { text: dissolved(`${label}${label && !/\s$/.test(label) ? ' ' : ''}(${codeSpan(url, ctx.table)})`), end: tail.end };
|
|
457
|
+
}
|
|
458
|
+
function imageAt(line, p, ctx) {
|
|
459
|
+
const close = bracketEnd(line, p + 1);
|
|
460
|
+
if (close < 0)
|
|
461
|
+
return undefined;
|
|
462
|
+
const alt = () => dissolved(sanitizeInline(line.slice(p + 2, close), { ...ctx, link: true }));
|
|
463
|
+
const tail = linkTail(line, close + 1);
|
|
464
|
+
if (tail)
|
|
465
|
+
return { text: alt(), end: tail.end };
|
|
466
|
+
if (line[close + 1] === '[') {
|
|
467
|
+
const label = bracketEnd(line, close + 1);
|
|
468
|
+
if (label >= 0)
|
|
469
|
+
return { text: alt(), end: label + 1 };
|
|
470
|
+
}
|
|
471
|
+
if (ctx.labels.has(normalizeLabel(line.slice(p + 2, close))))
|
|
472
|
+
return { text: alt(), end: close + 1 };
|
|
473
|
+
return undefined;
|
|
474
|
+
}
|
|
475
|
+
/**
|
|
476
|
+
* One line of text, sanitised. Code spans pair on the line, as GitHub pairs them once every unpaired backtick
|
|
477
|
+
* is escaped (in a table row, a span holding a `|` is not one). Images become their alt text; links survive
|
|
478
|
+
* only to this repository; every other bracket is escaped, so GitHub finds no link, image or reference the
|
|
479
|
+
* sanitiser did not.
|
|
480
|
+
*/
|
|
481
|
+
function sanitizeInline(line, ctx) {
|
|
482
|
+
const out = new Output();
|
|
483
|
+
let plain = '';
|
|
484
|
+
const flush = () => {
|
|
485
|
+
if (plain)
|
|
486
|
+
neutralize(plain, ctx, out);
|
|
487
|
+
plain = '';
|
|
488
|
+
};
|
|
489
|
+
let p = 0;
|
|
490
|
+
while (p < line.length) {
|
|
491
|
+
const ch = line[p];
|
|
492
|
+
if (ch === '\\' && isPunctuation(line[p + 1])) {
|
|
493
|
+
plain += line.slice(p, p + 2);
|
|
494
|
+
p += 2;
|
|
495
|
+
}
|
|
496
|
+
else if (ch === '`') {
|
|
497
|
+
const length = backtickRun(line, p);
|
|
498
|
+
const close = spanCloser(line, p + length, length);
|
|
499
|
+
if (close >= 0 && !(ctx.table && line.slice(p + length, close).includes('|'))) {
|
|
500
|
+
flush();
|
|
501
|
+
out.push(line.slice(p, close + length));
|
|
502
|
+
p = close + length;
|
|
503
|
+
}
|
|
504
|
+
else {
|
|
505
|
+
plain += '\\`'.repeat(length);
|
|
506
|
+
p += length;
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
else if (ch === '!' && line[p + 1] === '[') {
|
|
510
|
+
const image = imageAt(line, p, ctx);
|
|
511
|
+
if (image) {
|
|
512
|
+
flush();
|
|
513
|
+
out.push(image.text);
|
|
514
|
+
p = image.end;
|
|
515
|
+
}
|
|
516
|
+
else {
|
|
517
|
+
plain += '!';
|
|
518
|
+
p++;
|
|
519
|
+
}
|
|
520
|
+
}
|
|
521
|
+
else if (ch === '[') {
|
|
522
|
+
const link = linkAt(line, p, ctx);
|
|
523
|
+
if (link) {
|
|
524
|
+
flush();
|
|
525
|
+
out.push(link.text);
|
|
526
|
+
p = link.end;
|
|
527
|
+
}
|
|
528
|
+
else {
|
|
529
|
+
plain += '\\[';
|
|
530
|
+
p++;
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
else if (ch === ']') {
|
|
534
|
+
plain += '\\]';
|
|
535
|
+
p++;
|
|
536
|
+
}
|
|
537
|
+
else {
|
|
538
|
+
plain += ch;
|
|
539
|
+
p++;
|
|
540
|
+
}
|
|
541
|
+
}
|
|
542
|
+
flush();
|
|
543
|
+
return out.toString();
|
|
544
|
+
}
|
|
545
|
+
const URL_START = /(?:https?:\/\/|ftp:\/\/|www\.)/iy;
|
|
546
|
+
/** `owner/repo#N`, with the letters GitHub's case-insensitive match also takes (K, long s, dotted and dotless i). */
|
|
547
|
+
const CROSS_REFERENCE = /[A-Za-z0-9_.\u212a\u017f\u0130\u0131-]{1,100}\/[A-Za-z0-9_.\u212a\u017f\u0130\u0131-]{1,100}#\d+/y;
|
|
548
|
+
const REFERENCE_START = /[A-Za-z0-9_.\u212a\u017f\u0130\u0131-]/;
|
|
549
|
+
const GH_REFERENCE = /gh-\d+/iy;
|
|
550
|
+
const DIGITS = /\d+/y;
|
|
551
|
+
const ENTITY = /&(?:#\d{1,7}|#[xX][0-9a-fA-F]{1,6}|[A-Za-z][A-Za-z0-9]{0,31});/y;
|
|
552
|
+
function matchAt(pattern, text, index) {
|
|
553
|
+
pattern.lastIndex = index;
|
|
554
|
+
return pattern.exec(text);
|
|
555
|
+
}
|
|
556
|
+
/**
|
|
557
|
+
* Where a bare URL whose scheme (or `www.`) ends at `from` ends: at a space, `<`, `>`, `|`, a backtick, a backslash
|
|
558
|
+
* or `"`, less trailing punctuation and unbalanced closing parentheses. Linear: the parentheses are counted once.
|
|
559
|
+
*/
|
|
560
|
+
function urlEnd(text, from) {
|
|
561
|
+
let end = from;
|
|
562
|
+
let opens = 0;
|
|
563
|
+
let closes = 0;
|
|
564
|
+
for (; end < text.length && !/[\s<>`|\\"]/.test(text[end]); end++) {
|
|
565
|
+
if (text[end] === '(')
|
|
566
|
+
opens++;
|
|
567
|
+
else if (text[end] === ')')
|
|
568
|
+
closes++;
|
|
569
|
+
}
|
|
570
|
+
while (end > from) {
|
|
571
|
+
const last = text[end - 1];
|
|
572
|
+
if (/[?!.,:;*_~']/.test(last))
|
|
573
|
+
end--;
|
|
574
|
+
else if (last === ')' && closes > opens) {
|
|
575
|
+
closes--;
|
|
576
|
+
end--;
|
|
577
|
+
}
|
|
578
|
+
else
|
|
579
|
+
break;
|
|
580
|
+
}
|
|
581
|
+
return end;
|
|
582
|
+
}
|
|
583
|
+
/**
|
|
584
|
+
* Plain text (outside code, links and images) neutralised: `<` to `<`, character references shown as written
|
|
585
|
+
* (`@` would otherwise become an `@` that mentions), runs of three tildes escaped (no fence), every bare URL
|
|
586
|
+
* wrapped in code, cross-references wrapped in code, and a word joiner after every `@` that could start a mention.
|
|
587
|
+
*
|
|
588
|
+
* - A bare URL goes in code even to this repository: GitHub's autolink runs on to the next space or raw `<`, so it
|
|
589
|
+
* would swallow a code span, `\<` or `<` after it and leave what they held live. Links written as
|
|
590
|
+
* `[text](url)` to this repository stay links.
|
|
591
|
+
* - A mention or reference counts after any character but an ASCII letter or digit: after `_` or a backtick too,
|
|
592
|
+
* since GitHub reads the rendered text, where emphasis and escapes are gone. The joiner follows such an `@`
|
|
593
|
+
* whatever comes next, since GitHub's case-insensitive match takes non-ASCII letters too (K for `k`).
|
|
594
|
+
*/
|
|
595
|
+
function neutralize(text, ctx, out) {
|
|
596
|
+
let run = '';
|
|
597
|
+
const before = () => (run ? run[run.length - 1] : out.lastChar);
|
|
598
|
+
const emit = (part) => {
|
|
599
|
+
if (run)
|
|
600
|
+
out.push(run);
|
|
601
|
+
run = '';
|
|
602
|
+
out.push(part);
|
|
603
|
+
};
|
|
604
|
+
let i = 0;
|
|
605
|
+
while (i < text.length) {
|
|
606
|
+
const ch = text[i];
|
|
607
|
+
const boundary = !isAlphanumeric(before());
|
|
608
|
+
if (ch === '\\' && isPunctuation(text[i + 1])) {
|
|
609
|
+
const next = text[i + 1];
|
|
610
|
+
// `\#123` shows `#123`, which references: the code span keeps the `#` literal without the backslash.
|
|
611
|
+
const digits = next === '#' && boundary ? matchAt(DIGITS, text, i + 2) : null;
|
|
612
|
+
if (digits) {
|
|
613
|
+
emit(codeSpan(`#${digits[0]}`, ctx.table));
|
|
614
|
+
i += 2 + digits[0].length;
|
|
615
|
+
continue;
|
|
616
|
+
}
|
|
617
|
+
run += ch + next;
|
|
618
|
+
i += 2;
|
|
619
|
+
if (next === '@')
|
|
620
|
+
run += WORD_JOINER;
|
|
621
|
+
continue;
|
|
622
|
+
}
|
|
623
|
+
if (ch === '<') {
|
|
624
|
+
run += '<';
|
|
625
|
+
i++;
|
|
626
|
+
continue;
|
|
627
|
+
}
|
|
628
|
+
if (ch === '&') {
|
|
629
|
+
// A character reference shows as written. A numeric one goes in code whole, so its `#` is no reference.
|
|
630
|
+
const entity = matchAt(ENTITY, text, i);
|
|
631
|
+
if (entity && entity[0][1] === '#')
|
|
632
|
+
emit(codeSpan(entity[0], ctx.table));
|
|
633
|
+
else
|
|
634
|
+
run += entity ? `&${entity[0].slice(1)}` : '&';
|
|
635
|
+
i += entity ? entity[0].length : 1;
|
|
636
|
+
continue;
|
|
637
|
+
}
|
|
638
|
+
if (ch === '~') {
|
|
639
|
+
let n = 0;
|
|
640
|
+
while (text[i + n] === '~')
|
|
641
|
+
n++;
|
|
642
|
+
run += n >= 3 ? '\\~'.repeat(n) : '~'.repeat(n);
|
|
643
|
+
i += n;
|
|
644
|
+
continue;
|
|
645
|
+
}
|
|
646
|
+
const url = /[hHfFwW]/.test(ch) ? matchAt(URL_START, text, i) : null;
|
|
647
|
+
if (url) {
|
|
648
|
+
const end = urlEnd(text, i + url[0].length);
|
|
649
|
+
emit(codeSpan(text.slice(i, end), ctx.table));
|
|
650
|
+
i = end;
|
|
651
|
+
continue;
|
|
652
|
+
}
|
|
653
|
+
if (boundary) {
|
|
654
|
+
const startsReference = REFERENCE_START.test(ch);
|
|
655
|
+
const reference = (startsReference && ctx.ownerReference ? matchAt(ctx.ownerReference, text, i) : null)
|
|
656
|
+
?? (startsReference ? matchAt(CROSS_REFERENCE, text, i) : null)
|
|
657
|
+
?? (ch === 'g' || ch === 'G' ? matchAt(GH_REFERENCE, text, i) : null);
|
|
658
|
+
if (reference) {
|
|
659
|
+
emit(codeSpan(reference[0], ctx.table));
|
|
660
|
+
i += reference[0].length;
|
|
661
|
+
continue;
|
|
662
|
+
}
|
|
663
|
+
const digits = ch === '#' ? matchAt(DIGITS, text, i + 1) : null;
|
|
664
|
+
if (digits) {
|
|
665
|
+
emit(codeSpan(`#${digits[0]}`, ctx.table));
|
|
666
|
+
i += 1 + digits[0].length;
|
|
667
|
+
continue;
|
|
668
|
+
}
|
|
669
|
+
if (ch === '@') {
|
|
670
|
+
run += `@${WORD_JOINER}`;
|
|
671
|
+
i++;
|
|
672
|
+
continue;
|
|
673
|
+
}
|
|
674
|
+
}
|
|
675
|
+
run += ch;
|
|
676
|
+
i++;
|
|
677
|
+
}
|
|
678
|
+
if (run)
|
|
679
|
+
out.push(run);
|
|
680
|
+
}
|
|
681
|
+
const DEFINITION = /^ {0,3}\[((?:[^\[\]\\]|\\.){1,999})\]:/;
|
|
682
|
+
/** R16: every text the reviewer wrote, before it reaches the service. */
|
|
683
|
+
export function sanitizeReviewText(text, repo) {
|
|
684
|
+
const regions = splitFences(wellFormed(text).replace(/\r\n?/g, '\n').split('\n'), false);
|
|
685
|
+
const labels = new Set();
|
|
686
|
+
for (const region of regions) {
|
|
687
|
+
if (region.code)
|
|
688
|
+
continue;
|
|
689
|
+
for (const line of region.lines) {
|
|
690
|
+
const definition = DEFINITION.exec(line);
|
|
691
|
+
if (definition)
|
|
692
|
+
labels.add(normalizeLabel(definition[1]));
|
|
693
|
+
}
|
|
694
|
+
}
|
|
695
|
+
const ctx = contextFor(repo, labels);
|
|
696
|
+
const out = [];
|
|
697
|
+
for (const region of regions) {
|
|
698
|
+
if (region.code) {
|
|
699
|
+
out.push(plainFence(region.lines[0]), ...region.lines.slice(1));
|
|
700
|
+
if (region.close !== undefined)
|
|
701
|
+
out.push(region.close);
|
|
702
|
+
continue;
|
|
703
|
+
}
|
|
704
|
+
const tables = tableLines(region.lines);
|
|
705
|
+
region.lines.forEach((line, k) => out.push(sanitizeInline(line, { ...ctx, table: tables[k] })));
|
|
706
|
+
}
|
|
707
|
+
return breakMarker(out.join('\n'));
|
|
708
|
+
}
|
|
709
|
+
/**
|
|
710
|
+
* A fence's opening line with a `math` info string made `text`: GitHub renders a math block as text, where a
|
|
711
|
+
* mention or reference is live. An info string's first word holding `&` or `\` (which GitHub decodes) goes too.
|
|
712
|
+
*/
|
|
713
|
+
function plainFence(opening) {
|
|
714
|
+
const match = /^( {0,3}(?:`{3,}|~{3,})[ \t]*)(\S*)/.exec(opening);
|
|
715
|
+
if (!match || !(/[&\\]/.test(match[2]) || match[2].toLowerCase() === 'math'))
|
|
716
|
+
return opening;
|
|
717
|
+
return `${match[1]}text${opening.slice(match[0].length)}`;
|
|
718
|
+
}
|
|
719
|
+
/**
|
|
720
|
+
* CommonMark's HTML blocks that run on past blank lines (types 1, 3, 4 and 5): what opens one, and what closes it.
|
|
721
|
+
* Everything in one is raw HTML, backticks included, so a `<!--` there is a comment.
|
|
722
|
+
*/
|
|
723
|
+
const HTML_BLOCKS = [
|
|
724
|
+
[/^<(?:pre|script|style|textarea)(?:[\s>]|$)/i, /<\/(?:pre|script|style|textarea)>/i],
|
|
725
|
+
[/^<\?/, /\?>/],
|
|
726
|
+
[/^<![A-Za-z]/, />/],
|
|
727
|
+
[/^<!\[CDATA\[/, /\]\]>/],
|
|
728
|
+
];
|
|
729
|
+
/** For the fixer's own replies and PR comments: `<!--` outside code becomes `<!--`, and breakMarker everywhere. Nothing else changes. */
|
|
730
|
+
export function escapeWriteBody(text) {
|
|
731
|
+
// GitHub ends a line at `\r\n`, `\r` or `\n`; each line keeps the ending it had.
|
|
732
|
+
const pieces = wellFormed(text).split(/(\r\n|\r|\n)/);
|
|
733
|
+
const lines = pieces.filter((_, k) => k % 2 === 0);
|
|
734
|
+
const out = [];
|
|
735
|
+
for (const region of splitFences(lines, true)) {
|
|
736
|
+
if (region.code) {
|
|
737
|
+
out.push(...region.lines);
|
|
738
|
+
continue;
|
|
739
|
+
}
|
|
740
|
+
const tables = tableLines(region.lines);
|
|
741
|
+
let unsure = false;
|
|
742
|
+
let html;
|
|
743
|
+
region.lines.forEach((line, k) => {
|
|
744
|
+
if (!html) {
|
|
745
|
+
const opened = HTML_BLOCKS.find(([start]) => start.test(afterContainers(line)));
|
|
746
|
+
if (opened && !opened[1].test(line))
|
|
747
|
+
html = opened[1];
|
|
748
|
+
if (opened) {
|
|
749
|
+
out.push(escapeComments(line));
|
|
750
|
+
unsure = true;
|
|
751
|
+
return;
|
|
752
|
+
}
|
|
753
|
+
}
|
|
754
|
+
else {
|
|
755
|
+
out.push(escapeComments(line));
|
|
756
|
+
if (html.test(line))
|
|
757
|
+
html = undefined;
|
|
758
|
+
return;
|
|
759
|
+
}
|
|
760
|
+
if (isBlank(line))
|
|
761
|
+
unsure = false;
|
|
762
|
+
if (unsure) {
|
|
763
|
+
out.push(escapeComments(line));
|
|
764
|
+
return;
|
|
765
|
+
}
|
|
766
|
+
const escaped = escapeLine(line, tables[k]);
|
|
767
|
+
unsure = escaped.unsure;
|
|
768
|
+
out.push(escaped.text);
|
|
769
|
+
});
|
|
770
|
+
}
|
|
771
|
+
return breakMarker(out.map((line, k) => line + (pieces[2 * k + 1] ?? '')).join(''));
|
|
772
|
+
}
|
|
773
|
+
const escapeComments = (text) => text.replace(/<!--/g, '<!--');
|
|
774
|
+
/**
|
|
775
|
+
* One line of the fixer's text with `<!--` escaped outside code spans. A code span counts only while nothing
|
|
776
|
+
* before it in the paragraph could change how GitHub pairs backticks: an unpaired run, a tag or autolink (`<x`),
|
|
777
|
+
* or a link's destination or label (`](`, `][`), which GitHub reads before code spans. After one of those, the
|
|
778
|
+
* rest of the paragraph is treated as text.
|
|
779
|
+
*/
|
|
780
|
+
function escapeLine(line, table) {
|
|
781
|
+
let out = '';
|
|
782
|
+
for (let p = 0; p < line.length;) {
|
|
783
|
+
const ch = line[p];
|
|
784
|
+
if (ch === '\\' && isPunctuation(line[p + 1])) {
|
|
785
|
+
out += line.slice(p, p + 2);
|
|
786
|
+
p += 2;
|
|
787
|
+
continue;
|
|
788
|
+
}
|
|
789
|
+
if (ch === '`') {
|
|
790
|
+
const length = backtickRun(line, p);
|
|
791
|
+
const close = spanCloser(line, p + length, length);
|
|
792
|
+
if (close < 0 || (table && line.slice(p + length, close).includes('|')))
|
|
793
|
+
return { text: out + escapeComments(line.slice(p)), unsure: true };
|
|
794
|
+
out += line.slice(p, close + length);
|
|
795
|
+
p = close + length;
|
|
796
|
+
continue;
|
|
797
|
+
}
|
|
798
|
+
if (ch === '<' && line.startsWith('<!--', p)) {
|
|
799
|
+
out += '<!--';
|
|
800
|
+
p += 4;
|
|
801
|
+
continue;
|
|
802
|
+
}
|
|
803
|
+
if ((ch === '<' && /[A-Za-z/!?]/.test(line[p + 1] ?? '')) || (ch === ']' && (line[p + 1] === '(' || line[p + 1] === '['))) {
|
|
804
|
+
return { text: out + escapeComments(line.slice(p)), unsure: true };
|
|
805
|
+
}
|
|
806
|
+
out += ch;
|
|
807
|
+
p++;
|
|
808
|
+
}
|
|
809
|
+
return { text: out, unsure: false };
|
|
810
|
+
}
|
|
811
|
+
/** A path git wrote in C quoting (`"caf\303\251.ts"`), unquoted; any other text as it is. */
|
|
812
|
+
function unquote(text) {
|
|
813
|
+
if (text.length < 2 || !text.startsWith('"') || !text.endsWith('"'))
|
|
814
|
+
return text;
|
|
815
|
+
const body = text.slice(1, -1);
|
|
816
|
+
const bytes = [];
|
|
817
|
+
const named = { a: 7, b: 8, t: 9, n: 10, v: 11, f: 12, r: 13, '"': 34, '\\': 92 };
|
|
818
|
+
for (let i = 0; i < body.length; i++) {
|
|
819
|
+
if (body[i] === '\\' && i + 1 < body.length) {
|
|
820
|
+
const octal = /^[0-3][0-7]{2}/.exec(body.slice(i + 1, i + 4));
|
|
821
|
+
if (octal) {
|
|
822
|
+
bytes.push(parseInt(octal[0], 8));
|
|
823
|
+
i += 3;
|
|
824
|
+
continue;
|
|
825
|
+
}
|
|
826
|
+
const code = named[body[i + 1]];
|
|
827
|
+
if (code !== undefined) {
|
|
828
|
+
bytes.push(code);
|
|
829
|
+
i++;
|
|
830
|
+
continue;
|
|
831
|
+
}
|
|
832
|
+
}
|
|
833
|
+
const ch = String.fromCodePoint(body.codePointAt(i));
|
|
834
|
+
bytes.push(...Buffer.from(ch, 'utf8'));
|
|
835
|
+
i += ch.length - 1;
|
|
836
|
+
}
|
|
837
|
+
return Buffer.from(bytes).toString('utf8');
|
|
838
|
+
}
|
|
839
|
+
/** The path on a `---`/`+++` line, without git's prefix; undefined for `/dev/null`. */
|
|
840
|
+
function headerPath(text, prefix) {
|
|
841
|
+
const raw = text.startsWith('"') ? text : text.split('\t')[0];
|
|
842
|
+
const path = unquote(raw.replace(/\r$/, ''));
|
|
843
|
+
if (path === '/dev/null')
|
|
844
|
+
return undefined;
|
|
845
|
+
return path.startsWith(prefix) ? path.slice(prefix.length) : path;
|
|
846
|
+
}
|
|
847
|
+
/** The two paths of a `diff --git a/x b/y` line, without their prefixes. */
|
|
848
|
+
function gitLinePaths(rest) {
|
|
849
|
+
const strip = (path, prefix) => (path.startsWith(prefix) ? path.slice(prefix.length) : path);
|
|
850
|
+
const quoted = /^("(?:[^"\\]|\\.)*") ("(?:[^"\\]|\\.)*"|\S.*)$/.exec(rest) ?? /^(\S.*?) ("(?:[^"\\]|\\.)*")$/.exec(rest);
|
|
851
|
+
if (quoted)
|
|
852
|
+
return [strip(unquote(quoted[1]), 'a/'), strip(unquote(quoted[2]), 'b/')];
|
|
853
|
+
if ((rest.length - 1) % 2 === 0) {
|
|
854
|
+
const half = (rest.length - 1) / 2;
|
|
855
|
+
const a = rest.slice(0, half);
|
|
856
|
+
const b = rest.slice(half + 1);
|
|
857
|
+
if (rest[half] === ' ' && a.startsWith('a/') && b.startsWith('b/') && a.slice(2) === b.slice(2))
|
|
858
|
+
return [a.slice(2), b.slice(2)];
|
|
859
|
+
}
|
|
860
|
+
const split = rest.indexOf(' b/');
|
|
861
|
+
return split > 0 ? [strip(rest.slice(0, split), 'a/'), rest.slice(split + 3)] : undefined;
|
|
862
|
+
}
|
|
863
|
+
/** Parses a unified diff (git diff output, possibly many files, renames, binary files, ``). RIGHT covers added and context lines of the new file; LEFT covers deleted and context lines of the old file. covers() is true only when every line from startLine to line is inside ONE hunk on that side. */
|
|
864
|
+
export function indexDiff(patch) {
|
|
865
|
+
const files = [];
|
|
866
|
+
const hunks = new Map();
|
|
867
|
+
let file;
|
|
868
|
+
let hunk;
|
|
869
|
+
const finish = () => {
|
|
870
|
+
if (!file)
|
|
871
|
+
return;
|
|
872
|
+
const newPath = file.newPath ?? file.git?.[1];
|
|
873
|
+
const oldPath = file.oldPath ?? file.git?.[0];
|
|
874
|
+
const path = file.deleted ? oldPath : newPath ?? oldPath;
|
|
875
|
+
if (path !== undefined) {
|
|
876
|
+
if (!hunks.has(path))
|
|
877
|
+
files.push(path);
|
|
878
|
+
hunks.set(path, [...(hunks.get(path) ?? []), ...file.hunks]);
|
|
879
|
+
}
|
|
880
|
+
file = undefined;
|
|
881
|
+
};
|
|
882
|
+
const mark = (range, side, line) => {
|
|
883
|
+
const current = range[side];
|
|
884
|
+
range[side] = current ? [current[0], line] : [line, line];
|
|
885
|
+
};
|
|
886
|
+
const lines = patch.split('\n');
|
|
887
|
+
for (let i = 0; i < lines.length; i++) {
|
|
888
|
+
const line = lines[i].endsWith('\r') ? lines[i].slice(0, -1) : lines[i];
|
|
889
|
+
if (hunk) {
|
|
890
|
+
if (line.startsWith('\\'))
|
|
891
|
+
continue; // ``
|
|
892
|
+
if (hunk.leftLeft > 0 || hunk.rightLeft > 0) {
|
|
893
|
+
const kind = line === '' ? ' ' : line[0];
|
|
894
|
+
if (kind === ' ' && hunk.leftLeft > 0 && hunk.rightLeft > 0) {
|
|
895
|
+
mark(hunk.range, 'left', hunk.left++);
|
|
896
|
+
mark(hunk.range, 'right', hunk.right++);
|
|
897
|
+
hunk.leftLeft--;
|
|
898
|
+
hunk.rightLeft--;
|
|
899
|
+
continue;
|
|
900
|
+
}
|
|
901
|
+
if (kind === '-' && hunk.leftLeft > 0) {
|
|
902
|
+
mark(hunk.range, 'left', hunk.left++);
|
|
903
|
+
hunk.leftLeft--;
|
|
904
|
+
continue;
|
|
905
|
+
}
|
|
906
|
+
if (kind === '+' && hunk.rightLeft > 0) {
|
|
907
|
+
mark(hunk.range, 'right', hunk.right++);
|
|
908
|
+
hunk.rightLeft--;
|
|
909
|
+
continue;
|
|
910
|
+
}
|
|
911
|
+
}
|
|
912
|
+
// The hunk is done (or the diff was cut short): read this line as a header.
|
|
913
|
+
hunk = undefined;
|
|
914
|
+
}
|
|
915
|
+
if (line.startsWith('diff --git ')) {
|
|
916
|
+
finish();
|
|
917
|
+
file = { git: gitLinePaths(line.slice('diff --git '.length)), hunks: [] };
|
|
918
|
+
continue;
|
|
919
|
+
}
|
|
920
|
+
const header = /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/.exec(line);
|
|
921
|
+
if (header && file) {
|
|
922
|
+
const range = {};
|
|
923
|
+
file.hunks.push(range);
|
|
924
|
+
hunk = { left: Number(header[1]), right: Number(header[3]), leftLeft: header[2] === undefined ? 1 : Number(header[2]), rightLeft: header[4] === undefined ? 1 : Number(header[4]), range };
|
|
925
|
+
continue;
|
|
926
|
+
}
|
|
927
|
+
if (line.startsWith('--- ') && (lines[i + 1] ?? '').startsWith('+++ ')) {
|
|
928
|
+
// A plain unified diff has no `diff --git` line: each `---`/`+++` pair after a hunk starts the next file.
|
|
929
|
+
if (!file || file.hunks.length) {
|
|
930
|
+
finish();
|
|
931
|
+
file = { hunks: [] };
|
|
932
|
+
}
|
|
933
|
+
file.oldPath = headerPath(line.slice(4), 'a/');
|
|
934
|
+
const next = lines[++i].replace(/\r$/, '');
|
|
935
|
+
file.newPath = headerPath(next.slice(4), 'b/');
|
|
936
|
+
if (file.newPath === undefined)
|
|
937
|
+
file.deleted = true;
|
|
938
|
+
if (file.oldPath === undefined)
|
|
939
|
+
file.added = true;
|
|
940
|
+
continue;
|
|
941
|
+
}
|
|
942
|
+
if (!file)
|
|
943
|
+
continue;
|
|
944
|
+
if (line.startsWith('rename from ') || line.startsWith('copy from '))
|
|
945
|
+
file.oldPath = unquote(line.slice(line.indexOf(' from ') + 6));
|
|
946
|
+
else if (line.startsWith('rename to ') || line.startsWith('copy to '))
|
|
947
|
+
file.newPath = unquote(line.slice(line.indexOf(' to ') + 4));
|
|
948
|
+
else if (line.startsWith('deleted file mode'))
|
|
949
|
+
file.deleted = true;
|
|
950
|
+
else if (line.startsWith('new file mode'))
|
|
951
|
+
file.added = true;
|
|
952
|
+
}
|
|
953
|
+
finish();
|
|
954
|
+
return {
|
|
955
|
+
files,
|
|
956
|
+
covers(path, side, startLine, line) {
|
|
957
|
+
if (!Number.isInteger(startLine) || !Number.isInteger(line) || startLine < 1 || startLine > line)
|
|
958
|
+
return false;
|
|
959
|
+
return (hunks.get(path) ?? []).some(range => {
|
|
960
|
+
const lines = side === 'LEFT' ? range.left : side === 'RIGHT' ? range.right : undefined;
|
|
961
|
+
return lines !== undefined && lines[0] <= startLine && line <= lines[1];
|
|
962
|
+
});
|
|
963
|
+
},
|
|
964
|
+
};
|
|
965
|
+
}
|
|
966
|
+
const bytesOf = (text) => Buffer.byteLength(text, 'utf8');
|
|
967
|
+
const trimBlankLines = (text) => text.replace(/^(?:[ \t]*\n)+/, '').replace(/(?:\n[ \t]*)+$/, '');
|
|
968
|
+
/** A path the service takes for an inline comment: relative, at most 1,024 bytes, no `..` segment, NUL or backslash. */
|
|
969
|
+
function servicePath(path) {
|
|
970
|
+
return typeof path === 'string' && path !== '' && bytesOf(path) <= PATH_BYTES && !path.startsWith('/') && !path.includes('\0')
|
|
971
|
+
&& !path.includes('\\') && !path.split('/').includes('..');
|
|
972
|
+
}
|
|
973
|
+
/** The first `n` characters of `chars`, with an ellipsis when that cuts it; a fence the cut leaves open is closed first. */
|
|
974
|
+
function cutAt(chars, n) {
|
|
975
|
+
if (n >= chars.length)
|
|
976
|
+
return chars.join('');
|
|
977
|
+
const head = chars.slice(0, n).join('');
|
|
978
|
+
const regions = splitFences(head.replace(/\r\n?/g, '\n').split('\n'), false);
|
|
979
|
+
const last = regions[regions.length - 1];
|
|
980
|
+
return last?.code && last.close !== undefined ? `${head}\n${last.close}\n${ELLIPSIS}` : `${head}${ELLIPSIS}`;
|
|
981
|
+
}
|
|
982
|
+
/**
|
|
983
|
+
* The reviewer's text, sanitised, in at most `bytes`: the longest start of it that fits, with an ellipsis. The raw
|
|
984
|
+
* text is cut and then sanitised, never the other way round, so a cut never opens a code span or link.
|
|
985
|
+
*/
|
|
986
|
+
function fitted(raw, bytes, repo) {
|
|
987
|
+
const chars = Array.from(raw);
|
|
988
|
+
if (chars.length <= RAW_CHARS) {
|
|
989
|
+
const whole = sanitizeReviewText(raw, repo);
|
|
990
|
+
if (bytesOf(whole) <= bytes)
|
|
991
|
+
return whole;
|
|
992
|
+
}
|
|
993
|
+
let best = sanitizeReviewText(cutAt(chars, 0), repo);
|
|
994
|
+
let low = 1;
|
|
995
|
+
let high = Math.min(chars.length, RAW_CHARS);
|
|
996
|
+
while (low <= high) {
|
|
997
|
+
const mid = (low + high) >> 1;
|
|
998
|
+
const text = sanitizeReviewText(cutAt(chars, mid), repo);
|
|
999
|
+
if (bytesOf(text) <= bytes) {
|
|
1000
|
+
best = text;
|
|
1001
|
+
low = mid + 1;
|
|
1002
|
+
}
|
|
1003
|
+
else {
|
|
1004
|
+
high = mid - 1;
|
|
1005
|
+
}
|
|
1006
|
+
}
|
|
1007
|
+
return best;
|
|
1008
|
+
}
|
|
1009
|
+
/** A title on one line, cut to 200 characters, sanitised as inline text (it never starts a line). */
|
|
1010
|
+
function titleText(title, repo) {
|
|
1011
|
+
const flat = wellFormed(title).replace(/[\u0000-\u001f\u007f\u2028\u2029]+/g, ' ').replace(/ {2,}/g, ' ').trim();
|
|
1012
|
+
const chars = Array.from(flat);
|
|
1013
|
+
const short = chars.length > TITLE_CHARS ? `${chars.slice(0, TITLE_CHARS).join('')}${ELLIPSIS}` : flat;
|
|
1014
|
+
return breakMarker(sanitizeInline(short, contextFor(repo)));
|
|
1015
|
+
}
|
|
1016
|
+
/** `path:line` in inline code. */
|
|
1017
|
+
function location(path, line) {
|
|
1018
|
+
const chars = Array.from(wellFormed(path).replace(/[\u0000-\u001f\u007f\u2028\u2029]/g, '\ufffd'));
|
|
1019
|
+
return breakMarker(codeSpan(`${chars.length > PATH_CHARS ? `${chars.slice(0, PATH_CHARS).join('')}${ELLIPSIS}` : chars.join('')}:${line}`));
|
|
1020
|
+
}
|
|
1021
|
+
function inlineBody(finding, repo) {
|
|
1022
|
+
const head = `**${finding.priority}** ${titleText(finding.title, repo)}`;
|
|
1023
|
+
const body = trimBlankLines(fitted(finding.body, REVIEW_COMMENT_BYTES - bytesOf(head) - 2, repo));
|
|
1024
|
+
return wellFormed(breakMarker(isBlankText(body) ? head : `${head}\n\n${body}`));
|
|
1025
|
+
}
|
|
1026
|
+
/**
|
|
1027
|
+
* One finding as a list item. The marker is followed by three spaces, so its content starts at column 4 and the
|
|
1028
|
+
* body is indented by 4: tabs keep their stops, and GitHub reads the body exactly as the sanitiser did.
|
|
1029
|
+
*/
|
|
1030
|
+
function summaryItem(finding, repo) {
|
|
1031
|
+
const head = `- **${finding.priority}** ${titleText(finding.title, repo)} · ${location(finding.path, finding.line)}`;
|
|
1032
|
+
if (finding.body === undefined)
|
|
1033
|
+
return head;
|
|
1034
|
+
const body = trimBlankLines(sanitizeReviewText(cutAt(Array.from(finding.body), ITEM_BODY_CHARS), repo));
|
|
1035
|
+
if (isBlankText(body))
|
|
1036
|
+
return head;
|
|
1037
|
+
return `${head}\n\n${body.split('\n').map(line => (isBlank(line) ? '' : ` ${line}`)).join('\n')}`;
|
|
1038
|
+
}
|
|
1039
|
+
const plural = (count, noun) => `${count} ${noun}${count === 1 ? '' : 's'}`;
|
|
1040
|
+
export function composeReview(input) {
|
|
1041
|
+
const { repo, diff } = input;
|
|
1042
|
+
// Every P1 and P2 finding in order, with the inline comment it gets when it goes inline.
|
|
1043
|
+
const blocking = [];
|
|
1044
|
+
const nitList = [];
|
|
1045
|
+
let inline = 0;
|
|
1046
|
+
for (const finding of input.findings) {
|
|
1047
|
+
if (finding.priority === 'P3') {
|
|
1048
|
+
nitList.push(finding);
|
|
1049
|
+
continue;
|
|
1050
|
+
}
|
|
1051
|
+
if (finding.priority !== 'P1' && finding.priority !== 'P2')
|
|
1052
|
+
continue;
|
|
1053
|
+
const side = finding.side === 'LEFT' ? 'LEFT' : 'RIGHT';
|
|
1054
|
+
const start = finding.startLine !== undefined && Number.isInteger(finding.startLine) && finding.startLine >= 1 && finding.startLine < finding.line ? finding.startLine : undefined;
|
|
1055
|
+
const covered = !input.summaryOnly && inline < REVIEW_COMMENTS && servicePath(finding.path)
|
|
1056
|
+
&& Number.isInteger(finding.line) && finding.line > 0 && finding.line < LINE_CEILING
|
|
1057
|
+
&& diff.covers(finding.path, side, start ?? finding.line, finding.line);
|
|
1058
|
+
if (!covered) {
|
|
1059
|
+
blocking.push({ finding });
|
|
1060
|
+
continue;
|
|
1061
|
+
}
|
|
1062
|
+
inline++;
|
|
1063
|
+
const comment = { path: finding.path, line: finding.line, side, ...(start !== undefined ? { startLine: start, startSide: side } : {}), body: inlineBody(finding, repo) };
|
|
1064
|
+
blocking.push({ finding, comment });
|
|
1065
|
+
}
|
|
1066
|
+
const sha = codeSpan(input.headSha.slice(0, 7));
|
|
1067
|
+
const lead = [];
|
|
1068
|
+
if (blocking.length === 0)
|
|
1069
|
+
lead.push(`No findings on ${sha}.`);
|
|
1070
|
+
const summary = trimBlankLines(fitted(input.summary, REVIEWER_SUMMARY_BYTES, repo));
|
|
1071
|
+
if (!isBlankText(summary))
|
|
1072
|
+
lead.push(summary);
|
|
1073
|
+
else if (blocking.length > 0)
|
|
1074
|
+
lead.push(`${plural(blocking.length, 'finding')} on ${sha}.`);
|
|
1075
|
+
const items = new Map();
|
|
1076
|
+
const itemOf = (finding) => items.get(finding) ?? items.set(finding, summaryItem(finding, repo)).get(finding);
|
|
1077
|
+
const nitItems = nitList.map(itemOf);
|
|
1078
|
+
const openItems = blocking.length === 0 ? (input.stillOpen ?? []).map(finding => summaryItem({ ...finding, body: undefined }, repo)) : [];
|
|
1079
|
+
const closing = input.round === input.rounds && blocking.length > 0 ? `Round ${input.round} of ${input.rounds}: these findings are left for you.` : undefined;
|
|
1080
|
+
const compose = () => {
|
|
1081
|
+
const comments = [];
|
|
1082
|
+
const recorded = [];
|
|
1083
|
+
const below = [];
|
|
1084
|
+
for (const { finding, comment } of blocking) {
|
|
1085
|
+
const entry = { priority: finding.priority, title: finding.title, path: finding.path, line: finding.line };
|
|
1086
|
+
if (comment) {
|
|
1087
|
+
comments.push(comment);
|
|
1088
|
+
recorded.push({ ...entry, where: 'inline', comment: comments.length - 1 });
|
|
1089
|
+
}
|
|
1090
|
+
else {
|
|
1091
|
+
below.push(finding);
|
|
1092
|
+
recorded.push({ ...entry, where: 'summary' });
|
|
1093
|
+
}
|
|
1094
|
+
}
|
|
1095
|
+
const sections = [];
|
|
1096
|
+
if (below.length)
|
|
1097
|
+
sections.push({ heading: comments.length ? '**Findings outside the diff**' : undefined, items: below.map(itemOf) });
|
|
1098
|
+
if (nitItems.length)
|
|
1099
|
+
sections.push({ heading: '**Nits**', items: nitItems });
|
|
1100
|
+
if (openItems.length)
|
|
1101
|
+
sections.push({ heading: '**Still open from earlier rounds (disputed):**', items: openItems });
|
|
1102
|
+
const total = sections.reduce((count, section) => count + section.items.length, 0);
|
|
1103
|
+
const render = (shown) => {
|
|
1104
|
+
const blocks = [...lead];
|
|
1105
|
+
let left = shown;
|
|
1106
|
+
for (const section of sections) {
|
|
1107
|
+
if (left <= 0)
|
|
1108
|
+
break;
|
|
1109
|
+
const shownItems = section.items.slice(0, left);
|
|
1110
|
+
left -= shownItems.length;
|
|
1111
|
+
if (section.heading)
|
|
1112
|
+
blocks.push(section.heading);
|
|
1113
|
+
blocks.push(shownItems.join('\n\n'));
|
|
1114
|
+
}
|
|
1115
|
+
if (shown < total)
|
|
1116
|
+
blocks.push(`${plural(total - shown, 'more finding')} not shown.`);
|
|
1117
|
+
if (closing)
|
|
1118
|
+
blocks.push(closing);
|
|
1119
|
+
return wellFormed(breakMarker(blocks.join('\n\n')));
|
|
1120
|
+
};
|
|
1121
|
+
let body = render(total);
|
|
1122
|
+
for (let shown = total - 1; shown >= 0 && bytesOf(body) > REVIEW_SUMMARY_BYTES; shown--)
|
|
1123
|
+
body = render(shown);
|
|
1124
|
+
return { body, comments, recorded, nits: nitList.length, blocking: blocking.length };
|
|
1125
|
+
};
|
|
1126
|
+
// The service also caps the whole request: while the review would pass it, the last inline finding moves to the summary.
|
|
1127
|
+
let review = compose();
|
|
1128
|
+
while (review.comments.length && bytesOf(JSON.stringify({ body: review.body, comments: review.comments })) > REVIEW_REQUEST_BYTES - OTHER_FIELDS_BYTES) {
|
|
1129
|
+
blocking.findLast(entry => entry.comment).comment = undefined;
|
|
1130
|
+
review = compose();
|
|
1131
|
+
}
|
|
1132
|
+
return review;
|
|
1133
|
+
}
|