blastproof 0.30.0 → 0.32.0

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.md CHANGED
@@ -103,8 +103,7 @@ That test failed 3 runs of 3 written as one step, and passed 3 of 3 written this
103
103
 
104
104
  Not supported yet:
105
105
 
106
- - **`iframe` content** — a hosted payment widget is invisible, so an embedded checkout cannot be driven end to end
107
- - **hover, scroll-to, drag and drop, file upload**
106
+ - **scroll-to, drag and drop, file upload**
108
107
  - **multiple tabs**, and native `alert` / `confirm` dialogs
109
108
 
110
109
  **Windows is untested.** Development and CI run on Linux and macOS. Nothing is known to be broken and reports are welcome ([#8](https://github.com/hamc/blastproof/issues/8)).
@@ -284,6 +283,8 @@ The application under test is not trusted input: its page content reaches the mo
284
283
 
285
284
  If your application legitimately spans hosts (an identity provider, a hosted payment step), declare them. A suite that was quietly walking onto a foreign page will now fail and name the origin to add.
286
285
 
286
+ **Frames follow the same boundary.** The agent sees and acts inside an `iframe` on your application's origin, or on one `allowed_origins:` declares. A frame from any other origin shows up as the frame and one line saying its content is not shown and why, and the run prints one warning per origin left out. A hosted payment form is the usual case: declare its origin, and the agent can fill it. Providers' hosted card fields are often nested several frames deep and sandboxed; nesting is covered, but no provider's widget has been measured here, so spend one test on yours before relying on it ([#21](https://github.com/hamc/blastproof/issues/21)).
287
+
287
288
  **Your secrets stay out of prompts.** `{{env.*}}` placeholders survive intact and are substituted at the moment of typing. Every value your tests or auth recipe reference is redacted from everything else crossing into a prompt — page snapshots included — in literal and percent-encoded form, and replaced with a label naming its variable: `[redacted TEST_PASSWORD]`. The label carries the name and nothing derived from the value, so it tells a reader, and the model, *which* secret was there without telling anyone what it was. Redaction matches a known value case-insensitively and tolerantly of whitespace, so a page that uppercases what you typed is still covered. It does not chase a value your application re-encodes, hashes or truncates — no list of transforms can be complete, and one that pretends to be would make you careless. When a redaction is found only by that wider comparison, the run prints one warning naming the variable, because the same page could just as easily have returned a form nothing here can recognise. Treat all of it as a strong default rather than a guarantee against a hostile app.
288
289
 
289
290
  **Redaction covers text, not pixels.** A failure screenshot shows whatever was on screen, including a value typed from `{{env.*}}` or echoed back by the page. So when anything in a run references `{{env.*}}`, the HTML report does not embed screenshots: each failure links to its PNG under `.blastproof/reports/` instead. That keeps `report.html` safe to attach to a pull request. The PNGs themselves are not masked, so do not upload `.blastproof/reports/` anywhere you would not put the secret ([#110](https://github.com/hamc/blastproof/issues/110)).
@@ -0,0 +1,387 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/runner/actions.ts
4
+ var ActionError = class extends Error {
5
+ constructor(message) {
6
+ super(message);
7
+ this.name = "ActionError";
8
+ }
9
+ };
10
+ var BLANK_PAGE = "about:blank";
11
+ function allowedOriginsFor(baseUrl, allowedOrigins) {
12
+ const allowed = /* @__PURE__ */ new Set([new URL(baseUrl).origin]);
13
+ for (const origin of allowedOrigins ?? []) {
14
+ allowed.add(new URL(origin).origin);
15
+ }
16
+ return allowed;
17
+ }
18
+ function isOriginAllowed(url, allowed) {
19
+ if (url === BLANK_PAGE) return true;
20
+ let origin;
21
+ try {
22
+ origin = new URL(url).origin;
23
+ } catch {
24
+ return false;
25
+ }
26
+ if (origin === "null") return false;
27
+ return allowed.has(origin);
28
+ }
29
+ function describeBoundary(allowed) {
30
+ return [...allowed].join(" or ");
31
+ }
32
+ function assertAllowedOrigin(url, ctx) {
33
+ const allowed = allowedOriginsFor(ctx.baseUrl, ctx.allowedOrigins);
34
+ if (!isOriginAllowed(url.toString(), allowed)) {
35
+ throw new ActionError(
36
+ `Refusing to navigate outside the application: ${url.origin} is not ${describeBoundary(allowed)}. Add it to allowed_origins in .blastproof/config.yaml if the app legitimately spans hosts.`
37
+ );
38
+ }
39
+ }
40
+ function describeTarget(target) {
41
+ const parts = [];
42
+ if (target.role) parts.push(`role=${target.role}`);
43
+ if (target.name) parts.push(`name="${target.name}"`);
44
+ return parts.join(" ") || "(no target)";
45
+ }
46
+ function normaliseName(text) {
47
+ return (text ?? "").replace(/\s+/g, " ").trim().toLowerCase();
48
+ }
49
+ function bareRef(ref) {
50
+ return ref.trim().replace(/^\[/, "").replace(/^ref=/, "").replace(/\]$/, "");
51
+ }
52
+ function describeElement(element) {
53
+ const name = element.name ?? element.text;
54
+ return name === void 0 ? element.role : `${element.role} "${name}"`;
55
+ }
56
+ function bindTarget(action, refs) {
57
+ const target = action.target;
58
+ if (!target || !target.ref && !target.role && !target.name) return { ...action, target: void 0 };
59
+ const fix = "Use the [ref=\u2026] on the line of the element you mean in the current snapshot.";
60
+ if (!target.ref) {
61
+ throw new ActionError(`refused: the target names no ref, so nothing was done. ${fix}`);
62
+ }
63
+ const ref = bareRef(target.ref);
64
+ const element = refs.get(ref);
65
+ if (!element) {
66
+ throw new ActionError(`refused: no element in the current snapshot has ref "${ref}". ${fix}`);
67
+ }
68
+ const shown = element.name ?? element.text;
69
+ const sameRole = normaliseName(target.role) === normaliseName(element.role);
70
+ const sameName = normaliseName(target.name) === normaliseName(shown);
71
+ if (!sameRole || !sameName) {
72
+ const said = [target.role ?? "(no role)", target.name === void 0 ? "" : `"${target.name}"`].filter(Boolean).join(" ");
73
+ throw new ActionError(
74
+ `refused: ref ${ref} is ${describeElement(element)}, not ${said}, so nothing was done. ${fix}`
75
+ );
76
+ }
77
+ return { ...action, target: { ref, role: element.role, name: shown } };
78
+ }
79
+ async function resolveTarget(page, target, resolveTimeoutMs = 2e3) {
80
+ if (!target.ref) throw new ActionError(`Element not found: ${describeTarget(target)} has no ref`);
81
+ const ref = bareRef(target.ref);
82
+ const locator = page.locator(`aria-ref=${ref}`);
83
+ let count;
84
+ try {
85
+ count = await locator.count();
86
+ } catch {
87
+ count = 0;
88
+ }
89
+ if (count === 0) {
90
+ throw new ActionError(
91
+ `Element not found: ${describeTarget(target)} (ref ${ref}) is no longer on the page; it changed since the snapshot. Choose the element again from the fresh snapshot.`
92
+ );
93
+ }
94
+ try {
95
+ await locator.waitFor({ state: "visible", timeout: resolveTimeoutMs });
96
+ } catch {
97
+ throw new ActionError(
98
+ `Element not found: ${describeTarget(target)} (ref ${ref}) is on the page but did not become visible within ${resolveTimeoutMs}ms.`
99
+ );
100
+ }
101
+ return locator;
102
+ }
103
+ function requireTarget(action) {
104
+ if (!action.target?.ref) {
105
+ throw new ActionError(`Action "${action.action}" requires a target (its ref in the snapshot)`);
106
+ }
107
+ return action.target;
108
+ }
109
+ function resolve(value, ctx) {
110
+ return ctx.resolveValue ? ctx.resolveValue(value) : value;
111
+ }
112
+ function requireValue(action) {
113
+ if (action.value === void 0 || action.value === "") {
114
+ throw new ActionError(`Action "${action.action}" requires a value`);
115
+ }
116
+ return action.value;
117
+ }
118
+ var INTERCEPTS_POINTER = /(<[^>\n]{1,400}>)[^\n]{0,400}?intercepts pointer events/;
119
+ var MAX_BLOCKER_LENGTH = 80;
120
+ function truncateBlocker(tag) {
121
+ return tag.length <= MAX_BLOCKER_LENGTH ? tag : `${tag.slice(0, MAX_BLOCKER_LENGTH)}\u2026>`;
122
+ }
123
+ function obstructionFor(error, action) {
124
+ const message = error instanceof Error ? error.message : String(error);
125
+ const match = INTERCEPTS_POINTER.exec(message);
126
+ if (!match) return void 0;
127
+ const where = action.target ? ` on ${describeTarget(action.target)}` : "";
128
+ return new ActionError(
129
+ `blocked: the ${action.action}${where} was NOT performed. The target was found and is visible, enabled and stable \u2014 nothing about it is wrong. ${truncateBlocker(match[1])} is on top of it and received the pointer event instead. Something is covering the page: find it in the snapshot \u2014 a dialog, a cookie banner, an onboarding overlay \u2014 and dismiss it first, using its own close or accept control, or by pressing Escape with no target. Then act on this target again. Choosing a different name for the same target cannot help.`
130
+ );
131
+ }
132
+ async function performAction(page, action, ctx) {
133
+ try {
134
+ return await performResolvedAction(page, action, ctx);
135
+ } catch (error) {
136
+ throw obstructionFor(error, action) ?? error;
137
+ }
138
+ }
139
+ async function performResolvedAction(page, action, ctx) {
140
+ switch (action.action) {
141
+ case "navigate": {
142
+ const value = resolve(requireValue(action), ctx);
143
+ const url = new URL(value, ctx.baseUrl);
144
+ assertAllowedOrigin(url, ctx);
145
+ await page.goto(url.toString(), { timeout: ctx.resolveTimeoutMs ?? 3e4 });
146
+ const landed = page.url();
147
+ return landed === url.toString() ? `ok: navigated to ${url.toString()}` : `ok: navigated to ${url.toString()}, which redirected to ${landed}`;
148
+ }
149
+ case "click": {
150
+ const target = requireTarget(action);
151
+ const locator = await resolveTarget(page, target, ctx.resolveTimeoutMs);
152
+ await locator.click();
153
+ return `ok: clicked ${describeTarget(target)}`;
154
+ }
155
+ case "hover": {
156
+ const target = requireTarget(action);
157
+ const locator = await resolveTarget(page, target, ctx.resolveTimeoutMs);
158
+ await locator.hover();
159
+ return `ok: hovered ${describeTarget(target)}`;
160
+ }
161
+ case "fill": {
162
+ const target = requireTarget(action);
163
+ const value = resolve(requireValue(action), ctx);
164
+ const locator = await resolveTarget(page, target, ctx.resolveTimeoutMs);
165
+ await locator.fill(value);
166
+ return `ok: filled ${describeTarget(target)}`;
167
+ }
168
+ case "press": {
169
+ const key = action.value ? resolve(action.value, ctx) : "Enter";
170
+ if (action.target?.ref) {
171
+ const locator = await resolveTarget(page, action.target, ctx.resolveTimeoutMs);
172
+ await locator.press(key);
173
+ return `ok: pressed ${key} on ${describeTarget(action.target)}`;
174
+ }
175
+ await page.keyboard.press(key);
176
+ return `ok: pressed ${key}`;
177
+ }
178
+ case "select": {
179
+ const target = requireTarget(action);
180
+ const value = resolve(requireValue(action), ctx);
181
+ const locator = await resolveTarget(page, target, ctx.resolveTimeoutMs);
182
+ await locator.selectOption({ label: value });
183
+ return `ok: selected "${value}" in ${describeTarget(target)}`;
184
+ }
185
+ case "assert":
186
+ case "done":
187
+ case "fail":
188
+ throw new ActionError(`Action "${action.action}" is handled by the executor, not the page`);
189
+ }
190
+ }
191
+
192
+ // src/runner/snapshot.ts
193
+ var IFRAME_WITH_CONTENT = /^(\s*)- iframe\b.*:$/;
194
+ function contentUrl(chain) {
195
+ return chain.find((url) => !url.startsWith("about:"));
196
+ }
197
+ function webOrigin(url) {
198
+ try {
199
+ const origin = new URL(url).origin;
200
+ return origin === "null" ? void 0 : origin;
201
+ } catch {
202
+ return void 0;
203
+ }
204
+ }
205
+ async function cutUndeclaredFrames(snapshot, lookup, frames) {
206
+ if (!/- iframe\b/.test(snapshot)) return snapshot;
207
+ const lines = snapshot.split("\n");
208
+ const out = [];
209
+ for (let i = 0; i < lines.length; i++) {
210
+ const line = lines[i];
211
+ out.push(line);
212
+ const frame = IFRAME_WITH_CONTENT.exec(line);
213
+ if (!frame) continue;
214
+ const indent = frame[1].length;
215
+ let end = i + 1;
216
+ while (end < lines.length && indentOf(lines[end]) > indent) end++;
217
+ const frameRef = lineRef(line);
218
+ const contentRef = lines.slice(i + 1, end).map(lineRef).find((r) => r !== void 0);
219
+ const chain = frameRef === void 0 || contentRef === void 0 ? void 0 : await lookup(frameRef, contentRef);
220
+ const url = chain === void 0 ? void 0 : contentUrl(chain);
221
+ if (url !== void 0 && isOriginAllowed(url, frames.allowed)) continue;
222
+ const origin = url === void 0 ? void 0 : webOrigin(url);
223
+ const reason = url === void 0 ? "the frame's origin could not be read" : origin === void 0 ? `a ${url.split(":")[0]}: frame is never shown` : `${origin} is not in allowed_origins`;
224
+ if (origin !== void 0) frames.onHidden?.(origin);
225
+ out.push(`${" ".repeat(indent + 2)}- text: "content not shown: ${reason}"`);
226
+ i = end - 1;
227
+ }
228
+ return out.join("\n");
229
+ }
230
+ function frameChainOn(page) {
231
+ const handleOf = (ref) => page.locator(`aria-ref=${ref}`).elementHandle({ timeout: 1e3 });
232
+ return async (frameRef, contentRef) => {
233
+ const handles = [];
234
+ try {
235
+ const frameElement = await handleOf(frameRef);
236
+ if (frameElement) handles.push(frameElement);
237
+ const content = await handleOf(contentRef);
238
+ if (content) handles.push(content);
239
+ const shown = await frameElement?.contentFrame();
240
+ const owner = await content?.ownerFrame();
241
+ if (!shown || shown !== owner) return void 0;
242
+ const chain = [];
243
+ for (let f = shown; f; f = f.parentFrame()) chain.push(f.url());
244
+ return chain;
245
+ } catch {
246
+ return void 0;
247
+ } finally {
248
+ await Promise.all(handles.map((h) => h.dispose().catch(() => {
249
+ })));
250
+ }
251
+ };
252
+ }
253
+ var DEFAULT_MAX_LINES = 200;
254
+ function indentOf(line) {
255
+ return line.length - line.trimStart().length;
256
+ }
257
+ var DIALOG_LINE = /^\s*- '?(?:dialog|alertdialog)(?=[\s:"']|$)/;
258
+ var OMITTED_LINE = /^\s*- \.\.\. \(\d+ lines? omitted: max_snapshot_lines is (\d+)\)$/m;
259
+ function snapshotCutAt(snapshot) {
260
+ const match = OMITTED_LINE.exec(snapshot);
261
+ return match ? Number(match[1]) : void 0;
262
+ }
263
+ function linesToKeep(lines, maxLines) {
264
+ const keep = /* @__PURE__ */ new Set();
265
+ const subtreeEnd = (i) => {
266
+ let j = i + 1;
267
+ while (j < lines.length && indentOf(lines[j]) > indentOf(lines[i])) j++;
268
+ return j;
269
+ };
270
+ const ancestors = (i) => {
271
+ const found = [];
272
+ let indent = indentOf(lines[i]);
273
+ for (let j = i - 1; j >= 0 && indent > 0; j--) {
274
+ if (indentOf(lines[j]) < indent) {
275
+ found.unshift(j);
276
+ indent = indentOf(lines[j]);
277
+ }
278
+ }
279
+ return found;
280
+ };
281
+ const dialogs = lines.flatMap((line, i) => DIALOG_LINE.test(line) ? [i] : []).reverse();
282
+ const focused = lines.flatMap((line, i) => line.includes("[active]") ? [i] : []);
283
+ for (const anchor of [...dialogs.slice(0, 1), ...focused, ...dialogs.slice(1)]) {
284
+ for (const line of ancestors(anchor)) if (keep.size < maxLines) keep.add(line);
285
+ for (let line = anchor; line < subtreeEnd(anchor) && keep.size < maxLines; line++) keep.add(line);
286
+ }
287
+ for (let line = 0; line < lines.length && keep.size < maxLines; line++) keep.add(line);
288
+ return keep;
289
+ }
290
+ function trimSnapshot(snapshotYaml, maxLines = DEFAULT_MAX_LINES) {
291
+ let lines = snapshotYaml.split("\n").filter((line) => line.trim().length > 0);
292
+ for (let pass = 0; pass < 5; pass++) {
293
+ const kept = [];
294
+ let removed = 0;
295
+ for (let i = 0; i < lines.length; i++) {
296
+ const line = lines[i];
297
+ const isContainer = line.trimEnd().endsWith(":");
298
+ if (isContainer) {
299
+ const next = lines[i + 1];
300
+ const hasChildren = next !== void 0 && indentOf(next) > indentOf(line);
301
+ if (!hasChildren) {
302
+ removed++;
303
+ continue;
304
+ }
305
+ }
306
+ kept.push(line);
307
+ }
308
+ lines = kept;
309
+ if (removed === 0) break;
310
+ }
311
+ if (lines.length <= maxLines) return lines.join("\n");
312
+ const keep = linesToKeep(lines, maxLines);
313
+ const out = [];
314
+ let omitted = 0;
315
+ for (let i = 0; i <= lines.length; i++) {
316
+ if (i < lines.length && !keep.has(i)) {
317
+ omitted++;
318
+ continue;
319
+ }
320
+ if (omitted > 0) {
321
+ const indent = " ".repeat(indentOf(lines[i - omitted]));
322
+ out.push(`${indent}- ... (${omitted} ${omitted === 1 ? "line" : "lines"} omitted: max_snapshot_lines is ${maxLines})`);
323
+ omitted = 0;
324
+ }
325
+ if (i < lines.length) out.push(lines[i]);
326
+ }
327
+ return out.join("\n");
328
+ }
329
+ async function captureSnapshot(page, options) {
330
+ const raw = await page.locator("body").ariaSnapshot({ mode: "ai" });
331
+ const shown = await cutUndeclaredFrames(raw, frameChainOn(page), options.frames);
332
+ return `url: ${page.url()}
333
+ ${trimSnapshot(shown.replace(/ \[cursor=pointer\]/g, ""), options.maxLines)}`;
334
+ }
335
+ var REF_MARKER = / \[ref=[A-Za-z0-9_-]+\]/g;
336
+ function withoutRefs(snapshot) {
337
+ return snapshot.replace(REF_MARKER, "");
338
+ }
339
+ function unquote(value) {
340
+ const trimmed = value.trim();
341
+ if (trimmed.length >= 2 && trimmed.startsWith('"') && trimmed.endsWith('"')) {
342
+ return trimmed.slice(1, -1).replace(/\\(["\\])/g, "$1");
343
+ }
344
+ if (trimmed.length >= 2 && trimmed.startsWith("'") && trimmed.endsWith("'")) {
345
+ return trimmed.slice(1, -1).replace(/''/g, "'");
346
+ }
347
+ return trimmed;
348
+ }
349
+ var ELEMENT_LINE = /^\s*- ([a-z][a-zA-Z]*)(?: ("(?:[^"\\]|\\.)*"))?((?: \[[^\]]*\])*)(?::(?: (.*))?)?$/;
350
+ function parseElementLine(raw) {
351
+ const quoted = /^(\s*- )'((?:[^']|'')*)'(:.*)?$/.exec(raw);
352
+ const line = quoted ? `${quoted[1]}${quoted[2].replace(/''/g, "'")}${quoted[3] ?? ""}` : raw;
353
+ return ELEMENT_LINE.exec(line);
354
+ }
355
+ function lineRef(raw) {
356
+ const match = parseElementLine(raw);
357
+ return match ? /\[ref=([A-Za-z0-9_-]+)\]/.exec(match[3] ?? "")?.[1] : void 0;
358
+ }
359
+ function indexRefs(snapshot) {
360
+ const index = /* @__PURE__ */ new Map();
361
+ for (const raw of snapshot.split("\n")) {
362
+ const match = parseElementLine(raw);
363
+ if (!match) continue;
364
+ const ref = /\[ref=([A-Za-z0-9_-]+)\]/.exec(match[3] ?? "")?.[1];
365
+ if (!ref) continue;
366
+ const element = { role: match[1] };
367
+ if (match[2] !== void 0) element.name = unquote(match[2]);
368
+ if (match[4] !== void 0 && match[4].trim() !== "") element.text = unquote(match[4]);
369
+ index.set(ref, element);
370
+ }
371
+ return index;
372
+ }
373
+
374
+ export {
375
+ allowedOriginsFor,
376
+ isOriginAllowed,
377
+ describeBoundary,
378
+ bindTarget,
379
+ performAction,
380
+ cutUndeclaredFrames,
381
+ snapshotCutAt,
382
+ trimSnapshot,
383
+ captureSnapshot,
384
+ withoutRefs,
385
+ indexRefs
386
+ };
387
+ //# sourceMappingURL=chunk-O6UTUPT6.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/runner/actions.ts","../src/runner/snapshot.ts"],"sourcesContent":["import type { AgentAction, AgentTarget } from '../llm/schemas.js';\nimport type { SnapshotElement } from './snapshot.js';\n\n/**\n * Narrow Playwright subset used by the runner. Real `Page`/`Locator` objects are\n * structurally compatible (cast once at the boundary) and tests use fakes.\n */\nexport interface LocatorLike {\n click(): Promise<void>;\n hover(): Promise<void>;\n fill(value: string): Promise<void>;\n press(key: string): Promise<void>;\n selectOption(option: { label: string }): Promise<unknown>;\n waitFor(options?: { state?: 'attached' | 'visible'; timeout?: number }): Promise<void>;\n count(): Promise<number>;\n}\n\nexport interface PageLike {\n goto(url: string, options?: { timeout?: number }): Promise<unknown>;\n /**\n * Only ever called with `aria-ref=<ref>` (design act-on-the-element-the-model-read,\n * D1): the element the snapshot line the model read was printed from, or\n * nothing. There is no search by role, name or text to widen.\n */\n locator(selector: string): LocatorLike;\n keyboard: { press(key: string): Promise<void> };\n screenshot(options: { path: string; fullPage?: boolean }): Promise<unknown>;\n url(): string;\n /**\n * Waits for the page to reach the given load state, bounded by `timeout`\n * (design D1/D2, trustworthy-verdicts). Signature matches Playwright's own\n * `page.waitForLoadState`, so a real `Page` satisfies this with no adapter.\n *\n * Required, not optional (design D2): `PageLike` is *implemented* by every\n * test double rather than passed as options, so an optional method here is\n * exactly the shape that let `timeoutMs` and `budget` go silently unset at\n * one call site while every other one set them — a no-op fake is at least\n * visible in that fake; an absent method is invisible everywhere. A page\n * double that cannot say when it settled cannot support a trustworthy\n * verdict.\n *\n * Rejects on timeout, exactly like Playwright — this primitive stays\n * honest about what happened. `executor.ts`'s settling helper is what\n * decides that exceeding the budget is normal and silent, not this method.\n */\n waitForLoadState(state: 'networkidle', options?: { timeout?: number }): Promise<void>;\n}\n\nexport class ActionError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'ActionError';\n }\n}\n\nexport interface ActionContext {\n baseUrl: string;\n /**\n * The configured `browser.timeout_ms` (design D1: one knob, not two): bounds how\n * long resolution waits for each candidate element to become visible, and how\n * long `navigate` waits to load. Must be populated by the caller — a Playwright\n * locator's explicit per-call timeout always overrides `page.setDefaultTimeout()`,\n * so leaving this `undefined` silently reinstates a fixed two-second wait for\n * resolution (and thirty seconds for navigation) regardless of what\n * `browser.timeout_ms` says, which is exactly the defect this field once was.\n */\n resolveTimeoutMs?: number;\n /** Extra origins the agent may reach; `baseUrl`'s own is always allowed. */\n allowedOrigins?: string[];\n /** Resolves `{{env.*}}` in action payloads at the moment of acting (design D2). */\n resolveValue?: (value: string) => string;\n}\n\n/** The URL a fresh browser context shows before anything is loaded (design contained-navigation, D2). */\nconst BLANK_PAGE = 'about:blank';\n\n/**\n * The origins the agent may be on: the application's own, plus whatever the\n * configuration declares. One construction, used by both checks (design\n * contained-navigation, D3) — this defect existed because the rule lived at one\n * call site while claiming to cover everything, and two copies of it that can\n * drift apart would be a poor way to fix that.\n */\nexport function allowedOriginsFor(baseUrl: string, allowedOrigins: string[] | undefined): Set<string> {\n const allowed = new Set<string>([new URL(baseUrl).origin]);\n for (const origin of allowedOrigins ?? []) {\n allowed.add(new URL(origin).origin);\n }\n return allowed;\n}\n\n/**\n * Whether `url` is inside the boundary.\n *\n * `about:blank` is inside it: the browser's own empty page carries no content\n * and is what a fresh context shows before the first `goto`. Everything else is\n * compared by origin, and a URL with no comparable origin — `file:`, `data:` —\n * is **not** allowed. Treating \"no origin\" as \"fine\" would be the same\n * permissiveness that produced this defect (design D2).\n */\nexport function isOriginAllowed(url: string, allowed: ReadonlySet<string>): boolean {\n if (url === BLANK_PAGE) return true;\n let origin: string;\n try {\n origin = new URL(url).origin;\n } catch {\n return false;\n }\n if (origin === 'null') return false;\n return allowed.has(origin);\n}\n\n/** Describes the boundary the way both failure messages name it. */\nexport function describeBoundary(allowed: ReadonlySet<string>): string {\n return [...allowed].join(' or ');\n}\n\n/**\n * The one containment that does not depend on the model cooperating: an absolute\n * URL ignores the base entirely (`new URL('https://x/y', base)` is `https://x/y`),\n * so a page that can influence the agent could otherwise send it anywhere while it\n * holds a live session. Compared, not argued with (design D1).\n *\n * Refusing to make the request is strictly better than making it and objecting\n * afterwards, so this stays even though the executor now also checks where the\n * page ended up: the model is told its target is out of bounds and can choose\n * differently, rather than the step simply ending.\n */\nfunction assertAllowedOrigin(url: URL, ctx: ActionContext): void {\n const allowed = allowedOriginsFor(ctx.baseUrl, ctx.allowedOrigins);\n if (!isOriginAllowed(url.toString(), allowed)) {\n throw new ActionError(\n `Refusing to navigate outside the application: ${url.origin} is not ${describeBoundary(allowed)}. ` +\n 'Add it to allowed_origins in .blastproof/config.yaml if the app legitimately spans hosts.',\n );\n }\n}\n\nfunction describeTarget(target: AgentTarget): string {\n const parts: string[] = [];\n if (target.role) parts.push(`role=${target.role}`);\n if (target.name) parts.push(`name=\"${target.name}\"`);\n return parts.join(' ') || '(no target)';\n}\n\nfunction normaliseName(text: string | undefined): string {\n return (text ?? '').replace(/\\s+/g, ' ').trim().toLowerCase();\n}\n\n/** `f1e25`, however the model wrapped it: `[ref=f1e25]`, `ref=f1e25`. */\nfunction bareRef(ref: string): string {\n return ref.trim().replace(/^\\[/, '').replace(/^ref=/, '').replace(/\\]$/, '');\n}\n\nfunction describeElement(element: SnapshotElement): string {\n const name = element.name ?? element.text;\n return name === undefined ? element.role : `${element.role} \"${name}\"`;\n}\n\n/**\n * Binds an action's target to the element its ref names in the snapshot the\n * model was given (design act-on-the-element-the-model-read, D2/D5). The ref\n * alone decides the element; the role and name the model wrote are checked\n * against that element's line, so a ref copied from the neighbouring line is\n * refused instead of clicking the neighbour. The returned action carries the\n * snapshot's own role and name, which is what the record, the reports and the\n * commit-repeat identity read: the element acted on, never the model's words.\n *\n * Throws {@link ActionError}, one failed attempt, on a missing, unknown or\n * mismatched ref. An action with no target (navigate, a bare press) is\n * returned unchanged.\n */\nexport function bindTarget(action: AgentAction, refs: ReadonlyMap<string, SnapshotElement>): AgentAction {\n const target = action.target;\n // An empty target is no target: a press of the focused element sends one.\n if (!target || (!target.ref && !target.role && !target.name)) return { ...action, target: undefined };\n const fix = 'Use the [ref=…] on the line of the element you mean in the current snapshot.';\n if (!target.ref) {\n throw new ActionError(`refused: the target names no ref, so nothing was done. ${fix}`);\n }\n const ref = bareRef(target.ref);\n const element = refs.get(ref);\n if (!element) {\n throw new ActionError(`refused: no element in the current snapshot has ref \"${ref}\". ${fix}`);\n }\n const shown = element.name ?? element.text;\n const sameRole = normaliseName(target.role) === normaliseName(element.role);\n const sameName = normaliseName(target.name) === normaliseName(shown);\n if (!sameRole || !sameName) {\n const said = [target.role ?? '(no role)', target.name === undefined ? '' : `\"${target.name}\"`]\n .filter(Boolean)\n .join(' ');\n throw new ActionError(\n `refused: ref ${ref} is ${describeElement(element)}, not ${said}, so nothing was done. ${fix}`,\n );\n }\n return { ...action, target: { ref, role: element.role, name: shown } };\n}\n\n/**\n * Resolves the element a ref names (design act-on-the-element-the-model-read,\n * D1/D4), and nothing else: Playwright's `aria-ref` locator answers with the\n * element the snapshot line was printed from or with none. None means the page\n * changed since the snapshot (the element was replaced, or the page navigated,\n * which Playwright reports as an invalid frame), and fails at once instead of\n * waiting `browser.timeout_ms` for an element that cannot come back. A resolved\n * element is still waited on to be visible, bounded by `resolveTimeoutMs`.\n */\nexport async function resolveTarget(\n page: PageLike,\n target: AgentTarget,\n resolveTimeoutMs = 2_000,\n): Promise<LocatorLike> {\n if (!target.ref) throw new ActionError(`Element not found: ${describeTarget(target)} has no ref`);\n const ref = bareRef(target.ref);\n const locator = page.locator(`aria-ref=${ref}`);\n let count: number;\n try {\n count = await locator.count();\n } catch {\n count = 0;\n }\n if (count === 0) {\n throw new ActionError(\n `Element not found: ${describeTarget(target)} (ref ${ref}) is no longer on the page; it changed since the ` +\n 'snapshot. Choose the element again from the fresh snapshot.',\n );\n }\n try {\n await locator.waitFor({ state: 'visible', timeout: resolveTimeoutMs });\n } catch {\n throw new ActionError(\n `Element not found: ${describeTarget(target)} (ref ${ref}) is on the page but did not become visible ` +\n `within ${resolveTimeoutMs}ms.`,\n );\n }\n return locator;\n}\n\nfunction requireTarget(action: AgentAction): AgentTarget {\n if (!action.target?.ref) {\n throw new ActionError(`Action \"${action.action}\" requires a target (its ref in the snapshot)`);\n }\n return action.target;\n}\n\n/** Expands `{{env.*}}` only now, so the value was never in a prompt (design D2). */\nfunction resolve(value: string, ctx: ActionContext): string {\n return ctx.resolveValue ? ctx.resolveValue(value) : value;\n}\n\nfunction requireValue(action: AgentAction): string {\n if (action.value === undefined || action.value === '') {\n throw new ActionError(`Action \"${action.action}\" requires a value`);\n }\n return action.value;\n}\n\n/**\n * Playwright's own words for \"the target was fine and something else took the\n * click\", written into the call log of an action that then times out\n * (design name-what-blocks-the-click, D2).\n *\n * Quoted rather than re-derived: asking the page which element sits at the\n * target's coordinates costs a second round trip, at the moment an action has\n * just spent the whole browser timeout failing, to recompute what the error\n * already carries.\n *\n * Playwright renders the blocker as a whole element — `<div class=\"…\"></div>`\n * — so the capture takes the **opening** tag and the rest of the rendering is\n * skipped up to the phrase. Bounded to one line, because the call log holds a\n * second element a few lines above (`locator resolved to <button …>`, the\n * target itself) and a pattern allowed to cross newlines names that one\n * instead: the wrong element, and the one this message exists to exonerate.\n *\n * This pattern is the coupling this translation rests on. If Playwright ever\n * rewords the line, the translation stops firing and behaviour reverts to the\n * raw timeout — which is why `tests/actions.test.ts` pins a real call log\n * verbatim rather than a hand-written approximation.\n */\nconst INTERCEPTS_POINTER = /(<[^>\\n]{1,400}>)[^\\n]{0,400}?intercepts pointer events/;\n\n/** A framework's overlay class list is long, decorative, and about to be paid for by the token. */\nconst MAX_BLOCKER_LENGTH = 80;\n\nfunction truncateBlocker(tag: string): string {\n return tag.length <= MAX_BLOCKER_LENGTH ? tag : `${tag.slice(0, MAX_BLOCKER_LENGTH)}…>`;\n}\n\n/**\n * Translates an interception into an obstruction the model can act on, or\n * returns `undefined` for any other failure (design D1/D3).\n *\n * The message leads with the fact that inverts the model's default reading. A\n * bare `locator.click: Timeout 30000ms exceeded` says the target is the\n * problem, so a model given one does the only thing that message supports: it\n * re-resolves the same element under a different accessible name. That was\n * measured against a real application — three attempts, three names, all\n * resolving to the correct element, the whole retry budget spent while the\n * dialog on top of it was never touched. So the first thing this says is that\n * the target was found and is fine, and the last thing it says is that trying\n * another name cannot help.\n *\n * The captured tag is markup, and the model is forbidden from targeting by CSS\n * everywhere else. It is named here as *what took the click* and never as a\n * handle: the route to the overlay is the accessibility snapshot, where the\n * dialog and its close control appear as roles and names.\n */\nfunction obstructionFor(error: unknown, action: AgentAction): ActionError | undefined {\n const message = error instanceof Error ? error.message : String(error);\n const match = INTERCEPTS_POINTER.exec(message);\n if (!match) return undefined;\n const where = action.target ? ` on ${describeTarget(action.target)}` : '';\n return new ActionError(\n `blocked: the ${action.action}${where} was NOT performed. The target was found and is visible, ` +\n `enabled and stable — nothing about it is wrong. ${truncateBlocker(match[1]!)} is on top of it and ` +\n `received the pointer event instead. Something is covering the page: find it in the snapshot — a ` +\n `dialog, a cookie banner, an onboarding overlay — and dismiss it first, using its own close or ` +\n `accept control, or by pressing Escape with no target. Then act on this target again. Choosing a ` +\n `different name for the same target cannot help.`,\n );\n}\n\n/**\n * Performs one agent action on the page. `assert`/`done`/`fail` are control\n * actions handled by the executor and rejected here.\n * Returns a short human-readable result string fed back into the next prompt.\n *\n * The obstruction translation is guarded here, over the whole action path,\n * rather than at the five call sites that touch a locator (design D1).\n * `click`, `hover`, `fill`, `select` and a targeted `press` all wait for the\n * same actionability and can all be intercepted; wrapping each of them is five\n * places to forget the sixth, which is this codebase's named recurring defect\n * — a guarantee implemented at a call site instead of over its scope.\n */\nexport async function performAction(\n page: PageLike,\n action: AgentAction,\n ctx: ActionContext,\n): Promise<string> {\n try {\n return await performResolvedAction(page, action, ctx);\n } catch (error) {\n // Conditional on the error text, so anything that is not an interception\n // reaches the model byte-identical to before.\n throw obstructionFor(error, action) ?? error;\n }\n}\n\nasync function performResolvedAction(\n page: PageLike,\n action: AgentAction,\n ctx: ActionContext,\n): Promise<string> {\n switch (action.action) {\n case 'navigate': {\n const value = resolve(requireValue(action), ctx);\n const url = new URL(value, ctx.baseUrl);\n assertAllowedOrigin(url, ctx);\n // Same knob as resolution (design D1): a slow app is waited for, not just\n // the elements on the page it eventually renders.\n await page.goto(url.toString(), { timeout: ctx.resolveTimeoutMs ?? 30_000 });\n // Where it landed, when that is not where it was asked to go (design\n // judge-sees-the-record, D1). The executor has both facts and used to\n // discard one, which left every later reader — the model, the step\n // record, the judge, and whoever reads the log afterwards — believing a\n // redirected navigation had arrived at the requested URL.\n const landed = page.url();\n return landed === url.toString()\n ? `ok: navigated to ${url.toString()}`\n : `ok: navigated to ${url.toString()}, which redirected to ${landed}`;\n }\n case 'click': {\n const target = requireTarget(action);\n const locator = await resolveTarget(page, target, ctx.resolveTimeoutMs);\n await locator.click();\n return `ok: clicked ${describeTarget(target)}`;\n }\n case 'hover': {\n // Not a commit (design hover-over-an-element, D2): it changes what the\n // page shows, never what the application holds.\n const target = requireTarget(action);\n const locator = await resolveTarget(page, target, ctx.resolveTimeoutMs);\n await locator.hover();\n return `ok: hovered ${describeTarget(target)}`;\n }\n case 'fill': {\n const target = requireTarget(action);\n const value = resolve(requireValue(action), ctx);\n const locator = await resolveTarget(page, target, ctx.resolveTimeoutMs);\n await locator.fill(value);\n return `ok: filled ${describeTarget(target)}`;\n }\n case 'press': {\n const key = action.value ? resolve(action.value, ctx) : 'Enter';\n if (action.target?.ref) {\n const locator = await resolveTarget(page, action.target, ctx.resolveTimeoutMs);\n await locator.press(key);\n return `ok: pressed ${key} on ${describeTarget(action.target)}`;\n }\n await page.keyboard.press(key);\n return `ok: pressed ${key}`;\n }\n case 'select': {\n const target = requireTarget(action);\n const value = resolve(requireValue(action), ctx);\n const locator = await resolveTarget(page, target, ctx.resolveTimeoutMs);\n await locator.selectOption({ label: value });\n return `ok: selected \"${value}\" in ${describeTarget(target)}`;\n }\n case 'assert':\n case 'done':\n case 'fail':\n throw new ActionError(`Action \"${action.action}\" is handled by the executor, not the page`);\n }\n}\n","import type { Page } from 'playwright';\nimport { isOriginAllowed } from './actions.js';\n\n/**\n * Which frames' content a snapshot may carry (design\n * show-frames-from-declared-origins, D1): the boundary navigation is compared\n * against, and who to tell when a frame was left out.\n */\nexport interface FrameBoundary {\n /** `base_url`'s origin plus `allowed_origins:`, as `allowedOriginsFor` builds it. */\n allowed: ReadonlySet<string>;\n /** Called with the origin of every frame whose content was not shown. */\n onHidden?: (origin: string) => void;\n}\n\nexport interface SnapshotOptions {\n /** Maximum number of snapshot lines sent to the LLM. Default 200. */\n maxLines?: number;\n /** Required: a snapshot without it would carry every frame's content. */\n frames: FrameBoundary;\n}\n\n/**\n * The URLs of the frame an `iframe` element shows, then of each frame containing\n * it, up to the page — but only when the element `contentRef` names is in that\n * same frame. `undefined` otherwise, or when either element cannot be found.\n */\nexport type FrameChainLookup = (frameRef: string, contentRef: string) => Promise<string[] | undefined>;\n\nconst IFRAME_WITH_CONTENT = /^(\\s*)- iframe\\b.*:$/;\n\n/** The origin a frame's content is judged by: its own URL's, or for `about:` its container's (design D2). */\nfunction contentUrl(chain: string[]): string | undefined {\n return chain.find((url) => !url.startsWith('about:'));\n}\n\n/** The origin of a web URL, or `undefined` for one that has none (`data:`, `file:`). */\nfunction webOrigin(url: string): string | undefined {\n try {\n const origin = new URL(url).origin;\n return origin === 'null' ? undefined : origin;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Replaces the content of every frame outside the boundary with one line saying\n * so (design show-frames-from-declared-origins, D1/D2). Its refs go with it, so\n * an action naming one is refused by `bindTarget` as a ref the snapshot does not\n * have. A frame inside a cut frame goes with its lines. A page with no frame\n * costs no lookup.\n */\nexport async function cutUndeclaredFrames(\n snapshot: string,\n lookup: FrameChainLookup,\n frames: FrameBoundary,\n): Promise<string> {\n if (!/- iframe\\b/.test(snapshot)) return snapshot;\n const lines = snapshot.split('\\n');\n const out: string[] = [];\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i]!;\n out.push(line);\n const frame = IFRAME_WITH_CONTENT.exec(line);\n if (!frame) continue;\n const indent = frame[1]!.length;\n let end = i + 1;\n while (end < lines.length && indentOf(lines[end]!) > indent) end++;\n // Both refs are read from the lines' attribute groups, never from their\n // text: a frame controls the names in its own lines, and a heading named\n // \"[ref=e1]\" must not pass for the page's e1 (design D1).\n const frameRef = lineRef(line);\n const contentRef = lines.slice(i + 1, end).map(lineRef).find((r) => r !== undefined);\n const chain = frameRef === undefined || contentRef === undefined ? undefined : await lookup(frameRef, contentRef);\n const url = chain === undefined ? undefined : contentUrl(chain);\n if (url !== undefined && isOriginAllowed(url, frames.allowed)) continue;\n const origin = url === undefined ? undefined : webOrigin(url);\n const reason =\n url === undefined\n ? \"the frame's origin could not be read\"\n : origin === undefined\n ? `a ${url.split(':')[0]}: frame is never shown`\n : `${origin} is not in allowed_origins`;\n // Only an origin `allowed_origins:` can name gets a warning offering it.\n if (origin !== undefined) frames.onHidden?.(origin);\n out.push(`${' '.repeat(indent + 2)}- text: \"content not shown: ${reason}\"`);\n i = end - 1;\n }\n return out.join('\\n');\n}\n\n/**\n * The live lookup (design D1): the frame the `iframe` element shows, bound to\n * the frame its first content element is in. The `iframe` line's ref is written\n * by Playwright, not by the page; the content ref is tied to the document the\n * snapshot read, so a frame that navigated since does not resolve and is cut.\n */\nfunction frameChainOn(page: Page): FrameChainLookup {\n const handleOf = (ref: string) => page.locator(`aria-ref=${ref}`).elementHandle({ timeout: 1_000 });\n return async (frameRef, contentRef) => {\n const handles: { dispose(): Promise<void> }[] = [];\n try {\n const frameElement = await handleOf(frameRef);\n if (frameElement) handles.push(frameElement);\n const content = await handleOf(contentRef);\n if (content) handles.push(content);\n const shown = await frameElement?.contentFrame();\n const owner = await content?.ownerFrame();\n if (!shown || shown !== owner) return undefined;\n const chain: string[] = [];\n for (let f: typeof shown | null = shown; f; f = f.parentFrame()) chain.push(f.url());\n return chain;\n } catch {\n // Detached between the snapshot and the lookup: unknown, so not shown.\n return undefined;\n } finally {\n await Promise.all(handles.map((h) => h.dispose().catch(() => {})));\n }\n };\n}\n\nconst DEFAULT_MAX_LINES = 200;\n\nfunction indentOf(line: string): number {\n return line.length - line.trimStart().length;\n}\n\n// A line whose role is a dialog, YAML single-quoted or not.\nconst DIALOG_LINE = /^\\s*- '?(?:dialog|alertdialog)(?=[\\s:\"']|$)/;\nconst OMITTED_LINE = /^\\s*- \\.\\.\\. \\(\\d+ lines? omitted: max_snapshot_lines is (\\d+)\\)$/m;\n\n/**\n * The cap a snapshot was cut at, read from its markers, or `undefined` when\n * nothing was omitted (design keep-the-open-dialog-in-the-snapshot, D3). Read\n * from the text so a step's reason cannot disagree with what the model saw.\n */\nexport function snapshotCutAt(snapshot: string): number | undefined {\n const match = OMITTED_LINE.exec(snapshot);\n return match ? Number(match[1]) : undefined;\n}\n\n/**\n * Which lines of an over-cap snapshot to keep (design\n * keep-the-open-dialog-in-the-snapshot, D1). Frameworks render dialogs, menus\n * and palettes in a portal at the end of `<body>`, so a cut from the top\n * dropped first the element the last action opened (#162). The open dialogs\n * (the last one, on top, first) and the focused element are kept with their\n * subtree and the lines they sit under; the rest of the cap is filled from the\n * top, as before. Never more than `maxLines`.\n */\nfunction linesToKeep(lines: string[], maxLines: number): Set<number> {\n const keep = new Set<number>();\n const subtreeEnd = (i: number): number => {\n let j = i + 1;\n while (j < lines.length && indentOf(lines[j]!) > indentOf(lines[i]!)) j++;\n return j;\n };\n const ancestors = (i: number): number[] => {\n const found: number[] = [];\n let indent = indentOf(lines[i]!);\n for (let j = i - 1; j >= 0 && indent > 0; j--) {\n if (indentOf(lines[j]!) < indent) {\n found.unshift(j);\n indent = indentOf(lines[j]!);\n }\n }\n return found;\n };\n\n const dialogs = lines.flatMap((line, i) => (DIALOG_LINE.test(line) ? [i] : [])).reverse();\n const focused = lines.flatMap((line, i) => (line.includes('[active]') ? [i] : []));\n for (const anchor of [...dialogs.slice(0, 1), ...focused, ...dialogs.slice(1)]) {\n for (const line of ancestors(anchor)) if (keep.size < maxLines) keep.add(line);\n for (let line = anchor; line < subtreeEnd(anchor) && keep.size < maxLines; line++) keep.add(line);\n }\n for (let line = 0; line < lines.length && keep.size < maxLines; line++) keep.add(line);\n return keep;\n}\n\n/**\n * Trims an aria snapshot: drops empty containers (e.g. `- group:` with no children)\n * and caps the line count. Over the cap, each run of omitted lines is replaced in\n * place by a marker naming the setting that cut it (design\n * keep-the-open-dialog-in-the-snapshot, D2). Pure function, exported for tests.\n */\nexport function trimSnapshot(snapshotYaml: string, maxLines: number = DEFAULT_MAX_LINES): string {\n let lines = snapshotYaml.split('\\n').filter((line) => line.trim().length > 0);\n\n // Removing empty containers can empty their parents; iterate until stable (bounded).\n for (let pass = 0; pass < 5; pass++) {\n const kept: string[] = [];\n let removed = 0;\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i]!;\n const isContainer = line.trimEnd().endsWith(':');\n if (isContainer) {\n const next = lines[i + 1];\n const hasChildren = next !== undefined && indentOf(next) > indentOf(line);\n if (!hasChildren) {\n removed++;\n continue;\n }\n }\n kept.push(line);\n }\n lines = kept;\n if (removed === 0) break;\n }\n\n if (lines.length <= maxLines) return lines.join('\\n');\n\n const keep = linesToKeep(lines, maxLines);\n const out: string[] = [];\n let omitted = 0;\n for (let i = 0; i <= lines.length; i++) {\n if (i < lines.length && !keep.has(i)) {\n omitted++;\n continue;\n }\n if (omitted > 0) {\n const indent = ' '.repeat(indentOf(lines[i - omitted]!));\n out.push(`${indent}- ... (${omitted} ${omitted === 1 ? 'line' : 'lines'} omitted: max_snapshot_lines is ${maxLines})`);\n omitted = 0;\n }\n if (i < lines.length) out.push(lines[i]!);\n }\n return out.join('\\n');\n}\n\n/**\n * Captures the current page as a compact accessibility snapshot (design D1),\n * prefixed with the page URL so the model can reason about navigation.\n *\n * Always in AI mode (design act-on-the-element-the-model-read, D3): every\n * element carries the `[ref=…]` an action names it by, and a plain\n * `ariaSnapshot()` invalidates the refs of the last AI-mode one, measured. The\n * `[cursor=pointer]` marker it adds is dropped: it is about the mouse, not the\n * element, and it was most of the growth that was not a ref.\n */\nexport async function captureSnapshot(page: Page, options: SnapshotOptions): Promise<string> {\n const raw = await page.locator('body').ariaSnapshot({ mode: 'ai' });\n // Before the trim, so a hidden frame uses none of the line budget (design D1).\n const shown = await cutUndeclaredFrames(raw, frameChainOn(page), options.frames);\n return `url: ${page.url()}\\n${trimSnapshot(shown.replace(/ \\[cursor=pointer\\]/g, ''), options.maxLines)}`;\n}\n\nconst REF_MARKER = / \\[ref=[A-Za-z0-9_-]+\\]/g;\n\n/**\n * The snapshot as a reader that chooses no element sees it: the judge and the\n * planner (design act-on-the-element-the-model-read, D3). Refs are ids, not\n * page content, and the judge corpus's stored snapshots have none.\n */\nexport function withoutRefs(snapshot: string): string {\n return snapshot.replace(REF_MARKER, '');\n}\n\n/** What the snapshot line holding a ref shows about its element. */\nexport interface SnapshotElement {\n role: string;\n /** The accessible name, unquoted; absent when the line has none. */\n name?: string;\n /** Inline text after the colon (`- generic [ref=e4]: Promo code`), unquoted. */\n text?: string;\n}\n\n/** Undoes YAML double-quote escaping, the form a name containing `\"` is printed in. */\nfunction unquote(value: string): string {\n const trimmed = value.trim();\n if (trimmed.length >= 2 && trimmed.startsWith('\"') && trimmed.endsWith('\"')) {\n return trimmed.slice(1, -1).replace(/\\\\([\"\\\\])/g, '$1');\n }\n if (trimmed.length >= 2 && trimmed.startsWith(\"'\") && trimmed.endsWith(\"'\")) {\n return trimmed.slice(1, -1).replace(/''/g, \"'\");\n }\n return trimmed;\n}\n\n// `- role \"name\" [attr] [ref=x] [attr]: inline text`, every part after the role optional.\nconst ELEMENT_LINE =\n /^\\s*- ([a-z][a-zA-Z]*)(?: (\"(?:[^\"\\\\]|\\\\.)*\"))?((?: \\[[^\\]]*\\])*)(?::(?: (.*))?)?$/;\n\n/** A snapshot line as an element: its role, quoted name, attribute group and text. */\nfunction parseElementLine(raw: string): RegExpExecArray | null {\n // YAML single-quotes a whole entry whose text holds `: `, as in\n // `- 'heading \"Notes on file: 1\" [level=2] [ref=e16]'`.\n const quoted = /^(\\s*- )'((?:[^']|'')*)'(:.*)?$/.exec(raw);\n const line = quoted ? `${quoted[1]}${quoted[2]!.replace(/''/g, \"'\")}${quoted[3] ?? ''}` : raw;\n return ELEMENT_LINE.exec(line);\n}\n\n/** The ref in a line's attribute group, never one its name or text spells out. */\nfunction lineRef(raw: string): string | undefined {\n const match = parseElementLine(raw);\n return match ? /\\[ref=([A-Za-z0-9_-]+)\\]/.exec(match[3] ?? '')?.[1] : undefined;\n}\n\n/**\n * Each ref in a snapshot, with the role and name its line shows (design\n * act-on-the-element-the-model-read, D2). Read from the snapshot text the model\n * was given, masked as it was, so what is checked and recorded is what the\n * model read and no secret enters the record.\n */\nexport function indexRefs(snapshot: string): Map<string, SnapshotElement> {\n const index = new Map<string, SnapshotElement>();\n for (const raw of snapshot.split('\\n')) {\n const match = parseElementLine(raw);\n if (!match) continue;\n const ref = /\\[ref=([A-Za-z0-9_-]+)\\]/.exec(match[3] ?? '')?.[1];\n if (!ref) continue;\n const element: SnapshotElement = { role: match[1]! };\n if (match[2] !== undefined) element.name = unquote(match[2]);\n if (match[4] !== undefined && match[4].trim() !== '') element.text = unquote(match[4]);\n index.set(ref, element);\n }\n return index;\n}\n"],"mappings":";;;AAgDO,IAAM,cAAN,cAA0B,MAAM;AAAA,EACrC,YAAY,SAAiB;AAC3B,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACd;AACF;AAqBA,IAAM,aAAa;AASZ,SAAS,kBAAkB,SAAiB,gBAAmD;AACpG,QAAM,UAAU,oBAAI,IAAY,CAAC,IAAI,IAAI,OAAO,EAAE,MAAM,CAAC;AACzD,aAAW,UAAU,kBAAkB,CAAC,GAAG;AACzC,YAAQ,IAAI,IAAI,IAAI,MAAM,EAAE,MAAM;AAAA,EACpC;AACA,SAAO;AACT;AAWO,SAAS,gBAAgB,KAAa,SAAuC;AAClF,MAAI,QAAQ,WAAY,QAAO;AAC/B,MAAI;AACJ,MAAI;AACF,aAAS,IAAI,IAAI,GAAG,EAAE;AAAA,EACxB,QAAQ;AACN,WAAO;AAAA,EACT;AACA,MAAI,WAAW,OAAQ,QAAO;AAC9B,SAAO,QAAQ,IAAI,MAAM;AAC3B;AAGO,SAAS,iBAAiB,SAAsC;AACrE,SAAO,CAAC,GAAG,OAAO,EAAE,KAAK,MAAM;AACj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