@ihyeon/error-to-test 0.1.11 → 0.1.12

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 CHANGED
@@ -48,6 +48,21 @@ JavaScript API에서는 `analyzeErrors(content, { minCount: 3, top: 10 })`으로
48
48
 
49
49
  기본 suite는 검토 질문으로 실행이 차단됩니다. TC와 프로필을 확인한 뒤 다른 출력 폴더에 `--reviewed`로 다시 생성하면 검토 질문만 제거됩니다. 나머지 질문은 그대로 실행을 차단합니다. 프로필의 `setupConfirmed`는 준비 조건을 확인했다는 표시이며, 계정·데이터를 자동으로 준비하는 기능은 아닙니다.
50
50
 
51
+ 프로필 JSON은 기존 분석 결과에서 틀을 자동으로 만들 수 있습니다.
52
+
53
+ ```sh
54
+ error-to-test analyze --input errors.json --min-count 3 --out ./initial-analysis
55
+ error-to-test init-profile ./initial-analysis --out ./review-profile.json
56
+ # report.md와 확인한 앱 요구사항을 보며 review-profile.json 수정
57
+ error-to-test analyze --input errors.json --min-count 3 --profile ./review-profile.json --out ./review-analysis
58
+ ```
59
+
60
+ 선택된 오류 묶음마다 규칙을 하나씩 만들고 `match.groupId`로 정확히 연결합니다. 메시지·페이지가 같아도 소스 위치나 릴리스가 다른 묶음에 규칙이 퍼지지 않습니다. 같은 원본 입력과 필터·수동 메타데이터를 유지해서 다시 분석하세요. 새로 생기거나 달라진 묶음은 별도 검토가 필요합니다.
61
+
62
+ 각 규칙의 `requirement`와 `expectedSource`를 채우고, `preconditions`와 명시적인 재현 동작·assertion을 `steps`에 작성하세요. 확인된 관측 페이지 경로만 `open` 단계로 미리 넣으며, 동작이나 기대 결과는 추측하지 않습니다. 준비 조건을 확인한 뒤 `setupConfirmed: true`로 바꾸고, 생성된 질문에 답한 뒤 해당 질문을 제거하세요. 처음 생성한 빈 기대 결과·출처는 검증에서 거부됩니다. 나머지 질문, 원본의 충돌, 실행 환경 확인과 기존 검토 게이트도 계속 적용됩니다.
63
+
64
+ `init-profile`은 검증에 통과한 번들만 읽고 새 파일에 저장합니다. 수정된 번들, 선택된 TC가 없는 결과, 기존 출력 파일은 거부합니다. 원래 분석 산출물을 덮어쓰지 않습니다. API의 `createProfileTemplate(analysis)`도 편집용 `error-to-test/profile-1` 객체를 만들며, 완성된 실행 프로필을 의미하지 않습니다.
65
+
51
66
  ```sh
52
67
  node bin/error-to-test.mjs verify .error-to-test/example --input examples/errors.json --profile examples/profile.json
53
68
  node bin/error-to-test.mjs analyze --input examples/errors.json --profile examples/profile.json --reviewed --out .error-to-test/reviewed
package/README.md CHANGED
@@ -73,6 +73,23 @@ See [examples/profile.json](examples/profile.json). Profiles use `schemaVersion:
73
73
 
74
74
  Supported web steps match Flow QA: `open`, `click`, `fill`, `act`, `assertVisible`, `assertText`, `assertUrl`, and `assertAgent`. Several matching rules produce several traceable candidates. Conflicts/questions in any original report are checked before representative evidence is sampled and stay blocked even when a profile matches.
75
75
 
