@ihyeon/error-to-test 0.1.10 → 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
@@ -34,12 +34,35 @@ node bin/error-to-test.mjs analyze --input examples/error.txt --page /items --ru
34
34
  node bin/error-to-test.mjs analyze --input examples/errors.json --profile examples/profile.json --out .error-to-test/example
35
35
  ```
36
36
 
37
- 결과는 `analysis.json`, `report.md`, `flows/error-to-test.md`, `cases/error-to-test.json`, `provenance.json`입니다. 빈 조회 결과에는 suite를 만들지 않습니다. 출력 폴더는 매번 새 경로를 지정해야 합니다.
37
+ 결과는 `analysis.json`, `report.md`, `flows/error-to-test.md`, `cases/error-to-test.json`, `provenance.json`입니다. 선택된 TC 후보가 없으면 suite를 만들지 않습니다. 출력 폴더는 매번 새 경로를 지정해야 합니다.
38
+
39
+ `--min-count N`으로 입력에 N건 이상 있는 오류 묶음만 TC 후보로 만들 수 있습니다. 범위는 1~10,000이며 기본값은 1입니다. 중복 제거·날짜 필터 적용 후 건수를 기준으로 고르고, `--top`은 그중 순위가 높은 묶음 수를 제한합니다. 기준 미만의 묶음도 `analysis.json`과 `report.md`에 남으며, 제외가 발생하면 보고서에 선택 기준을 표시합니다. 이 건수는 입력에 포함된 수집 이벤트·제출 보고서 수입니다.
40
+
41
+ ```sh
42
+ error-to-test analyze --input errors.json --min-count 3 --top 10 --out ./recurring-errors
43
+ ```
44
+
45
+ JavaScript API에서는 `analyzeErrors(content, { minCount: 3, top: 10 })`으로 같은 기준을 적용합니다.
38
46
 
39
47
  `report.md` 상단에서 TC 초안 수와 추가 정보가 필요한 TC 수를 확인할 수 있습니다. 초안도 실행 전에 검토해야 합니다. 오류 묶음·수집 건수와 함께 대표 로그의 오류·React 컴포넌트 스택, 재현 방법·사전 조건·테스트 단계·부족한 정보도 표시합니다. 같은 스택은 한 번만 표시하며, 전체 로그의 모든 스택을 나열하지는 않습니다. 재현 단계와 정상 기대 결과, 명시적인 assertion이 없으면 질문이 있는 TC를 생성합니다. 직접 입력한 보고서에는 실제 발생 시각·사용자 수를 만들어 넣지 않습니다. 수집 건수도 실제 발생률을 뜻하지 않으며, 원본 내보내기의 일부 데이터 표시를 유지합니다.
40
48
 
41
49
  기본 suite는 검토 질문으로 실행이 차단됩니다. TC와 프로필을 확인한 뒤 다른 출력 폴더에 `--reviewed`로 다시 생성하면 검토 질문만 제거됩니다. 나머지 질문은 그대로 실행을 차단합니다. 프로필의 `setupConfirmed`는 준비 조건을 확인했다는 표시이며, 계정·데이터를 자동으로 준비하는 기능은 아닙니다.
42
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
+
43
66
  ```sh
44
67
  node bin/error-to-test.mjs verify .error-to-test/example --input examples/errors.json --profile examples/profile.json
