@ihyeon/error-to-test 0.2.0 → 0.2.1

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
@@ -137,6 +137,23 @@ error-to-test analyze --input errors.json --min-count 3 --profile ./review-profi
137
137
 
138
138
  `init-profile`은 검증에 통과한 번들만 읽고 새 파일에 저장합니다. 수정된 번들, 선택된 TC가 없는 결과, 기존 출력 파일은 거부합니다. 원래 분석 산출물을 덮어쓰지 않습니다. API의 `createProfileTemplate(analysis)`도 편집용 `error-to-test/profile-1` 객체를 만들며, 완성된 실행 프로필을 의미하지 않습니다.
139
139
 
140
+ 이미 작성한 프로필은 `--profile`로 이어서 보완할 수 있습니다.
141
+
142
+ ```sh
143
+ error-to-test analyze --input current-errors.jsonl --format jsonl --out ./current-analysis
144
+ error-to-test init-profile ./current-analysis --profile ./existing-profile.json --out ./expanded-profile.json
145
+ # 새로 추가된 빈 요구사항·출처·준비 조건·동작·assertion 작성
146
+ error-to-test analyze --input current-errors.jsonl --format jsonl --profile ./expanded-profile.json --out ./expanded-analysis
147
+ ```
148
+
149
+ 기존 프로필은 요구사항·기대 결과 출처 등 일반 프로필 검증을 통과해야 합니다. 이름과 규칙 순서·ID·조건·단계·기대 결과·준비 확인·질문을 검증된 값 그대로 보존합니다. 알 수 없는 필드와 파일 서식은 보존하지 않습니다. 기존 질문과 준비 미확인 상태도 남아 실행을 차단합니다.
150
+
151
+ TC 생성과 동일하게 모든 조건을 함께 검사해 기존 규칙이 적용되는 선택 묶음을 찾습니다. 넓은 조건의 규칙은 원래 조건 안에서 여러 묶음에 적용될 수 있습니다. 다른 릴리스의 정확한 `match.groupId`는 그대로 두며, 새 묶음에 단계·기대 결과를 복사하지 않습니다. 기존 규칙이 없는 선택 묶음에만 순위대로 빈 검토 항목을 붙입니다. 새 항목의 ID가 충돌하면 숫자 접미사를 붙이고 기존 ID는 유지합니다. 모두 기존 규칙으로 다뤄지면 항목을 추가하지 않습니다.
152
+
153
+ 새 항목은 기대 결과·출처가 비어 있고, 준비 미확인과 검토 질문을 유지합니다. 직접 채운 뒤 원래 입력·메타데이터·필터·이전 분석 기준으로 다시 분석하세요. 기존 검토 조건도 적용합니다. 과거 규칙을 자동 삭제하지 않으므로 합산 100개 규칙·1 MiB 한도를 지켜야 합니다. 민감한 정보가 있는 기존 메타데이터·실행 단계는 파일 생성 전에 거부합니다. 기본·확장 템플릿 모두 번들의 `results` 폴더 밖에 있는 새 파일에 저장합니다.
154
+
155
+ API는 `createProfileTemplate(analysis, { profile: existingProfile })`입니다. JSON 값만으로 구성한 객체 또는 BOM 하나를 지원하는 JSON 문자열을 1 MiB까지 받으며 입력 객체를 변경하지 않습니다. 객체의 선택 필드가 `undefined`이면 해당 속성을 생략하세요. `profile`을 생략하면 기존 빈 템플릿을 만듭니다.
156
+
140
157
  ```sh
141
158
  node bin/error-to-test.mjs verify .error-to-test/example --input examples/errors.json --profile examples/profile.json
142
159
  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
@@ -174,6 +174,25 @@ For each scenario, fill `requirement` and `expectedSource`, establish `precondit
174
174
 
