@ihyeon/error-to-test 0.1.14 → 0.1.16
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 +39 -0
- package/dist/analysis.d.ts +2 -1
- package/dist/analysis.js +47 -6
- package/dist/artifacts.d.ts +2 -2
- package/dist/artifacts.js +39 -5
- package/dist/cli.js +47 -11
- package/dist/comparison.d.ts +1 -0
- package/dist/comparison.js +9 -2
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/input-source.d.ts +8 -0
- package/dist/input-source.js +61 -0
- package/dist/input.d.ts +1 -1
- package/dist/input.js +45 -31
- package/dist/types.d.ts +16 -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
|
+
`--input`을 반복하면 **여러 로그 파일을 함께 분석**할 수 있습니다.
|
|
48
|
+
|
|
49
|
+
```sh
|
|
50
|
+
error-to-test analyze --input morning.json --input afternoon.json --min-count 3 --top 10 --out ./combined
|
|
51
|
+
error-to-test verify ./combined --input morning.json --input afternoon.json
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
최대 50개 파일, 합산 10 MiB·원본 10,000건까지 받습니다. 중복도 한도에 포함합니다. SDK JSON 내보내기·배열끼리, 수동 JSON끼리, 텍스트끼리처럼 같은 입력 형식끼리 합칩니다. 텍스트는 파일 하나가 보고서 한 건이며, `--format`과 메타데이터·필터는 모든 파일에 적용합니다. 표준 입력(`--input -`)은 `analyze`에서 단독으로 사용하고, `verify`에는 원본 파일을 지정하세요.
|
|
55
|
+
|
|
56
|
+
파일과 표준 입력은 올바른 UTF-8이어야 합니다. 잘못된 바이트가 같은 대체 문자로 변환되어 원본 변경을 놓치지 않도록 해시 계산 전에 잘못된 인코딩을 거부합니다.
|
|
57
|
+
|
|
58
|
+
파일 전체에서 프로젝트·레코드 ID 중복을 먼저 검사한 뒤 필터·그룹 순위·TC 선택을 적용합니다. 동일한 레코드는 한 번만 세며, 같은 ID의 원본 내용이 다르면 정제 후 같아 보이거나 필터로 제외될 데이터여도 거부합니다. 하나라도 부분 내보내기이면 전체 결과에도 부분 입력으로 표시합니다. 건수는 제공한 로그 기준이며 실제 발생률을 의미하지 않습니다.
|
|
59
|
+
|
|
60
|
+
여러 파일의 원본 SHA-256과 UTF-8 바이트 수를 입력 순서대로 `analysis.source.inputs`와 보고서에 남깁니다. 파일명과 원문은 저장하지 않습니다. `source.sha256`은 `JSON.stringify({ schemaVersion: 'error-to-test/inputs-1', inputs })`의 SHA-256이며, 각 항목은 `{ sha256, byteLength }` 순서입니다. 이 목록도 분석 해시로 검증합니다. 원본 확인에는 BOM·공백까지 동일한 모든 파일을 같은 순서로 지정해야 합니다. 단일 입력의 기존 바이트 해시와 결과 형식은 유지합니다.
|
|
61
|
+
|
|
62
|
+
API에서도 `analyzeErrors([firstContent, secondContent], options)`, `parseInput([firstContent, secondContent], options)`, `await analyzeWithBaseline([firstContent, secondContent], baselineDirectory, options)`으로 사용합니다. 원본 검증은 `await verifyBundle(directory, { input: [firstContent, secondContent] })`입니다. 원소 하나의 배열은 문자열 하나와 동일합니다. 프로필 보완·이전 분석 대비 선택에도 같은 입력 순서를 유지하고, 기존 맥락 질문과 검토 조건을 적용합니다.
|
|
63
|
+
|
|
47
64
|
두 분석 결과는 `compare`로 비교할 수 있습니다. 릴리스가 바뀐 뒤 어떤 오류 서명이 다시 관측됐는지 확인할 때 사용합니다.
|
|
48
65
|
|
|
49
66
|
```sh
|
|
@@ -61,6 +78,22 @@ TC 생성 대상에서 제외된 묶음도 모두 비교합니다. 한쪽에 여
|
|
|
61
78
|
|
|
62
79
|
양쪽 번들을 검증한 뒤 읽으며 원래 산출물·TC 상태·검토 조건·연결 결과는 수정하지 않습니다. 기본 출력은 Markdown이고, `--format json`은 `error-to-test/comparison-1`을 반환합니다. `--out`은 양쪽 번들의 `results` 폴더 밖에 있는 새 파일만 허용합니다. API는 `compareBundles()`와 `renderComparison()`입니다.
|
|
63
80
|
|
|
81
|
+
`analyze --baseline`을 쓰면 **이전 분석에서 관측되지 않은 서명만 골라 TC를 생성**할 수 있습니다.
|
|
82
|
+
|
|
83
|
+
```sh
|
|
84
|
+
error-to-test analyze --input before-errors.json --out ./before
|
|
85
|
+
error-to-test analyze --input current-errors.json --baseline ./before --min-count 3 --top 10 --out ./new-signature-tcs
|
|
86
|
+
error-to-test init-profile ./new-signature-tcs --out ./new-signature-profile.json
|
|
87
|
+
# 확인한 요구사항·준비 조건·동작·assertion으로 프로필 수정
|
|
88
|
+
error-to-test analyze --input current-errors.json --baseline ./before --min-count 3 --top 10 --profile ./new-signature-profile.json --out ./reviewed-new-signatures
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
`compare`와 같은 기준으로 릴리스만 제외한 전체 서명을 비교합니다. 이전 분석에서 TC 생성 대상이 아니었던 묶음도 비교에 포함합니다. 이전에 없던 현재 묶음을 먼저 고른 뒤 `--min-count`, `--top`을 적용하므로 순위가 높은 기존 오류 때문에 새 서명의 TC가 밀려나지 않습니다. 최소 건수는 현재의 각 묶음별로 적용하며 서로 다른 릴리스의 건수를 합치지 않습니다. 현재의 전체 묶음·원본 해시·수집 범위는 그대로 남습니다. 선택할 후보가 없으면 suite 없이 정상 번들을 만듭니다.
|
|
92
|
+
|
|
93
|
+
`analysis.json`의 `selection`과 보고서에 선택 방식(`only-current`), 이전 입력·검증된 분석 파일의 SHA-256, 이전 수집 범위, 선택·제외 묶음 수를 기록합니다. 이 정보도 새 번들의 분석 해시로 검증됩니다. 이전 번들은 한 번 검증해 읽으며 수정하지 않습니다. 이후 이전 번들이 바뀌어도 저장된 선택 결과는 바뀌지 않습니다. 프로필을 보완할 때 같은 이전 번들과 필터를 유지하세요. 맥락 질문과 검토 조건도 계속 적용하며, `--reviewed`는 검토 확인만 처리합니다.
|
|
94
|
+
|
|
95
|
+
이전에 없었다는 표시가 새로 유입된 버그나 회귀를 확정하지는 않습니다. 부분 내보내기·기간·수집 범위 차이 등 비교 경고를 유지하고, 수집 이벤트와 수동 제출 보고서를 섞으면 거부합니다. 출력은 이전 번들의 `results` 폴더 밖에 있는 새 디렉터리만 허용합니다. API는 `await analyzeWithBaseline(content, baselineDirectory, { minCount: 3, top: 10, profile })`이며 이전 번들 검증도 수행합니다.
|
|
96
|
+
|
|
64
97
|
`report.md` 상단에서 TC 초안 수와 추가 정보가 필요한 TC 수를 확인할 수 있습니다. 초안도 실행 전에 검토해야 합니다. 오류 묶음·수집 건수와 함께 대표 로그의 오류·React 컴포넌트 스택, 재현 방법·사전 조건·테스트 단계·부족한 정보도 표시합니다. 같은 스택은 한 번만 표시하며, 전체 로그의 모든 스택을 나열하지는 않습니다. 재현 단계와 정상 기대 결과, 명시적인 assertion이 없으면 질문이 있는 TC를 생성합니다. 직접 입력한 보고서에는 실제 발생 시각·사용자 수를 만들어 넣지 않습니다. 수집 건수도 실제 발생률을 뜻하지 않으며, 원본 내보내기의 일부 데이터 표시를 유지합니다.
|
|
65
98
|
|
|
66
99
|
기본 suite는 검토 질문으로 실행이 차단됩니다. TC와 프로필을 확인한 뒤 다른 출력 폴더에 `--reviewed`로 다시 생성하면 검토 질문만 제거됩니다. 나머지 질문은 그대로 실행을 차단합니다. 프로필의 `setupConfirmed`는 준비 조건을 확인했다는 표시이며, 계정·데이터를 자동으로 준비하는 기능은 아닙니다.
|
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
|
+
### Analyze several log files together
|
|
71
|
+
|
|
72
|
+
Repeat `--input` to combine exports before deduplication, filters, ranking, and TC selection:
|
|
73
|
+
|
|
74
|
+
```sh
|
|
75
|
+
error-to-test analyze --input morning.json --input afternoon.json --min-count 3 --top 10 --out ./combined
|
|
76
|
+
error-to-test verify ./combined --input morning.json --input afternoon.json
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
Supply up to 50 files with a combined limit of 10 MiB and 10,000 raw records, including duplicates. Files must have the same input kind: SDK JSON exports/arrays together, manual JSON files together, or text reports together. Each text file is one report. `--format` and metadata/filter options apply to every file. Standard input (`--input -`) must be the only input to `analyze`; `verify` requires original files.
|
|
80
|
+
|
|
81
|
+
Files and standard input must be valid UTF-8. Malformed encoding is rejected before hashing, so distinct invalid bytes cannot silently become the same replacement character.
|
|
82
|
+
|
|
83
|
+
Duplicate project/record IDs are resolved across all files before filtering. Identical records count once; conflicting raw records are rejected even if redaction would make them look alike or filters would exclude them. The partial-export flag is true if any source is partial. Counts describe supplied records, not a global occurrence rate.
|
|
84
|
+
|
|
85
|
+
For multiple files, `analysis.source.inputs` records each original SHA-256 and UTF-8 byte length in the supplied order. Filenames and raw contents are not stored. `source.sha256` is the SHA-256 of `JSON.stringify({ schemaVersion: 'error-to-test/inputs-1', inputs })`, with each descriptor ordered as `{ sha256, byteLength }`. The analysis hash protects the manifest, and the report lists it. Verification requires every original file in the same order, including its BOM and whitespace. A single input retains its original byte hash and existing output contract.
|
|
86
|
+
|
|
87
|
+
The API accepts ordered content arrays: `analyzeErrors([firstContent, secondContent], options)`, `parseInput([firstContent, secondContent], options)`, and `await analyzeWithBaseline([firstContent, secondContent], baselineDirectory, options)`. Verify with `await verifyBundle(directory, { input: [firstContent, secondContent] })`. A one-element array is equivalent to its single string. Profile refinement and baseline selection work with the same ordered inputs and existing review gates.
|
|
88
|
+
|
|
70
89
|
### Compare two analyses
|
|
71
90
|
|
|
72
91
|
Compare verified snapshots, including snapshots from different releases:
|
|
@@ -86,6 +105,26 @@ All source groups participate, including groups excluded from TC generation by `
|
|
|
86
105
|
|
|
87
106
|
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
107
|
|
|
108
|
+
### Generate TCs for signatures absent from a baseline
|
|
109
|
+
|
|
110
|
+
Pass a verified analysis bundle to `analyze --baseline` to focus TC generation on current signatures that were not observed in that baseline:
|
|
111
|
+
|
|
112
|
+
```sh
|
|
113
|
+
error-to-test analyze --input before-errors.json --out ./before
|
|
114
|
+
error-to-test analyze --input current-errors.json --baseline ./before --min-count 3 --top 10 --out ./new-signature-tcs
|
|
115
|
+
error-to-test init-profile ./new-signature-tcs --out ./new-signature-profile.json
|
|
116
|
+
# Fill the profile with confirmed requirements, setup, actions, and assertions.
|
|
117
|
+
error-to-test analyze --input current-errors.json --baseline ./before --min-count 3 --top 10 --profile ./new-signature-profile.json --out ./reviewed-new-signatures
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
The filter uses the same exact identity as `compare`, excluding release only. Every baseline group participates, even one excluded from its TC selection. Current groups absent from the baseline are selected first, then `--min-count` and `--top` apply in the existing ranked order. Counts remain per current group; different releases are not pooled to meet `--min-count`. All current groups and source coverage remain in the analysis and report. No matching candidates means a valid bundle without a suite.
|
|
121
|
+
|
|
122
|
+
The analysis records `selection.mode: "only-current"`, the baseline input and verified analysis SHA-256 hashes, baseline coverage, and group selection counts. These are covered by the new bundle's analysis hash. The baseline is read once without modification; later baseline edits do not alter this saved selection. Reuse the same baseline and filters when refining the profile. Existing context questions and the review gate still apply; `--reviewed` only acknowledges review.
|
|
123
|
+
|
|
124
|
+
“Absent from baseline” does not establish that an error was newly introduced or is a confirmed regression. Partial exports, different periods, and reporting practices can explain absence; comparison coverage warnings are retained. Captured-event and submitted-report sources cannot be mixed. Output must be a new directory outside the baseline's `results` directory.
|
|
125
|
+
|
|
126
|
+
The async API is `await analyzeWithBaseline(content, baselineDirectory, { minCount: 3, top: 10, profile })`. It verifies the baseline bundle itself and accepts the same analysis options as `analyzeErrors`.
|
|
127
|
+
|
|
89
128
|
## Confirm the intended behavior
|
|
90
129
|
|
|
91
130
|
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.
|
package/dist/analysis.d.ts
CHANGED
|
@@ -5,4 +5,5 @@ export interface AnalyzeOptions extends ParseInputOptions {
|
|
|
5
5
|
top?: number;
|
|
6
6
|
minCount?: number;
|
|
7
7
|
}
|
|
8
|
-
export declare function analyzeErrors(content: string, options?: AnalyzeOptions): Analysis;
|
|
8
|
+
export declare function analyzeErrors(content: string | readonly string[], options?: AnalyzeOptions): Analysis;
|
|
9
|
+
export declare function analyzeWithBaseline(content: string | readonly string[], baselineDirectory: string, options?: AnalyzeOptions): Promise<Analysis>;
|
package/dist/analysis.js
CHANGED
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
import { parseInput } from "./input.js";
|
|
2
2
|
import { groupObservations } from "./grouping.js";
|
|
3
3
|
import { createCandidates, parseProfile } from "./candidates.js";
|
|
4
|
+
import { readVerifiedBundle } from "./artifacts.js";
|
|
5
|
+
import { compareAnalyses } from "./comparison.js";
|
|
4
6
|
import { hash } from "./validation.js";
|
|
5
|
-
|
|
7
|
+
function analyze(content, options, baseline) {
|
|
6
8
|
const top = options.top ?? 100;
|
|
7
9
|
if (!Number.isInteger(top) || top < 1 || top > 100)
|
|
8
10
|
throw new Error('top must be an integer between 1 and 100.');
|
|
@@ -24,20 +26,59 @@ export function analyzeErrors(content, options = {}) {
|
|
|
24
26
|
const profile = rawProfile === undefined ? undefined : parseProfile(rawProfile);
|
|
25
27
|
const input = parseInput(content, options);
|
|
26
28
|
const groups = groupObservations(input.observations);
|
|
27
|
-
const
|
|
29
|
+
const source = { sha256: input.sha256, ...(input.inputs ? { inputs: input.inputs } : {}),
|
|
30
|
+
...(profileSource !== undefined ? { profileSha256: hash(profileSource) } : {}) };
|
|
28
31
|
const warnings = [...input.warnings];
|
|
29
|
-
|
|
30
|
-
|
|
32
|
+
let selectedGroups = groups;
|
|
33
|
+
let selection;
|
|
34
|
+
if (baseline) {
|
|
35
|
+
const comparison = compareAnalyses(baseline.analysis, {
|
|
36
|
+
schemaVersion: 'error-to-test/analysis-1', source, coverage: input.coverage, groups, warnings: [],
|
|
37
|
+
});
|
|
38
|
+
const onlyCurrentIds = new Set(comparison.issues.filter(issue => issue.status === 'only-current')
|
|
39
|
+
.flatMap(issue => issue.current?.groupIds ?? []));
|
|
40
|
+
selectedGroups = groups.filter(group => onlyCurrentIds.has(group.id));
|
|
41
|
+
selection = {
|
|
42
|
+
mode: 'only-current',
|
|
43
|
+
baseline: { inputSha256: comparison.baseline.inputSha256, analysisSha256: baseline.analysisSha256,
|
|
44
|
+
coverage: comparison.baseline.coverage },
|
|
45
|
+
onlyCurrentGroupCount: selectedGroups.length,
|
|
46
|
+
excludedGroupCount: groups.length - selectedGroups.length,
|
|
47
|
+
};
|
|
48
|
+
warnings.push(`Baseline TC selection: ${selection.onlyCurrentGroupCount} of ${groups.length} current groups have signatures absent from the supplied baseline; ${selection.excludedGroupCount} already observed. Selection precedes minCount and top. Absence from this baseline does not establish introduction, regression, or resolution.`);
|
|
49
|
+
// A prior baseline-aware bundle may already carry comparison notes. Keep the
|
|
50
|
+
// comparison's bounded coverage cautions without recursively echoing history.
|
|
51
|
+
warnings.push(...comparison.warnings.filter(warning => !warning.startsWith('Baseline:') && !warning.startsWith('Current:')));
|
|
52
|
+
if (comparison.baseline.coverage.duplicates || comparison.baseline.coverage.filtered) {
|
|
53
|
+
warnings.push(`Baseline source coverage: ${comparison.baseline.coverage.duplicates} duplicate and ${comparison.baseline.coverage.filtered} filtered supplied records.`);
|
|
54
|
+
}
|
|
55
|
+
if (comparison.baseline.coverage.period) {
|
|
56
|
+
warnings.push('Baseline date filtering applies only to reports with observed timestamps; undated reports may have been excluded.');
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
const eligibleGroups = selectedGroups.filter(group => group.count >= minCount);
|
|
60
|
+
if (eligibleGroups.length < selectedGroups.length)
|
|
61
|
+
warnings.push(`TC selection requires at least ${minCount} supplied records per group; ${eligibleGroups.length} of ${selectedGroups.length} groups are eligible. All groups remain in analysis.json. These counts are supplied records, not global rates.`);
|
|
31
62
|
if (eligibleGroups.length > top)
|
|
32
63
|
warnings.push(minCount === 1
|
|
33
|
-
? `TC selection includes the first ${top} of ${
|
|
64
|
+
? `TC selection includes the first ${top} of ${selectedGroups.length} ranked groups. All groups remain in analysis.json.`
|
|
34
65
|
: `TC selection includes the first ${top} of ${eligibleGroups.length} eligible ranked groups. All groups remain in analysis.json.`);
|
|
35
66
|
return {
|
|
36
67
|
schemaVersion: 'error-to-test/analysis-1',
|
|
37
|
-
source
|
|
68
|
+
source,
|
|
38
69
|
coverage: input.coverage,
|
|
39
70
|
groups,
|
|
40
71
|
candidates: createCandidates(eligibleGroups.slice(0, top), profile),
|
|
41
72
|
warnings,
|
|
73
|
+
...(selection ? { selection } : {}),
|
|
42
74
|
};
|
|
43
75
|
}
|
|
76
|
+
export function analyzeErrors(content, options = {}) {
|
|
77
|
+
return analyze(content, options);
|
|
78
|
+
}
|
|
79
|
+
export async function analyzeWithBaseline(content, baselineDirectory, options = {}) {
|
|
80
|
+
const baseline = await readVerifiedBundle(baselineDirectory);
|
|
81
|
+
if (typeof baseline.provenance.analysisSha256 !== 'string')
|
|
82
|
+
throw new Error('STALE_BUNDLE: The baseline analysis hash is missing.');
|
|
83
|
+
return analyze(content, options, { analysis: baseline.analysis, analysisSha256: baseline.provenance.analysisSha256 });
|
|
84
|
+
}
|
package/dist/artifacts.d.ts
CHANGED
|
@@ -8,7 +8,7 @@ export declare function writeBundle(directory: string, analysis: Analysis, optio
|
|
|
8
8
|
}): Promise<string[]>;
|
|
9
9
|
export declare function readBoundedFile(path: string, maxBytes?: number): Promise<string>;
|
|
10
10
|
export declare function readVerifiedBundle(directory: string, options?: {
|
|
11
|
-
input?: string;
|
|
11
|
+
input?: string | readonly string[];
|
|
12
12
|
profile?: string;
|
|
13
13
|
}): Promise<{
|
|
14
14
|
analysis: Record<string, unknown>;
|
|
@@ -20,7 +20,7 @@ export declare function readVerifiedBundle(directory: string, options?: {
|
|
|
20
20
|
};
|
|
21
21
|
}>;
|
|
22
22
|
export declare function verifyBundle(directory: string, options?: {
|
|
23
|
-
input?: string;
|
|
23
|
+
input?: string | readonly string[];
|
|
24
24
|
profile?: string;
|
|
25
25
|
}): Promise<{
|
|
26
26
|
suite: boolean;
|
package/dist/artifacts.js
CHANGED
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
import { mkdir, readFile, stat, writeFile } from 'node:fs/promises';
|
|
2
|
+
import { isUtf8 } from 'node:buffer';
|
|
2
3
|
import { dirname, resolve } from 'node:path';
|
|
3
4
|
import { exportFlowQa } from "./exports/flow-qa.js";
|
|
4
5
|
import { hash, record, text } from "./validation.js";
|
|
5
6
|
import { redactText } from "./redact.js";
|
|
7
|
+
import { inputSource, validateInputSource } from "./input-source.js";
|
|
6
8
|
export function jsonText(value) { return `${JSON.stringify(value, null, 2)}\n`; }
|
|
7
9
|
// Use only after callers have sanitized each untrusted field for its context.
|
|
8
10
|
export function fencedText(value) {
|
|
@@ -22,6 +24,22 @@ export function renderReport(analysis) {
|
|
|
22
24
|
`Duplicate records: ${analysis.coverage.duplicates} · Filtered records: ${analysis.coverage.filtered}`, '',
|
|
23
25
|
'Counts describe the supplied records. They are not error rates, affected-user counts, or proof of complete collection.',
|
|
24
26
|
'Drafts require review. A passing TC proves only its assertions; it does not automatically close the source issue.', ''];
|
|
27
|
+
if (analysis.source.inputs)
|
|
28
|
+
lines.push('## Input files', '', literal([
|
|
29
|
+
`Files: ${analysis.source.inputs.length} · Order: the supplied --input order`,
|
|
30
|
+
'The source SHA-256 commits to the ordered file hashes and byte lengths. Verify with every original file in the same order.',
|
|
31
|
+
...analysis.source.inputs.map((input, index) => `${index + 1}. SHA-256: ${input.sha256} · Bytes: ${input.byteLength}`),
|
|
32
|
+
].join('\n')), '');
|
|
33
|
+
if (analysis.selection)
|
|
34
|
+
lines.push('## Baseline candidate selection', '', literal([
|
|
35
|
+
'Mode: only-current (signatures absent from the supplied baseline)',
|
|
36
|
+
`Baseline input SHA-256: ${analysis.selection.baseline.inputSha256}`,
|
|
37
|
+
`Baseline analysis SHA-256: ${analysis.selection.baseline.analysisSha256}`,
|
|
38
|
+
`Baseline: ${analysis.selection.baseline.coverage.kind} / ${analysis.selection.baseline.coverage.frequency} · partial ${analysis.selection.baseline.coverage.partial ? 'yes' : 'no'} · retention unknown`,
|
|
39
|
+
`Only-current groups before min-count/top: ${analysis.selection.onlyCurrentGroupCount}`,
|
|
40
|
+
`Groups excluded as already observed: ${analysis.selection.excludedGroupCount}`,
|
|
41
|
+
'All current groups remain below. Absence from this baseline does not establish when an error was introduced.',
|
|
42
|
+
].join('\n')), '');
|
|
25
43
|
if (analysis.warnings.length)
|
|
26
44
|
lines.push('## Coverage and selection notes', '', literal(analysis.warnings.join('\n')), '');
|
|
27
45
|
if (!analysis.groups.length)
|
|
@@ -82,10 +100,12 @@ export async function readBoundedFile(path, maxBytes = 10 * 1024 * 1024) {
|
|
|
82
100
|
const info = await stat(path);
|
|
83
101
|
if (!info.isFile() || info.size > maxBytes)
|
|
84
102
|
throw new Error('Input must be a regular file within the size limit.');
|
|
85
|
-
const content = await readFile(path
|
|
86
|
-
if (
|
|
103
|
+
const content = await readFile(path);
|
|
104
|
+
if (content.length > maxBytes)
|
|
87
105
|
throw new Error('Input exceeded the size limit while reading.');
|
|
88
|
-
|
|
106
|
+
if (!isUtf8(content))
|
|
107
|
+
throw new Error('Input must be valid UTF-8.');
|
|
108
|
+
return content.toString('utf8');
|
|
89
109
|
}
|
|
90
110
|
export async function readVerifiedBundle(directory, options = {}) {
|
|
91
111
|
const root = resolve(directory);
|
|
@@ -110,6 +130,14 @@ export async function readVerifiedBundle(directory, options = {}) {
|
|
|
110
130
|
if (analysis.schemaVersion !== 'error-to-test/analysis-1')
|
|
111
131
|
throw new Error('Unsupported analysis contract.');
|
|
112
132
|
const source = record(analysis.source, 'analysis.source');
|
|
133
|
+
if (source.inputs !== undefined) {
|
|
134
|
+
try {
|
|
135
|
+
validateInputSource(source);
|
|
136
|
+
}
|
|
137
|
+
catch {
|
|
138
|
+
throw new Error('STALE_BUNDLE: The ordered input manifest is invalid or does not match the source hash.');
|
|
139
|
+
}
|
|
140
|
+
}
|
|
113
141
|
const flow = await readBoundedFile(resolve(root, 'flows/error-to-test.md'), 8 * 1024 * 1024);
|
|
114
142
|
if (hash(flow) !== provenance.flowSha256 || source.sha256 !== provenance.inputSha256 || source.profileSha256 !== provenance.profileSha256)
|
|
115
143
|
throw new Error('STALE_BUNDLE: Analysis, flow, and provenance no longer match.');
|
|
@@ -131,8 +159,14 @@ export async function readVerifiedBundle(directory, options = {}) {
|
|
|
131
159
|
throw new Error('STALE_BUNDLE: Suite source no longer matches the flow.');
|
|
132
160
|
suiteExists = true;
|
|
133
161
|
}
|
|
134
|
-
if (options.input !== undefined
|
|
135
|
-
|
|
162
|
+
if (options.input !== undefined) {
|
|
163
|
+
const provided = inputSource(options.input);
|
|
164
|
+
const stored = source.inputs;
|
|
165
|
+
const sameFiles = provided.inputs === undefined ? stored === undefined : stored !== undefined &&
|
|
166
|
+
provided.inputs.length === stored.length && provided.inputs.every((input, index) => input.sha256 === stored[index].sha256 && input.byteLength === stored[index].byteLength);
|
|
167
|
+
if (!sameFiles || provided.sha256 !== text(provenance.inputSha256, 'provenance.inputSha256'))
|
|
168
|
+
throw new Error('STALE_BUNDLE: Input changed since analysis. Supply every original file in the same order.');
|
|
169
|
+
}
|
|
136
170
|
if (options.profile !== undefined && hash(options.profile) !== provenance.profileSha256)
|
|
137
171
|
throw new Error('STALE_BUNDLE: Profile changed since analysis.');
|
|
138
172
|
return { analysis, provenance, verification: { suite: suiteExists, reviewed: provenance.reviewed, sourceChecked: options.input !== undefined } };
|
package/dist/cli.js
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import { parseArgs } from 'node:util';
|
|
2
|
+
import { isUtf8 } from 'node:buffer';
|
|
2
3
|
import { randomUUID } from 'node:crypto';
|
|
3
4
|
import { lstat, mkdir, readFile, realpath, writeFile } from 'node:fs/promises';
|
|
4
5
|
import { dirname, isAbsolute, relative, resolve, sep } from 'node:path';
|
|
5
|
-
import { analyzeErrors } from "./analysis.js";
|
|
6
|
+
import { analyzeErrors, analyzeWithBaseline } from "./analysis.js";
|
|
6
7
|
import { jsonText, readBoundedFile, readVerifiedBundle, verifyBundle, writeBundle } from "./artifacts.js";
|
|
7
8
|
import { compareBundles, renderComparison } from "./comparison.js";
|
|
8
9
|
import { createProfileTemplate } from "./profile-template.js";
|
|
@@ -11,23 +12,25 @@ import { linkFlowQaReport } from "./results.js";
|
|
|
11
12
|
import { readRunSummary, renderRunSummary } from "./run-summary.js";
|
|
12
13
|
const help = `Error to Test — local error analysis and regression TC drafts
|
|
13
14
|
|
|
14
|
-
error-to-test analyze --input errors.json --profile profile.json --out new-directory
|
|
15
|
+
error-to-test analyze --input errors-1.json --input errors-2.json --profile profile.json --out new-directory
|
|
16
|
+
error-to-test analyze --input errors.json --baseline previous-bundle --out new-directory
|
|
15
17
|
error-to-test analyze --input error.txt --format text --page /items --out new-directory
|
|
16
18
|
error-to-test analyze --error "TypeError: item is undefined" --page /items --out new-directory
|
|
17
19
|
cat error.txt | error-to-test analyze --input - --format text --out new-directory
|
|
18
|
-
error-to-test verify new-directory [--input errors.json] [--profile profile.json]
|
|
20
|
+
error-to-test verify new-directory [--input errors-1.json --input errors-2.json] [--profile profile.json]
|
|
19
21
|
error-to-test init-profile new-directory --out profile.json
|
|
20
22
|
error-to-test link-run new-directory --report path/to/qa-report.json
|
|
21
23
|
error-to-test results new-directory [--format text|json] [--out summary.md]
|
|
22
24
|
error-to-test compare BASELINE CURRENT [--format text|json] [--out comparison.md]
|
|
23
25
|
|
|
24
26
|
Options:
|
|
25
|
-
--input FILE SDK export, manual JSON, or plain error text (- for stdin)
|
|
27
|
+
--input FILE SDK export, manual JSON, or plain error text; repeat for same-format files in order (analyze: sole - for stdin)
|
|
26
28
|
--error TEXT Submit a single error directly; remaining lines are its stack
|
|
27
29
|
--format auto|json|text Analyze input format; auto rejects malformed JSON-looking input
|
|
28
30
|
--format text|json Results summary format (default: text Markdown)
|
|
29
31
|
--format text|json Compare format (default: text Markdown)
|
|
30
32
|
--profile FILE Confirmed app scenarios and explicit assertions (optional)
|
|
33
|
+
--baseline DIRECTORY Select only signatures absent from this verified bundle, before --min-count and --top; retain all groups in analysis.json (analyze only)
|
|
31
34
|
--project NAME Metadata for a manual report
|
|
32
35
|
--environment NAME Metadata for a manual report
|
|
33
36
|
--release NAME Metadata for a manual report
|
|
@@ -64,7 +67,31 @@ async function stdinText() {
|
|
|
64
67
|
throw new Error('Input must be 10 MiB or smaller.');
|
|
65
68
|
chunks.push(buffer);
|
|
66
69
|
}
|
|
67
|
-
|
|
70
|
+
const input = Buffer.concat(chunks);
|
|
71
|
+
if (!isUtf8(input))
|
|
72
|
+
throw new Error('Input must be valid UTF-8.');
|
|
73
|
+
return input.toString('utf8');
|
|
74
|
+
}
|
|
75
|
+
async function inputContents(paths, allowStdin) {
|
|
76
|
+
if (paths.length < 1 || paths.length > 50)
|
|
77
|
+
throw new Error('Provide between 1 and 50 --input files.');
|
|
78
|
+
if (paths.some(path => !path.trim()))
|
|
79
|
+
throw new Error('--input requires a nonempty file path.');
|
|
80
|
+
if (paths.includes('-')) {
|
|
81
|
+
if (!allowStdin)
|
|
82
|
+
throw new Error('verify --input - is not supported. Supply the original file.');
|
|
83
|
+
if (paths.length !== 1)
|
|
84
|
+
throw new Error('--input - must be the sole input.');
|
|
85
|
+
return stdinText();
|
|
86
|
+
}
|
|
87
|
+
let remaining = 10 * 1024 * 1024;
|
|
88
|
+
const contents = [];
|
|
89
|
+
for (const path of paths) {
|
|
90
|
+
const content = await readBoundedFile(resolve(path), remaining);
|
|
91
|
+
remaining -= Buffer.byteLength(content);
|
|
92
|
+
contents.push(content);
|
|
93
|
+
}
|
|
94
|
+
return contents.length === 1 ? contents[0] : contents;
|
|
68
95
|
}
|
|
69
96
|
async function canonicalOutput(path) {
|
|
70
97
|
let existing = path;
|
|
@@ -92,8 +119,8 @@ function insideBundleResults(bundleRoot, path) {
|
|
|
92
119
|
}
|
|
93
120
|
export async function main(args = process.argv.slice(2)) {
|
|
94
121
|
const { values, positionals } = parseArgs({ args, allowPositionals: true, strict: true, options: {
|
|
95
|
-
help: { type: 'boolean', short: 'h' }, version: { type: 'boolean', short: 'v' }, input: { type: 'string' }, error: { type: 'string' }, report: { type: 'string' },
|
|
96
|
-
format: { type: 'string' }, profile: { type: 'string' }, project: { type: 'string' }, environment: { type: 'string' },
|
|
122
|
+
help: { type: 'boolean', short: 'h' }, version: { type: 'boolean', short: 'v' }, input: { type: 'string', multiple: true }, error: { type: 'string' }, report: { type: 'string' },
|
|
123
|
+
format: { type: 'string' }, profile: { type: 'string' }, baseline: { type: 'string' }, project: { type: 'string' }, environment: { type: 'string' },
|
|
97
124
|
release: { type: 'string' }, page: { type: 'string' }, type: { type: 'string' }, runtime: { type: 'string' }, from: { type: 'string' }, to: { type: 'string' },
|
|
98
125
|
top: { type: 'string' }, 'min-count': { type: 'string' }, out: { type: 'string' }, reviewed: { type: 'boolean' },
|
|
99
126
|
reproduce: { type: 'string', multiple: true }, precondition: { type: 'string', multiple: true },
|
|
@@ -232,7 +259,7 @@ export async function main(args = process.argv.slice(2)) {
|
|
|
232
259
|
if (Object.keys(values).some(key => !['input', 'profile', 'help'].includes(key)))
|
|
233
260
|
throw new Error('Unsupported option for verify.');
|
|
234
261
|
const result = await verifyBundle(resolve(positionals[1]), {
|
|
235
|
-
...(values.input ? { input: await
|
|
262
|
+
...(values.input ? { input: await inputContents(values.input, false) } : {}),
|
|
236
263
|
...(values.profile ? { profile: await readBoundedFile(resolve(values.profile), 1024 * 1024) } : {}),
|
|
237
264
|
});
|
|
238
265
|
process.stdout.write(`Bundle verified. Suite: ${result.suite ? 'present' : 'none'}; review: ${result.reviewed ? 'acknowledged' : 'pending'}; original input: ${result.sourceChecked ? 'checked' : 'not supplied'}.\n`);
|
|
@@ -242,6 +269,8 @@ export async function main(args = process.argv.slice(2)) {
|
|
|
242
269
|
throw new Error('Use analyze, init-profile, verify, link-run, results, or compare. See --help.');
|
|
243
270
|
if (values.report)
|
|
244
271
|
throw new Error('--report applies to link-run only.');
|
|
272
|
+
if (values.baseline !== undefined && values.baseline.trim() === '')
|
|
273
|
+
throw new Error('--baseline requires a bundle directory.');
|
|
245
274
|
if ((values.input === undefined) === (values.error === undefined))
|
|
246
275
|
throw new Error('Provide exactly one of --input or --error.');
|
|
247
276
|
const format = values.format ?? 'auto';
|
|
@@ -271,18 +300,25 @@ export async function main(args = process.argv.slice(2)) {
|
|
|
271
300
|
else {
|
|
272
301
|
if (values.reproduce || values.precondition || values.expected || values['expected-source'])
|
|
273
302
|
throw new Error('Reported context options require --error. Use manual JSON or a profile for file input.');
|
|
274
|
-
content =
|
|
303
|
+
content = await inputContents(values.input, true);
|
|
275
304
|
}
|
|
276
|
-
const
|
|
305
|
+
const options = {
|
|
277
306
|
format: inputFormat, ...(values.profile ? { profile: await readBoundedFile(resolve(values.profile), 1024 * 1024) } : {}),
|
|
278
307
|
project: values.project, environment: values.environment, release: values.release, page: values.page, type: values.type, runtime: values.runtime,
|
|
279
308
|
from: values.from, to: values.to, ...(values.top !== undefined ? { top: Number(values.top) } : {}),
|
|
280
309
|
...(values['min-count'] !== undefined ? { minCount: Number(values['min-count']) } : {}),
|
|
281
|
-
}
|
|
310
|
+
};
|
|
311
|
+
const baseline = values.baseline === undefined ? undefined : resolve(values.baseline);
|
|
312
|
+
const analysis = baseline === undefined ? analyzeErrors(content, options) : await analyzeWithBaseline(content, baseline, options);
|
|
282
313
|
const out = resolve(values.out ?? `.error-to-test/run-${Date.now()}-${randomUUID().slice(0, 8)}`);
|
|
314
|
+
if (baseline !== undefined && insideBundleResults(await realpath(baseline), await canonicalOutput(out))) {
|
|
315
|
+
throw new Error('The analysis cannot be written inside the baseline bundle results directory. Choose an outside --out DIRECTORY path.');
|
|
316
|
+
}
|
|
283
317
|
const files = await writeBundle(out, analysis, { reviewed: values.reviewed });
|
|
284
318
|
const drafts = analysis.candidates.filter(candidate => candidate.state === 'draft').length;
|
|
285
319
|
process.stdout.write(`${analysis.groups.length} error groups; ${analysis.candidates.length} TC candidates (${drafts} drafts, ${analysis.candidates.length - drafts} need context).\n`);
|
|
320
|
+
if (analysis.selection)
|
|
321
|
+
process.stdout.write(`${analysis.selection.onlyCurrentGroupCount} only-current groups; ${analysis.selection.excludedGroupCount} baseline-matched groups excluded from TC selection.\n`);
|
|
286
322
|
process.stdout.write(`Review ${resolve(out, 'report.md')}\n${files.length} artifacts written. Review acknowledgment: ${values.reviewed ? 'yes' : 'pending'}.\n`);
|
|
287
323
|
}
|
|
288
324
|
export function reportCliError(error) {
|
package/dist/comparison.d.ts
CHANGED
|
@@ -34,4 +34,5 @@ export interface AnalysisComparison {
|
|
|
34
34
|
warnings: string[];
|
|
35
35
|
}
|
|
36
36
|
export declare function compareBundles(baselineDirectory: string, currentDirectory: string): Promise<AnalysisComparison>;
|
|
37
|
+
export declare function compareAnalyses(baselineAnalysis: unknown, currentAnalysis: unknown): AnalysisComparison;
|
|
37
38
|
export declare function renderComparison(comparison: AnalysisComparison): string;
|
package/dist/comparison.js
CHANGED
|
@@ -96,8 +96,15 @@ function aggregate(groups) {
|
|
|
96
96
|
const sorted = (items) => [...items].sort();
|
|
97
97
|
function occurrence(a) { return { count: a.count, groupIds: sorted(a.ids), releases: sorted(a.releases).map(redactText) }; }
|
|
98
98
|
export async function compareBundles(baselineDirectory, currentDirectory) {
|
|
99
|
-
const baseline =
|
|
100
|
-
const current =
|
|
99
|
+
const baseline = (await readVerifiedBundle(baselineDirectory)).analysis;
|
|
100
|
+
const current = (await readVerifiedBundle(currentDirectory)).analysis;
|
|
101
|
+
return compareAnalyses(baseline, current);
|
|
102
|
+
}
|
|
103
|
+
// Shared by verified bundle comparison and baseline-aware candidate selection.
|
|
104
|
+
// Identity is computed from the stored normalized fields before display redaction.
|
|
105
|
+
export function compareAnalyses(baselineAnalysis, currentAnalysis) {
|
|
106
|
+
const baseline = parseSnapshot(baselineAnalysis, 'Baseline');
|
|
107
|
+
const current = parseSnapshot(currentAnalysis, 'Current');
|
|
101
108
|
if (baseline.side.coverage.frequency !== current.side.coverage.frequency)
|
|
102
109
|
throw new Error('Comparison requires matching count frequency; captured events and submitted reports cannot share a delta.');
|
|
103
110
|
const before = aggregate(baseline.groups), after = aggregate(current.groups);
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { analyzeErrors, type AnalyzeOptions } from './analysis.ts';
|
|
1
|
+
export { analyzeErrors, analyzeWithBaseline, type AnalyzeOptions } from './analysis.ts';
|
|
2
2
|
export { parseInput, type ParseInputOptions } from './input.ts';
|
|
3
3
|
export { groupObservations } from './grouping.ts';
|
|
4
4
|
export { createCandidates, parseProfile } from './candidates.ts';
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { analyzeErrors } from "./analysis.js";
|
|
1
|
+
export { analyzeErrors, analyzeWithBaseline } from "./analysis.js";
|
|
2
2
|
export { parseInput } from "./input.js";
|
|
3
3
|
export { groupObservations } from "./grouping.js";
|
|
4
4
|
export { createCandidates, parseProfile } from "./candidates.js";
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { InputFileFingerprint } from './types.ts';
|
|
2
|
+
/** Internal source fingerprint used by the parser and bundle verifier. */
|
|
3
|
+
export declare function inputSource(content: string | readonly string[]): {
|
|
4
|
+
sha256: string;
|
|
5
|
+
inputs?: InputFileFingerprint[];
|
|
6
|
+
};
|
|
7
|
+
/** Validate persisted source metadata without reading or retaining original input. */
|
|
8
|
+
export declare function validateInputSource(value: unknown): void;
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
const MAX_FILES = 50;
|
|
3
|
+
const MAX_BYTES = 10 * 1024 * 1024;
|
|
4
|
+
const SHA256 = /^[a-f0-9]{64}$/;
|
|
5
|
+
function hash(value) {
|
|
6
|
+
return createHash('sha256').update(value).digest('hex');
|
|
7
|
+
}
|
|
8
|
+
function descriptor(inputs) {
|
|
9
|
+
return JSON.stringify({ schemaVersion: 'error-to-test/inputs-1', inputs });
|
|
10
|
+
}
|
|
11
|
+
/** Internal source fingerprint used by the parser and bundle verifier. */
|
|
12
|
+
export function inputSource(content) {
|
|
13
|
+
if (typeof content !== 'string' && !Array.isArray(content))
|
|
14
|
+
throw new Error('Input must be a string or an array of strings.');
|
|
15
|
+
const files = typeof content === 'string' ? [content] : content;
|
|
16
|
+
if (files.length < 1 || files.length > MAX_FILES)
|
|
17
|
+
throw new Error('Input must contain 1 to 50 files.');
|
|
18
|
+
let totalBytes = 0;
|
|
19
|
+
const inputs = files.map((file) => {
|
|
20
|
+
if (typeof file !== 'string')
|
|
21
|
+
throw new Error('Every input file must be a string.');
|
|
22
|
+
const byteLength = Buffer.byteLength(file, 'utf8');
|
|
23
|
+
totalBytes += byteLength;
|
|
24
|
+
if (totalBytes > MAX_BYTES)
|
|
25
|
+
throw new Error('Input exceeds 10 MiB.');
|
|
26
|
+
return { sha256: hash(file), byteLength };
|
|
27
|
+
});
|
|
28
|
+
return inputs.length === 1 ? { sha256: inputs[0].sha256 } : { sha256: hash(descriptor(inputs)), inputs };
|
|
29
|
+
}
|
|
30
|
+
/** Validate persisted source metadata without reading or retaining original input. */
|
|
31
|
+
export function validateInputSource(value) {
|
|
32
|
+
const invalid = () => { throw new Error('STALE_BUNDLE: Invalid input source fingerprint.'); };
|
|
33
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value))
|
|
34
|
+
invalid();
|
|
35
|
+
const source = value;
|
|
36
|
+
if (typeof source.sha256 !== 'string' || !SHA256.test(source.sha256))
|
|
37
|
+
invalid();
|
|
38
|
+
if (source.inputs === undefined)
|
|
39
|
+
return;
|
|
40
|
+
const rawInputs = source.inputs;
|
|
41
|
+
if (!Array.isArray(rawInputs))
|
|
42
|
+
throw new Error('STALE_BUNDLE: Invalid input source fingerprint.');
|
|
43
|
+
if (rawInputs.length < 2 || rawInputs.length > MAX_FILES)
|
|
44
|
+
invalid();
|
|
45
|
+
let totalBytes = 0;
|
|
46
|
+
const inputs = rawInputs.map((value) => {
|
|
47
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value))
|
|
48
|
+
invalid();
|
|
49
|
+
const file = value;
|
|
50
|
+
if (typeof file.sha256 !== 'string' || !SHA256.test(file.sha256) ||
|
|
51
|
+
typeof file.byteLength !== 'number' || !Number.isInteger(file.byteLength) ||
|
|
52
|
+
file.byteLength < 0 || file.byteLength > MAX_BYTES)
|
|
53
|
+
invalid();
|
|
54
|
+
totalBytes += file.byteLength;
|
|
55
|
+
if (totalBytes > MAX_BYTES)
|
|
56
|
+
invalid();
|
|
57
|
+
return { sha256: file.sha256, byteLength: file.byteLength };
|
|
58
|
+
});
|
|
59
|
+
if (hash(descriptor(inputs)) !== source.sha256)
|
|
60
|
+
invalid();
|
|
61
|
+
}
|
package/dist/input.d.ts
CHANGED
|
@@ -10,4 +10,4 @@ export interface ParseInputOptions {
|
|
|
10
10
|
from?: string;
|
|
11
11
|
to?: string;
|
|
12
12
|
}
|
|
13
|
-
export declare function parseInput(content: string, options?: ParseInputOptions): ParsedInput;
|
|
13
|
+
export declare function parseInput(content: string | readonly string[], options?: ParseInputOptions): ParsedInput;
|
package/dist/input.js
CHANGED
|
@@ -1,9 +1,8 @@
|
|
|
1
|
-
import { createHash } from 'node:crypto';
|
|
2
1
|
import { record, text, optionalText, strings, timestamp, parseWebSteps, hash } from "./validation.js";
|
|
3
2
|
import { redactText, safeUrl } from "./redact.js";
|
|
3
|
+
import { inputSource } from "./input-source.js";
|
|
4
4
|
const TYPES = new Set(['javascript', 'promise', 'react', 'console', 'http', 'network', 'manual']);
|
|
5
5
|
const RUNTIMES = new Set(['browser', 'webview-ios', 'webview-android', 'unknown']);
|
|
6
|
-
const MAX_BYTES = 10 * 1024 * 1024;
|
|
7
6
|
const MAX_RECORDS = 10_000;
|
|
8
7
|
const LOGGER_PREFIX = /^\[(?:ERROR|WARN|WARNING|INFO|DEBUG|TRACE|FATAL|vite|timestamp|\d{4}-\d{2}-\d{2}(?:[ T]\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2})?)?|\d{2}:\d{2}:\d{2})\][ \t]+\S/i;
|
|
9
8
|
function eventType(value, label) {
|
|
@@ -152,24 +151,9 @@ function manualError(value, index, defaults) {
|
|
|
152
151
|
...(!alteredExpected && expectedSource !== undefined ? { expectedSource } : {}), steps: stepResult.steps,
|
|
153
152
|
};
|
|
154
153
|
}
|
|
155
|
-
|
|
156
|
-
if (Buffer.byteLength(content, 'utf8') > MAX_BYTES)
|
|
157
|
-
throw new Error('Input exceeds 10 MiB');
|
|
158
|
-
if (!content.trim())
|
|
159
|
-
throw new Error('Input is empty');
|
|
160
|
-
const from = options.from === undefined ? undefined : timestamp(options.from, 'from');
|
|
161
|
-
const to = options.to === undefined ? undefined : timestamp(options.to, 'to');
|
|
162
|
-
if (from && to && from > to)
|
|
163
|
-
throw new Error('from must not exceed to');
|
|
164
|
-
const format = options.format ?? 'auto';
|
|
165
|
-
if (!['auto', 'json', 'text'].includes(format))
|
|
166
|
-
throw new Error('Invalid input format');
|
|
154
|
+
function decodeDocument(content, format) {
|
|
167
155
|
const trimmed = content.trimStart();
|
|
168
156
|
const isJson = format === 'json' || (format === 'auto' && /^[\[{]/.test(trimmed) && !LOGGER_PREFIX.test(trimmed));
|
|
169
|
-
let observations;
|
|
170
|
-
let kind;
|
|
171
|
-
let partial = false;
|
|
172
|
-
let raw;
|
|
173
157
|
if (isJson) {
|
|
174
158
|
let parsed;
|
|
175
159
|
// Ignore a file's BOM only while parsing; provenance hashes the original content.
|
|
@@ -179,6 +163,9 @@ export function parseInput(content, options = {}) {
|
|
|
179
163
|
catch {
|
|
180
164
|
throw new Error('Malformed JSON input');
|
|
181
165
|
}
|
|
166
|
+
let kind;
|
|
167
|
+
let partial = false;
|
|
168
|
+
let raw;
|
|
182
169
|
if (Array.isArray(parsed)) {
|
|
183
170
|
kind = 'browser-error-json';
|
|
184
171
|
raw = parsed;
|
|
@@ -205,19 +192,44 @@ export function parseInput(content, options = {}) {
|
|
|
205
192
|
}
|
|
206
193
|
if (raw.length === 0)
|
|
207
194
|
throw new Error('Input has no records');
|
|
208
|
-
|
|
209
|
-
throw new Error('Input exceeds 10000 records');
|
|
210
|
-
observations = raw.map((item, index) => kind === 'browser-error-json' ? browserEvent(item, index) : manualError(item, index, options));
|
|
195
|
+
return { kind, partial, raw };
|
|
211
196
|
}
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
raw
|
|
197
|
+
const lines = content.trim().split(/\r?\n/);
|
|
198
|
+
const message = lines.shift().trim();
|
|
199
|
+
if (!message)
|
|
200
|
+
throw new Error('Error message is empty');
|
|
201
|
+
// Text is one logical report. Its canonical raw identity must not depend on
|
|
202
|
+
// whitespace outside the parsed message and stack.
|
|
203
|
+
return { kind: 'manual-text', partial: false,
|
|
204
|
+
raw: [{ message, ...(lines.length ? { stack: lines.join('\n') } : {}) }] };
|
|
205
|
+
}
|
|
206
|
+
export function parseInput(content, options = {}) {
|
|
207
|
+
const source = inputSource(content);
|
|
208
|
+
const files = typeof content === 'string' ? [content] : content;
|
|
209
|
+
if (files.some(file => !file.trim()))
|
|
210
|
+
throw new Error('Input is empty');
|
|
211
|
+
const from = options.from === undefined ? undefined : timestamp(options.from, 'from');
|
|
212
|
+
const to = options.to === undefined ? undefined : timestamp(options.to, 'to');
|
|
213
|
+
if (from && to && from > to)
|
|
214
|
+
throw new Error('from must not exceed to');
|
|
215
|
+
const format = options.format ?? 'auto';
|
|
216
|
+
if (!['auto', 'json', 'text'].includes(format))
|
|
217
|
+
throw new Error('Invalid input format');
|
|
218
|
+
let kind;
|
|
219
|
+
let partial = false;
|
|
220
|
+
const raw = [];
|
|
221
|
+
for (const file of files) {
|
|
222
|
+
const document = decodeDocument(file, format);
|
|
223
|
+
if (kind !== undefined && document.kind !== kind)
|
|
224
|
+
throw new Error('Input files must have the same source kind.');
|
|
225
|
+
kind = document.kind;
|
|
226
|
+
partial ||= document.partial;
|
|
227
|
+
if (raw.length + document.raw.length > MAX_RECORDS)
|
|
228
|
+
throw new Error('Input exceeds 10000 records');
|
|
229
|
+
raw.push(...document.raw);
|
|
220
230
|
}
|
|
231
|
+
const observations = raw.map((item, index) => kind === 'browser-error-json'
|
|
232
|
+
? browserEvent(item, index) : manualError(item, index, options));
|
|
221
233
|
const inputCount = raw.length;
|
|
222
234
|
const seen = new Map();
|
|
223
235
|
const unique = [];
|
|
@@ -238,6 +250,8 @@ export function parseInput(content, options = {}) {
|
|
|
238
250
|
}
|
|
239
251
|
}
|
|
240
252
|
const warnings = [];
|
|
253
|
+
if (source.inputs)
|
|
254
|
+
warnings.push(`Combined ${source.inputs.length} input files in supplied order; counts describe the supplied records across files, not global rates.`);
|
|
241
255
|
if (partial)
|
|
242
256
|
warnings.push('Source export is partial; observed counts may be incomplete.');
|
|
243
257
|
if (duplicates)
|
|
@@ -263,9 +277,9 @@ export function parseInput(content, options = {}) {
|
|
|
263
277
|
warnings.push('Undated manual reports were excluded by date filters.');
|
|
264
278
|
return {
|
|
265
279
|
observations: selected,
|
|
266
|
-
coverage: { kind, frequency: kind === 'browser-error-json' ? 'captured-events' : 'submitted-reports',
|
|
280
|
+
coverage: { kind: kind, frequency: kind === 'browser-error-json' ? 'captured-events' : 'submitted-reports',
|
|
267
281
|
partial, inputCount, duplicates, filtered, retention: 'unknown',
|
|
268
282
|
...(from || to ? { period: { ...(from ? { from } : {}), ...(to ? { to } : {}) } } : {}) },
|
|
269
|
-
sha256:
|
|
283
|
+
sha256: source.sha256, ...(source.inputs ? { inputs: source.inputs } : {}), warnings,
|
|
270
284
|
};
|
|
271
285
|
}
|
package/dist/types.d.ts
CHANGED
|
@@ -78,10 +78,15 @@ export interface SourceCoverage {
|
|
|
78
78
|
to?: string;
|
|
79
79
|
};
|
|
80
80
|
}
|
|
81
|
+
export interface InputFileFingerprint {
|
|
82
|
+
sha256: string;
|
|
83
|
+
byteLength: number;
|
|
84
|
+
}
|
|
81
85
|
export interface ParsedInput {
|
|
82
86
|
observations: ErrorObservation[];
|
|
83
87
|
coverage: SourceCoverage;
|
|
84
88
|
sha256: string;
|
|
89
|
+
inputs?: InputFileFingerprint[];
|
|
85
90
|
warnings: string[];
|
|
86
91
|
}
|
|
87
92
|
export interface IssueGroup {
|
|
@@ -157,12 +162,23 @@ export interface Analysis {
|
|
|
157
162
|
schemaVersion: 'error-to-test/analysis-1';
|
|
158
163
|
source: {
|
|
159
164
|
sha256: string;
|
|
165
|
+
inputs?: InputFileFingerprint[];
|
|
160
166
|
profileSha256?: string;
|
|
161
167
|
};
|
|
162
168
|
coverage: SourceCoverage;
|
|
163
169
|
groups: IssueGroup[];
|
|
164
170
|
candidates: TestCandidate[];
|
|
165
171
|
warnings: string[];
|
|
172
|
+
selection?: {
|
|
173
|
+
mode: 'only-current';
|
|
174
|
+
baseline: {
|
|
175
|
+
inputSha256: string;
|
|
176
|
+
analysisSha256: string;
|
|
177
|
+
coverage: SourceCoverage;
|
|
178
|
+
};
|
|
179
|
+
onlyCurrentGroupCount: number;
|
|
180
|
+
excludedGroupCount: number;
|
|
181
|
+
};
|
|
166
182
|
}
|
|
167
183
|
export interface FlowQaSuite {
|
|
168
184
|
schemaVersion: 'flow-qa/suite-1';
|
package/package.json
CHANGED