45
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
@@ -61,12 +61,35 @@ Accepts Browser Error Log v1 `{schemaVersion: 1, partial?: boolean, events: [...
61
61
 
62
62
  Grouping is deterministic and separates project, environment, release, runtime, page path, error message/name, and source location or HTTP method/path/status. Similar messages do not establish the same root cause. Counts mean **captured events** or **submitted reports**, not actual occurrence rates or affected users. Collection retention is unknown; imported `partial` status is preserved. TC selection defaults to the first 100 ranked groups; all groups remain in the analysis. More than 100 generated cases must be narrowed with `--top` or a smaller profile.
63
63
 
64
+ Use `--min-count N` (1..10,000; default 1) to generate TCs only for groups with at least N supplied records after deduplication and date filtering. `--top` then limits the remaining ranked groups. Groups below the threshold remain in `analysis.json` and `report.md`; the report explains any exclusions. If no groups qualify, no suite is generated.
65
+
66
+ ```sh
67
+ error-to-test analyze --input errors.json --min-count 3 --top 10 --out ./recurring-errors
68
+ ```
69
+
64
70
  ## Confirm the intended behavior
65
71
 
66
72
  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.
67
73
 
68
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.
69
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
+
70
93
  ## Review and use Flow QA
71
94
 
72
95
  Generated files (Flow QA source is limited to 128 KB; suite JSON to 512 KiB):
@@ -74,7 +97,7 @@ Generated files (Flow QA source is limited to 128 KB; suite JSON to 512 KiB):
74
97
  - `analysis.json`: coverage, ranked groups, safe representative evidence, full-source context checks, and TC candidates.
75
98
  - `report.md`: human-readable analysis with draft and needs-context TC totals, unique error and React component stacks from representative evidence, reported reproduction, preconditions, proposed test steps, and missing context.
76
99
  - `flows/error-to-test.md`: observed facts, requirements, steps, and questions.
77
- - `cases/error-to-test.json`: Flow QA `suite-1` (omitted when no records match).
100
+ - `cases/error-to-test.json`: Flow QA `suite-1` (omitted when no TC candidates are selected).
78
101
  - `provenance.json`: source/profile/analysis/report/flow/suite hashes and event → group → case mappings.
79
102
 
80
103
  Default suites have a review question on every case. Read the artifacts, confirm the profile/steps, then repeat analysis to **another output directory** with `--reviewed`. This acknowledges review; missing context still blocks execution. No analysis command runs the browser.
@@ -103,6 +126,8 @@ await writeBundle('./new-result', analysis);
103
126
 
104
127
  Analysis is deterministic and has no runtime dependencies. Optional model-assisted drafting, collecting new interaction breadcrumbs, direct collector APIs, and a dedicated web input screen are later extensions. Browser/WebView logs can be analyzed; native or WebView execution is not established by a log and remains blocked until the correct context is supplied.
105
128
 
129
+ The API supports the same selection with `analyzeErrors(content, { minCount: 3, top: 10 })`.
130
+
106
131
  After a Flow QA run, associate its normalized report with the exact exported suite:
107
132
 
108
133
  ```sh
@@ -3,5 +3,6 @@ import type { Analysis } from './types.ts';
3
3
  export interface AnalyzeOptions extends ParseInputOptions {
4
4
  profile?: unknown;
5
5
  top?: number;
6
+ minCount?: number;
6
7
  }
7
8
  export declare function analyzeErrors(content: string, options?: AnalyzeOptions): Analysis;