76
+ ### Start a profile from an analysis
77
+
78
+ Generate an editable profile from a verified analysis bundle instead of writing its structure and match rules by hand:
79
+
80
+ ```sh
81
+ error-to-test analyze --input errors.json --min-count 3 --out ./initial-analysis
82
+ error-to-test init-profile ./initial-analysis --out ./review-profile.json
83
+ # Edit review-profile.json using report.md and your confirmed app requirements.
84
+ error-to-test analyze --input errors.json --min-count 3 --profile ./review-profile.json --out ./review-analysis
85
+ ```
86
+
87
+ The template contains one scenario per selected error group, even when several candidates refer to that group. Each scenario uses an exact `match.groupId`, so a different source location, release, or other grouping boundary cannot receive the scenario just because its message and page look similar. Reuse the original input and the same analysis filters/manual metadata. New or changed groups require their own review.
88
+
89
+ For each scenario, fill `requirement` and `expectedSource`, establish `preconditions`, and supply explicit reproduction actions and an observable assertion in `steps`. Only a safe observed page path is prefilled as an `open` step. No actions or expected outcomes are inferred. Set `setupConfirmed: true` after checking setup, and remove the template question after answering it. The initial empty requirement/source deliberately fail profile validation; setup, runtime, source conflicts, missing steps, and remaining questions still block incomplete cases. A complete draft still needs the usual `--reviewed` acknowledgement before execution.
90
+
91
+ `init-profile` requires a new output file, refuses stale bundles and empty candidate selections, and never overwrites an existing file. The original analysis artifacts remain unchanged. The API equivalent is `createProfileTemplate(analysis)`; its result is an incomplete `error-to-test/profile-1` object for editing, not an execution-ready profile.
92
+
76
93
  ## Review and use Flow QA
77
94
 
78
95
  Generated files (Flow QA source is limited to 128 KB; suite JSON to 512 KiB):
@@ -5,6 +5,17 @@ export declare function writeBundle(directory: string, analysis: Analysis, optio
5
5
  reviewed?: boolean;
6
6
  }): Promise<string[]>;
7
7
  export declare function readBoundedFile(path: string, maxBytes?: number): Promise<string>;