175
175
  `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.
176
176
 
177
+ ### Extend an existing profile
178
+
179
+ Keep existing scenario rules and add review templates for selected groups that they do not cover:
180
+
181
+ ```sh
182
+ error-to-test analyze --input current-errors.jsonl --format jsonl --out ./current-analysis
183
+ error-to-test init-profile ./current-analysis --profile ./existing-profile.json --out ./expanded-profile.json
184
+ # Fill only the new blank requirements, sources, setup, actions, and assertions.
185
+ error-to-test analyze --input current-errors.jsonl --format jsonl --profile ./expanded-profile.json --out ./expanded-analysis
186
+ ```
187
+
188
+ The existing profile must pass normal profile validation: its requirements and expectation sources must already be filled. Profile name, scenario order, IDs, match conditions, steps, expectations, setup flags, and questions are retained as validated profile values. Unknown fields and file formatting are not preserved. Existing questions and unconfirmed setup still block cases.
189
+
190
+ Coverage uses exactly the same matching rules as TC generation, with all supplied predicates combined. An existing broad rule can cover several selected groups within its original conditions. An exact `match.groupId` from another release remains exact; its steps and expectation are not copied to a new group. Only uncovered selected groups receive new blank templates in ranked order. New scenario IDs gain deterministic numeric suffixes on collision; existing IDs stay unchanged. If all selected groups are covered, the result contains only the existing rules.
191
+
192
+ New templates retain blank expectation fields, `setupConfirmed: false`, and the review question. Fill them explicitly before reanalysis, using the original inputs, metadata, filters, and optional baseline. The usual review gate applies. Existing scenarios are never automatically deleted; the combined profile must stay within 100 scenarios and 1 MiB. Sensitive existing metadata or execution steps are rejected before writing. Output must be a new file outside the bundle's `results` directory, for both basic and extended templates.
193
+
194
+ The API is `createProfileTemplate(analysis, { profile: existingProfile })`; `profile` accepts an object containing only JSON values or a JSON string, including one leading BOM, within 1 MiB. Omit undefined optional properties from object inputs. The function does not mutate either input. Without `profile`, it produces the original blank template.
195
+
177
196
  ## Review and use Flow QA
178
197
 
179
198
  Generated files (Flow QA source is limited to 128 KB; suite JSON to 512 KiB):
@@ -1,3 +1,5 @@
1
- import type { AppProfile, IssueGroup, TestCandidate } from './types.ts';
1
+ import type { AppProfile, IssueGroup, ScenarioRule, TestCandidate, WebStep } from './types.ts';
2
+ export declare function stepsContainSensitiveData(steps: WebStep[]): boolean;
2
3
  export declare function parseProfile(raw: unknown): AppProfile;
4
+ export declare function matchesScenarioRule(rule: ScenarioRule, group: IssueGroup): boolean;
3
5
  export declare function createCandidates(groups: IssueGroup[], profile?: AppProfile): TestCandidate[];
@@ -23,7 +23,7 @@ function profileText(value, label) {
23
23
  function profileStrings(value, label) {
24
24
  return strings(value, label).map((item, index) => profileText(item, `${label}[${index}]`));
25
25
  }
26
- function stepsContainSensitiveData(steps) {
26
+ export function stepsContainSensitiveData(steps) {
27
27
  const credentialFill = steps.some((step) => step.type === 'fill' &&
28
28
  /password|passwd|secret|token|api[_-]?key|authorization|cookie|session/i.test(`${step.locator.value} ${'name' in step.locator ? step.locator.name ?? '' : ''}`));
29
29
  if (credentialFill)
@@ -92,7 +92,7 @@ function confirmed(value, label) {
92
92
  throw new Error(`${label} must be a boolean.`);
93
93
  return value;
94
94
  }
95
- function matches(rule, group) {
95
+ export function matchesScenarioRule(rule, group) {
96
96
  const match = rule.match;
97
97
  return (match.groupId === undefined || match.groupId === group.id)
98
98
  && (!match.type || match.type === group.type)
@@ -184,7 +184,7 @@ function createOne(group, rule) {
184
184
  }
185
185
  export function createCandidates(groups, profile) {
186
186
  return groups.flatMap((group) => {
187
- const rules = (profile?.scenarios ?? []).filter((rule) => matches(rule, group)).sort((a, b) => a.id.localeCompare(b.id));
187
+ const rules = (profile?.scenarios ?? []).filter((rule) => matchesScenarioRule(rule, group)).sort((a, b) => a.id.localeCompare(b.id));
188
188
  return rules.length ? rules.map((rule) => createOne(group, rule)) : [createOne(group)];
189
189
  });
190
190
  }
package/dist/cli.js CHANGED
@@ -20,6 +20,7 @@ const help = `Error to Test — local error analysis and regression TC drafts
20
20
  cat error.txt | error-to-test analyze --input - --format text --out new-directory