package/dist/analysis.js CHANGED
@@ -6,6 +6,9 @@ export function analyzeErrors(content, options = {}) {
6
6
  const top = options.top ?? 100;
7
7
  if (!Number.isInteger(top) || top < 1 || top > 100)
8
8
  throw new Error('top must be an integer between 1 and 100.');
9
+ const minCount = options.minCount ?? 1;
10
+ if (!Number.isInteger(minCount) || minCount < 1 || minCount > 10000)
11
+ throw new Error('minCount must be an integer between 1 and 10000.');
9
12
  let rawProfile = options.profile;
10
13
  const profileSource = typeof rawProfile === 'string' ? rawProfile : rawProfile === undefined ? undefined : JSON.stringify(rawProfile);
11
14
  if (typeof rawProfile === 'string') {
@@ -21,15 +24,20 @@ export function analyzeErrors(content, options = {}) {
21
24
  const profile = rawProfile === undefined ? undefined : parseProfile(rawProfile);
22
25
  const input = parseInput(content, options);
23
26
  const groups = groupObservations(input.observations);
27
+ const eligibleGroups = groups.filter(group => group.count >= minCount);
24
28
  const warnings = [...input.warnings];
25
- if (groups.length > top)
26
- warnings.push(`TC selection includes the first ${top} of ${groups.length} ranked groups. All groups remain in analysis.json.`);
29
+ if (eligibleGroups.length < groups.length)
30
+ warnings.push(`TC selection requires at least ${minCount} supplied records per group; ${eligibleGroups.length} of ${groups.length} groups are eligible. All groups remain in analysis.json. These counts are supplied records, not global rates.`);
31
+ if (eligibleGroups.length > top)
32
+ warnings.push(minCount === 1
33
+ ? `TC selection includes the first ${top} of ${groups.length} ranked groups. All groups remain in analysis.json.`
34
+ : `TC selection includes the first ${top} of ${eligibleGroups.length} eligible ranked groups. All groups remain in analysis.json.`);
27
35
  return {
28
36
  schemaVersion: 'error-to-test/analysis-1',
29
37
  source: { sha256: input.sha256, ...(profileSource !== undefined ? { profileSha256: hash(profileSource) } : {}) },
30
38
  coverage: input.coverage,
31
39
  groups,
32
- candidates: createCandidates(groups.slice(0, top), profile),
40
+ candidates: createCandidates(eligibleGroups.slice(0, top), profile),
33
41
  warnings,
34
42
  };
35
43
  }
@@ -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:
@@ -31,8 +33,10 @@ Options:
31
33
  --expected TEXT Reported intended result (--error only)
32
34
  --expected-source TEXT Expected-result source (--error only)
33
35
  --from ISO --to ISO Filter observed timestamps; undated reports are excluded
34
- --top N Generate TCs for the first N ranked groups (1..100)
35
- --out DIRECTORY New directory; existing files are never overwritten
36
+ --min-count N Select groups with at least N records after dedup/date filtering (1..10000)
37
+ --top N Generate TCs for the first N eligible ranked groups (1..100; after --min-count)
38
+ --out DIRECTORY New analyze directory; existing files are never overwritten
39
+ --out FILE New init-profile JSON file; existing files are never overwritten
36
40
  --reviewed Acknowledge review; unresolved questions still block cases
37
41
  --report FILE Normalized Flow QA report (link-run only)
38
42
  --version, -v Print the package version
@@ -59,7 +63,7 @@ export async function main(args = process.argv.slice(2)) {
59
63
  help: { type: 'boolean', short: 'h' }, version: { type: 'boolean', short: 'v' }, input: { type: 'string' }, error: { type: 'string' }, report: { type: 'string' },
60
64
  format: { type: 'string' }, profile: { type: 'string' }, project: { type: 'string' }, environment: { type: 'string' },
61
65
  release: { type: 'string' }, page: { type: 'string' }, type: { type: 'string' }, runtime: { type: 'string' }, from: { type: 'string' }, to: { type: 'string' },
62
- top: { type: 'string' }, out: { type: 'string' }, reviewed: { type: 'boolean' },
66
+ top: { type: 'string' }, 'min-count': { type: 'string' }, out: { type: 'string' }, reviewed: { type: 'boolean' },
63
67
  reproduce: { type: 'string', multiple: true }, precondition: { type: 'string', multiple: true },
64
68
  expected: { type: 'string' }, 'expected-source': { type: 'string' },
65
69
  } });
@@ -74,11 +78,36 @@ export async function main(args = process.argv.slice(2)) {
74
78
  }
75
79
  if (positionals.length === 0) {
76
80
  if (Object.keys(values).length)
77
- 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.');
78
82
  process.stdout.write(help);
79
83
  return;
80
84
  }
81
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
+ }
82
111
  if (command === 'link-run') {
83
112
  if (positionals.length !== 2 || !positionals[1] || !values.report)
84
113
  throw new Error('link-run requires a bundle directory and --report.');
@@ -108,7 +137,7 @@ export async function main(args = process.argv.slice(2)) {
108
137
  return;
109
138
  }
110
139
  if (command !== 'analyze' || positionals.length !== 1)
111
- 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.');
112
141
  if (values.report)
113
142
  throw new Error('--report applies to link-run only.');
114
143
  if ((values.input === undefined) === (values.error === undefined))
@@ -146,6 +175,7 @@ export async function main(args = process.argv.slice(2)) {
146
175
  format: inputFormat, ...(values.profile ? { profile: await readBoundedFile(resolve(values.profile), 1024 * 1024) } : {}),
147
176
  project: values.project, environment: values.environment, release: values.release, page: values.page, type: values.type, runtime: values.runtime,
148
177
  from: values.from, to: values.to, ...(values.top !== undefined ? { top: Number(values.top) } : {}),
178
+ ...(values['min-count'] !== undefined ? { minCount: Number(values['min-count']) } : {}),
149
179
  });
150
180
  const out = resolve(values.out ?? `.error-to-test/run-${Date.now()}-${randomUUID().slice(0, 8)}`);
151
181
  const files = await writeBundle(out, analysis, { reviewed: values.reviewed });
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.10",
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",