@ihyeon/error-to-test 0.1.12 → 0.1.14
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/README.ko.md +33 -0
- package/README.md +45 -0
- package/dist/artifacts.d.ts +3 -0
- package/dist/artifacts.js +6 -5
- package/dist/cli.js +107 -5
- package/dist/comparison.d.ts +37 -0
- package/dist/comparison.js +191 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +2 -0
- package/dist/results.js +2 -3
- package/dist/run-summary.d.ts +31 -0
- package/dist/run-summary.js +288 -0
- package/package.json +1 -1
package/README.ko.md
CHANGED
|
@@ -44,6 +44,23 @@ error-to-test analyze --input errors.json --min-count 3 --top 10 --out ./recurri
|
|
|
44
44
|
|
|
45
45
|
JavaScript API에서는 `analyzeErrors(content, { minCount: 3, top: 10 })`으로 같은 기준을 적용합니다.
|
|
46
46
|
|
|
47
|
+
두 분석 결과는 `compare`로 비교할 수 있습니다. 릴리스가 바뀐 뒤 어떤 오류 서명이 다시 관측됐는지 확인할 때 사용합니다.
|
|
48
|
+
|
|
49
|
+
```sh
|
|
50
|
+
error-to-test analyze --input before-errors.json --release r1 --out ./before
|
|
51
|
+
error-to-test analyze --input current-errors.json --release r2 --out ./current
|
|
52
|
+
error-to-test compare ./before ./current
|
|
53
|
+
error-to-test compare ./before ./current --format json --out ./comparison.json
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
현재에만 있는 서명(`only-current`), 양쪽에 있는 서명(`both`), 이전에만 있는 서명(`only-baseline`)으로 나누고 제공된 로그 건수와 증감을 보여줍니다. 릴리스만 제외하고 프로젝트·환경·실행 환경·오류 유형·페이지 경로·전체 오류 서명이 일치해야 합니다. 메시지나 소스 위치가 바뀌면 별도 서명이며, 비슷한 문장을 같은 원인으로 추정하지 않습니다.
|
|
57
|
+
|
|
58
|
+
TC 생성 대상에서 제외된 묶음도 모두 비교합니다. 한쪽에 여러 릴리스가 있으면 같은 비교 키의 건수를 합산하고 원래 묶음 ID·릴리스 목록을 남깁니다. 단일 릴리스끼리 비교하려면 먼저 `analyze --release`로 범위를 정하세요. 페이지 조회 수는 합산하지 않습니다.
|
|
59
|
+
|
|
60
|
+
이전에만 관측됐다는 표시가 수정 완료를 의미하지 않습니다. 건수는 입력에 포함된 이벤트·보고서 수이며, 발생률이나 영향 사용자 수가 아닙니다. 양쪽의 부분 내보내기·기간·필터·수집 범위와 경고도 표시합니다. 수집 이벤트 건수와 수동 제출 보고서 건수의 비교는 거부합니다. 수동 JSON과 텍스트는 같은 제출 보고서 기준으로 비교하되 형식 차이를 알립니다.
|
|
61
|
+
|
|
62
|
+
양쪽 번들을 검증한 뒤 읽으며 원래 산출물·TC 상태·검토 조건·연결 결과는 수정하지 않습니다. 기본 출력은 Markdown이고, `--format json`은 `error-to-test/comparison-1`을 반환합니다. `--out`은 양쪽 번들의 `results` 폴더 밖에 있는 새 파일만 허용합니다. API는 `compareBundles()`와 `renderComparison()`입니다.
|
|
63
|
+
|
|
47
64
|
`report.md` 상단에서 TC 초안 수와 추가 정보가 필요한 TC 수를 확인할 수 있습니다. 초안도 실행 전에 검토해야 합니다. 오류 묶음·수집 건수와 함께 대표 로그의 오류·React 컴포넌트 스택, 재현 방법·사전 조건·테스트 단계·부족한 정보도 표시합니다. 같은 스택은 한 번만 표시하며, 전체 로그의 모든 스택을 나열하지는 않습니다. 재현 단계와 정상 기대 결과, 명시적인 assertion이 없으면 질문이 있는 TC를 생성합니다. 직접 입력한 보고서에는 실제 발생 시각·사용자 수를 만들어 넣지 않습니다. 수집 건수도 실제 발생률을 뜻하지 않으며, 원본 내보내기의 일부 데이터 표시를 유지합니다.
|
|
48
65
|
|
|
49
66
|
기본 suite는 검토 질문으로 실행이 차단됩니다. TC와 프로필을 확인한 뒤 다른 출력 폴더에 `--reviewed`로 다시 생성하면 검토 질문만 제거됩니다. 나머지 질문은 그대로 실행을 차단합니다. 프로필의 `setupConfirmed`는 준비 조건을 확인했다는 표시이며, 계정·데이터를 자동으로 준비하는 기능은 아닙니다.
|
|
@@ -77,6 +94,22 @@ Flow QA 설치와 실행 대상 설정은 별도로 필요합니다. 위 `flows/
|
|
|
77
94
|
|
|
78
95
|
실행 후 `node bin/error-to-test.mjs link-run .error-to-test/reviewed --report /path/to/qa-report.json`으로 결과를 원래 오류 묶음에 연결할 수 있습니다. suite 해시와 모든 case ID가 일치해야 하며, 결과는 `results/<runId>.json`에 저장합니다. 원본 e2e 리포트 대신 Flow QA가 정리한 `report-1`을 사용하세요.
|
|
79
96
|
|
|
97
|
+
연결한 결과는 `results`로 오류 묶음별 최신 TC 결과를 모아 볼 수 있습니다.
|
|
98
|
+
|
|
99
|
+
```sh
|
|
100
|
+
error-to-test results .error-to-test/reviewed
|
|
101
|
+
error-to-test results .error-to-test/reviewed --out ./run-summary.md
|
|
102
|
+
error-to-test results .error-to-test/reviewed --format json --out ./run-summary.json
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
연결된 실행 수, 최신 실행의 상태·시각, TC 상태별 건수와 묶음별 결과·사유를 표시합니다. 통과·실패·flaky·차단·건너뜀·오류를 구분하고, 실행 결과가 없으면 선택된 TC를 `not-run`으로 표시합니다. TC가 선택되지 않은 원본 묶음도 남습니다.
|
|
106
|
+
|
|
107
|
+
보고된 종료 시각이 가장 늦은 실행 하나를 기준으로 합니다. 종료 시각이 같으면 시작 시각, 실행 ID 순으로 결정하며 파일 수정 시각은 사용하지 않습니다. 여러 실행의 통과 결과를 섞지 않습니다. 연결된 실행이 있으면 검토 대기와 미확인 맥락도 표시하며, 결과를 원래 오류의 수정 완료나 실행 승인으로 취급하지 않습니다.
|
|
108
|
+
|
|
109
|
+
출력 전에 번들과 연결 결과의 형식·원본/suite 해시·case/group/event 연결·상태·시각을 검사합니다. 오래된 결과라도 잘못된 JSON이 있으면 실패하며, 기존 산출물과 결과 파일은 수정하지 않습니다. 결과 폴더는 최대 1,000개 항목, 각 JSON은 2 MiB, 전체 결과는 64 MiB까지 지원합니다. 다른 확장자의 부수 파일은 무시하고 잘못된 JSON 이름·심볼릭 링크·일반 파일이 아닌 결과·한도 초과는 거부합니다. `--out`은 번들의 `results` 폴더 밖에 있는 새 파일만 허용합니다.
|
|
110
|
+
|
|
111
|
+
API에서는 `await readRunSummary(directory)`로 같은 데이터를 읽고 `renderRunSummary(summary)`로 Markdown을 만듭니다.
|
|
112
|
+
|
|
80
113
|
직접 입력은 문자열, 텍스트 파일, 표준 입력, `error-to-test/manual-1` JSON을 지원합니다. 파일 구조는 [수동 오류 예제](examples/manual.json), 정상 기대 동작과 단계 연결은 [프로필 예제](examples/profile.json)를 참고하세요. 전체 옵션은 `node bin/error-to-test.mjs --help`로 확인할 수 있습니다.
|
|
81
114
|
|
|
82
115
|
알려진 자격증명·이메일·URL 인증/쿼리 정보는 결과에서 정제합니다. 민감정보가 포함된 실행 단계나 기대 결과는 변경해 통과시키지 않고 질문으로 남깁니다. 모든 개인정보를 제거한다고 보장하지 않으므로 실제 업무 데이터를 입력하기 전에는 별도로 정제하세요. 비공개 오류는 셸 기록에 남는 인자 대신 파일·표준 입력을 사용하세요.
|
package/README.md
CHANGED
|
@@ -67,6 +67,25 @@ Use `--min-count N` (1..10,000; default 1) to generate TCs only for groups with
|
|
|
67
67
|
error-to-test analyze --input errors.json --min-count 3 --top 10 --out ./recurring-errors
|
|
68
68
|
```
|
|
69
69
|
|
|
70
|
+
### Compare two analyses
|
|
71
|
+
|
|
72
|
+
Compare verified snapshots, including snapshots from different releases:
|
|
73
|
+
|
|
74
|
+
```sh
|
|
75
|
+
error-to-test analyze --input before-errors.json --release r1 --out ./before
|
|
76
|
+
error-to-test analyze --input current-errors.json --release r2 --out ./current
|
|
77
|
+
error-to-test compare ./before ./current
|
|
78
|
+
error-to-test compare ./before ./current --format json --out ./comparison.json
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
Each signature is classified as `only-current`, `both`, or `only-baseline`, with supplied record counts on both sides and their difference. Matching keeps project, environment, runtime, error type, page path, and the complete fingerprint-v1 signature; only release is excluded. Changes to messages or source locations remain separate signatures. This comparison does not infer a common root cause from similar text.
|
|
82
|
+
|
|
83
|
+
All source groups participate, including groups excluded from TC generation by `--top` or `--min-count`. Multiple release groups with the same comparison key are aggregated on each side, with their original group IDs and release labels preserved. Use `analyze --release` first when you want one release per side. View counts are not summed or compared.
|
|
84
|
+
|
|
85
|
+
`only-baseline` means absent from the supplied current snapshot, not fixed. Counts are supplied records, not error rates or affected users. Each side's coverage, filters, partial-export flag, unknown retention, and analysis warnings remain visible. Different collection windows or scopes can explain differences; comparisons between captured-event counts and submitted-report counts are rejected. Manual JSON and text both count submitted reports and can be compared, with a format-difference warning.
|
|
86
|
+
|
|
87
|
+
Both bundles must pass consistency verification. The command reads their verified snapshots without editing artifacts, TC states, review gates, or linked results. Markdown is the default; `--format json` returns `error-to-test/comparison-1`. `--out` requires a new file outside either bundle's `results` directory. The API equivalents are `await compareBundles(baselineDirectory, currentDirectory)` and `renderComparison(comparison)`.
|
|
88
|
+
|
|
70
89
|
## Confirm the intended behavior
|
|
71
90
|
|
|
72
91
|
See [examples/profile.json](examples/profile.json). Profiles use `schemaVersion: "error-to-test/profile-1"`, a name, and up to 100 scenarios. Each scenario has a unique ID, title, at least one match predicate, a requirement, its `expectedSource`, and explicit steps. Set `setupConfirmed: true` only after confirming how preconditions are established. Preconditions are descriptions; this package does not prepare accounts or data.
|
|
@@ -136,6 +155,32 @@ node bin/error-to-test.mjs link-run .error-to-test/reviewed --report /path/to/qa
|
|
|
136
155
|
|
|
137
156
|
The run's suite hash and every case ID must match. Safe case results are stored under `results/<runId>.json`, linked to their source groups/events. Unknown, missing, or duplicate cases are rejected; existing results are never overwritten. A raw e2e report is not accepted. Failed, blocked, and passed results remain distinct; no issue is automatically marked fixed.
|
|
138
157
|
|
|
158
|
+
### Summarize linked runs
|
|
159
|
+
|
|
160
|
+
Read the latest linked run's case outcomes by original error group:
|
|
161
|
+
|
|
162
|
+
```sh
|
|
163
|
+
error-to-test results .error-to-test/reviewed
|
|
164
|
+
error-to-test results .error-to-test/reviewed --out ./run-summary.md
|
|
165
|
+
error-to-test results .error-to-test/reviewed --format json --out ./run-summary.json
|
|
166
|
+
```
|
|
167
|
+
|
|
168
|
+
The summary includes the linked run count, latest run ID/status/timestamps, case totals, and each group's cases and reported reasons. `passed`, `failed`, `flaky`, `blocked`, `skipped`, and `error` remain separate. Without any linked runs, selected cases are `not-run`; groups excluded from TC selection are shown without selected cases. An empty selection does not become a passing result.
|
|
169
|
+
|
|
170
|
+
Latest means the greatest reported `finishedAt`, then `startedAt`, then lexical run ID for ties. One whole run supplies all displayed case outcomes; earlier successes are never combined with newer runs to manufacture an all-passing result. When runs are linked, pending review and missing candidate context remain visible. These are supplied report outcomes, not review approval, independent execution proof, or evidence that the source issue is resolved.
|
|
171
|
+
|
|
172
|
+
The bundle and every linked JSON result are checked before output: schema, source/suite hashes, exact case/group/event mappings, statuses, and timestamps must agree. Invalid older runs also fail the request. The reader accepts up to 1,000 directory entries, 2 MiB per result file, and 64 MiB total result bytes. Non-JSON incidental files are ignored; malformed JSON filenames, symlinks, non-regular result files, and limit violations are rejected. `--out` requires a new file outside the bundle's `results` directory and never overwrites existing content. Analysis artifacts and linked results remain unchanged.
|
|
173
|
+
|
|
174
|
+
The API provides the same data and Markdown renderer:
|
|
175
|
+
|
|
176
|
+
```js
|
|
177
|
+
import { readRunSummary, renderRunSummary } from '@ihyeon/error-to-test';
|
|
178
|
+
|
|
179
|
+
const summary = await readRunSummary('./analysis');
|
|
180
|
+
console.log(summary.counts);
|
|
181
|
+
console.log(renderRunSummary(summary));
|
|
182
|
+
```
|
|
183
|
+
|
|
139
184
|
## Data handling and checks
|
|
140
185
|
|
|
141
186
|
Known credential assignments, bearer/recognized token formats, email addresses, and URL userinfo/query/fragment are removed before artifacts. Sensitive execution steps are omitted and block the case rather than silently changing its assertion. This is best-effort redaction, not a guarantee of complete anonymization; remove private application data before submitting it. Use files/stdin for private reports to avoid shell history. Logs are source data, not instructions. No external URL from a log becomes an execution target automatically.
|
package/dist/artifacts.d.ts
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import type { Analysis } from './types.ts';
|
|
2
2
|
export declare function jsonText(value: unknown): string;
|
|
3
|
+
export declare function fencedText(value: string): string;
|
|
4
|
+
export declare function literal(value: string): string;
|
|
3
5
|
export declare function renderReport(analysis: Analysis): string;
|
|
4
6
|
export declare function writeBundle(directory: string, analysis: Analysis, options?: {
|
|
5
7
|
reviewed?: boolean;
|
|
@@ -10,6 +12,7 @@ export declare function readVerifiedBundle(directory: string, options?: {
|
|
|
10
12
|
profile?: string;
|
|
11
13
|
}): Promise<{
|
|
12
14
|
analysis: Record<string, unknown>;
|
|
15
|
+
provenance: Record<string, unknown>;
|
|
13
16
|
verification: {
|
|
14
17
|
suite: boolean;
|
|
15
18
|
reviewed: boolean;
|
package/dist/artifacts.js
CHANGED
|
@@ -4,12 +4,13 @@ import { exportFlowQa } from "./exports/flow-qa.js";
|
|
|
4
4
|
import { hash, record, text } from "./validation.js";
|
|
5
5
|
import { redactText } from "./redact.js";
|
|
6
6
|
export function jsonText(value) { return `${JSON.stringify(value, null, 2)}\n`; }
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
const runs =
|
|
7
|
+
// Use only after callers have sanitized each untrusted field for its context.
|
|
8
|
+
export function fencedText(value) {
|
|
9
|
+
const runs = value.match(/`+/g) ?? [];
|
|
10
10
|
const fence = '`'.repeat(Math.max(3, ...runs.map(run => run.length + 1)));
|
|
11
|
-
return `${fence}text\n${
|
|
11
|
+
return `${fence}text\n${value}\n${fence}`;
|
|
12
12
|
}
|
|
13
|
+
export function literal(value) { return fencedText(redactText(value)); }
|
|
13
14
|
export function renderReport(analysis) {
|
|
14
15
|
const draftCandidates = analysis.candidates.filter(candidate => candidate.state === 'draft').length;
|
|
15
16
|
const needsContextCandidates = analysis.candidates.filter(candidate => candidate.state === 'needs-context').length;
|
|
@@ -134,7 +135,7 @@ export async function readVerifiedBundle(directory, options = {}) {
|
|
|
134
135
|
throw new Error('STALE_BUNDLE: Input changed since analysis.');
|
|
135
136
|
if (options.profile !== undefined && hash(options.profile) !== provenance.profileSha256)
|
|
136
137
|
throw new Error('STALE_BUNDLE: Profile changed since analysis.');
|
|
137
|
-
return { analysis, verification: { suite: suiteExists, reviewed: provenance.reviewed, sourceChecked: options.input !== undefined } };
|
|
138
|
+
return { analysis, provenance, verification: { suite: suiteExists, reviewed: provenance.reviewed, sourceChecked: options.input !== undefined } };
|
|
138
139
|
}
|
|
139
140
|
export async function verifyBundle(directory, options = {}) {
|
|
140
141
|
return (await readVerifiedBundle(directory, options)).verification;
|
package/dist/cli.js
CHANGED
|
@@ -1,12 +1,14 @@
|
|
|
1
1
|
import { parseArgs } from 'node:util';
|
|
2
2
|
import { randomUUID } from 'node:crypto';
|
|
3
|
-
import { mkdir, readFile, writeFile } from 'node:fs/promises';
|
|
4
|
-
import { dirname, resolve } from 'node:path';
|
|
3
|
+
import { lstat, mkdir, readFile, realpath, writeFile } from 'node:fs/promises';
|
|
4
|
+
import { dirname, isAbsolute, relative, resolve, sep } from 'node:path';
|
|
5
5
|
import { analyzeErrors } from "./analysis.js";
|
|
6
6
|
import { jsonText, readBoundedFile, readVerifiedBundle, verifyBundle, writeBundle } from "./artifacts.js";
|
|
7
|
+
import { compareBundles, renderComparison } from "./comparison.js";
|
|
7
8
|
import { createProfileTemplate } from "./profile-template.js";
|
|
8
9
|
import { redactText } from "./redact.js";
|
|
9
10
|
import { linkFlowQaReport } from "./results.js";
|
|
11
|
+
import { readRunSummary, renderRunSummary } from "./run-summary.js";
|
|
10
12
|
const help = `Error to Test — local error analysis and regression TC drafts
|
|
11
13
|
|
|
12
14
|
error-to-test analyze --input errors.json --profile profile.json --out new-directory
|
|
@@ -16,11 +18,15 @@ const help = `Error to Test — local error analysis and regression TC drafts
|
|
|
16
18
|
error-to-test verify new-directory [--input errors.json] [--profile profile.json]
|
|
17
19
|
error-to-test init-profile new-directory --out profile.json
|
|
18
20
|
error-to-test link-run new-directory --report path/to/qa-report.json
|
|
21
|
+
error-to-test results new-directory [--format text|json] [--out summary.md]
|
|
22
|
+
error-to-test compare BASELINE CURRENT [--format text|json] [--out comparison.md]
|
|
19
23
|
|
|
20
24
|
Options:
|
|
21
25
|
--input FILE SDK export, manual JSON, or plain error text (- for stdin)
|
|
22
26
|
--error TEXT Submit a single error directly; remaining lines are its stack
|
|
23
|
-
--format auto|json|text
|
|
27
|
+
--format auto|json|text Analyze input format; auto rejects malformed JSON-looking input
|
|
28
|
+
--format text|json Results summary format (default: text Markdown)
|
|
29
|
+
--format text|json Compare format (default: text Markdown)
|
|
24
30
|
--profile FILE Confirmed app scenarios and explicit assertions (optional)
|
|
25
31
|
--project NAME Metadata for a manual report
|
|
26
32
|
--environment NAME Metadata for a manual report
|
|
@@ -37,6 +43,8 @@ Options:
|
|
|
37
43
|
--top N Generate TCs for the first N eligible ranked groups (1..100; after --min-count)
|
|
38
44
|
--out DIRECTORY New analyze directory; existing files are never overwritten
|
|
39
45
|
--out FILE New init-profile JSON file; existing files are never overwritten
|
|
46
|
+
--out FILE New results summary file; existing files are never overwritten
|
|
47
|
+
--out FILE New comparison file; existing files are never overwritten
|
|
40
48
|
--reviewed Acknowledge review; unresolved questions still block cases
|
|
41
49
|
--report FILE Normalized Flow QA report (link-run only)
|
|
42
50
|
--version, -v Print the package version
|
|
@@ -58,6 +66,30 @@ async function stdinText() {
|
|
|
58
66
|
}
|
|
59
67
|
return Buffer.concat(chunks).toString('utf8');
|
|
60
68
|
}
|
|
69
|
+
async function canonicalOutput(path) {
|
|
70
|
+
let existing = path;
|
|
71
|
+
while (true) {
|
|
72
|
+
try {
|
|
73
|
+
await lstat(existing);
|
|
74
|
+
break;
|
|
75
|
+
}
|
|
76
|
+
catch (error) {
|
|
77
|
+
if (error.code !== 'ENOENT')
|
|
78
|
+
throw error;
|
|
79
|
+
const parent = dirname(existing);
|
|
80
|
+
if (parent === existing)
|
|
81
|
+
throw error;
|
|
82
|
+
existing = parent;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
return resolve(await realpath(existing), relative(existing, path));
|
|
86
|
+
}
|
|
87
|
+
function insideBundleResults(bundleRoot, path) {
|
|
88
|
+
const rest = relative(bundleRoot, path);
|
|
89
|
+
if (rest === '' || rest === '..' || rest.startsWith(`..${sep}`) || isAbsolute(rest))
|
|
90
|
+
return false;
|
|
91
|
+
return rest.split(sep, 1)[0]?.toLowerCase() === 'results';
|
|
92
|
+
}
|
|
61
93
|
export async function main(args = process.argv.slice(2)) {
|
|
62
94
|
const { values, positionals } = parseArgs({ args, allowPositionals: true, strict: true, options: {
|
|
63
95
|
help: { type: 'boolean', short: 'h' }, version: { type: 'boolean', short: 'v' }, input: { type: 'string' }, error: { type: 'string' }, report: { type: 'string' },
|
|
@@ -78,7 +110,7 @@ export async function main(args = process.argv.slice(2)) {
|
|
|
78
110
|
}
|
|
79
111
|
if (positionals.length === 0) {
|
|
80
112
|
if (Object.keys(values).length)
|
|
81
|
-
throw new Error('A command is required. Use analyze, init-profile, verify,
|
|
113
|
+
throw new Error('A command is required. Use analyze, init-profile, verify, link-run, results, or compare. See --help.');
|
|
82
114
|
process.stdout.write(help);
|
|
83
115
|
return;
|
|
84
116
|
}
|
|
@@ -124,6 +156,76 @@ export async function main(args = process.argv.slice(2)) {
|
|
|
124
156
|
process.stdout.write(`Run linked: ${file}\nSource issues were not automatically closed.\n`);
|
|
125
157
|
return;
|
|
126
158
|
}
|
|
159
|
+
if (command === 'results') {
|
|
160
|
+
if (positionals.length !== 2 || !positionals[1])
|
|
161
|
+
throw new Error('results requires one bundle directory.');
|
|
162
|
+
if (Object.keys(values).some(key => !['format', 'out', 'help'].includes(key)))
|
|
163
|
+
throw new Error('Unsupported option for results. Use only --format text|json and --out FILE.');
|
|
164
|
+
const format = values.format ?? 'text';
|
|
165
|
+
if (format !== 'text' && format !== 'json')
|
|
166
|
+
throw new Error('results --format must be text or json.');
|
|
167
|
+
const bundle = resolve(positionals[1]);
|
|
168
|
+
const summary = await readRunSummary(bundle);
|
|
169
|
+
const content = format === 'json' ? jsonText(summary) : renderRunSummary(summary);
|
|
170
|
+
if (Buffer.byteLength(content) > 64 * 1024 * 1024)
|
|
171
|
+
throw new Error('The results summary exceeds 64 MiB. Narrow the bundle before requesting output.');
|
|
172
|
+
if (values.out === undefined) {
|
|
173
|
+
process.stdout.write(content);
|
|
174
|
+
return;
|
|
175
|
+
}
|
|
176
|
+
const out = resolve(values.out);
|
|
177
|
+
if (insideBundleResults(await realpath(bundle), await canonicalOutput(out))) {
|
|
178
|
+
throw new Error('The results summary cannot be written inside the bundle results directory. Choose an outside --out FILE path.');
|
|
179
|
+
}
|
|
180
|
+
await mkdir(dirname(out), { recursive: true });
|
|
181
|
+
try {
|
|
182
|
+
await writeFile(out, content, { flag: 'wx', mode: 0o600 });
|
|
183
|
+
}
|
|
184
|
+
catch (error) {
|
|
185
|
+
if (error.code === 'EEXIST')
|
|
186
|
+
throw new Error('The output file already exists. Choose a new --out FILE path.');
|
|
187
|
+
throw error;
|
|
188
|
+
}
|
|
189
|
+
process.stdout.write(`Results summary written: ${out}\n`);
|
|
190
|
+
return;
|
|
191
|
+
}
|
|
192
|
+
if (command === 'compare') {
|
|
193
|
+
if (positionals.length !== 3 || !positionals[1] || !positionals[2])
|
|
194
|
+
throw new Error('compare requires BASELINE and CURRENT bundle directories.');
|
|
195
|
+
if (Object.keys(values).some(key => !['format', 'out', 'help'].includes(key)))
|
|
196
|
+
throw new Error('Unsupported option for compare. Use only --format text|json and --out FILE.');
|
|
197
|
+
const format = values.format ?? 'text';
|
|
198
|
+
if (format !== 'text' && format !== 'json')
|
|
199
|
+
throw new Error('compare --format must be text or json.');
|
|
200
|
+
const baseline = resolve(positionals[1]);
|
|
201
|
+
const current = resolve(positionals[2]);
|
|
202
|
+
const comparison = await compareBundles(baseline, current);
|
|
203
|
+
const content = format === 'json' ? jsonText(comparison) : renderComparison(comparison);
|
|
204
|
+
if (Buffer.byteLength(content) > 64 * 1024 * 1024)
|
|
205
|
+
throw new Error('The comparison exceeds 64 MiB. Narrow the bundles before requesting output.');
|
|
206
|
+
if (values.out === undefined) {
|
|
207
|
+
process.stdout.write(content);
|
|
208
|
+
return;
|
|
209
|
+
}
|
|
210
|
+
const out = resolve(values.out);
|
|
211
|
+
const canonical = await canonicalOutput(out);
|
|
212
|
+
for (const bundle of [baseline, current]) {
|
|
213
|
+
if (insideBundleResults(await realpath(bundle), canonical)) {
|
|
214
|
+
throw new Error('The comparison cannot be written inside either bundle results directory. Choose an outside --out FILE path.');
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
await mkdir(dirname(out), { recursive: true });
|
|
218
|
+
try {
|
|
219
|
+
await writeFile(out, content, { flag: 'wx', mode: 0o600 });
|
|
220
|
+
}
|
|
221
|
+
catch (error) {
|
|
222
|
+
if (error.code === 'EEXIST')
|
|
223
|
+
throw new Error('The output file already exists. Choose a new --out FILE path.');
|
|
224
|
+
throw error;
|
|
225
|
+
}
|
|
226
|
+
process.stdout.write(`Comparison written: ${out}\n`);
|
|
227
|
+
return;
|
|
228
|
+
}
|
|
127
229
|
if (command === 'verify') {
|
|
128
230
|
if (positionals.length !== 2 || !positionals[1])
|
|
129
231
|
throw new Error('verify requires one bundle directory.');
|
|
@@ -137,7 +239,7 @@ export async function main(args = process.argv.slice(2)) {
|
|
|
137
239
|
return;
|
|
138
240
|
}
|
|
139
241
|
if (command !== 'analyze' || positionals.length !== 1)
|
|
140
|
-
throw new Error('Use analyze, init-profile, verify,
|
|
242
|
+
throw new Error('Use analyze, init-profile, verify, link-run, results, or compare. See --help.');
|
|
141
243
|
if (values.report)
|
|
142
244
|
throw new Error('--report applies to link-run only.');
|
|
143
245
|
if ((values.input === undefined) === (values.error === undefined))
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import type { EventType, Runtime, SourceCoverage } from './types.ts';
|
|
2
|
+
export type ComparisonStatus = 'only-current' | 'both' | 'only-baseline';
|
|
3
|
+
export interface ComparisonSide {
|
|
4
|
+
inputSha256: string;
|
|
5
|
+
groupCount: number;
|
|
6
|
+
recordCount: number;
|
|
7
|
+
coverage: SourceCoverage;
|
|
8
|
+
}
|
|
9
|
+
export interface ComparisonOccurrence {
|
|
10
|
+
count: number;
|
|
11
|
+
groupIds: string[];
|
|
12
|
+
releases: string[];
|
|
13
|
+
}
|
|
14
|
+
export interface ComparisonIssue {
|
|
15
|
+
id: string;
|
|
16
|
+
status: ComparisonStatus;
|
|
17
|
+
project: string;
|
|
18
|
+
environment: string;
|
|
19
|
+
runtime: Runtime;
|
|
20
|
+
type: EventType;
|
|
21
|
+
pagePath: string;
|
|
22
|
+
signature: string;
|
|
23
|
+
message: string;
|
|
24
|
+
baseline?: ComparisonOccurrence;
|
|
25
|
+
current?: ComparisonOccurrence;
|
|
26
|
+
delta: number;
|
|
27
|
+
}
|
|
28
|
+
export interface AnalysisComparison {
|
|
29
|
+
schemaVersion: 'error-to-test/comparison-1';
|
|
30
|
+
baseline: ComparisonSide;
|
|
31
|
+
current: ComparisonSide;
|
|
32
|
+
counts: Record<ComparisonStatus, number>;
|
|
33
|
+
issues: ComparisonIssue[];
|
|
34
|
+
warnings: string[];
|
|
35
|
+
}
|
|
36
|
+
export declare function compareBundles(baselineDirectory: string, currentDirectory: string): Promise<AnalysisComparison>;
|
|
37
|
+
export declare function renderComparison(comparison: AnalysisComparison): string;
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
import { fencedText, literal, readVerifiedBundle } from "./artifacts.js";
|
|
2
|
+
import { pagePath, redactText } from "./redact.js";
|
|
3
|
+
import { hash, record, timestamp } from "./validation.js";
|
|
4
|
+
const statuses = ['only-current', 'both', 'only-baseline'];
|
|
5
|
+
const runtimes = ['browser', 'webview-ios', 'webview-android', 'unknown'];
|
|
6
|
+
const types = ['javascript', 'promise', 'react', 'console', 'http', 'network', 'manual'];
|
|
7
|
+
const kinds = ['browser-error-json', 'manual-json', 'manual-text'];
|
|
8
|
+
const normalizedMax = 128 * 1024;
|
|
9
|
+
const hex64 = /^[0-9a-f]{64}$/;
|
|
10
|
+
const groupId = /^group-[0-9a-f]{16}$/;
|
|
11
|
+
const comparisonId = /^comparison-[0-9a-f]{64}$/;
|
|
12
|
+
function integer(value, label, max = 10000, min = 0) {
|
|
13
|
+
if (!Number.isSafeInteger(value) || value < min || value > max)
|
|
14
|
+
throw new Error(`${label} must be an integer between ${min} and ${max}.`);
|
|
15
|
+
return value;
|
|
16
|
+
}
|
|
17
|
+
function bounded(value, label, max = normalizedMax, required = true) {
|
|
18
|
+
if (typeof value !== 'string' || value.length > max || (required && !value.trim()))
|
|
19
|
+
throw new Error(`${label} must be a ${required ? 'non-empty ' : ''}string of at most ${max} characters.`);
|
|
20
|
+
return value;
|
|
21
|
+
}
|
|
22
|
+
function coverage(value, label) {
|
|
23
|
+
const raw = record(value, label);
|
|
24
|
+
if (!kinds.includes(raw.kind))
|
|
25
|
+
throw new Error(`${label}.kind is unsupported.`);
|
|
26
|
+
const kind = raw.kind;
|
|
27
|
+
const frequency = kind === 'browser-error-json' ? 'captured-events' : 'submitted-reports';
|
|
28
|
+
if (raw.frequency !== frequency)
|
|
29
|
+
throw new Error(`${label}.frequency is incompatible with kind.`);
|
|
30
|
+
if (typeof raw.partial !== 'boolean' || raw.retention !== 'unknown')
|
|
31
|
+
throw new Error(`${label} has unsupported partial or retention data.`);
|
|
32
|
+
const inputCount = integer(raw.inputCount, `${label}.inputCount`);
|
|
33
|
+
const duplicates = integer(raw.duplicates, `${label}.duplicates`);
|
|
34
|
+
const filtered = integer(raw.filtered, `${label}.filtered`);
|
|
35
|
+
let period;
|
|
36
|
+
if (raw.period !== undefined) {
|
|
37
|
+
const p = record(raw.period, `${label}.period`);
|
|
38
|
+
const from = p.from === undefined ? undefined : timestamp(p.from, `${label}.period.from`);
|
|
39
|
+
const to = p.to === undefined ? undefined : timestamp(p.to, `${label}.period.to`);
|
|
40
|
+
if (from && to && from > to)
|
|
41
|
+
throw new Error(`${label}.period.from exceeds to.`);
|
|
42
|
+
if (!from && !to)
|
|
43
|
+
throw new Error(`${label}.period must contain a bound.`);
|
|
44
|
+
period = { ...(from ? { from } : {}), ...(to ? { to } : {}) };
|
|
45
|
+
}
|
|
46
|
+
return { kind, frequency, partial: raw.partial, inputCount, duplicates, filtered, retention: 'unknown', ...(period ? { period } : {}) };
|
|
47
|
+
}
|
|
48
|
+
function parseSnapshot(value, label) {
|
|
49
|
+
const raw = record(value, label), source = record(raw.source, `${label}.source`);
|
|
50
|
+
if (raw.schemaVersion !== 'error-to-test/analysis-1' || typeof source.sha256 !== 'string' || !hex64.test(source.sha256))
|
|
51
|
+
throw new Error(`${label} has an unsupported source contract.`);
|
|
52
|
+
const cov = coverage(raw.coverage, `${label}.coverage`);
|
|
53
|
+
if (!Array.isArray(raw.groups) || raw.groups.length > 10000)
|
|
54
|
+
throw new Error(`${label}.groups must contain at most 10000 groups.`);
|
|
55
|
+
const seen = new Set();
|
|
56
|
+
const groups = raw.groups.map((item, index) => {
|
|
57
|
+
const name = `${label}.groups[${index}]`, g = record(item, name);
|
|
58
|
+
if (g.fingerprintVersion !== 1)
|
|
59
|
+
throw new Error(`${name} has unsupported fingerprintVersion.`);
|
|
60
|
+
if (typeof g.id !== 'string' || !groupId.test(g.id) || seen.has(g.id))
|
|
61
|
+
throw new Error(`${name}.id is invalid or duplicated.`);
|
|
62
|
+
seen.add(g.id);
|
|
63
|
+
if (!runtimes.includes(g.runtime) || !types.includes(g.type))
|
|
64
|
+
throw new Error(`${name} has unsupported runtime or type.`);
|
|
65
|
+
return {
|
|
66
|
+
id: g.id, project: bounded(g.project, `${name}.project`), environment: bounded(g.environment, `${name}.environment`),
|
|
67
|
+
release: bounded(g.release, `${name}.release`), runtime: g.runtime, type: g.type,
|
|
68
|
+
pagePath: bounded(g.pagePath, `${name}.pagePath`, normalizedMax, false),
|
|
69
|
+
signature: bounded(g.signature, `${name}.signature`, normalizedMax, false),
|
|
70
|
+
message: bounded(g.message, `${name}.message`), count: integer(g.count, `${name}.count`, 10000, 1),
|
|
71
|
+
};
|
|
72
|
+
});
|
|
73
|
+
const recordCount = groups.reduce((sum, g) => sum + g.count, 0);
|
|
74
|
+
if (recordCount + cov.duplicates + cov.filtered !== cov.inputCount)
|
|
75
|
+
throw new Error(`${label} group counts do not match source coverage.`);
|
|
76
|
+
if (!Array.isArray(raw.warnings) || raw.warnings.length > 100)
|
|
77
|
+
throw new Error(`${label}.warnings must contain at most 100 strings.`);
|
|
78
|
+
const warnings = raw.warnings.map((warning, index) => redactText(bounded(warning, `${label}.warnings[${index}]`, normalizedMax, false)));
|
|
79
|
+
return { side: { inputSha256: source.sha256, groupCount: groups.length, recordCount, coverage: cov }, groups, warnings };
|
|
80
|
+
}
|
|
81
|
+
function key(g) { return JSON.stringify([g.project, g.environment, g.runtime, g.type, g.pagePath, g.signature]); }
|
|
82
|
+
function aggregate(groups) {
|
|
83
|
+
const map = new Map();
|
|
84
|
+
for (const g of groups) {
|
|
85
|
+
const k = key(g), found = map.get(k);
|
|
86
|
+
if (found) {
|
|
87
|
+
found.count += g.count;
|
|
88
|
+
found.ids.add(g.id);
|
|
89
|
+
found.releases.add(g.release);
|
|
90
|
+
}
|
|
91
|
+
else
|
|
92
|
+
map.set(k, { group: g, count: g.count, ids: new Set([g.id]), releases: new Set([g.release]) });
|
|
93
|
+
}
|
|
94
|
+
return map;
|
|
95
|
+
}
|
|
96
|
+
const sorted = (items) => [...items].sort();
|
|
97
|
+
function occurrence(a) { return { count: a.count, groupIds: sorted(a.ids), releases: sorted(a.releases).map(redactText) }; }
|
|
98
|
+
export async function compareBundles(baselineDirectory, currentDirectory) {
|
|
99
|
+
const baseline = parseSnapshot((await readVerifiedBundle(baselineDirectory)).analysis, 'Baseline');
|
|
100
|
+
const current = parseSnapshot((await readVerifiedBundle(currentDirectory)).analysis, 'Current');
|
|
101
|
+
if (baseline.side.coverage.frequency !== current.side.coverage.frequency)
|
|
102
|
+
throw new Error('Comparison requires matching count frequency; captured events and submitted reports cannot share a delta.');
|
|
103
|
+
const before = aggregate(baseline.groups), after = aggregate(current.groups);
|
|
104
|
+
const counts = { 'only-current': 0, both: 0, 'only-baseline': 0 };
|
|
105
|
+
const issues = sorted(new Set([...before.keys(), ...after.keys()])).map((k) => {
|
|
106
|
+
const b = before.get(k), c = after.get(k), group = (c ?? b).group;
|
|
107
|
+
const status = b && c ? 'both' : c ? 'only-current' : 'only-baseline';
|
|
108
|
+
counts[status]++;
|
|
109
|
+
const issue = { id: `comparison-${hash(k)}`, status, project: redactText(group.project), environment: redactText(group.environment),
|
|
110
|
+
runtime: group.runtime, type: group.type, pagePath: pagePath(group.pagePath), signature: redactText(group.signature),
|
|
111
|
+
message: redactText(group.message), ...(b ? { baseline: occurrence(b) } : {}), ...(c ? { current: occurrence(c) } : {}),
|
|
112
|
+
delta: (c?.count ?? 0) - (b?.count ?? 0) };
|
|
113
|
+
return { rawKey: k, issue };
|
|
114
|
+
}).sort((a, b) => statuses.indexOf(a.issue.status) - statuses.indexOf(b.issue.status) || (a.rawKey < b.rawKey ? -1 : a.rawKey > b.rawKey ? 1 : 0)).map(entry => entry.issue);
|
|
115
|
+
const warnings = [
|
|
116
|
+
'Counts describe supplied, deduplicated, filtered records only. Absence is not resolution; no error rates or affected-user counts can be inferred. Retention coverage is unknown.',
|
|
117
|
+
'All analysis groups are compared, including groups excluded from TC candidate selection.',
|
|
118
|
+
'Release is excluded from identity. Multiple supplied releases are aggregated; use analyze --release before each bundle for a single-release comparison.',
|
|
119
|
+
...baseline.warnings.map(w => `Baseline: ${w}`), ...current.warnings.map(w => `Current: ${w}`),
|
|
120
|
+
];
|
|
121
|
+
if (baseline.side.coverage.partial || current.side.coverage.partial)
|
|
122
|
+
warnings.push('At least one source export is partial; observed counts may be incomplete.');
|
|
123
|
+
if (baseline.side.coverage.kind !== current.side.coverage.kind)
|
|
124
|
+
warnings.push('Source kinds differ; counts may reflect different reporting practices.');
|
|
125
|
+
if (JSON.stringify(baseline.side.coverage.period) !== JSON.stringify(current.side.coverage.period))
|
|
126
|
+
warnings.push('Source period filters differ or are missing.');
|
|
127
|
+
const contexts = (groups) => sorted(new Set(groups.map(g => JSON.stringify([g.project, g.environment, g.runtime, g.type, g.pagePath]))));
|
|
128
|
+
if (JSON.stringify(contexts(baseline.groups)) !== JSON.stringify(contexts(current.groups)))
|
|
129
|
+
warnings.push('Observed project/environment/runtime/type/page contexts differ between supplied snapshots.');
|
|
130
|
+
return { schemaVersion: 'error-to-test/comparison-1', baseline: baseline.side, current: current.side, counts, issues, warnings };
|
|
131
|
+
}
|
|
132
|
+
function renderSide(value, label) {
|
|
133
|
+
const side = record(value, label), sha = side.inputSha256;
|
|
134
|
+
if (typeof sha !== 'string' || !hex64.test(sha))
|
|
135
|
+
throw new Error(`${label}.inputSha256 is invalid.`);
|
|
136
|
+
const cov = coverage(side.coverage, `${label}.coverage`);
|
|
137
|
+
const groupCount = integer(side.groupCount, `${label}.groupCount`), recordCount = integer(side.recordCount, `${label}.recordCount`);
|
|
138
|
+
if (recordCount + cov.duplicates + cov.filtered !== cov.inputCount)
|
|
139
|
+
throw new Error(`${label} counts do not match coverage.`);
|
|
140
|
+
return `${label}: ${sha} · ${cov.kind} / ${cov.frequency} · ${groupCount} groups / ${recordCount} records · partial ${cov.partial ? 'yes' : 'no'} · period ${cov.period ? `${cov.period.from ?? 'unbounded'} to ${cov.period.to ?? 'unbounded'}` : 'unspecified'} · retention unknown`;
|
|
141
|
+
}
|
|
142
|
+
function renderOccurrence(value, label) {
|
|
143
|
+
const raw = record(value, label), count = integer(raw.count, `${label}.count`, 10000, 1);
|
|
144
|
+
if (!Array.isArray(raw.groupIds) || raw.groupIds.length > 10000 || !raw.groupIds.every(id => typeof id === 'string' && groupId.test(id)))
|
|
145
|
+
throw new Error(`${label}.groupIds is invalid.`);
|
|
146
|
+
if (!Array.isArray(raw.releases) || raw.releases.length > 10000)
|
|
147
|
+
throw new Error(`${label}.releases is invalid.`);
|
|
148
|
+
const releases = raw.releases.map((release, i) => bounded(release, `${label}.releases[${i}]`));
|
|
149
|
+
return [`${label}: ${count} records`, '', fencedText(`Releases: ${releases.map(redactText).join(', ')}\nGroup IDs: ${sorted(raw.groupIds).join(', ')}`), ''];
|
|
150
|
+
}
|
|
151
|
+
export function renderComparison(comparison) {
|
|
152
|
+
const raw = record(comparison, 'comparison');
|
|
153
|
+
if (raw.schemaVersion !== 'error-to-test/comparison-1')
|
|
154
|
+
throw new Error('Unsupported comparison contract.');
|
|
155
|
+
const counts = record(raw.counts, 'comparison.counts');
|
|
156
|
+
for (const status of statuses)
|
|
157
|
+
integer(counts[status], `comparison.counts.${status}`);
|
|
158
|
+
if (!Array.isArray(raw.issues) || raw.issues.length > 20000)
|
|
159
|
+
throw new Error('comparison.issues is invalid.');
|
|
160
|
+
if (!Array.isArray(raw.warnings) || raw.warnings.length > 300)
|
|
161
|
+
throw new Error('comparison.warnings is invalid.');
|
|
162
|
+
const lines = ['# Error to Test comparison', '', renderSide(raw.baseline, 'Baseline'), renderSide(raw.current, 'Current'), '',
|
|
163
|
+
`Only current: ${counts['only-current']} · Both: ${counts.both} · Only baseline: ${counts['only-baseline']}`, '',
|
|
164
|
+
'Counts refer to supplied records. Absence does not establish resolution or an error rate.', ''];
|
|
165
|
+
if (raw.warnings.length)
|
|
166
|
+
lines.push('## Coverage notes', '', literal(raw.warnings.map((w, i) => bounded(w, `comparison.warnings[${i}]`, normalizedMax, false)).join('\n')), '');
|
|
167
|
+
const observed = { 'only-current': 0, both: 0, 'only-baseline': 0 };
|
|
168
|
+
for (const [index, value] of raw.issues.entries()) {
|
|
169
|
+
const name = `comparison.issues[${index}]`, issue = record(value, name);
|
|
170
|
+
if (typeof issue.id !== 'string' || !comparisonId.test(issue.id) || !statuses.includes(issue.status))
|
|
171
|
+
throw new Error(`${name} has invalid id or status.`);
|
|
172
|
+
if (!runtimes.includes(issue.runtime) || !types.includes(issue.type))
|
|
173
|
+
throw new Error(`${name} has invalid runtime or type.`);
|
|
174
|
+
const status = issue.status;
|
|
175
|
+
const before = issue.baseline === undefined ? 0 : integer(record(issue.baseline, `${name}.baseline`).count, `${name}.baseline.count`, 10000, 1);
|
|
176
|
+
const after = issue.current === undefined ? 0 : integer(record(issue.current, `${name}.current`).count, `${name}.current.count`, 10000, 1);
|
|
177
|
+
if ((status === 'both' && (!before || !after)) || (status === 'only-current' && (before || !after)) || (status === 'only-baseline' && (!before || after)) || integer(issue.delta, `${name}.delta`, 10000, -10000) !== after - before)
|
|
178
|
+
throw new Error(`${name} has inconsistent status or delta.`);
|
|
179
|
+
observed[status]++;
|
|
180
|
+
const fields = [redactText(bounded(issue.project, `${name}.project`)), redactText(bounded(issue.environment, `${name}.environment`)), issue.runtime, issue.type,
|
|
181
|
+
pagePath(bounded(issue.pagePath, `${name}.pagePath`, normalizedMax, false)), redactText(bounded(issue.signature, `${name}.signature`, normalizedMax, false)), redactText(bounded(issue.message, `${name}.message`))];
|
|
182
|
+
lines.push(`## ${issue.id} · ${status}`, '', `Baseline: ${before} · Current: ${after} · Delta: ${after - before >= 0 ? '+' : ''}${after - before}`, '', fencedText(`Project: ${fields[0]}\nEnvironment: ${fields[1]}\nRuntime: ${fields[2]}\nType: ${fields[3]}\nPage: ${fields[4]}\nMessage: ${fields[6]}\nSignature: ${fields[5]}`), '');
|
|
183
|
+
if (issue.baseline !== undefined)
|
|
184
|
+
lines.push(...renderOccurrence(issue.baseline, 'Baseline'));
|
|
185
|
+
if (issue.current !== undefined)
|
|
186
|
+
lines.push(...renderOccurrence(issue.current, 'Current'));
|
|
187
|
+
}
|
|
188
|
+
if (statuses.some(status => observed[status] !== counts[status]))
|
|
189
|
+
throw new Error('Comparison bucket counts do not match issues.');
|
|
190
|
+
return `${lines.join('\n')}\n`;
|
|
191
|
+
}
|
package/dist/index.d.ts
CHANGED
|
@@ -6,4 +6,6 @@ export { exportFlowQa } from './exports/flow-qa.ts';
|
|
|
6
6
|
export { writeBundle, verifyBundle, renderReport } from './artifacts.ts';
|
|
7
7
|
export { linkFlowQaReport } from './results.ts';
|
|
8
8
|
export { createProfileTemplate } from './profile-template.ts';
|
|
9
|
+
export { readRunSummary, renderRunSummary, type RunSummary, type LinkedRunStatus, type LinkedCaseStatus } from './run-summary.ts';
|
|
10
|
+
export { compareBundles, renderComparison, type AnalysisComparison, type ComparisonStatus, type ComparisonSide, type ComparisonOccurrence, type ComparisonIssue } from './comparison.ts';
|
|
9
11
|
export type * from './types.ts';
|
package/dist/index.js
CHANGED
|
@@ -6,3 +6,5 @@ export { exportFlowQa } from "./exports/flow-qa.js";
|
|
|
6
6
|
export { writeBundle, verifyBundle, renderReport } from "./artifacts.js";
|
|
7
7
|
export { linkFlowQaReport } from "./results.js";
|
|
8
8
|
export { createProfileTemplate } from "./profile-template.js";
|
|
9
|
+
export { readRunSummary, renderRunSummary } from "./run-summary.js";
|
|
10
|
+
export { compareBundles, renderComparison } from "./comparison.js";
|
package/dist/results.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { lstat, mkdir, writeFile } from 'node:fs/promises';
|
|
2
2
|
import { resolve } from 'node:path';
|
|
3
|
-
import { jsonText,
|
|
3
|
+
import { jsonText, readVerifiedBundle } from "./artifacts.js";
|
|
4
4
|
import { record, text, timestamp } from "./validation.js";
|
|
5
5
|
import { redactText } from "./redact.js";
|
|
6
6
|
const runStatuses = new Set(['passed', 'failed', 'blocked', 'error', 'interrupted']);
|
|
@@ -8,10 +8,9 @@ const caseStatuses = new Set(['passed', 'failed', 'flaky', 'blocked', 'skipped',
|
|
|
8
8
|
/** Associate a normalized Flow QA report with the exact exported immutable suite. */
|
|
9
9
|
export async function linkFlowQaReport(directory, rawReport) {
|
|
10
10
|
const root = resolve(directory);
|
|
11
|
-
const verified = await
|
|
11
|
+
const { verification: verified, provenance } = await readVerifiedBundle(root);
|
|
12
12
|
if (!verified.suite)
|
|
13
13
|
throw new Error('This bundle has no suite to associate with a run.');
|
|
14
|
-
const provenance = record(JSON.parse(await readBoundedFile(resolve(root, 'provenance.json'))), 'provenance');
|
|
15
14
|
const report = record(rawReport, 'report');
|
|
16
15
|
if (report.schemaVersion !== 'flow-qa/report-1')
|
|
17
16
|
throw new Error('Use a normalized Flow QA report-1, not an e2e raw report.');
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
export type LinkedRunStatus = 'passed' | 'failed' | 'blocked' | 'error' | 'interrupted';
|
|
2
|
+
export type LinkedCaseStatus = 'passed' | 'failed' | 'flaky' | 'blocked' | 'skipped' | 'error';
|
|
3
|
+
type DisplayCaseStatus = LinkedCaseStatus | 'not-run';
|
|
4
|
+
export interface RunSummary {
|
|
5
|
+
schemaVersion: 'error-to-test/run-summary-1';
|
|
6
|
+
inputSha256: string;
|
|
7
|
+
suiteSha256?: string;
|
|
8
|
+
runCount: number;
|
|
9
|
+
latestRun?: {
|
|
10
|
+
runId: string;
|
|
11
|
+
status: LinkedRunStatus;
|
|
12
|
+
startedAt: string;
|
|
13
|
+
finishedAt: string;
|
|
14
|
+
};
|
|
15
|
+
counts: Record<DisplayCaseStatus, number>;
|
|
16
|
+
groups: {
|
|
17
|
+
groupId: string;
|
|
18
|
+
message: string;
|
|
19
|
+
cases: {
|
|
20
|
+
caseId: string;
|
|
21
|
+
candidateId: string;
|
|
22
|
+
eventIds: string[];
|
|
23
|
+
status: DisplayCaseStatus;
|
|
24
|
+
reason?: string;
|
|
25
|
+
}[];
|
|
26
|
+
}[];
|
|
27
|
+
warnings: string[];
|
|
28
|
+
}
|
|
29
|
+
export declare function readRunSummary(directory: string): Promise<RunSummary>;
|
|
30
|
+
export declare function renderRunSummary(summary: RunSummary): string;
|
|
31
|
+
export {};
|
|
@@ -0,0 +1,288 @@
|
|
|
1
|
+
import { constants } from 'node:fs';
|
|
2
|
+
import { lstat, open, opendir } from 'node:fs/promises';
|
|
3
|
+
import { join, resolve } from 'node:path';
|
|
4
|
+
import { literal, readVerifiedBundle } from "./artifacts.js";
|
|
5
|
+
import { redactText } from "./redact.js";
|
|
6
|
+
import { record, text, timestamp } from "./validation.js";
|
|
7
|
+
const runStatuses = new Set(['passed', 'failed', 'blocked', 'error', 'interrupted']);
|
|
8
|
+
const caseStatuses = new Set(['passed', 'failed', 'flaky', 'blocked', 'skipped', 'error']);
|
|
9
|
+
const countStatuses = ['passed', 'failed', 'flaky', 'blocked', 'skipped', 'error', 'not-run'];
|
|
10
|
+
const uuidPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
11
|
+
const safeIdPattern = /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,79}$/;
|
|
12
|
+
const shaPattern = /^[0-9a-f]{64}$/;
|
|
13
|
+
const maxEntries = 1000;
|
|
14
|
+
const maxResultBytes = 2 * 1024 * 1024;
|
|
15
|
+
const maxTotalBytes = 64 * 1024 * 1024;
|
|
16
|
+
function safeId(value, label) {
|
|
17
|
+
const id = text(value, label);
|
|
18
|
+
if (!safeIdPattern.test(id))
|
|
19
|
+
throw new Error(`${label} must be a Flow QA-compatible ID.`);
|
|
20
|
+
return id;
|
|
21
|
+
}
|
|
22
|
+
function sha256(value, label) {
|
|
23
|
+
const sha = text(value, label);
|
|
24
|
+
if (!shaPattern.test(sha))
|
|
25
|
+
throw new Error(`${label} must be a SHA-256 digest.`);
|
|
26
|
+
return sha;
|
|
27
|
+
}
|
|
28
|
+
function exactKeys(value, required, optional, label) {
|
|
29
|
+
if (required.some(key => !Object.hasOwn(value, key)) || Object.keys(value).some(key => !required.includes(key) && !optional.includes(key))) {
|
|
30
|
+
throw new Error(`${label} has missing or unsupported fields.`);
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
function stringList(value, label) {
|
|
34
|
+
if (!Array.isArray(value))
|
|
35
|
+
throw new Error(`${label} must be an array.`);
|
|
36
|
+
return value.map((item, index) => text(item, `${label}[${index}]`));
|
|
37
|
+
}
|
|
38
|
+
function sameFile(a, b) {
|
|
39
|
+
return a.dev === b.dev && a.ino === b.ino;
|
|
40
|
+
}
|
|
41
|
+
async function readResultFile(path, name) {
|
|
42
|
+
const before = await lstat(path);
|
|
43
|
+
if (!before.isFile() || before.isSymbolicLink())
|
|
44
|
+
throw new Error(`Linked result ${name} must be a regular file, not a link or directory.`);
|
|
45
|
+
if (before.size > maxResultBytes)
|
|
46
|
+
throw new Error(`Linked result ${name} exceeds 2 MiB.`);
|
|
47
|
+
const handle = await open(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0));
|
|
48
|
+
try {
|
|
49
|
+
const opened = await handle.stat();
|
|
50
|
+
if (!opened.isFile() || !sameFile(before, opened))
|
|
51
|
+
throw new Error(`Linked result ${name} changed while opening.`);
|
|
52
|
+
if (opened.size > maxResultBytes)
|
|
53
|
+
throw new Error(`Linked result ${name} exceeds 2 MiB.`);
|
|
54
|
+
const chunks = [];
|
|
55
|
+
const buffer = Buffer.allocUnsafe(64 * 1024);
|
|
56
|
+
let bytes = 0;
|
|
57
|
+
while (true) {
|
|
58
|
+
const { bytesRead } = await handle.read(buffer, 0, Math.min(buffer.length, maxResultBytes + 1 - bytes), null);
|
|
59
|
+
if (!bytesRead)
|
|
60
|
+
break;
|
|
61
|
+
bytes += bytesRead;
|
|
62
|
+
if (bytes > maxResultBytes)
|
|
63
|
+
throw new Error(`Linked result ${name} exceeds 2 MiB.`);
|
|
64
|
+
chunks.push(Buffer.from(buffer.subarray(0, bytesRead)));
|
|
65
|
+
}
|
|
66
|
+
const after = await handle.stat();
|
|
67
|
+
if (!after.isFile() || !sameFile(opened, after) || after.size !== bytes || after.mtimeMs !== opened.mtimeMs || after.ctimeMs !== opened.ctimeMs) {
|
|
68
|
+
throw new Error(`Linked result ${name} changed while reading.`);
|
|
69
|
+
}
|
|
70
|
+
return { content: Buffer.concat(chunks, bytes).toString('utf8'), bytes };
|
|
71
|
+
}
|
|
72
|
+
finally {
|
|
73
|
+
await handle.close();
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
function parseResult(content, name, inputSha256, suiteSha256, expected) {
|
|
77
|
+
let raw;
|
|
78
|
+
try {
|
|
79
|
+
raw = record(JSON.parse(content), `Linked result ${name}`);
|
|
80
|
+
}
|
|
81
|
+
catch {
|
|
82
|
+
throw new Error(`Linked result ${name} is not a valid JSON object.`);
|
|
83
|
+
}
|
|
84
|
+
exactKeys(raw, ['schemaVersion', 'runId', 'inputSha256', 'suiteSha256', 'startedAt', 'finishedAt', 'status', 'cases', 'note'], [], `Linked result ${name}`);
|
|
85
|
+
if (raw.schemaVersion !== 'error-to-test/results-1')
|
|
86
|
+
throw new Error(`Linked result ${name} uses an unsupported schema.`);
|
|
87
|
+
const runId = text(raw.runId, `${name}.runId`);
|
|
88
|
+
if (!uuidPattern.test(runId) || `${runId}.json` !== name)
|
|
89
|
+
throw new Error(`Linked result ${name} run ID does not match its filename.`);
|
|
90
|
+
if (raw.inputSha256 !== inputSha256 || raw.suiteSha256 !== suiteSha256 || suiteSha256 === undefined) {
|
|
91
|
+
throw new Error(`Linked result ${name} does not match the verified input and suite.`);
|
|
92
|
+
}
|
|
93
|
+
const status = text(raw.status, `${name}.status`);
|
|
94
|
+
if (!runStatuses.has(status))
|
|
95
|
+
throw new Error(`Linked result ${name} has an invalid run status.`);
|
|
96
|
+
const startedAt = timestamp(raw.startedAt, `${name}.startedAt`);
|
|
97
|
+
const finishedAt = timestamp(raw.finishedAt, `${name}.finishedAt`);
|
|
98
|
+
if (finishedAt < startedAt)
|
|
99
|
+
throw new Error(`Linked result ${name} finished before it started.`);
|
|
100
|
+
text(raw.note, `${name}.note`);
|
|
101
|
+
if (!Array.isArray(raw.cases) || raw.cases.length !== expected.size)
|
|
102
|
+
throw new Error(`Linked result ${name} has an incomplete case list.`);
|
|
103
|
+
const seen = new Set();
|
|
104
|
+
const cases = raw.cases.map((item, index) => {
|
|
105
|
+
const label = `${name}.cases[${index}]`;
|
|
106
|
+
const entry = record(item, label);
|
|
107
|
+
exactKeys(entry, ['caseId', 'candidateId', 'groupId', 'eventIds', 'status'], ['reason'], label);
|
|
108
|
+
const caseId = safeId(entry.caseId, `${label}.caseId`);
|
|
109
|
+
const mapping = expected.get(caseId);
|
|
110
|
+
if (!mapping || seen.has(caseId))
|
|
111
|
+
throw new Error(`Linked result ${name} has an unknown or duplicate case ID.`);
|
|
112
|
+
seen.add(caseId);
|
|
113
|
+
if (entry.candidateId !== mapping.candidateId || entry.groupId !== mapping.groupId || JSON.stringify(entry.eventIds) !== JSON.stringify(mapping.eventIds)) {
|
|
114
|
+
throw new Error(`Linked result ${name} has a case mapping that differs from verified provenance.`);
|
|
115
|
+
}
|
|
116
|
+
const caseStatus = text(entry.status, `${label}.status`);
|
|
117
|
+
if (!caseStatuses.has(caseStatus))
|
|
118
|
+
throw new Error(`Linked result ${name} has an invalid case status.`);
|
|
119
|
+
const reason = entry.reason === undefined ? undefined : redactText(text(entry.reason, `${label}.reason`));
|
|
120
|
+
return { ...mapping, eventIds: mapping.eventIds.map(redactText), status: caseStatus, ...(reason === undefined ? {} : { reason }) };
|
|
121
|
+
});
|
|
122
|
+
if (seen.size !== expected.size)
|
|
123
|
+
throw new Error(`Linked result ${name} does not account for every exported case.`);
|
|
124
|
+
if (status === 'passed' && cases.some(item => item.status === 'failed' || item.status === 'error')) {
|
|
125
|
+
throw new Error(`Linked result ${name} contradicts its case results.`);
|
|
126
|
+
}
|
|
127
|
+
return { runId, status: status, startedAt, finishedAt, cases };
|
|
128
|
+
}
|
|
129
|
+
function later(a, b) {
|
|
130
|
+
if (a.finishedAt !== b.finishedAt)
|
|
131
|
+
return a.finishedAt > b.finishedAt;
|
|
132
|
+
if (a.startedAt !== b.startedAt)
|
|
133
|
+
return a.startedAt > b.startedAt;
|
|
134
|
+
return a.runId > b.runId;
|
|
135
|
+
}
|
|
136
|
+
function nonnegativeCount(value, label) {
|
|
137
|
+
if (!Number.isSafeInteger(value) || value < 0)
|
|
138
|
+
throw new Error(`${label} must be a non-negative integer.`);
|
|
139
|
+
return value;
|
|
140
|
+
}
|
|
141
|
+
export async function readRunSummary(directory) {
|
|
142
|
+
const root = resolve(directory);
|
|
143
|
+
const { analysis, provenance, verification } = await readVerifiedBundle(root);
|
|
144
|
+
const inputSha256 = sha256(provenance.inputSha256, 'provenance.inputSha256');
|
|
145
|
+
const suiteSha256 = provenance.suiteSha256 === undefined ? undefined : sha256(provenance.suiteSha256, 'provenance.suiteSha256');
|
|
146
|
+
if (Boolean(suiteSha256) !== verification.suite)
|
|
147
|
+
throw new Error('STALE_BUNDLE: Suite provenance is inconsistent.');
|
|
148
|
+
if (!Array.isArray(analysis.groups) || !Array.isArray(provenance.mappings) || provenance.mappings.length > 100) {
|
|
149
|
+
throw new Error('STALE_BUNDLE: Analysis groups or case mappings are invalid.');
|
|
150
|
+
}
|
|
151
|
+
const groups = analysis.groups.map((item, index) => {
|
|
152
|
+
const group = record(item, `analysis.groups[${index}]`);
|
|
153
|
+
return { groupId: safeId(group.id, `analysis.groups[${index}].id`), message: redactText(text(group.message, `analysis.groups[${index}].message`)), cases: [] };
|
|
154
|
+
});
|
|
155
|
+
const groupById = new Map(groups.map(group => [group.groupId, group]));
|
|
156
|
+
if (groupById.size !== groups.length)
|
|
157
|
+
throw new Error('STALE_BUNDLE: Analysis group IDs are duplicated.');
|
|
158
|
+
const mappings = provenance.mappings.map((item, index) => {
|
|
159
|
+
const mapping = record(item, `provenance.mappings[${index}]`);
|
|
160
|
+
const caseId = safeId(mapping.caseId, `provenance.mappings[${index}].caseId`);
|
|
161
|
+
const candidateId = safeId(mapping.candidateId, `provenance.mappings[${index}].candidateId`);
|
|
162
|
+
const groupId = safeId(mapping.groupId, `provenance.mappings[${index}].groupId`);
|
|
163
|
+
if (!groupById.has(groupId))
|
|
164
|
+
throw new Error('STALE_BUNDLE: A selected case refers to a missing group.');
|
|
165
|
+
return { caseId, candidateId, groupId, eventIds: stringList(mapping.eventIds, `provenance.mappings[${index}].eventIds`) };
|
|
166
|
+
});
|
|
167
|
+
if ((!verification.suite && mappings.length) || (verification.suite && !mappings.length))
|
|
168
|
+
throw new Error('STALE_BUNDLE: Suite and case mappings disagree.');
|
|
169
|
+
const expected = new Map(mappings.map(mapping => [mapping.caseId, mapping]));
|
|
170
|
+
if (expected.size !== mappings.length)
|
|
171
|
+
throw new Error('STALE_BUNDLE: Case IDs are duplicated.');
|
|
172
|
+
const resultsRoot = join(root, 'results');
|
|
173
|
+
let resultsInfo;
|
|
174
|
+
try {
|
|
175
|
+
resultsInfo = await lstat(resultsRoot);
|
|
176
|
+
}
|
|
177
|
+
catch (error) {
|
|
178
|
+
if (error.code !== 'ENOENT')
|
|
179
|
+
throw error;
|
|
180
|
+
}
|
|
181
|
+
let runCount = 0;
|
|
182
|
+
let latest;
|
|
183
|
+
if (resultsInfo) {
|
|
184
|
+
if (!resultsInfo.isDirectory() || resultsInfo.isSymbolicLink())
|
|
185
|
+
throw new Error('Results must be a real directory inside this bundle.');
|
|
186
|
+
const names = [];
|
|
187
|
+
const seenNames = new Set();
|
|
188
|
+
let entries = 0;
|
|
189
|
+
for await (const entry of await opendir(resultsRoot)) {
|
|
190
|
+
if (++entries > maxEntries)
|
|
191
|
+
throw new Error('Results directory exceeds 1000 entries.');
|
|
192
|
+
if (!/\.json$/i.test(entry.name))
|
|
193
|
+
continue;
|
|
194
|
+
const name = entry.name;
|
|
195
|
+
const id = name.slice(0, -5);
|
|
196
|
+
if (!uuidPattern.test(id) || !name.endsWith('.json'))
|
|
197
|
+
throw new Error(`Invalid linked result filename: ${name}.`);
|
|
198
|
+
if (seenNames.has(id.toLowerCase()))
|
|
199
|
+
throw new Error(`Duplicate linked result UUID: ${id}.`);
|
|
200
|
+
seenNames.add(id.toLowerCase());
|
|
201
|
+
names.push(name);
|
|
202
|
+
}
|
|
203
|
+
let totalBytes = 0;
|
|
204
|
+
for (const name of names) {
|
|
205
|
+
const { content, bytes } = await readResultFile(join(resultsRoot, name), name);
|
|
206
|
+
totalBytes += bytes;
|
|
207
|
+
if (totalBytes > maxTotalBytes)
|
|
208
|
+
throw new Error('Linked results exceed 64 MiB in total.');
|
|
209
|
+
const run = parseResult(content, name, inputSha256, suiteSha256, expected);
|
|
210
|
+
runCount++;
|
|
211
|
+
if (!latest || later(run, latest))
|
|
212
|
+
latest = run;
|
|
213
|
+
}
|
|
214
|
+
const after = await lstat(resultsRoot);
|
|
215
|
+
if (!after.isDirectory() || after.isSymbolicLink() || !sameFile(resultsInfo, after))
|
|
216
|
+
throw new Error('Results directory changed while reading.');
|
|
217
|
+
}
|
|
218
|
+
const latestCases = new Map(latest?.cases.map(item => [item.caseId, item]) ?? []);
|
|
219
|
+
const counts = Object.fromEntries(countStatuses.map(status => [status, 0]));
|
|
220
|
+
for (const mapping of mappings) {
|
|
221
|
+
const runCase = latestCases.get(mapping.caseId);
|
|
222
|
+
const status = runCase?.status ?? 'not-run';
|
|
223
|
+
counts[status]++;
|
|
224
|
+
groupById.get(mapping.groupId).cases.push({
|
|
225
|
+
caseId: mapping.caseId, candidateId: mapping.candidateId, eventIds: mapping.eventIds.map(redactText), status,
|
|
226
|
+
...(runCase?.reason === undefined ? {} : { reason: runCase.reason }),
|
|
227
|
+
});
|
|
228
|
+
}
|
|
229
|
+
const warnings = ['Counts are the latest reported case outcomes, not proof that any source issue is resolved.'];
|
|
230
|
+
if (analysis.warnings !== undefined)
|
|
231
|
+
warnings.push(...stringList(analysis.warnings, 'analysis.warnings').map(redactText));
|
|
232
|
+
if (runCount) {
|
|
233
|
+
if (!verification.reviewed)
|
|
234
|
+
warnings.push('Bundle review is pending. Reported results do not authorize execution.');
|
|
235
|
+
if (!Array.isArray(analysis.candidates))
|
|
236
|
+
throw new Error('STALE_BUNDLE: Analysis candidates are missing.');
|
|
237
|
+
if (analysis.candidates.some((item, index) => {
|
|
238
|
+
const candidate = record(item, `analysis.candidates[${index}]`);
|
|
239
|
+
if (candidate.state !== 'draft' && candidate.state !== 'needs-context')
|
|
240
|
+
throw new Error('STALE_BUNDLE: A selected candidate has an invalid state.');
|
|
241
|
+
return candidate.state === 'needs-context';
|
|
242
|
+
}))
|
|
243
|
+
warnings.push('One or more selected cases still need context; reported outcomes do not settle the missing information.');
|
|
244
|
+
}
|
|
245
|
+
return {
|
|
246
|
+
schemaVersion: 'error-to-test/run-summary-1', inputSha256,
|
|
247
|
+
...(suiteSha256 === undefined ? {} : { suiteSha256 }), runCount,
|
|
248
|
+
...(latest === undefined ? {} : { latestRun: { runId: latest.runId, status: latest.status, startedAt: latest.startedAt, finishedAt: latest.finishedAt } }),
|
|
249
|
+
counts, groups, warnings,
|
|
250
|
+
};
|
|
251
|
+
}
|
|
252
|
+
export function renderRunSummary(summary) {
|
|
253
|
+
const lines = ['# Linked run summary', '', `Input SHA-256: ${sha256(summary.inputSha256, 'summary.inputSha256')}`];
|
|
254
|
+
if (summary.suiteSha256 !== undefined)
|
|
255
|
+
lines.push(`Suite SHA-256: ${sha256(summary.suiteSha256, 'summary.suiteSha256')}`);
|
|
256
|
+
lines.push(`Linked runs: ${nonnegativeCount(summary.runCount, 'summary.runCount')}`, '');
|
|
257
|
+
if (summary.latestRun) {
|
|
258
|
+
const run = summary.latestRun;
|
|
259
|
+
if (!uuidPattern.test(run.runId) || !runStatuses.has(run.status))
|
|
260
|
+
throw new Error('Invalid latest run in summary.');
|
|
261
|
+
lines.push('## Latest linked run', '', `Run ID: ${run.runId}`, `Reported status: ${run.status}`, `Started: ${timestamp(run.startedAt, 'summary.latestRun.startedAt')}`, `Finished: ${timestamp(run.finishedAt, 'summary.latestRun.finishedAt')}`, '');
|
|
262
|
+
}
|
|
263
|
+
else
|
|
264
|
+
lines.push('No linked runs were found. All selected cases are not-run.', '');
|
|
265
|
+
lines.push('## Latest reported case counts', '');
|
|
266
|
+
for (const status of countStatuses)
|
|
267
|
+
lines.push(`- ${status}: ${nonnegativeCount(summary.counts[status], `summary.counts.${status}`)}`);
|
|
268
|
+
lines.push('', '## Warnings', '');
|
|
269
|
+
lines.push(literal(summary.warnings.join('\n') || 'None'), '');
|
|
270
|
+
if (!summary.groups.length)
|
|
271
|
+
lines.push('No source groups were found.', '');
|
|
272
|
+
for (const group of summary.groups) {
|
|
273
|
+
const groupId = safeId(group.groupId, 'summary.groupId');
|
|
274
|
+
lines.push(`## ${groupId}`, '', 'Observed message:', '', literal(group.message), '');
|
|
275
|
+
if (!group.cases.length)
|
|
276
|
+
lines.push('No selected cases for this group.', '');
|
|
277
|
+
for (const item of group.cases) {
|
|
278
|
+
const caseId = safeId(item.caseId, 'summary.caseId');
|
|
279
|
+
const candidateId = safeId(item.candidateId, 'summary.candidateId');
|
|
280
|
+
if (!countStatuses.includes(item.status))
|
|
281
|
+
throw new Error('Invalid case status in summary.');
|
|
282
|
+
lines.push(`### ${caseId}`, '', `Candidate ID: ${candidateId}`, `Reported status: ${item.status}`, '');
|
|
283
|
+
if (item.reason !== undefined)
|
|
284
|
+
lines.push('Reported reason:', '', literal(item.reason), '');
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
return `${lines.join('\n')}\n`;
|
|
288
|
+
}
|
package/package.json
CHANGED