8
+ export declare function readVerifiedBundle(directory: string, options?: {
9
+ input?: string;
10
+ profile?: string;
11
+ }): Promise<{
12
+ analysis: Record<string, unknown>;
13
+ verification: {
14
+ suite: boolean;
15
+ reviewed: boolean;
16
+ sourceChecked: boolean;
17
+ };
18
+ }>;
8
19
  export declare function verifyBundle(directory: string, options?: {
9
20
  input?: string;
10
21
  profile?: string;
package/dist/artifacts.js CHANGED
@@ -86,7 +86,7 @@ export async function readBoundedFile(path, maxBytes = 10 * 1024 * 1024) {
86
86
  throw new Error('Input exceeded the size limit while reading.');
87
87
  return content;
88
88
  }
89
- export async function verifyBundle(directory, options = {}) {
89
+ export async function readVerifiedBundle(directory, options = {}) {
90
90
  const root = resolve(directory);
91
91
  const parse = (content, label) => {
92
92
  try {
@@ -134,5 +134,8 @@ export async function verifyBundle(directory, options = {}) {
134
134
  throw new Error('STALE_BUNDLE: Input changed since analysis.');
135
135
  if (options.profile !== undefined && hash(options.profile) !== provenance.profileSha256)
136
136
  throw new Error('STALE_BUNDLE: Profile changed since analysis.');
137
- return { suite: suiteExists, reviewed: provenance.reviewed, sourceChecked: options.input !== undefined };
137
+ return { analysis, verification: { suite: suiteExists, reviewed: provenance.reviewed, sourceChecked: options.input !== undefined } };
138
+ }
139
+ export async function verifyBundle(directory, options = {}) {
140
+ return (await readVerifiedBundle(directory, options)).verification;
138
141
  }
@@ -47,7 +47,7 @@ export function parseProfile(raw) {
47
47
  const label = `profile.scenarios[${index}]`;
48
48
  const rule = record(rawRule, label);
49
49
  const match = record(rule.match, `${label}.match`);
50
- const fields = ['type', 'messageIncludes', 'pagePath', 'networkPath', 'environment', 'release', 'runtime'];
50
+ const fields = ['groupId', 'type', 'messageIncludes', 'pagePath', 'networkPath', 'environment', 'release', 'runtime'];
51
51
  if (!fields.some((field) => match[field] !== undefined))
52
52
  throw new Error(`${label}.match needs at least one predicate.`);
53
53
  const type = optionalText(match.type, `${label}.match.type`);
@@ -66,6 +66,7 @@ export function parseProfile(raw) {
66
66
  id: identifier(rule.id, `${label}.id`),
67
67
  title: profileText(rule.title, `${label}.title`),
68
68
  match: {
69
+ ...(match.groupId !== undefined ? { groupId: identifier(match.groupId, `${label}.match.groupId`) } : {}),
69
70
  ...(type ? { type: type } : {}),
70
71
  ...(match.messageIncludes !== undefined ? { messageIncludes: profileText(match.messageIncludes, `${label}.match.messageIncludes`) } : {}),
71
72
  ...(page ? { pagePath: page } : {}),
@@ -93,7 +94,8 @@ function confirmed(value, label) {
93
94
  }
94
95
  function matches(rule, group) {
95
96
  const match = rule.match;
96
- return (!match.type || match.type === group.type)
97
+ return (match.groupId === undefined || match.groupId === group.id)
98
+ && (!match.type || match.type === group.type)
97
99
  && (!match.messageIncludes || group.message.includes(match.messageIncludes))
98
100
  && (!match.pagePath || match.pagePath === group.pagePath)
99
101
  && (!match.environment || match.environment === group.environment)
package/dist/cli.js CHANGED
@@ -1,9 +1,10 @@
1
1
  import { parseArgs } from 'node:util';
2
2
  import { randomUUID } from 'node:crypto';
3
- import { readFile } from 'node:fs/promises';
4
- import { resolve } from 'node:path';
3
+ import { mkdir, readFile, writeFile } from 'node:fs/promises';
4
+ import { dirname, resolve } from 'node:path';
5
5
  import { analyzeErrors } from "./analysis.js";
6
- import { readBoundedFile, verifyBundle, writeBundle } from "./artifacts.js";
6
+ import { jsonText, readBoundedFile, readVerifiedBundle, verifyBundle, writeBundle } from "./artifacts.js";
7
+ import { createProfileTemplate } from "./profile-template.js";
7
8
  import { redactText } from "./redact.js";
8
9
  import { linkFlowQaReport } from "./results.js";
9
10
  const help = `Error to Test — local error analysis and regression TC drafts
@@ -13,6 +14,7 @@ const help = `Error to Test — local error analysis and regression TC drafts
13
14
  error-to-test analyze --error "TypeError: item is undefined" --page /items --out new-directory
14
15
  cat error.txt | error-to-test analyze --input - --format text --out new-directory
15
16
  error-to-test verify new-directory [--input errors.json] [--profile profile.json]
17
+ error-to-test init-profile new-directory --out profile.json
16
18
  error-to-test link-run new-directory --report path/to/qa-report.json
17
19
 
18
20
  Options:
@@ -33,7 +35,8 @@ Options:
33
35
  --from ISO --to ISO Filter observed timestamps; undated reports are excluded
34
36
  --min-count N Select groups with at least N records after dedup/date filtering (1..10000)
35
37
  --top N Generate TCs for the first N eligible ranked groups (1..100; after --min-count)
36
- --out DIRECTORY New directory; existing files are never overwritten
38
+ --out DIRECTORY New analyze directory; existing files are never overwritten
39
+ --out FILE New init-profile JSON file; existing files are never overwritten
37
40
  --reviewed Acknowledge review; unresolved questions still block cases
38
41
  --report FILE Normalized Flow QA report (link-run only)
39
42
  --version, -v Print the package version
@@ -75,11 +78,36 @@ export async function main(args = process.argv.slice(2)) {
75
78
  }
76
79
  if (positionals.length === 0) {
77
80
  if (Object.keys(values).length)
78
- throw new Error('A command is required. Use analyze, verify, or link-run. See --help.');
81
+ throw new Error('A command is required. Use analyze, init-profile, verify, or link-run. See --help.');
79
82
  process.stdout.write(help);
80
83
  return;
81
84
  }
82
85
  const command = positionals[0];
86
+ if (command === 'init-profile') {
87
+ if (positionals.length !== 2 || !positionals[1] || !values.out)
88
+ throw new Error('init-profile requires one bundle directory and --out FILE.');
89
+ if (Object.keys(values).some(key => !['out', 'help'].includes(key)))
90
+ throw new Error('Unsupported option for init-profile. Use only --out FILE.');
91
+ const { analysis } = await readVerifiedBundle(resolve(positionals[1]));
92
+ if (analysis.schemaVersion !== 'error-to-test/analysis-1' || !Array.isArray(analysis.groups) || !Array.isArray(analysis.candidates))
93
+ throw new Error('Unsupported analysis contract.');
94
+ const profile = createProfileTemplate(analysis);
95
+ const content = jsonText(profile);
96
+ if (Buffer.byteLength(content) > 1024 * 1024)
97
+ throw new Error('The generated profile exceeds 1 MiB. Narrow the selected groups.');
98
+ const out = resolve(values.out);
99
+ await mkdir(dirname(out), { recursive: true });
100
+ try {
101
+ await writeFile(out, content, { flag: 'wx', mode: 0o600 });
102
+ }
103
+ catch (error) {
104
+ if (error.code === 'EEXIST')
105
+ throw new Error('The output file already exists. Choose a new --out FILE path.');
106
+ throw error;
107
+ }
108
+ process.stdout.write(`Profile template written: ${out}\nFill requirement, expectedSource, preconditions, and steps; confirm setupConfirmed and clear answered questions. Then rerun analyze with the original input and --profile ${out}.\n`);
109
+ return;
110
+ }
83
111
  if (command === 'link-run') {
84
112
  if (positionals.length !== 2 || !positionals[1] || !values.report)
85
113
  throw new Error('link-run requires a bundle directory and --report.');
@@ -109,7 +137,7 @@ export async function main(args = process.argv.slice(2)) {
109
137
  return;
110
138
  }
111
139
  if (command !== 'analyze' || positionals.length !== 1)
112
- throw new Error('Use analyze, verify, or link-run. See --help.');
140
+ throw new Error('Use analyze, init-profile, verify, or link-run. See --help.');
113
141
  if (values.report)
114
142
  throw new Error('--report applies to link-run only.');
115
143
  if ((values.input === undefined) === (values.error === undefined))
package/dist/index.d.ts CHANGED
@@ -5,4 +5,5 @@ export { createCandidates, parseProfile } from './candidates.ts';
5
5
  export { exportFlowQa } from './exports/flow-qa.ts';
6
6
  export { writeBundle, verifyBundle, renderReport } from './artifacts.ts';
7
7
  export { linkFlowQaReport } from './results.ts';
8
+ export { createProfileTemplate } from './profile-template.ts';
8
9
  export type * from './types.ts';
package/dist/index.js CHANGED
@@ -5,3 +5,4 @@ export { createCandidates, parseProfile } from "./candidates.js";
5
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
+ export { createProfileTemplate } from "./profile-template.js";
@@ -0,0 +1,2 @@
1
+ import type { Analysis, AppProfile } from './types.ts';
2
+ export declare function createProfileTemplate(analysis: Analysis): AppProfile;
@@ -0,0 +1,75 @@
1
+ import { pagePath, redactText, safeUrl } from "./redact.js";
2
+ import { parseWebSteps, record } from "./validation.js";
3
+ const idPattern = /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,79}$/;
4
+ const question = 'Confirm the expected behavior, setup, reproduction steps, and assertion, then remove this question.';
5
+ function selectedId(value, label) {
6
+ if (typeof value !== 'string' || !idPattern.test(value))
7
+ throw new Error(`${label} must be a Flow QA-compatible ID.`);
8
+ return value;
9
+ }
10
+ function observedPath(group) {
11
+ const sources = [group.pagePath, ...(Array.isArray(group.evidence) ? group.evidence.map((event) => event?.page) : [])];
12
+ for (const source of sources) {
13
+ if (typeof source !== 'string' || !source.startsWith('/') || source.startsWith('//') || /[\p{Cc}\p{Cf}\\]/u.test(source))
14
+ continue;
15
+ const originalPath = source.split(/[?#]/, 1)[0] ?? '';
16
+ if (/\[redacted[^\]]*\]/i.test(originalPath) || redactText(originalPath) !== originalPath)
17
+ continue;
18
+ const sanitized = safeUrl(source);
19
+ const path = pagePath(sanitized);
20
+ if (!path.startsWith('/') || path.startsWith('//') || /[\p{Cc}\p{Cf}\\]/u.test(path) || path.includes('?') || path.includes('#') || path.length > 8192)
21
+ continue;
22
+ try {
23
+ return parseWebSteps([{ type: 'open', path }], 'template.steps');
24
+ }
25
+ catch {
26
+ // The observation is optional; an invalid path must not invent a navigation target.
27
+ }
28
+ }
29
+ return [];
30
+ }
31
+ function reviewTitle(message) {
32
+ const safe = typeof message === 'string' ? redactText(message).replace(/[\p{Cc}\p{Cf}]/gu, ' ').trim() : '';
33
+ const short = [...safe].slice(0, 190).join('').trim();
34
+ return `Review ${short || 'observed error'}`;
35
+ }
36
+ export function createProfileTemplate(analysis) {
37
+ const input = record(analysis, 'analysis');
38
+ if (!Array.isArray(input.groups) || input.groups.length > 10000)
39
+ throw new Error('analysis.groups must be an array of at most 10000 groups.');
40
+ if (!Array.isArray(input.candidates) || !input.candidates.length)
41
+ throw new Error('analysis.candidates must contain selected candidates.');
42
+ const selected = new Set();
43
+ for (const [index, raw] of input.candidates.entries()) {
44
+ selected.add(selectedId(record(raw, `analysis.candidates[${index}]`).groupId, `analysis.candidates[${index}].groupId`));
45
+ }
46
+ if (selected.size > 100)
47
+ throw new Error('Template supports at most 100 selected groups and scenarios.');
48
+ const seen = new Set();
49
+ const scenarios = [];
50
+ for (const [index, raw] of input.groups.entries()) {
51
+ const group = record(raw, `analysis.groups[${index}]`);
52
+ const id = selectedId(group.id, `analysis.groups[${index}].id`);
53
+ if (!selected.has(id))
54
+ continue;
55
+ if (seen.has(id))
56
+ throw new Error(`Selected group ID is duplicated: ${id}.`);
57
+ seen.add(id);
58
+ if (`review-${id}`.length > 80)
59
+ throw new Error(`Selected group ID is too long for a profile scenario: ${id}.`);
60
+ scenarios.push({
61
+ id: `review-${id}`,
62
+ title: reviewTitle(group.message),
63
+ match: { groupId: id },
64
+ requirement: '',
65
+ expectedSource: '',
66
+ preconditions: [],
67
+ setupConfirmed: false,
68
+ questions: [question],
69
+ steps: observedPath(group),
70
+ });
71
+ }
72
+ if (seen.size !== selected.size)
73
+ throw new Error('Selected candidate references a missing group ID.');
74
+ return { schemaVersion: 'error-to-test/profile-1', name: 'Error to Test review', scenarios };
75
+ }
package/dist/types.d.ts CHANGED
@@ -114,6 +114,7 @@ export interface ScenarioRule {
114
114
  id: string;
115
115
  title: string;
116
116
  match: {
117
+ groupId?: string;
117
118
  type?: EventType;
118
119
  messageIncludes?: string;
119
120
  pagePath?: string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ihyeon/error-to-test",
3
- "version": "0.1.11",
3
+ "version": "0.1.12",
4
4
  "description": "Turn captured browser errors and pasted error reports into traceable regression test candidates.",
5
5
  "license": "MIT",
6
6
  "author": "Hyeonse Im",