21
21
  error-to-test verify new-directory [--input errors-1.json --input errors-2.json] [--profile profile.json]
22
22
  error-to-test init-profile new-directory --out profile.json
23
+ error-to-test init-profile new-directory --profile existing.json --out extended.json
23
24
  error-to-test link-run new-directory --report path/to/qa-report.json
24
25
  error-to-test results new-directory [--format text|json] [--out summary.md]
25
26
  error-to-test compare BASELINE CURRENT [--format text|json] [--out comparison.md]
@@ -30,7 +31,7 @@ Options:
30
31
  --format auto|json|jsonl|text Analyze input format; JSONL requires explicit selection and one record per line; auto rejects malformed JSON-looking input
31
32
  --format text|json Results summary format (default: text Markdown)
32
33
  --format text|json Compare format (default: text Markdown)
33
- --profile FILE Confirmed app scenarios and explicit assertions (optional)
34
+ --profile FILE Confirmed app scenarios and explicit assertions (analyze/verify); existing profile to extend (init-profile)
34
35
  --baseline DIRECTORY Select only signatures absent from this verified bundle, before --min-count and --top; retain all groups in analysis.json (analyze only)
35
36
  --project NAME Metadata for a manual report
36
37
  --environment NAME Metadata for a manual report
@@ -146,16 +147,24 @@ export async function main(args = process.argv.slice(2)) {
146
147
  if (command === 'init-profile') {
147
148
  if (positionals.length !== 2 || !positionals[1] || !values.out)
148
149
  throw new Error('init-profile requires one bundle directory and --out FILE.');
149
- if (Object.keys(values).some(key => !['out', 'help'].includes(key)))
150
- throw new Error('Unsupported option for init-profile. Use only --out FILE.');
151
- const { analysis } = await readVerifiedBundle(resolve(positionals[1]));
150
+ if (Object.keys(values).some(key => !['out', 'profile', 'help'].includes(key)))
151
+ throw new Error('Unsupported option for init-profile. Use only --profile FILE and --out FILE.');
152
+ if (values.profile !== undefined && !values.profile.trim())
153
+ throw new Error('--profile requires a nonempty file path.');
154
+ const bundle = resolve(positionals[1]);
155
+ const { analysis } = await readVerifiedBundle(bundle);
152
156
  if (analysis.schemaVersion !== 'error-to-test/analysis-1' || !Array.isArray(analysis.groups) || !Array.isArray(analysis.candidates))
153
157
  throw new Error('Unsupported analysis contract.');
154
- const profile = createProfileTemplate(analysis);
158
+ const profile = values.profile === undefined
159
+ ? createProfileTemplate(analysis)
160
+ : createProfileTemplate(analysis, { profile: await readBoundedFile(resolve(values.profile), 1024 * 1024) });
155
161
  const content = jsonText(profile);
156
162
  if (Buffer.byteLength(content) > 1024 * 1024)
157
163
  throw new Error('The generated profile exceeds 1 MiB. Narrow the selected groups.');
158
164
  const out = resolve(values.out);
165
+ if (insideBundleResults(await realpath(bundle), await canonicalOutput(out))) {
166
+ throw new Error('The profile cannot be written inside the bundle results directory. Choose an outside --out FILE path.');
167
+ }
159
168
  await mkdir(dirname(out), { recursive: true });
160
169
  try {
161
170
  await writeFile(out, content, { flag: 'wx', mode: 0o600 });
@@ -165,7 +174,7 @@ export async function main(args = process.argv.slice(2)) {
165
174
  throw new Error('The output file already exists. Choose a new --out FILE path.');
166
175
  throw error;
167
176
  }
168
- 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`);
177
+ process.stdout.write(`Profile template written: ${out}\n${values.profile === undefined ? '' : 'Existing rules were retained; fill and review any new blank scenarios manually. This does not approve the profile.\n'}Fill requirement, expectedSource, preconditions, and steps; confirm setupConfirmed and clear answered questions. Then rerun analyze with the original input and --profile ${out}.\n`);
169
178
  return;
170
179
  }
171
180
  if (command === 'link-run') {
package/dist/index.d.ts CHANGED
@@ -5,7 +5,7 @@ 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
+ export { createProfileTemplate, type ProfileTemplateOptions } from './profile-template.ts';
9
9
  export { readRunSummary, renderRunSummary, type RunSummary, type LinkedRunStatus, type LinkedCaseStatus } from './run-summary.ts';
10
10
  export { compareBundles, renderComparison, type AnalysisComparison, type ComparisonStatus, type ComparisonSide, type ComparisonOccurrence, type ComparisonIssue } from './comparison.ts';
11
11
  export type * from './types.ts';
@@ -1,2 +1,5 @@
1
1
  import type { Analysis, AppProfile } from './types.ts';
2
- export declare function createProfileTemplate(analysis: Analysis): AppProfile;
2
+ export interface ProfileTemplateOptions {
3
+ profile?: unknown;
4
+ }
5
+ export declare function createProfileTemplate(analysis: Analysis, options?: ProfileTemplateOptions): AppProfile;
@@ -1,7 +1,85 @@
1
+ import { matchesScenarioRule, parseProfile, stepsContainSensitiveData } from "./candidates.js";
1
2
  import { pagePath, redactText, safeUrl } from "./redact.js";
2
3
  import { parseWebSteps, record } from "./validation.js";
3
4
  const idPattern = /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,79}$/;
4
5
  const question = 'Confirm the expected behavior, setup, reproduction steps, and assertion, then remove this question.';
6
+ const maxProfileBytes = 1024 * 1024;
7
+ function assertJsonValue(value, active) {
8
+ if (value === null || typeof value === 'string' || typeof value === 'boolean' || (typeof value === 'number' && Number.isFinite(value)))
9
+ return;
10
+ if (typeof value !== 'object')
11
+ throw new Error('The profile object must contain only JSON values.');
12
+ if (active.has(value))
13
+ throw new Error('The profile object must contain only JSON values.');
14
+ if (!Array.isArray(value) && Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) {
15
+ throw new Error('The profile object must contain only JSON values.');
16
+ }
17
+ active.add(value);
18
+ try {
19
+ const keys = Reflect.ownKeys(value);
20
+ if (Array.isArray(value) && keys.length !== value.length + 1)
21
+ throw new Error('The profile object must contain only JSON values.');
22
+ for (const key of keys) {
23
+ if (Array.isArray(value) && key === 'length')
24
+ continue;
25
+ if (typeof key !== 'string' || (Array.isArray(value) && (!/^(0|[1-9]\d*)$/.test(key) || Number(key) >= value.length))) {
26
+ throw new Error('The profile object must contain only JSON values.');
27
+ }
28
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
29
+ if (!descriptor?.enumerable || !('value' in descriptor))
30
+ throw new Error('The profile object must contain only JSON values.');
31
+ assertJsonValue(descriptor.value, active);
32
+ }
33
+ }
34
+ finally {
35
+ active.delete(value);
36
+ }
37
+ }
38
+ function existingProfile(raw) {
39
+ let input;
40
+ if (typeof raw === 'string') {
41
+ if (Buffer.byteLength(raw, 'utf8') > maxProfileBytes)
42
+ throw new Error('The profile must be 1 MiB or smaller.');
43
+ try {
44
+ input = JSON.parse(raw.replace(/^\uFEFF/, ''));
45
+ }
46
+ catch {
47
+ throw new Error('The profile is not valid JSON.');
48
+ }
49
+ }
50
+ else {
51
+ let serialized;
52
+ try {
53
+ assertJsonValue(raw, new WeakSet());
54
+ serialized = JSON.stringify(raw);
55
+ }
56
+ catch {
57
+ throw new Error('The profile object must contain only JSON values.');
58
+ }
59
+ if (Buffer.byteLength(serialized, 'utf8') > maxProfileBytes)
60
+ throw new Error('The profile must be 1 MiB or smaller.');
61
+ input = JSON.parse(serialized);
62
+ }
63
+ const parsed = parseProfile(input);
64
+ if (parsed.scenarios.some((scenario) => redactText(scenario.id) !== scenario.id ||
65
+ (scenario.match.groupId !== undefined && redactText(scenario.match.groupId) !== scenario.match.groupId))) {
66
+ throw new Error('The existing profile contains sensitive scenario IDs; remove them before extending it.');
67
+ }
68
+ if (parsed.scenarios.some((scenario) => stepsContainSensitiveData(scenario.steps))) {
69
+ throw new Error('The existing profile contains sensitive execution steps; remove them before extending it.');
70
+ }
71
+ return parsed;
72
+ }
73
+ function newScenarioId(base, used) {
74
+ if (!used.has(base))
75
+ return base;
76
+ for (let number = 2;; number++) {
77
+ const suffix = `-${number}`;
78
+ const candidate = `${base.slice(0, 80 - suffix.length)}${suffix}`;
79
+ if (!used.has(candidate))
80
+ return candidate;
81
+ }
82
+ }
5
83
  function selectedId(value, label) {
6
84
  if (typeof value !== 'string' || !idPattern.test(value))
7
85
  throw new Error(`${label} must be a Flow QA-compatible ID.`);
@@ -33,7 +111,7 @@ function reviewTitle(message) {
33
111
  const short = [...safe].slice(0, 190).join('').trim();
34
112
  return `Review ${short || 'observed error'}`;
35
113
  }
36
- export function createProfileTemplate(analysis) {
114
+ export function createProfileTemplate(analysis, options = {}) {
37
115
  const input = record(analysis, 'analysis');
38
116
  if (!Array.isArray(input.groups) || input.groups.length > 10000)
39
117
  throw new Error('analysis.groups must be an array of at most 10000 groups.');
@@ -45,8 +123,10 @@ export function createProfileTemplate(analysis) {
45
123
  }
46
124
  if (selected.size > 100)
47
125
  throw new Error('Template supports at most 100 selected groups and scenarios.');
126
+ const existing = options.profile === undefined ? undefined : existingProfile(options.profile);
48
127
  const seen = new Set();
49
- const scenarios = [];
128
+ const scenarios = existing ? [...existing.scenarios] : [];
129
+ const usedIds = new Set(scenarios.map((scenario) => scenario.id));
50
130
  for (const [index, raw] of input.groups.entries()) {
51
131
  const group = record(raw, `analysis.groups[${index}]`);
52
132
  const id = selectedId(group.id, `analysis.groups[${index}].id`);
@@ -55,10 +135,16 @@ export function createProfileTemplate(analysis) {
55
135
  if (seen.has(id))
56
136
  throw new Error(`Selected group ID is duplicated: ${id}.`);
57
137
  seen.add(id);
138
+ if (existing && existing.scenarios.some((scenario) => matchesScenarioRule(scenario, group)))
139
+ continue;
58
140
  if (`review-${id}`.length > 80)
59
141
  throw new Error(`Selected group ID is too long for a profile scenario: ${id}.`);
142
+ if (scenarios.length >= 100)
143
+ throw new Error('The extended profile supports at most 100 scenarios.');
144
+ const scenarioId = existing ? newScenarioId(`review-${id}`, usedIds) : `review-${id}`;
145
+ usedIds.add(scenarioId);
60
146
  scenarios.push({
61
- id: `review-${id}`,
147
+ id: scenarioId,
62
148
  title: reviewTitle(group.message),
63
149
  match: { groupId: id },
64
150
  requirement: '',
@@ -71,5 +157,9 @@ export function createProfileTemplate(analysis) {
71
157
  }
72
158
  if (seen.size !== selected.size)
73
159
  throw new Error('Selected candidate references a missing group ID.');
74
- return { schemaVersion: 'error-to-test/profile-1', name: 'Error to Test review', scenarios };
160
+ const profile = { schemaVersion: 'error-to-test/profile-1', name: existing?.name ?? 'Error to Test review', scenarios };
161
+ if (existing && Buffer.byteLength(`${JSON.stringify(profile, null, 2)}\n`, 'utf8') > maxProfileBytes) {
162
+ throw new Error('The generated profile exceeds 1 MiB. Narrow the selected groups or scenario details.');
163
+ }
164
+ return profile;
75
165
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ihyeon/error-to-test",
3
- "version": "0.2.0",
3
+ "version": "0.2.1",
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",