lazyscout 0.5.0 → 0.6.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/dist/index.js CHANGED
@@ -10997,6 +10997,341 @@ async function launchBrowser(options = {}) {
10997
10997
  throw new ExplorerError("browser-error", `unable to launch a browser (tried: ${failures.join(", ")})`, options.userDataDir ? "Close any other LazyScout browser for this Project \u2014 the login browser and a recording both hold its profile \u2014 and try again" : 'Please install Google Chrome or Microsoft Edge or run "npx playwright install chromium" and try again');
10998
10998
  }
10999
10999
 
11000
+ // ../../packages/explorer/dist/browser/scoutTraceText.js
11001
+ function tracePath(value) {
11002
+ try {
11003
+ return redactSensitiveText(new URL(value).pathname).slice(0, 320);
11004
+ } catch {
11005
+ return "";
11006
+ }
11007
+ }
11008
+ function displayText(value) {
11009
+ return redactSensitiveText(value).replace(/https?:\/\/[^\s<>"']+/gi, (url) => tracePath(url)).replace(/[\w.+-]+@[\w.-]+\.[a-z]{2,}/gi, "[email]").slice(0, 220);
11010
+ }
11011
+ function elementMarkup(tag, attributes) {
11012
+ const escaped = attributes.map(([name, raw]) => {
11013
+ const value = displayText(raw).replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
11014
+ return ` ${name}="${value}"`;
11015
+ });
11016
+ return "<" + tag + escaped.join("") + ">";
11017
+ }
11018
+
11019
+ // ../../packages/explorer/dist/browser/scoutPreview.js
11020
+ async function captureScoutPreview(page2, origin, stepId, target2) {
11021
+ if (new URL(page2.url()).origin !== origin)
11022
+ return null;
11023
+ if (target2) {
11024
+ const offscreen = await target2.evaluate((el) => {
11025
+ const r = el.getBoundingClientRect();
11026
+ return r.width > 0 && r.height > 0 && (r.bottom <= 0 || r.right <= 0 || r.top >= innerHeight || r.left >= innerWidth);
11027
+ }, void 0, { timeout: 300 });
11028
+ if (offscreen)
11029
+ await target2.scrollIntoViewIfNeeded({ timeout: 350 });
11030
+ }
11031
+ const anchor = target2 ? await target2.elementHandle({ timeout: 300 }) : await page2.evaluateHandle(() => document.documentElement);
11032
+ if (!anchor)
11033
+ return null;
11034
+ try {
11035
+ const map = await anchor.evaluate((anchor2, args) => {
11036
+ if (window !== window.top || location.origin !== args.origin || anchor2.ownerDocument !== document)
11037
+ return null;
11038
+ const query = "button,a[href],input:not([type=hidden]),select,textarea,summary,label[for],[role=button],[role=link],[role=tab],[role=menuitem],[role=checkbox],[role=radio],[role=switch],[tabindex]";
11039
+ const elements2 = [];
11040
+ const seen = /* @__PURE__ */ new Set();
11041
+ for (const el of [...args.hasTarget ? [anchor2] : [], ...Array.from(document.querySelectorAll(query))]) {
11042
+ if (elements2.length >= 180)
11043
+ break;
11044
+ if (seen.has(el) || !el.checkVisibility({ visibilityProperty: true, opacityProperty: true }))
11045
+ continue;
11046
+ seen.add(el);
11047
+ const r = el.getBoundingClientRect();
11048
+ const x = Math.max(0, r.left);
11049
+ const y = Math.max(0, r.top);
11050
+ const width = Math.min(innerWidth, r.right) - x;
11051
+ const height = Math.min(innerHeight, r.bottom) - y;
11052
+ if (width < 1 || height < 1)
11053
+ continue;
11054
+ const isTarget = args.hasTarget && el === anchor2;
11055
+ if (!isTarget && !el.contains(document.elementFromPoint(x + width / 2, y + height / 2)))
11056
+ continue;
11057
+ const attrs = ["id", "role", "type", "data-testid"].filter((key) => el.hasAttribute(key)).map((key) => [key, (el.getAttribute(key) || "").slice(0, 80)]);
11058
+ const label = el.getAttribute("aria-label") || !el.closest("input,textarea,select,[contenteditable]") && !el.querySelector("input,textarea,select,[contenteditable]") && el.innerText || el.id || el.localName;
11059
+ elements2.push({
11060
+ tag: el.localName,
11061
+ label: label.replace(/\s+/g, " ").trim().slice(0, 100),
11062
+ attrs,
11063
+ x,
11064
+ y,
11065
+ width,
11066
+ height,
11067
+ isTarget
11068
+ });
11069
+ }
11070
+ return { elements: elements2, width: innerWidth, height: innerHeight, path: location.pathname, scrollX, scrollY };
11071
+ }, { origin, hasTarget: !!target2 });
11072
+ if (!map)
11073
+ return null;
11074
+ const bytes = await page2.screenshot({
11075
+ type: "jpeg",
11076
+ quality: 48,
11077
+ scale: "css",
11078
+ timeout: 1100,
11079
+ mask: [
11080
+ page2.locator('input, textarea, select, [contenteditable]:not([contenteditable="false"]), iframe, frame, object, embed')
11081
+ ],
11082
+ maskColor: "#64748b"
11083
+ });
11084
+ if (bytes.length > 45e4 || !await anchor.evaluate((el, m) => el.ownerDocument === document && el.isConnected && location.origin === m.origin && location.pathname === m.path && innerWidth === m.width && innerHeight === m.height && scrollX === m.scrollX && scrollY === m.scrollY, { origin, path: map.path, width: map.width, height: map.height, scrollX: map.scrollX, scrollY: map.scrollY }))
11085
+ return null;
11086
+ const targetIndex = map.elements.findIndex((el) => el.isTarget);
11087
+ const elements = map.elements.map(({ attrs, isTarget: _, label, ...el }) => ({
11088
+ ...el,
11089
+ label: displayText(label),
11090
+ html: elementMarkup(el.tag, attrs)
11091
+ }));
11092
+ return {
11093
+ stepId,
11094
+ path: displayText(map.path),
11095
+ width: map.width,
11096
+ height: map.height,
11097
+ jpeg: bytes.toString("base64"),
11098
+ elements,
11099
+ ...targetIndex < 0 ? {} : { targetIndex }
11100
+ };
11101
+ } finally {
11102
+ await anchor.dispose();
11103
+ }
11104
+ }
11105
+
11106
+ // ../../packages/explorer/dist/browser/scoutTrace.js
11107
+ function commandFailure(error, navigation = false) {
11108
+ const message = error instanceof Error ? error.message : String(error);
11109
+ if (/No locator candidate matched/i.test(message))
11110
+ return "not-found";
11111
+ if (/intercepts pointer events/i.test(message))
11112
+ return "covered";
11113
+ if (/element is not enabled/i.test(message))
11114
+ return "disabled";
11115
+ if (/element is not visible/i.test(message))
11116
+ return "not-visible";
11117
+ if (/element (?:was detached|is not attached)/i.test(message))
11118
+ return "detached";
11119
+ if (/element is not stable/i.test(message))
11120
+ return "unstable";
11121
+ if (/has been closed|page crashed/i.test(message))
11122
+ return "closed";
11123
+ const { code } = toExploreIssue("", error);
11124
+ if (code === "timeout" || code === "connection-refused" || code === "dns-error" || code === "ssl-error")
11125
+ return code;
11126
+ return navigation ? "navigation-failed" : "action-failed";
11127
+ }
11128
+ function visibleTraceText() {
11129
+ const result2 = /* @__PURE__ */ new Set();
11130
+ const regions = document.querySelectorAll('h1,h2,h3,dialog[open],[role="dialog"],[role="alert"],[role="status"],[aria-live],[data-state],[aria-invalid="true"],.invalid-feedback');
11131
+ for (const el of Array.from(regions)) {
11132
+ if (result2.size >= 80)
11133
+ break;
11134
+ if (!el.checkVisibility({ visibilityProperty: true }) || el.closest('input,textarea,select,[contenteditable="true"]'))
11135
+ continue;
11136
+ const label = el.getAttribute("aria-label") || el.querySelector("h1,h2,h3")?.textContent;
11137
+ const text = label || !el.querySelector('input,textarea,select,[contenteditable="true"]') && el.innerText;
11138
+ if (text)
11139
+ result2.add(text.replace(/\s+/g, " ").trim().slice(0, 200));
11140
+ }
11141
+ return [...result2].filter(Boolean);
11142
+ }
11143
+ var ScoutTrace = class {
11144
+ origin;
11145
+ publish;
11146
+ publishPreview;
11147
+ active;
11148
+ sequence = 0;
11149
+ reads = /* @__PURE__ */ new Set();
11150
+ before = /* @__PURE__ */ new WeakMap();
11151
+ constructor(origin, publish, publishPreview) {
11152
+ this.origin = origin;
11153
+ this.publish = publish;
11154
+ this.publishPreview = publishPreview;
11155
+ }
11156
+ async preview(step, page2, target2) {
11157
+ if (!this.publishPreview || !step)
11158
+ return;
11159
+ const frame = await captureScoutPreview(page2, this.origin, step.id, target2).catch(() => null);
11160
+ this.publishPreview(frame);
11161
+ }
11162
+ listen(page2) {
11163
+ const pending = /* @__PURE__ */ new WeakMap();
11164
+ const documents = /* @__PURE__ */ new WeakMap();
11165
+ page2.on("request", (request2) => {
11166
+ const step = this.active;
11167
+ if (!step || new URL(request2.url()).origin !== this.origin)
11168
+ return;
11169
+ if (request2.isNavigationRequest() && (step.kind === "click" || step.kind === "press")) {
11170
+ try {
11171
+ if (request2.frame() === page2.mainFrame())
11172
+ documents.set(request2, step);
11173
+ } catch {
11174
+ }
11175
+ }
11176
+ if (!["xhr", "fetch"].includes(request2.resourceType()))
11177
+ return;
11178
+ if (step.requests.length >= 24) {
11179
+ if (!step.requestsLimited) {
11180
+ step.requestsLimited = true;
11181
+ this.publish(step);
11182
+ }
11183
+ return;
11184
+ }
11185
+ const item = { method: request2.method(), path: tracePath(request2.url()), state: "pending" };
11186
+ step.requests.push(item);
11187
+ pending.set(request2, { step, item, start: Date.now() });
11188
+ this.publish(step);
11189
+ });
11190
+ page2.on("response", (response) => {
11191
+ const request2 = response.request();
11192
+ const step = documents.get(request2);
11193
+ if (step) {
11194
+ step.navigation = { path: tracePath(response.url()), status: response.status() };
11195
+ this.publish(step);
11196
+ }
11197
+ const record = pending.get(request2);
11198
+ if (!record)
11199
+ return;
11200
+ record.item.state = "response";
11201
+ record.item.status = response.status();
11202
+ record.item.durationMs = Date.now() - record.start;
11203
+ const mime = response.headers()["content-type"]?.split(";")[0].trim();
11204
+ if (mime && /^[\w.+-]+\/[\w.+-]+$/.test(mime))
11205
+ record.item.contentType = mime.slice(0, 80);
11206
+ this.publish(record.step);
11207
+ });
11208
+ page2.on("requestfailed", (request2) => {
11209
+ const record = pending.get(request2);
11210
+ if (!record)
11211
+ return;
11212
+ record.item.state = "failed";
11213
+ record.item.networkError = request2.failure()?.errorText.match(/^(?:net::)?(ERR_[A-Z0-9_]+)$/)?.[1];
11214
+ record.item.durationMs = Date.now() - record.start;
11215
+ this.publish(record.step);
11216
+ });
11217
+ page2.on("requestfinished", (request2) => {
11218
+ const record = pending.get(request2);
11219
+ if (!record || !record.item.contentType?.match(/(?:\/|\+)json$/i))
11220
+ return;
11221
+ const read = this.jsonShape(request2, record.item).then(() => this.publish(record.step)).catch(() => void 0);
11222
+ this.reads.add(read);
11223
+ void read.finally(() => this.reads.delete(read));
11224
+ });
11225
+ }
11226
+ async jsonShape(request2, item) {
11227
+ const response = await request2.response();
11228
+ if (!response || response.fromServiceWorker() || response.headers()["content-encoding"])
11229
+ return;
11230
+ const { responseBodySize } = await request2.sizes();
11231
+ if (responseBodySize <= 0 || responseBodySize > 32768)
11232
+ return;
11233
+ const data = JSON.parse((await response.body()).toString("utf8"));
11234
+ if (Array.isArray(data))
11235
+ item.itemCount = data.length;
11236
+ const example = Array.isArray(data) ? data[0] : data;
11237
+ if (!example || typeof example !== "object" || Array.isArray(example))
11238
+ return;
11239
+ item.jsonFields = Object.keys(example).filter((key) => /^[A-Za-z_][\w-]{0,39}$/.test(key) && !/token|secret|password|passwd|cookie|auth|session|api.?key/i.test(key)).slice(0, 12);
11240
+ }
11241
+ begin(kind, url, name, attempt) {
11242
+ const step = {
11243
+ id: ++this.sequence,
11244
+ kind,
11245
+ name: displayText(name),
11246
+ path: tracePath(url),
11247
+ startedAt: Date.now(),
11248
+ status: "running",
11249
+ attempt,
11250
+ requests: []
11251
+ };
11252
+ this.active = step;
11253
+ this.publish(step);
11254
+ return step;
11255
+ }
11256
+ skip(url, name, reason) {
11257
+ this.publish({
11258
+ id: ++this.sequence,
11259
+ kind: "skip",
11260
+ path: tracePath(url),
11261
+ name: displayText(name),
11262
+ startedAt: Date.now(),
11263
+ status: "skipped",
11264
+ skipReason: reason,
11265
+ requests: []
11266
+ });
11267
+ }
11268
+ async element(step, locator4) {
11269
+ const before = await locator4.page().evaluate(visibleTraceText).catch(() => void 0);
11270
+ if (before)
11271
+ this.before.set(step, new Set(before));
11272
+ const node = await locator4.evaluate((el) => {
11273
+ const tag = el.localName;
11274
+ const attrs = ["id", "role", "type", "data-testid", "aria-expanded", "aria-selected", "aria-checked"].filter((key) => el.hasAttribute(key)).map((key) => [key, (el.getAttribute(key) ?? "").slice(0, 160)]);
11275
+ const parts = [];
11276
+ for (let item = el; item && parts.length < 8; item = item.parentElement) {
11277
+ if (item.id) {
11278
+ parts.unshift("#" + CSS.escape(item.id));
11279
+ break;
11280
+ }
11281
+ const siblings = Array.from(item.parentElement?.children ?? []).filter((sibling) => sibling.localName === item.localName);
11282
+ parts.unshift(CSS.escape(item.localName) + (siblings.length > 1 ? ":nth-of-type(" + (siblings.indexOf(item) + 1) + ")" : ""));
11283
+ }
11284
+ return { tag, attrs, selector: parts.join(" > ") };
11285
+ }, void 0, { timeout: 400 }).catch(() => void 0);
11286
+ if (!node)
11287
+ return;
11288
+ step.html = elementMarkup(node.tag, node.attrs);
11289
+ step.selector = displayText(node.selector);
11290
+ this.publish(step);
11291
+ }
11292
+ finish(step, success, url, failure, httpStatus) {
11293
+ if (!step)
11294
+ return;
11295
+ if (this.active === step)
11296
+ this.active = void 0;
11297
+ step.status = success ? "done" : "failed";
11298
+ step.failure = failure;
11299
+ step.httpStatus = httpStatus;
11300
+ step.afterPath = tracePath(url);
11301
+ step.durationMs = Date.now() - step.startedAt;
11302
+ this.publish(step);
11303
+ }
11304
+ async observed(step, page2) {
11305
+ if (!step)
11306
+ return;
11307
+ if (new URL(page2.url()).origin !== this.origin) {
11308
+ this.publishPreview?.(null);
11309
+ return;
11310
+ }
11311
+ const prior = this.before.get(step);
11312
+ if (step.kind === "click" && !prior)
11313
+ return;
11314
+ const after = await page2.evaluate(visibleTraceText).catch(() => void 0);
11315
+ if (!after)
11316
+ return;
11317
+ step.changes = [...new Set(after.filter((item) => !prior?.has(item)).map(displayText))].slice(0, 6);
11318
+ this.publish(step);
11319
+ await this.preview(step, page2);
11320
+ }
11321
+ async close(url) {
11322
+ if (this.active)
11323
+ this.finish(this.active, false, url);
11324
+ if (this.reads.size)
11325
+ await Promise.race([
11326
+ Promise.all(this.reads),
11327
+ new Promise((resolve5) => {
11328
+ const timer = setTimeout(resolve5, 300);
11329
+ timer.unref();
11330
+ })
11331
+ ]);
11332
+ }
11333
+ };
11334
+
11000
11335
  // ../../packages/explorer/dist/browser/functionalScope.js
11001
11336
  function isWithinFunctionalScope(value, origin, scopePath) {
11002
11337
  try {
@@ -11120,6 +11455,7 @@ async function exploreWithScope(startUrl, explorationConfig = {}, exploreOptions
11120
11455
  if (!check.ok)
11121
11456
  throw new ExplorerError(check.code, check.message);
11122
11457
  const origin = check.url.origin;
11458
+ const trace = legacyOptions.onTraceStep ? new ScoutTrace(origin, legacyOptions.onTraceStep, legacyOptions.onPreview) : void 0;
11123
11459
  const entryUrl = normalizeUrl(check.url.toString());
11124
11460
  const pages = [];
11125
11461
  const issues = [];
@@ -11515,6 +11851,35 @@ async function exploreWithScope(startUrl, explorationConfig = {}, exploreOptions
11515
11851
  candidates.sort((a, b) => rank(a) - rank(b));
11516
11852
  return candidates;
11517
11853
  }
11854
+ async function navigate2(page2, url, reload = false) {
11855
+ const step = trace?.begin(reload ? "reload" : "open", url, "");
11856
+ const options = { waitUntil: "domcontentloaded", timeout: legacyOptions.pageTimeoutMs };
11857
+ try {
11858
+ const response = reload ? await page2.reload(options) : await page2.goto(url, options);
11859
+ const status = response?.status();
11860
+ const failure = !response ? "no-response" : response.status() >= 400 ? "http-error" : void 0;
11861
+ trace?.finish(step, !failure, page2.url(), failure, status);
11862
+ await trace?.preview(step, page2);
11863
+ return response;
11864
+ } catch (error) {
11865
+ trace?.finish(step, false, page2.url(), commandFailure(error, true));
11866
+ throw error;
11867
+ }
11868
+ }
11869
+ async function restoreCommand(page2, kind, name, perform, target2) {
11870
+ const step = trace?.begin(kind, page2.url(), name);
11871
+ try {
11872
+ if (target2)
11873
+ await trace?.preview(step, page2, target2);
11874
+ await perform();
11875
+ trace?.finish(step, true, page2.url());
11876
+ if (!target2)
11877
+ await trace?.preview(step, page2);
11878
+ } catch (error) {
11879
+ trace?.finish(step, false, page2.url(), commandFailure(error));
11880
+ throw error;
11881
+ }
11882
+ }
11518
11883
  async function replayEntryFlow(page2, entryFlow) {
11519
11884
  const inPageSteps = entryFlow.filter((step) => step.action.selector && step.action.type !== "navigate");
11520
11885
  if (inPageSteps.length === 0)
@@ -11529,7 +11894,7 @@ async function exploreWithScope(startUrl, explorationConfig = {}, exploreOptions
11529
11894
  continue;
11530
11895
  if (!await target2.isVisible())
11531
11896
  continue;
11532
- await target2.click({ timeout: legacyOptions.actionTimeoutMs });
11897
+ await restoreCommand(page2, "click", step.action.target ?? step.action.type, () => target2.click({ timeout: legacyOptions.actionTimeoutMs }), target2);
11533
11898
  await page2.waitForTimeout(legacyOptions.stateDiscoveryTimeoutMs);
11534
11899
  } catch {
11535
11900
  }
@@ -11538,18 +11903,18 @@ async function exploreWithScope(startUrl, explorationConfig = {}, exploreOptions
11538
11903
  async function restoreState(page2, targetUrl, strategy, entryFlow) {
11539
11904
  switch (strategy) {
11540
11905
  case "goto":
11541
- await page2.goto(targetUrl, { waitUntil: "domcontentloaded", timeout: legacyOptions.pageTimeoutMs }).catch(() => void 0);
11906
+ await navigate2(page2, targetUrl).catch(() => void 0);
11542
11907
  await page2.waitForTimeout(legacyOptions.waitAfterNavigationMs);
11543
11908
  await replayEntryFlow(page2, entryFlow);
11544
11909
  break;
11545
11910
  case "reload":
11546
- await page2.reload({ waitUntil: "domcontentloaded", timeout: legacyOptions.pageTimeoutMs }).catch(() => void 0);
11911
+ await navigate2(page2, page2.url(), true).catch(() => void 0);
11547
11912
  await page2.waitForTimeout(legacyOptions.waitAfterNavigationMs);
11548
11913
  await replayEntryFlow(page2, entryFlow);
11549
11914
  break;
11550
11915
  case "close-dialog":
11551
11916
  try {
11552
- await page2.keyboard.press("Escape");
11917
+ await restoreCommand(page2, "press", "Escape", () => page2.keyboard.press("Escape"));
11553
11918
  await page2.waitForTimeout(300);
11554
11919
  } catch {
11555
11920
  }
@@ -11561,7 +11926,8 @@ async function exploreWithScope(startUrl, explorationConfig = {}, exploreOptions
11561
11926
  for (const step of entryFlow) {
11562
11927
  try {
11563
11928
  if (step.action.selector) {
11564
- await page2.locator(step.action.selector).click({ timeout: legacyOptions.actionTimeoutMs }).catch(() => void 0);
11929
+ const target2 = page2.locator(step.action.selector);
11930
+ await restoreCommand(page2, "click", step.action.target ?? step.action.type, () => target2.click({ timeout: legacyOptions.actionTimeoutMs }), target2).catch(() => void 0);
11565
11931
  await page2.waitForTimeout(legacyOptions.stateDiscoveryTimeoutMs);
11566
11932
  }
11567
11933
  } catch {
@@ -11581,6 +11947,7 @@ async function exploreWithScope(startUrl, explorationConfig = {}, exploreOptions
11581
11947
  return false;
11582
11948
  }
11583
11949
  }
11950
+ const reportedDisabled = /* @__PURE__ */ new Set();
11584
11951
  async function executeWithRetry(page2, candidate, currentUrl, entryFlow, maxRetries) {
11585
11952
  const locatorsFor = () => {
11586
11953
  const options = [];
@@ -11596,10 +11963,13 @@ async function exploreWithScope(startUrl, explorationConfig = {}, exploreOptions
11596
11963
  return options;
11597
11964
  };
11598
11965
  for (let attempt = 0; attempt <= maxRetries; attempt++) {
11966
+ const step = trace?.begin("click", page2.url(), candidate.action.target ?? candidate.action.type, attempt + 1);
11599
11967
  try {
11600
11968
  const options = locatorsFor();
11601
- if (options.length === 0)
11969
+ if (options.length === 0) {
11970
+ trace?.finish(step, false, page2.url(), "not-found");
11602
11971
  return { success: false };
11972
+ }
11603
11973
  let locator4;
11604
11974
  for (const build2 of options) {
11605
11975
  const next = build2();
@@ -11610,11 +11980,16 @@ async function exploreWithScope(startUrl, explorationConfig = {}, exploreOptions
11610
11980
  }
11611
11981
  if (!locator4)
11612
11982
  throw new Error("No locator candidate matched");
11983
+ if (step)
11984
+ await trace.element(step, locator4);
11985
+ await trace?.preview(step, page2, locator4);
11613
11986
  await locator4.click({ timeout: legacyOptions.actionTimeoutMs });
11614
11987
  await page2.waitForTimeout(legacyOptions.stateDiscoveryTimeoutMs);
11615
11988
  const newUrl = page2.url();
11616
- return { success: true, newUrl };
11617
- } catch (_error) {
11989
+ trace?.finish(step, true, newUrl);
11990
+ return { success: true, newUrl, step };
11991
+ } catch (error) {
11992
+ trace?.finish(step, false, page2.url(), commandFailure(error));
11618
11993
  if (attempt < maxRetries) {
11619
11994
  totalActionsRetried++;
11620
11995
  debug(`Retrying action: ${candidate.action.description} (attempt ${attempt + 1}/${maxRetries})`, {
@@ -11726,6 +12101,7 @@ async function exploreWithScope(startUrl, explorationConfig = {}, exploreOptions
11726
12101
  const newRaw = await page2.evaluate(collectPageData);
11727
12102
  const newModel = mapToPageModel(newRaw, { url: page2.url(), finalUrl: page2.url(), depth, statusCode: 200 }, legacyOptions.blockedKeywords);
11728
12103
  const newState = newModel.state;
12104
+ await trace?.observed(result2.step, page2);
11729
12105
  if (strictlyScoped)
11730
12106
  recordTransition(modalState, mc.action, { url: beforeUrl, fingerprint: modalState.fingerprint }, { url: page2.url(), state: newState }, newState?.id !== modalState.id ? "changed" : "unchanged");
11731
12107
  if (newState && !visitedStates.has(newState.id)) {
@@ -11742,7 +12118,7 @@ async function exploreWithScope(startUrl, explorationConfig = {}, exploreOptions
11742
12118
  }
11743
12119
  if (closeWhenDone) {
11744
12120
  try {
11745
- await page2.keyboard.press("Escape");
12121
+ await restoreCommand(page2, "press", "Escape", () => page2.keyboard.press("Escape"));
11746
12122
  await page2.waitForTimeout(300);
11747
12123
  } catch {
11748
12124
  }
@@ -11784,13 +12160,20 @@ async function exploreWithScope(startUrl, explorationConfig = {}, exploreOptions
11784
12160
  }
11785
12161
  context.setDefaultTimeout(legacyOptions.pageTimeoutMs);
11786
12162
  const page2 = await context.newPage();
12163
+ trace?.listen(page2);
12164
+ const opening = trace?.begin("open", targetStartUrl, "");
11787
12165
  debug(`Navigating to: ${redactUrl(targetStartUrl)}`);
11788
12166
  const response = await page2.goto(targetStartUrl, {
11789
12167
  waitUntil: "domcontentloaded",
11790
12168
  timeout: legacyOptions.pageTimeoutMs
12169
+ }).catch((error) => {
12170
+ trace?.finish(opening, false, page2.url(), commandFailure(error, true));
12171
+ throw error;
11791
12172
  });
12173
+ await trace?.preview(opening, page2);
11792
12174
  if (!response || response.status() >= 400 && response.status() < 600) {
11793
12175
  const status = response?.status();
12176
+ trace?.finish(opening, false, page2.url(), response ? "http-error" : "no-response", status);
11794
12177
  if (status && status >= 400) {
11795
12178
  issues.push({
11796
12179
  url: targetStartUrl,
@@ -11805,6 +12188,8 @@ async function exploreWithScope(startUrl, explorationConfig = {}, exploreOptions
11805
12188
  const raw = await page2.evaluate(collectPageData);
11806
12189
  const initialPage = mapToPageModel(raw, { url: targetStartUrl, finalUrl: page2.url(), depth: 0, statusCode: response.status() }, legacyOptions.blockedKeywords);
11807
12190
  pages.push(initialPage);
12191
+ trace?.finish(opening, true, page2.url(), void 0, response.status());
12192
+ await trace?.observed(opening, page2);
11808
12193
  visitedUrls.add(normalizeUrl(initialPage.finalUrl));
11809
12194
  if (initialPage.state) {
11810
12195
  visitedStates.add(initialPage.state.id);
@@ -11863,7 +12248,7 @@ async function exploreWithScope(startUrl, explorationConfig = {}, exploreOptions
11863
12248
  const targetUrl = normalizeUrl(item.url);
11864
12249
  if (currentUrl !== targetUrl) {
11865
12250
  try {
11866
- await page2.goto(item.url, { waitUntil: "domcontentloaded", timeout: legacyOptions.pageTimeoutMs });
12251
+ await navigate2(page2, item.url);
11867
12252
  await page2.waitForTimeout(legacyOptions.waitAfterNavigationMs);
11868
12253
  } catch (error) {
11869
12254
  issues.push(toExploreIssue(item.url, error));
@@ -11873,7 +12258,7 @@ async function exploreWithScope(startUrl, explorationConfig = {}, exploreOptions
11873
12258
  if (isAuthLost(page2.url(), page2)) {
11874
12259
  debug(`Auth lost, attempting recovery`, { url: redactUrl(page2.url()) });
11875
12260
  try {
11876
- await page2.goto(item.url, { waitUntil: "domcontentloaded", timeout: legacyOptions.pageTimeoutMs });
12261
+ await navigate2(page2, item.url);
11877
12262
  await page2.waitForTimeout(legacyOptions.waitAfterNavigationMs);
11878
12263
  if (isAuthLost(page2.url(), page2)) {
11879
12264
  debug(`Auth recovery failed`, { url: redactUrl(page2.url()) });
@@ -11907,6 +12292,15 @@ async function exploreWithScope(startUrl, explorationConfig = {}, exploreOptions
11907
12292
  }
11908
12293
  if (config2.mode === "current-page")
11909
12294
  continue;
12295
+ if (trace) {
12296
+ for (const control of currentState.controls) {
12297
+ const key = item.url + "|" + control.cssSelector;
12298
+ if (control.kind === "button" && control.disabled && control.visible !== false && !reportedDisabled.has(key)) {
12299
+ reportedDisabled.add(key);
12300
+ trace.skip(page2.url(), control.accessibleName || control.cssSelector, "disabled");
12301
+ }
12302
+ }
12303
+ }
11910
12304
  const candidates = await discoverSafeCandidates(page2, currentState);
11911
12305
  const safeActions = candidates.filter((c) => c.action.safe).filter((c) => !actionGraph.visitedActionKeys.includes(c.action.id)).filter((c) => !actionGraph.failedActionKeys.includes(c.action.id)).slice(0, config2.limits.maxActionsPerState);
11912
12306
  debug(`State: ${currentState.name} \u2014 Found ${candidates.length} candidates, ${safeActions.length} safe`, {
@@ -11920,6 +12314,7 @@ async function exploreWithScope(startUrl, explorationConfig = {}, exploreOptions
11920
12314
  addEdge(actionGraph, currentState.id, void 0, candidate.action, "blocked");
11921
12315
  actionGraph.blockedActionKeys.push(candidate.action.id);
11922
12316
  const blockReason = isSessionEnding(candidate.action.target, void 0) ? "session-ending action" : candidate.action.reason;
12317
+ trace?.skip(page2.url(), candidate.action.target ?? candidate.action.type, blockReason === "session-ending action" ? "session-ending" : "filtered");
11923
12318
  debug(`Blocked: ${candidate.action.target} (${blockReason})`, {
11924
12319
  actionId: candidate.action.id,
11925
12320
  stateId: currentState.id
@@ -11942,6 +12337,7 @@ async function exploreWithScope(startUrl, explorationConfig = {}, exploreOptions
11942
12337
  const href = candidate.href;
11943
12338
  if (href && !isWithinScope(href)) {
11944
12339
  urlsSkippedByScope++;
12340
+ trace?.skip(page2.url(), candidate.action.target ?? candidate.action.type, "outside-scope");
11945
12341
  debug(`Skipped: ${candidate.action.target} (outside scope ${config2.scopePath || "root"})`, {
11946
12342
  actionId: candidate.action.id,
11947
12343
  reason: `outside scope ${config2.scopePath || "root"}`
@@ -11979,6 +12375,7 @@ async function exploreWithScope(startUrl, explorationConfig = {}, exploreOptions
11979
12375
  const newRaw = await page2.evaluate(collectPageData);
11980
12376
  const newModel = mapToPageModel(newRaw, { url: beforeUrl, finalUrl: afterUrl, depth: item.depth + 1, statusCode: 200 }, legacyOptions.blockedKeywords);
11981
12377
  const newState = newModel.state;
12378
+ await trace?.observed(result2.step, page2);
11982
12379
  const changed = Boolean(newState && (newState.fingerprint !== currentState.fingerprint || afterUrl !== beforeUrl));
11983
12380
  recordTransition(currentState, candidate.action, { url: beforeUrl, fingerprint: currentState.fingerprint }, { url: afterUrl, state: newState }, changed ? "changed" : "unchanged", Date.now() - actionStartedAt);
11984
12381
  if (newState && !visitedStates.has(newState.id)) {
@@ -12017,6 +12414,7 @@ async function exploreWithScope(startUrl, explorationConfig = {}, exploreOptions
12017
12414
  endReason = "browser-crash";
12018
12415
  }
12019
12416
  } finally {
12417
+ await trace?.close(targetStartUrl);
12020
12418
  legacyOptions.signal?.removeEventListener("abort", cancelBrowser);
12021
12419
  await launched.close().catch(() => void 0);
12022
12420
  }
@@ -15086,6 +15484,7 @@ function normalizeResult(value) {
15086
15484
  blockedActionKeys: Array.isArray(actionGraph?.blockedActionKeys) ? actionGraph.blockedActionKeys : []
15087
15485
  },
15088
15486
  runEvents: Array.isArray(value?.runEvents) ? value.runEvents : [],
15487
+ ...Array.isArray(value?.scoutTrace) ? { scoutTrace: value.scoutTrace } : {},
15089
15488
  apiChecks: Array.isArray(value?.apiChecks) ? value.apiChecks : [],
15090
15489
  // Optional, so a Project saved before pattern coverage existed still loads.
15091
15490
  ...value?.coverage ? { coverage: value.coverage } : {},
@@ -15118,19 +15517,44 @@ function registerAnalyzeRoute(app, workspaceRoot) {
15118
15517
  const controller = new AbortController();
15119
15518
  const abort = () => controller.abort();
15120
15519
  reply.raw.once("close", abort);
15520
+ const streaming = request2.headers.accept?.split(",").some((value) => value.trim() === "application/x-ndjson");
15521
+ const write = (message) => {
15522
+ if (!reply.raw.destroyed && !reply.raw.writableEnded)
15523
+ reply.raw.write(JSON.stringify(message) + "\n");
15524
+ };
15121
15525
  try {
15122
- return reply.send(await runScout(workspaceRoot, { ...body, url: check.url.toString() }, {
15526
+ if (streaming) {
15527
+ reply.hijack();
15528
+ reply.raw.writeHead(200, { "content-type": "application/x-ndjson; charset=utf-8", "cache-control": "no-store" });
15529
+ write({ type: "ready" });
15530
+ }
15531
+ const result2 = await runScout(workspaceRoot, { ...body, url: check.url.toString() }, {
15123
15532
  signal: controller.signal,
15533
+ onPreview: streaming && request2.headers["x-lazyscout-preview"] === "1" ? (frame) => {
15534
+ if (!reply.raw.writableNeedDrain || !frame)
15535
+ write({ type: "preview", frame });
15536
+ } : void 0,
15537
+ onTraceStep: streaming ? (step) => {
15538
+ if (!reply.raw.writableNeedDrain)
15539
+ write({ type: "step", step });
15540
+ } : void 0,
15124
15541
  log: (message) => request2.log.info(message)
15125
- }));
15542
+ });
15543
+ if (!streaming)
15544
+ return reply.send(result2);
15545
+ write({ type: "result", result: result2 });
15126
15546
  } catch (error) {
15127
- if (error instanceof AuthProfileBusyError)
15128
- return reply.status(409).send({ error: { code: error.code, message: error.message } });
15129
15547
  request2.log.error({ message: redactSensitiveText(error instanceof Error ? error.message : String(error)) }, "analyze failed");
15130
- const { status, body: errorBody } = toApiError(error);
15548
+ const { status, body: errorBody } = error instanceof AuthProfileBusyError ? { status: 409, body: { error: { code: error.code, message: error.message } } } : toApiError(error);
15549
+ if (streaming) {
15550
+ write({ type: "error", error: errorBody.error });
15551
+ return;
15552
+ }
15131
15553
  return reply.status(status).send(errorBody);
15132
15554
  } finally {
15133
15555
  reply.raw.off("close", abort);
15556
+ if (streaming && !reply.raw.destroyed)
15557
+ reply.raw.end();
15134
15558
  }
15135
15559
  });
15136
15560
  }
@@ -15149,6 +15573,7 @@ async function runScout(workspaceRoot, body, options = {}) {
15149
15573
  releaseAuthLock = await acquireAuthLock(projectDirectory2, "scout", { log: options.log });
15150
15574
  }
15151
15575
  try {
15576
+ const trace = /* @__PURE__ */ new Map();
15152
15577
  const result2 = await exploreWithScope(check.url.toString(), {
15153
15578
  startPath: body.startPath,
15154
15579
  scopePath: body.scopePath,
@@ -15170,6 +15595,11 @@ async function runScout(workspaceRoot, body, options = {}) {
15170
15595
  enforceReadOnlyScope: options.approvedScope,
15171
15596
  prioritizeAction: options.prioritizeAction,
15172
15597
  onQaProgress: options.onQaProgress,
15598
+ onPreview: options.approvedScope ? void 0 : options.onPreview,
15599
+ onTraceStep: options.approvedScope ? void 0 : (step) => {
15600
+ trace.set(step.id, step);
15601
+ options.onTraceStep?.(step);
15602
+ },
15173
15603
  ...options.approvedScope ? { pageTimeoutMs: 8e3, actionTimeoutMs: 1500 } : {},
15174
15604
  headless: config.headless,
15175
15605
  ...authRestore ? { authRestore: { storageState: authRestore.storageState, sessionStorage: authRestore.sessionStorage } } : browserProfileDir && !options.approvedScope ? { browserProfileDir } : {}
@@ -15248,6 +15678,7 @@ async function runScout(workspaceRoot, body, options = {}) {
15248
15678
  stats: result2.stats,
15249
15679
  actionGraph: result2.actionGraph,
15250
15680
  runEvents,
15681
+ ...trace.size ? { scoutTrace: [...trace.values()] } : {},
15251
15682
  apiChecks: body.includeApiChecks ? buildApiChecks(result2.pages) : [],
15252
15683
  ...result2.coverage ? { coverage: { ...result2.coverage, casesGenerated: testCases.length } } : {},
15253
15684
  ...result2.transitions ? { transitions: result2.transitions } : {}
@@ -15779,8 +16210,8 @@ function registerAutomationRunRoute(app, workspaceRoot) {
15779
16210
  addLog("info", `$ lazyscout test --case ${testCase2.id}`);
15780
16211
  addLog("info", `Starting Playwright Test CLI: ${testCase2.title}`);
15781
16212
  addLog("info", `Test budget: ${MAX_STEPS} steps \xB7 ${STEP_TIMEOUT_MS / 1e3}s per action \xB7 ${MAX_LOGS2} log lines`);
15782
- if (!body.code?.trim() && testCase2.steps.length === 0) {
15783
- addLog("warn", "This Test Case has no Steps or Playwright code to run");
16213
+ if (framework === "playwright" && testCase2.steps.every((step) => step.type === "manual") && (!body.code?.trim() || body.code.trim() === generatePlaywrightTest(testCase2).trim())) {
16214
+ addLog("warn", "This case needs an action or a check. Add one under Edit steps before running it.");
15784
16215
  await persistLog("blocked");
15785
16216
  return reply.send({ status: "blocked", framework, logs });
15786
16217
  }
@@ -19485,7 +19916,7 @@ async function openInBrowser(url) {
19485
19916
  }
19486
19917
 
19487
19918
  // src/version.ts
19488
- var VERSION = true ? "0.5.0" : "0.0.0-dev";
19919
+ var VERSION = true ? "0.6.0" : "0.0.0-dev";
19489
19920
 
19490
19921
  // src/commands/serve.ts
19491
19922
  var DEFAULT_PORT = 4321;