lazyscout 0.3.1 → 0.3.3

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
@@ -30,7 +30,8 @@ function fingerprintState(input) {
30
30
  expanded,
31
31
  visible
32
32
  })),
33
- stateContent: [...input.stateContent].sort()
33
+ stateContent: [...input.stateContent].sort(),
34
+ validationMessages: [...input.validationMessages].sort()
34
35
  });
35
36
  let hash = 2166136261;
36
37
  for (let index = 0; index < canonical.length; index += 1) {
@@ -242,6 +243,24 @@ function redactUrl(value) {
242
243
  }
243
244
  }
244
245
 
246
+ // ../../packages/core/dist/safety/blocklist.js
247
+ var MAX_BLOCK_KEYWORDS = 100;
248
+ var MAX_KEYWORD_LENGTH = 80;
249
+ function normalizeBlockedKeywords(value) {
250
+ if (!Array.isArray(value))
251
+ return [];
252
+ const cleaned = value.filter((keyword) => typeof keyword === "string").map((keyword) => keyword.trim().toLowerCase().slice(0, MAX_KEYWORD_LENGTH)).filter(Boolean);
253
+ return [...new Set(cleaned)].slice(0, MAX_BLOCK_KEYWORDS);
254
+ }
255
+ function isBlockedLabel(keywords, ...labels) {
256
+ if (keywords.length === 0)
257
+ return false;
258
+ const haystack = labels.filter(Boolean).join(" ").toLowerCase();
259
+ if (!haystack.trim())
260
+ return false;
261
+ return keywords.some((keyword) => keyword && haystack.includes(keyword.toLowerCase()));
262
+ }
263
+
245
264
  // ../../packages/core/dist/testcase/describeStep.js
246
265
  function describeTarget(target) {
247
266
  const name = target.name || target.label || target.text || target.placeholder;
@@ -422,6 +441,13 @@ function collectPageData() {
422
441
  return false;
423
442
  if (el instanceof HTMLInputElement && el.type === "hidden")
424
443
  return false;
444
+ if (el instanceof HTMLElement) {
445
+ const style = window.getComputedStyle(el);
446
+ if (el.hidden || style.display === "none" || style.visibility === "hidden" || style.opacity === "0")
447
+ return false;
448
+ if (el.getClientRects().length === 0)
449
+ return false;
450
+ }
425
451
  return true;
426
452
  }
427
453
  function collect(selector, kind, defaultRole) {
@@ -455,11 +481,17 @@ function collectPageData() {
455
481
  textareas: collect("textarea", "textarea", "textbox"),
456
482
  selects: collect("select", "select", "combobox"),
457
483
  forms,
458
- visibleDialogs: Array.from(document.querySelectorAll('[role="dialog"], dialog[open], [aria-modal="true"]')).filter(isCollectable).map((element) => accessibleName(element) || cleanText(element.textContent).slice(0, 120)).filter(Boolean).slice(0, 20),
459
- interactions: Array.from(document.querySelectorAll('[role="tab"], [role="tablist"] [aria-controls], [aria-expanded], select')).filter(isCollectable).map((element) => {
484
+ visibleDialogs: Array.from(document.querySelectorAll('[role="dialog"], dialog[open], [aria-modal="true"], .modal-backdrop:not(.hidden), .modal:not(.hidden), .drawer:not(.hidden)')).filter(isCollectable).map((element) => accessibleName(element) || cleanText(element.querySelector("h1, h2, h3")?.textContent) || cleanText(element.textContent).slice(0, 120)).filter(Boolean).slice(0, 20),
485
+ interactions: Array.from(document.querySelectorAll('[role="tab"], [role="tablist"] [aria-controls], [aria-expanded], [aria-haspopup], [data-toggle], [data-bs-toggle], [data-modal], [data-drawer], [data-tab], details[data-accordion], select')).filter(isCollectable).map((element) => {
460
486
  const role = attr(element, "role") || (element instanceof HTMLSelectElement ? "combobox" : "button");
461
487
  const expanded = element.getAttribute("aria-expanded");
462
- const kind = role === "tab" ? "tab" : element instanceof HTMLSelectElement ? "dropdown" : element.matches("[aria-expanded]") ? "accordion" : "dialog";
488
+ const popup = element.getAttribute("aria-haspopup");
489
+ const toggle = element.getAttribute("data-toggle") || element.getAttribute("data-bs-toggle");
490
+ const dataModal = element.hasAttribute("data-modal");
491
+ const dataDrawer = element.hasAttribute("data-drawer");
492
+ const dataTab = element.hasAttribute("data-tab");
493
+ const accordion = element.matches("details[data-accordion]");
494
+ const kind = role === "tab" || dataTab ? "tab" : dataDrawer ? "drawer" : popup === "dialog" || toggle === "modal" || dataModal ? "dialog" : popup === "menu" || popup === "listbox" || toggle === "dropdown" ? "dropdown" : accordion ? "accordion" : element instanceof HTMLSelectElement ? "dropdown" : element.matches("[aria-expanded]") ? "accordion" : "dialog";
463
495
  return {
464
496
  kind,
465
497
  name: accessibleName(element),
@@ -469,106 +501,45 @@ function collectPageData() {
469
501
  visible: true
470
502
  };
471
503
  }).filter((item) => item.name).slice(0, 40),
472
- stateContent: Array.from(document.querySelectorAll('[aria-live], [data-state], [data-testid*="state" i]')).filter(isCollectable).map((element) => cleanText(element.textContent)).filter(Boolean).slice(0, 30)
504
+ stateContent: Array.from(document.querySelectorAll('[aria-live], [data-state], [data-testid*="state" i]')).filter(isCollectable).map((element) => cleanText(element.textContent)).filter(Boolean).slice(0, 30),
505
+ validationMessages: Array.from(document.querySelectorAll('[role="alert"], [aria-invalid="true"], .error, .errors, .invalid-feedback')).filter(isCollectable).map((element) => cleanText(element.textContent)).filter(Boolean).slice(0, 20)
473
506
  };
474
507
  }
475
508
 
476
509
  // ../../packages/explorer/dist/safety.js
477
- var DESTRUCTIVE_KEYWORDS = [
478
- "delete",
479
- "remove",
480
- "destroy",
481
- "erase",
482
- "drop",
483
- "reset",
484
- "purchase",
485
- "buy",
486
- "checkout",
487
- "pay",
488
- "payment",
489
- "transfer",
490
- "withdraw",
491
- "refund",
492
- "send",
493
- "submit order",
494
- "place order",
495
- "confirm payment",
496
- "confirm order",
497
- "logout",
498
- "log out",
499
- "sign out",
500
- "signout",
501
- "deactivate",
502
- "disable account",
503
- "delete account",
504
- "close account",
505
- "unsubscribe",
506
- "cancel subscription",
507
- "archive",
508
- "publish",
509
- "approve",
510
- "reject",
511
- "\u0E25\u0E1A",
512
- "\u0E22\u0E01\u0E40\u0E25\u0E34\u0E01",
513
- "\u0E0A\u0E33\u0E23\u0E30\u0E40\u0E07\u0E34\u0E19",
514
- "\u0E08\u0E48\u0E32\u0E22",
515
- "\u0E42\u0E2D\u0E19",
516
- "\u0E0B\u0E37\u0E49\u0E2D",
517
- "\u0E2A\u0E31\u0E48\u0E07\u0E0B\u0E37\u0E49\u0E2D",
518
- "\u0E22\u0E37\u0E19\u0E22\u0E31\u0E19\u0E01\u0E32\u0E23\u0E0A\u0E33\u0E23\u0E30",
519
- "\u0E2D\u0E2D\u0E01\u0E08\u0E32\u0E01\u0E23\u0E30\u0E1A\u0E1A",
520
- "\u0E2A\u0E48\u0E07\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25",
521
- "\u0E1A\u0E31\u0E19\u0E17\u0E36\u0E01"
522
- ];
523
- function isDestructiveLabel(...labels) {
524
- const haystack = labels.filter(Boolean).join(" ").toLowerCase();
525
- if (!haystack.trim())
526
- return false;
527
- return DESTRUCTIVE_KEYWORDS.some((keyword) => haystack.includes(keyword));
528
- }
529
- function canFollowLink(href, accessibleName) {
510
+ function canFollowLink(href, accessibleName, keywords = []) {
530
511
  if (!href)
531
512
  return false;
532
- if (isDestructiveLabel(accessibleName, href))
533
- return false;
534
- return true;
513
+ return !isBlockedLabel(keywords, accessibleName, href);
535
514
  }
536
515
 
537
516
  // ../../packages/explorer/dist/mapToPageModel.js
538
- function toUIElement(raw) {
517
+ function toUIElement(raw, keywords) {
539
518
  return {
540
519
  ...raw,
541
- destructive: isDestructiveLabel(raw.accessibleName, raw.text, raw.name, raw.id)
520
+ destructive: isBlockedLabel(keywords, raw.accessibleName, raw.text, raw.name, raw.id)
542
521
  };
543
522
  }
544
- function toFormInfo(raw) {
523
+ function toFormInfo(raw, keywords) {
545
524
  return {
546
525
  id: raw.id,
547
526
  name: raw.name,
548
527
  action: raw.action,
549
528
  method: raw.method,
550
529
  accessibleName: raw.accessibleName,
551
- fields: raw.fields.map(toUIElement),
552
- submitButtons: raw.submitButtons.map(toUIElement)
530
+ fields: raw.fields.map((field) => toUIElement(field, keywords)),
531
+ submitButtons: raw.submitButtons.map((button) => toUIElement(button, keywords))
553
532
  };
554
533
  }
555
- function mapToPageModel(raw, meta) {
556
- const links = raw.links.map(toUIElement);
557
- const buttons = raw.buttons.map(toUIElement);
558
- const inputs = raw.inputs.map(toUIElement);
559
- const textareas = raw.textareas.map(toUIElement);
560
- const selects = raw.selects.map(toUIElement);
534
+ function mapToPageModel(raw, meta, blockedKeywords = []) {
535
+ const toElement = (element) => toUIElement(element, blockedKeywords);
536
+ const links = raw.links.map(toElement);
537
+ const buttons = raw.buttons.map(toElement);
538
+ const inputs = raw.inputs.map(toElement);
539
+ const textareas = raw.textareas.map(toElement);
540
+ const selects = raw.selects.map(toElement);
561
541
  const controls = [...links, ...buttons, ...inputs, ...textareas, ...selects];
562
- const stateInput = {
563
- url: meta.finalUrl,
564
- title: raw.title,
565
- visibleDialogs: raw.visibleDialogs,
566
- headings: raw.headings,
567
- controls,
568
- interactions: raw.interactions,
569
- stateContent: raw.stateContent
570
- };
571
- const fingerprint = fingerprintState(stateInput);
542
+ const state = createPageState(raw, meta.finalUrl, controls);
572
543
  return {
573
544
  url: meta.url,
574
545
  finalUrl: meta.finalUrl,
@@ -581,10 +552,41 @@ function mapToPageModel(raw, meta) {
581
552
  inputs,
582
553
  textareas,
583
554
  selects,
584
- forms: raw.forms.map(toFormInfo),
555
+ forms: raw.forms.map((form) => toFormInfo(form, blockedKeywords)),
585
556
  apiRequests: meta.apiRequests ?? [],
586
- state: { id: stateId(meta.finalUrl, fingerprint), ...stateInput, fingerprint }
557
+ state
558
+ };
559
+ }
560
+ function createPageState(raw, url, controls) {
561
+ const stateInput = {
562
+ url,
563
+ title: raw.title,
564
+ name: stateName(raw, url),
565
+ type: stateType(raw),
566
+ discoveredAt: (/* @__PURE__ */ new Date()).toISOString(),
567
+ visibleDialogs: raw.visibleDialogs,
568
+ headings: raw.headings,
569
+ controls,
570
+ interactions: raw.interactions,
571
+ stateContent: raw.stateContent,
572
+ validationMessages: raw.validationMessages
587
573
  };
574
+ const fingerprint = fingerprintState(stateInput);
575
+ return { id: stateId(url, fingerprint), ...stateInput, fingerprint };
576
+ }
577
+ function stateName(raw, url) {
578
+ if (raw.visibleDialogs[0])
579
+ return raw.visibleDialogs[0];
580
+ if (raw.validationMessages[0])
581
+ return raw.validationMessages[0];
582
+ return raw.title || new URL(url).pathname || "Page";
583
+ }
584
+ function stateType(raw) {
585
+ if (raw.visibleDialogs.length)
586
+ return "dialog";
587
+ if (raw.validationMessages.length)
588
+ return "validation";
589
+ return "page";
588
590
  }
589
591
 
590
592
  // ../../packages/explorer/dist/errors.js
@@ -638,15 +640,24 @@ var CANDIDATES = [
638
640
  { channel: "chrome", label: "Google Chrome" },
639
641
  { channel: "msedge", label: "Microsoft Edge" }
640
642
  ];
641
- async function launchBrowser() {
643
+ async function launchBrowser(options = {}) {
642
644
  const failures = [];
643
645
  for (const candidate of CANDIDATES) {
644
646
  try {
647
+ if (options.userDataDir) {
648
+ const context2 = await chromium.launchPersistentContext(options.userDataDir, {
649
+ headless: options.headless ?? true,
650
+ viewport: { width: 1366, height: 900 },
651
+ ...candidate.channel ? { channel: candidate.channel } : {}
652
+ });
653
+ return { context: context2, label: candidate.label, close: () => context2.close() };
654
+ }
645
655
  const browser = await chromium.launch({
646
- headless: true,
656
+ headless: options.headless ?? true,
647
657
  ...candidate.channel ? { channel: candidate.channel } : {}
648
658
  });
649
- return { browser, label: candidate.label };
659
+ const context = await browser.newContext({ viewport: { width: 1366, height: 900 } });
660
+ return { context, label: candidate.label, close: () => browser.close() };
650
661
  } catch (error) {
651
662
  failures.push(candidate.label);
652
663
  void error;
@@ -661,7 +672,13 @@ var DEFAULT_EXPLORE_OPTIONS = {
661
672
  maxDepth: 3,
662
673
  pageTimeoutMs: 2e4,
663
674
  totalTimeoutMs: 12e4,
664
- waitAfterNavigationMs: 750
675
+ waitAfterNavigationMs: 750,
676
+ maxStatesPerPage: 8,
677
+ maxActionsPerState: 8,
678
+ maxTotalStates: 80,
679
+ actionTimeoutMs: 2e3,
680
+ stateDiscoveryTimeoutMs: 350,
681
+ blockedKeywords: []
665
682
  };
666
683
  async function exploreWebsite(startUrl, options = {}, policy = LOCAL_QA_POLICY) {
667
684
  const config2 = { ...DEFAULT_EXPLORE_OPTIONS, ...options };
@@ -675,11 +692,19 @@ async function exploreWebsite(startUrl, options = {}, policy = LOCAL_QA_POLICY)
675
692
  const issues = [];
676
693
  const visited = /* @__PURE__ */ new Set();
677
694
  const queue = [{ url: entryUrl, depth: 0 }];
695
+ const actionGraph = {
696
+ states: [],
697
+ edges: [],
698
+ visitedStateIds: [],
699
+ visitedActionKeys: [],
700
+ failedActionKeys: [],
701
+ blockedActionKeys: []
702
+ };
678
703
  let urlsSkipped = 0;
679
704
  let limitReached = "none";
680
- const { browser, label: browserLabel } = await launchBrowser();
705
+ const launched = await launchBrowser();
706
+ const { context, label: browserLabel } = launched;
681
707
  try {
682
- const context = await browser.newContext({ viewport: { width: 1366, height: 900 } });
683
708
  context.setDefaultTimeout(config2.pageTimeoutMs);
684
709
  const page = await context.newPage();
685
710
  while (queue.length > 0) {
@@ -697,7 +722,7 @@ async function exploreWebsite(startUrl, options = {}, policy = LOCAL_QA_POLICY)
697
722
  if (visited.has(item.url))
698
723
  continue;
699
724
  visited.add(item.url);
700
- const result = await visitPage(page, item, config2);
725
+ const result = await visitPage(page, item, config2, config2.blockedKeywords);
701
726
  if (result.kind === "issue") {
702
727
  issues.push(result.issue);
703
728
  continue;
@@ -709,13 +734,15 @@ async function exploreWebsite(startUrl, options = {}, policy = LOCAL_QA_POLICY)
709
734
  }
710
735
  visited.add(finalKey);
711
736
  pages.push(result.page);
737
+ addState(actionGraph, result.page.state);
738
+ await discoverSafeStates(page, result.page, config2, origin, actionGraph);
712
739
  if (item.depth >= config2.maxDepth) {
713
740
  if (result.page.links.length > 0)
714
741
  limitReached = limitReached === "none" ? "max-depth" : limitReached;
715
742
  continue;
716
743
  }
717
744
  for (const link of result.page.links) {
718
- if (!canFollowLink(link.href, link.accessibleName))
745
+ if (!canFollowLink(link.href, link.accessibleName, config2.blockedKeywords))
719
746
  continue;
720
747
  if (!isSameOrigin(link.href, origin) || !isCrawlableUrl(link.href)) {
721
748
  urlsSkipped++;
@@ -728,8 +755,9 @@ async function exploreWebsite(startUrl, options = {}, policy = LOCAL_QA_POLICY)
728
755
  }
729
756
  }
730
757
  } finally {
731
- await browser.close().catch(() => void 0);
758
+ await launched.close().catch(() => void 0);
732
759
  }
760
+ addNavigationEdges(pages, actionGraph, config2.blockedKeywords);
733
761
  return {
734
762
  startUrl: entryUrl,
735
763
  origin,
@@ -742,64 +770,113 @@ async function exploreWebsite(startUrl, options = {}, policy = LOCAL_QA_POLICY)
742
770
  durationMs: Date.now() - startedAt,
743
771
  limitReached
744
772
  },
745
- actionGraph: buildActionGraph(pages)
773
+ actionGraph
746
774
  };
747
775
  }
748
- function buildActionGraph(pages) {
749
- const states = pages.flatMap((page) => page.state ? [page.state] : []);
750
- const edges = [];
751
- const visitedActionKeys = [];
752
- const failedActionKeys = [];
753
- const blockedActionKeys = [];
776
+ function addNavigationEdges(pages, graph, keywords) {
754
777
  for (const page of pages) {
755
- const state = page.state;
756
- if (!state)
778
+ const source = page.state;
779
+ if (!source)
757
780
  continue;
758
- const fromStateId = state.id;
759
781
  for (const link of page.links) {
760
782
  if (!link.href || !link.accessibleName)
761
783
  continue;
762
- const targetPage = pages.find((candidate) => candidate.url === link.href || candidate.finalUrl === link.href);
784
+ const safe = canFollowLink(link.href, link.accessibleName, keywords);
785
+ const target = pages.find((candidate) => candidate.finalUrl === link.href || candidate.url === link.href)?.state;
763
786
  const action = {
787
+ id: `${source.id}|navigate|${link.cssSelector}`,
764
788
  type: "navigate",
789
+ description: `Navigate to \u201C${link.accessibleName}\u201D`,
765
790
  target: link.accessibleName,
766
791
  selector: link.cssSelector,
767
- safe: canFollowLink(link.href, link.accessibleName)
792
+ locator: { role: link.role, name: link.accessibleName },
793
+ safe,
794
+ reason: safe ? void 0 : "Link matched the Project click filter and was not opened"
768
795
  };
769
- const key = `${fromStateId}|navigate|${link.cssSelector}`;
770
- const status = action.safe ? targetPage ? "visited" : "discovered" : "blocked";
771
- edges.push({ fromStateId, toStateId: targetPage?.state?.id, action, status });
772
- if (status === "visited")
773
- visitedActionKeys.push(key);
774
- if (status === "blocked")
775
- blockedActionKeys.push(key);
776
- }
777
- for (const interaction of state.interactions) {
778
- const destructive = isDestructiveLabel(interaction.name);
779
- const type = interaction.kind === "tab" ? "selectTab" : interaction.kind === "accordion" ? "expandAccordion" : interaction.kind === "dropdown" ? "openDropdown" : interaction.expanded ? "closeDialog" : "openModal";
780
- const key = `${fromStateId}|${type}|${interaction.cssSelector}`;
781
- const action = {
782
- type,
783
- target: interaction.name,
784
- selector: interaction.cssSelector,
785
- safe: !destructive,
786
- reason: destructive ? "Destructive action was discovered but not executed" : void 0
787
- };
788
- edges.push({ fromStateId, action, status: destructive ? "blocked" : "discovered" });
789
- if (destructive)
790
- blockedActionKeys.push(key);
796
+ addEdge(graph, source.id, target?.id, action, safe && target ? "visited" : safe ? "discovered" : "blocked");
797
+ if (!safe)
798
+ graph.blockedActionKeys.push(action.id);
791
799
  }
792
800
  }
801
+ }
802
+ function addState(graph, state) {
803
+ if (!state || graph.states.some((candidate) => candidate.id === state.id))
804
+ return;
805
+ graph.states.push(state);
806
+ graph.visitedStateIds.push(state.id);
807
+ }
808
+ async function discoverSafeStates(page, source, config2, origin, graph) {
809
+ const initial = source.state;
810
+ if (!initial || graph.states.length >= config2.maxTotalStates)
811
+ return;
812
+ const sourceUrl = source.finalUrl;
813
+ const interactions = initial.interactions.slice(0, config2.maxActionsPerState);
814
+ let statesForPage = 1;
815
+ for (const interaction of interactions) {
816
+ if (statesForPage >= config2.maxStatesPerPage || graph.states.length >= config2.maxTotalStates)
817
+ break;
818
+ const action = actionFromInteraction(initial.id, interaction, config2.blockedKeywords);
819
+ const actionKey = action.id;
820
+ if (graph.visitedActionKeys.includes(actionKey) || graph.failedActionKeys.includes(actionKey))
821
+ continue;
822
+ if (!action.safe) {
823
+ addEdge(graph, initial.id, void 0, action, "blocked");
824
+ graph.blockedActionKeys.push(actionKey);
825
+ continue;
826
+ }
827
+ try {
828
+ await page.locator(interaction.cssSelector).click({ timeout: config2.actionTimeoutMs });
829
+ await page.waitForTimeout(config2.stateDiscoveryTimeoutMs);
830
+ if (!isSameOrigin(page.url(), origin)) {
831
+ addEdge(graph, initial.id, void 0, { ...action, safe: false, reason: "Action left the approved origin" }, "blocked");
832
+ graph.blockedActionKeys.push(actionKey);
833
+ continue;
834
+ }
835
+ const raw = await page.evaluate(collectPageData);
836
+ const observed = mapToPageModel(raw, {
837
+ url: page.url(),
838
+ finalUrl: page.url(),
839
+ depth: source.depth,
840
+ statusCode: source.statusCode
841
+ }, config2.blockedKeywords).state;
842
+ if (!observed)
843
+ continue;
844
+ addState(graph, observed);
845
+ addEdge(graph, initial.id, observed.id, action, "visited");
846
+ graph.visitedActionKeys.push(actionKey);
847
+ if (observed.id !== initial.id)
848
+ statesForPage += 1;
849
+ } catch (error) {
850
+ addEdge(graph, initial.id, void 0, action, "failed");
851
+ graph.failedActionKeys.push(actionKey);
852
+ } finally {
853
+ await page.goto(sourceUrl, { waitUntil: "domcontentloaded", timeout: config2.pageTimeoutMs }).catch(() => void 0);
854
+ await page.waitForTimeout(Math.min(config2.waitAfterNavigationMs, 300));
855
+ }
856
+ }
857
+ }
858
+ function actionFromInteraction(stateId2, interaction, keywords) {
859
+ const type = interaction.kind === "tab" ? "selectTab" : interaction.kind === "accordion" ? "expandAccordion" : interaction.kind === "dropdown" ? "openDropdown" : interaction.expanded ? "closeDialog" : "openModal";
860
+ const blocked = isBlockedLabel(keywords, interaction.name);
861
+ const description = `${type === "selectTab" ? "Select" : type === "expandAccordion" ? "Expand" : "Open"} \u201C${interaction.name}\u201D`;
793
862
  return {
794
- states,
795
- edges,
796
- visitedStateIds: states.map((state) => state.id),
797
- visitedActionKeys,
798
- failedActionKeys,
799
- blockedActionKeys
863
+ id: `${stateId2}|${type}|${interaction.cssSelector}`,
864
+ type,
865
+ description,
866
+ target: interaction.name,
867
+ selector: interaction.cssSelector,
868
+ locator: { role: interaction.role, name: interaction.name },
869
+ safe: !blocked,
870
+ reason: blocked ? "Action matched the Project click filter and was not executed" : void 0
800
871
  };
801
872
  }
802
- async function visitPage(page, item, config2) {
873
+ function addEdge(graph, fromStateId, toStateId, action, status) {
874
+ const id = `${fromStateId}|${action.id}|${toStateId ?? status}`;
875
+ if (graph.edges.some((edge) => edge.id === id))
876
+ return;
877
+ graph.edges.push({ id, fromStateId, toStateId, action, status });
878
+ }
879
+ async function visitPage(page, item, config2, keywords) {
803
880
  try {
804
881
  const apiRequests = [];
805
882
  const requestStarted = /* @__PURE__ */ new Map();
@@ -860,13 +937,328 @@ async function visitPage(page, item, config2) {
860
937
  depth: item.depth,
861
938
  statusCode: status,
862
939
  apiRequests
863
- })
940
+ }, keywords)
864
941
  };
865
942
  } catch (error) {
866
943
  return { kind: "issue", issue: toExploreIssue(item.url, error) };
867
944
  }
868
945
  }
869
946
 
947
+ // ../../packages/explorer/dist/recorder/recorderScript.js
948
+ function recorderInitScript() {
949
+ const scope = window;
950
+ const marker = document;
951
+ if (marker.__lazyscoutRecorderReady)
952
+ return;
953
+ marker.__lazyscoutRecorderReady = true;
954
+ const CLICKABLE = 'a,button,input,select,textarea,[role="button"],[role="link"],[role="tab"],[role="menuitem"],[role="checkbox"],[role="radio"],[role="option"]';
955
+ const NON_TEXT_INPUTS = ["button", "submit", "reset", "checkbox", "radio", "file", "image"];
956
+ const send = (event) => {
957
+ try {
958
+ void scope.__lazyscoutRecord?.(event);
959
+ } catch {
960
+ }
961
+ };
962
+ const clean = (value) => (value ?? "").replace(/\s+/g, " ").trim().slice(0, 120);
963
+ const inputType = (element) => element.tagName.toLowerCase() === "input" ? element.type.toLowerCase() : "";
964
+ const roleOf = (element) => {
965
+ const explicit = element.getAttribute("role");
966
+ if (explicit)
967
+ return explicit;
968
+ const tag = element.tagName.toLowerCase();
969
+ if (tag === "a")
970
+ return element.hasAttribute("href") ? "link" : void 0;
971
+ if (tag === "button")
972
+ return "button";
973
+ if (tag === "select")
974
+ return "combobox";
975
+ if (tag === "textarea")
976
+ return "textbox";
977
+ if (/^h[1-6]$/.test(tag))
978
+ return "heading";
979
+ if (tag !== "input")
980
+ return void 0;
981
+ const type = inputType(element);
982
+ if (type === "button" || type === "submit" || type === "reset" || type === "image")
983
+ return "button";
984
+ if (type === "checkbox")
985
+ return "checkbox";
986
+ if (type === "radio")
987
+ return "radio";
988
+ if (type === "range")
989
+ return "slider";
990
+ if (type === "number")
991
+ return "spinbutton";
992
+ if (type === "search")
993
+ return "searchbox";
994
+ if (type === "hidden")
995
+ return void 0;
996
+ return "textbox";
997
+ };
998
+ const labelOf2 = (element) => {
999
+ const id = element.getAttribute("id");
1000
+ if (id) {
1001
+ const explicit = document.querySelector(`label[for="${CSS.escape(id)}"]`);
1002
+ const value = clean(explicit?.textContent);
1003
+ if (value)
1004
+ return value;
1005
+ }
1006
+ const wrapping = element.closest("label");
1007
+ return clean(wrapping?.textContent) || void 0;
1008
+ };
1009
+ const accessibleName = (element) => {
1010
+ const aria = clean(element.getAttribute("aria-label"));
1011
+ if (aria)
1012
+ return aria;
1013
+ const labelledBy = element.getAttribute("aria-labelledby");
1014
+ if (labelledBy) {
1015
+ const parts = labelledBy.split(/\s+/).map((ref) => document.getElementById(ref)?.textContent ?? "");
1016
+ const joined = clean(parts.join(" "));
1017
+ if (joined)
1018
+ return joined;
1019
+ }
1020
+ const label = labelOf2(element);
1021
+ if (label)
1022
+ return label;
1023
+ const title = clean(element.getAttribute("title"));
1024
+ if (title)
1025
+ return title;
1026
+ const alt = clean(element.getAttribute("alt"));
1027
+ if (alt)
1028
+ return alt;
1029
+ if (element.tagName.toLowerCase() === "input") {
1030
+ const type = inputType(element);
1031
+ if (type === "button" || type === "submit" || type === "reset") {
1032
+ const value = clean(element.getAttribute("value"));
1033
+ if (value)
1034
+ return value;
1035
+ }
1036
+ return void 0;
1037
+ }
1038
+ return clean(element.textContent) || void 0;
1039
+ };
1040
+ const cssPath = (element) => {
1041
+ const testId = element.getAttribute("data-testid") ?? element.getAttribute("data-test-id") ?? element.getAttribute("data-test");
1042
+ if (testId)
1043
+ return `[data-testid="${testId}"]`;
1044
+ const id = element.getAttribute("id");
1045
+ if (id && !/\d{4,}/.test(id))
1046
+ return `#${CSS.escape(id)}`;
1047
+ const name = element.getAttribute("name");
1048
+ if (name)
1049
+ return `${element.tagName.toLowerCase()}[name="${CSS.escape(name)}"]`;
1050
+ const parts = [];
1051
+ let node = element;
1052
+ let depth = 0;
1053
+ while (node && depth < 4) {
1054
+ const parent = node.parentElement;
1055
+ let part = node.tagName.toLowerCase();
1056
+ if (parent) {
1057
+ const tagName = node.tagName;
1058
+ const siblings = Array.from(parent.children).filter((child) => child.tagName === tagName);
1059
+ if (siblings.length > 1)
1060
+ part += `:nth-of-type(${siblings.indexOf(node) + 1})`;
1061
+ }
1062
+ parts.unshift(part);
1063
+ node = parent;
1064
+ depth += 1;
1065
+ }
1066
+ return parts.join(" > ");
1067
+ };
1068
+ const targetOf = (element) => {
1069
+ const role = roleOf(element);
1070
+ return {
1071
+ role,
1072
+ name: accessibleName(element),
1073
+ // Only offer text matching where there is no role to match on.
1074
+ text: role ? void 0 : clean(element.textContent) || void 0,
1075
+ label: labelOf2(element),
1076
+ placeholder: clean(element.getAttribute("placeholder")) || void 0,
1077
+ cssSelector: cssPath(element)
1078
+ };
1079
+ };
1080
+ document.addEventListener("click", (event) => {
1081
+ const origin = event.target instanceof Element ? event.target : null;
1082
+ const element = origin?.closest(CLICKABLE);
1083
+ if (!element)
1084
+ return;
1085
+ const tag = element.tagName.toLowerCase();
1086
+ if (tag === "select")
1087
+ return;
1088
+ if (tag === "textarea")
1089
+ return;
1090
+ if (tag === "input" && !NON_TEXT_INPUTS.includes(inputType(element)))
1091
+ return;
1092
+ send({ kind: "click", target: targetOf(element), url: location.href });
1093
+ }, true);
1094
+ const pendingFlush = /* @__PURE__ */ new WeakMap();
1095
+ const flushField = (element) => {
1096
+ const timer = pendingFlush.get(element);
1097
+ if (timer !== void 0) {
1098
+ clearTimeout(timer);
1099
+ pendingFlush.delete(element);
1100
+ }
1101
+ const tag = element.tagName.toLowerCase();
1102
+ if (tag === "textarea") {
1103
+ send({
1104
+ kind: "fill",
1105
+ target: targetOf(element),
1106
+ value: element.value.slice(0, 200),
1107
+ url: location.href
1108
+ });
1109
+ return;
1110
+ }
1111
+ if (tag !== "input")
1112
+ return;
1113
+ const input = element;
1114
+ const type = inputType(element);
1115
+ if (NON_TEXT_INPUTS.includes(type))
1116
+ return;
1117
+ if (type === "password") {
1118
+ send({ kind: "fill", target: targetOf(element), value: "", secret: true, url: location.href });
1119
+ return;
1120
+ }
1121
+ send({ kind: "fill", target: targetOf(element), value: input.value.slice(0, 200), url: location.href });
1122
+ };
1123
+ document.addEventListener("input", (event) => {
1124
+ const element = event.target instanceof Element ? event.target : null;
1125
+ if (!element)
1126
+ return;
1127
+ const tag = element.tagName.toLowerCase();
1128
+ if (tag !== "input" && tag !== "textarea")
1129
+ return;
1130
+ const existing = pendingFlush.get(element);
1131
+ if (existing !== void 0)
1132
+ clearTimeout(existing);
1133
+ pendingFlush.set(element, setTimeout(() => flushField(element), 400));
1134
+ }, true);
1135
+ document.addEventListener("change", (event) => {
1136
+ const element = event.target instanceof Element ? event.target : null;
1137
+ if (!element)
1138
+ return;
1139
+ const tag = element.tagName.toLowerCase();
1140
+ if (tag === "select") {
1141
+ const select = element;
1142
+ const option = select.options[select.selectedIndex];
1143
+ send({
1144
+ kind: "select",
1145
+ target: targetOf(element),
1146
+ option: clean(option?.text) || select.value,
1147
+ url: location.href
1148
+ });
1149
+ return;
1150
+ }
1151
+ flushField(element);
1152
+ }, true);
1153
+ window.addEventListener("pagehide", () => {
1154
+ const active = document.activeElement;
1155
+ if (active)
1156
+ flushField(active);
1157
+ });
1158
+ }
1159
+
1160
+ // ../../packages/explorer/dist/recorder/attachRecorder.js
1161
+ var SECRET_PLACEHOLDER = "{{TEST_PASSWORD}}";
1162
+ var MAX_RECORDED_STEPS = 200;
1163
+ function closingAssertion(lastActionUrl, finalUrl) {
1164
+ if (!finalUrl || finalUrl === lastActionUrl)
1165
+ return void 0;
1166
+ let path;
1167
+ try {
1168
+ path = new URL(finalUrl).pathname;
1169
+ } catch {
1170
+ return void 0;
1171
+ }
1172
+ if (!path || path === "/")
1173
+ return void 0;
1174
+ return { type: "assertUrl", urlContains: path };
1175
+ }
1176
+ var sameTarget = (left, right) => left.cssSelector === right.cssSelector && left.role === right.role && left.name === right.name;
1177
+ function compactTarget(target) {
1178
+ const entries = Object.entries(target).filter(([, value]) => value !== void 0 && value !== "");
1179
+ return Object.fromEntries(entries);
1180
+ }
1181
+ function buildStep(event) {
1182
+ const target = compactTarget(event.target);
1183
+ if (event.kind === "click")
1184
+ return { type: "click", target };
1185
+ if (event.kind === "select")
1186
+ return { type: "select", target, option: event.option };
1187
+ return { type: "fill", target, value: event.secret ? SECRET_PLACEHOLDER : event.value };
1188
+ }
1189
+ async function attachRecorder(context, startUrl, options = {}) {
1190
+ const steps = [];
1191
+ let lastUrl = "";
1192
+ let finalUrl = "";
1193
+ let sawPage = false;
1194
+ let ended = false;
1195
+ const end = () => {
1196
+ if (ended)
1197
+ return;
1198
+ ended = true;
1199
+ options.onEnded?.();
1200
+ };
1201
+ const pushNavigate = (url) => {
1202
+ if (!url || url === "about:blank" || url === lastUrl)
1203
+ return;
1204
+ lastUrl = url;
1205
+ if (steps.length < MAX_RECORDED_STEPS)
1206
+ steps.push({ type: "navigate", url });
1207
+ };
1208
+ const record = (event) => {
1209
+ if (steps.length >= MAX_RECORDED_STEPS)
1210
+ return;
1211
+ pushNavigate(event.url);
1212
+ const step = buildStep(event);
1213
+ if (!step)
1214
+ return;
1215
+ const previous = steps[steps.length - 1];
1216
+ if (step.type === "fill" && previous && previous.type === "fill" && sameTarget(previous.target, step.target) && previous.value !== SECRET_PLACEHOLDER) {
1217
+ steps[steps.length - 1] = step;
1218
+ return;
1219
+ }
1220
+ steps.push(step);
1221
+ };
1222
+ await context.exposeBinding("__lazyscoutRecord", (_source, event) => {
1223
+ try {
1224
+ record(event);
1225
+ } catch {
1226
+ }
1227
+ });
1228
+ await context.addInitScript(recorderInitScript);
1229
+ const inject = (page) => {
1230
+ void page.evaluate(recorderInitScript).catch(() => void 0);
1231
+ };
1232
+ const watchPage = (page) => {
1233
+ sawPage = true;
1234
+ inject(page);
1235
+ page.on("domcontentloaded", () => inject(page));
1236
+ page.on("framenavigated", (frame) => {
1237
+ if (frame !== page.mainFrame())
1238
+ return;
1239
+ const url = frame.url();
1240
+ if (url && url !== "about:blank")
1241
+ finalUrl = url;
1242
+ });
1243
+ page.on("close", () => {
1244
+ if (sawPage && context.pages().length === 0)
1245
+ end();
1246
+ });
1247
+ };
1248
+ context.pages().forEach(watchPage);
1249
+ context.on("page", watchPage);
1250
+ context.on("close", end);
1251
+ pushNavigate(startUrl);
1252
+ return {
1253
+ steps: () => steps.slice(),
1254
+ finalize: () => {
1255
+ const closing = closingAssertion(lastUrl, finalUrl);
1256
+ return closing ? [...steps, closing] : steps.slice();
1257
+ },
1258
+ currentUrl: () => lastUrl
1259
+ };
1260
+ }
1261
+
870
1262
  // ../../packages/generators/dist/moduleNames.js
871
1263
  function assignModules(pages) {
872
1264
  const result = /* @__PURE__ */ new Map();
@@ -1430,13 +1822,17 @@ function registerAnalyzeRoute(app) {
1430
1822
  const result = await exploreWebsite(check.url.toString(), {
1431
1823
  maxPages: clamp(body.maxPages, 1, config.limits.maxPages, config.limits.maxPages),
1432
1824
  maxDepth: clamp(body.maxDepth, 0, config.limits.maxDepth, config.limits.maxDepth),
1433
- waitAfterNavigationMs: clamp(body.waitAfterNavigationMs, 0, 5e3, 750)
1825
+ waitAfterNavigationMs: clamp(body.waitAfterNavigationMs, 0, 5e3, 750),
1826
+ blockedKeywords: normalizeBlockedKeywords(body.blockedKeywords)
1434
1827
  }, config.urlPolicy);
1435
1828
  if (result.pages.length === 0) {
1436
1829
  const firstIssue = result.issues[0];
1437
1830
  throw new ExplorerError(firstIssue?.code ?? "navigation-failed", firstIssue?.message ?? "Could not open the website.", "Check that the URL is correct and the website is available.");
1438
1831
  }
1439
- const testCases = generateTestCases(result.pages, { language: body.language ?? "en" });
1832
+ const testCases = [
1833
+ ...generateTestCases(result.pages, { language: body.language ?? "en" }),
1834
+ ...generateStateFlowTestCases(result.actionGraph)
1835
+ ];
1440
1836
  const runEvents = [
1441
1837
  {
1442
1838
  timestamp: new Date(Date.now() - result.stats.durationMs).toISOString(),
@@ -1462,6 +1858,23 @@ function registerAnalyzeRoute(app) {
1462
1858
  message: `${interaction.kind}: ${interaction.name}`
1463
1859
  }))
1464
1860
  ]),
1861
+ ...result.actionGraph.states.map((state) => ({
1862
+ timestamp: state.discoveredAt,
1863
+ eventType: "state-discovered",
1864
+ currentUrl: state.url,
1865
+ currentStateId: state.id,
1866
+ result: "passed",
1867
+ message: `State observed: ${state.name || state.title || state.url}`
1868
+ })),
1869
+ ...result.actionGraph.edges.map((edge) => ({
1870
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1871
+ eventType: edge.status === "blocked" ? "action-blocked" : edge.status === "failed" ? "action-failed" : edge.status === "visited" ? "action-executed" : "transition-discovered",
1872
+ currentUrl: result.actionGraph.states.find((state) => state.id === edge.fromStateId)?.url,
1873
+ currentStateId: edge.fromStateId,
1874
+ action: edge.action,
1875
+ result: edge.status === "blocked" ? "blocked" : edge.status === "failed" ? "failed" : edge.status === "visited" ? "passed" : "warning",
1876
+ message: edge.action.description
1877
+ })),
1465
1878
  ...result.issues.map((issue) => ({
1466
1879
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1467
1880
  eventType: "error",
@@ -1498,6 +1911,56 @@ function registerAnalyzeRoute(app) {
1498
1911
  }
1499
1912
  });
1500
1913
  }
1914
+ function generateStateFlowTestCases(graph) {
1915
+ const states = new Map(graph.states.map((state) => [state.id, state]));
1916
+ let sequence = 1;
1917
+ return graph.edges.flatMap((edge) => {
1918
+ if (edge.status !== "visited" || !edge.toStateId || edge.fromStateId === edge.toStateId)
1919
+ return [];
1920
+ const target = states.get(edge.toStateId);
1921
+ const source = states.get(edge.fromStateId);
1922
+ if (!target || !source)
1923
+ return [];
1924
+ const observation = expectedObservation(target);
1925
+ const id = `TC-FLOW-${String(sequence).padStart(3, "0")}`;
1926
+ sequence += 1;
1927
+ return [
1928
+ {
1929
+ id,
1930
+ module: "FLOW",
1931
+ tags: ["state-flow"],
1932
+ title: `${edge.action.description} reaches ${target.name}`,
1933
+ preconditions: [`The application is available at ${source.url}`],
1934
+ steps: [
1935
+ { type: "navigate", url: source.url },
1936
+ {
1937
+ type: "click",
1938
+ target: {
1939
+ role: edge.action.locator?.role,
1940
+ name: edge.action.locator?.name,
1941
+ cssSelector: edge.action.selector
1942
+ }
1943
+ }
1944
+ ],
1945
+ expectedResult: observation ?? "Observed state requires tester review before automation.",
1946
+ type: target.type === "validation" || target.type === "error" ? "validation" : "positive",
1947
+ priority: "medium",
1948
+ automationStatus: observation ? "ready" : "needs-review",
1949
+ sourceUrl: source.url,
1950
+ notes: observation ? "Generated from an observed UI state transition." : "Explorer observed a new UI state but no stable assertion text."
1951
+ }
1952
+ ];
1953
+ });
1954
+ }
1955
+ function expectedObservation(state) {
1956
+ if (state.visibleDialogs[0])
1957
+ return `Dialog "${state.visibleDialogs[0]}" is visible.`;
1958
+ if (state.validationMessages[0])
1959
+ return `Validation message "${state.validationMessages[0]}" is visible.`;
1960
+ if (state.headings[0])
1961
+ return `Heading "${state.headings[0]}" is visible.`;
1962
+ return void 0;
1963
+ }
1501
1964
  function buildApiChecks(pages) {
1502
1965
  const seen = /* @__PURE__ */ new Set();
1503
1966
  const checks = [];
@@ -1704,6 +2167,9 @@ async function openWorkspace(root) {
1704
2167
  else
1705
2168
  await execFileAsync("xdg-open", [root]);
1706
2169
  }
2170
+ async function browserProfileDirectory(root, projectId) {
2171
+ return join(await ensureProject(root, projectId), "browser-profile");
2172
+ }
1707
2173
  async function readProject(root, projectId) {
1708
2174
  try {
1709
2175
  const directory = projectDirectory(root, projectId);
@@ -1719,7 +2185,7 @@ async function readProject(root, projectId) {
1719
2185
  async function ensureProject(root, projectId) {
1720
2186
  await ensureWorkspace(root);
1721
2187
  const directory = projectDirectory(root, projectId);
1722
- await Promise.all(["automation", "screenshots", "bugs", "reports", "logs"].map((name) => mkdir(join(directory, name), { recursive: true })));
2188
+ await Promise.all(["automation", "screenshots", "bugs", "reports", "logs", "browser-profile"].map((name) => mkdir(join(directory, name), { recursive: true })));
1723
2189
  return directory;
1724
2190
  }
1725
2191
  function projectDirectory(root, projectId) {
@@ -1828,13 +2294,14 @@ function registerAutomationRunRoute(app, workspaceRoot) {
1828
2294
  if (!active)
1829
2295
  return reply.send({ stopped: false });
1830
2296
  active.stopped = true;
1831
- await active.browser?.close().catch(() => void 0);
2297
+ await active.close?.().catch(() => void 0);
1832
2298
  return reply.send({ stopped: true });
1833
2299
  });
1834
2300
  app.post("/api/automation/run", async (request, reply) => {
1835
2301
  const body = request.body;
1836
2302
  const testCase = body.testCase;
1837
2303
  const secrets = body.secrets;
2304
+ const blockedKeywords = normalizeBlockedKeywords(body.blockedKeywords);
1838
2305
  const framework = body.framework ?? "playwright";
1839
2306
  const runId = body.runId || crypto.randomUUID();
1840
2307
  if (!testCase || !Array.isArray(testCase.steps))
@@ -1884,21 +2351,22 @@ function registerAutomationRunRoute(app, workspaceRoot) {
1884
2351
  }
1885
2352
  const active = { stopped: false };
1886
2353
  activeRuns.set(runId, active);
1887
- let browser;
2354
+ let close;
1888
2355
  let page;
1889
2356
  const capturedScreenshots = [];
1890
2357
  try {
1891
- const launched = await launchBrowser();
1892
- browser = launched.browser;
1893
- active.browser = browser;
2358
+ const profile = body.projectId ? await browserProfileDirectory(workspaceRoot, body.projectId) : void 0;
2359
+ const launched = await launchBrowser({ userDataDir: profile });
2360
+ close = launched.close;
2361
+ active.close = close;
1894
2362
  if (active.stopped)
1895
2363
  throw new Error("Run stopped by user");
1896
- const context = await browser.newContext({ viewport: { width: 1366, height: 900 } });
2364
+ const { context } = launched;
1897
2365
  context.setDefaultTimeout(STEP_TIMEOUT_MS);
1898
2366
  page = await context.newPage();
1899
2367
  if (typeof body.code === "string" && body.code.trim()) {
1900
2368
  addLog("info", "Running edited automation source");
1901
- await executeEditedCode(page, body.code, testCase.id, capturedScreenshots, addLog, secrets);
2369
+ await executeEditedCode(page, body.code, testCase.id, capturedScreenshots, addLog, blockedKeywords, secrets);
1902
2370
  if (active.stopped)
1903
2371
  throw new Error("Run stopped by user");
1904
2372
  addLog("pass", "\u2713 edited source completed");
@@ -1907,7 +2375,7 @@ function registerAutomationRunRoute(app, workspaceRoot) {
1907
2375
  if (active.stopped)
1908
2376
  throw new Error("Run stopped by user");
1909
2377
  const stepStarted = Date.now();
1910
- await executeStep(page, step, addLog, secrets);
2378
+ await executeStep(page, step, addLog, blockedKeywords, secrets);
1911
2379
  if (active.stopped)
1912
2380
  throw new Error("Run stopped by user");
1913
2381
  addLog("pass", `\u2713 ${step.type}`, Date.now() - stepStarted);
@@ -1924,6 +2392,7 @@ function registerAutomationRunRoute(app, workspaceRoot) {
1924
2392
  });
1925
2393
  } catch (error) {
1926
2394
  const message = redactSensitiveText(error instanceof Error ? error.message : String(error), secretValues);
2395
+ debugLocator("StepFailed", { testCaseId: testCase.id, url: page?.url(), error: message });
1927
2396
  if (active.stopped) {
1928
2397
  addLog("warn", "Run stopped by user", Date.now() - started);
1929
2398
  await persistLog("stopped");
@@ -1942,14 +2411,14 @@ function registerAutomationRunRoute(app, workspaceRoot) {
1942
2411
  });
1943
2412
  } finally {
1944
2413
  activeRuns.delete(runId);
1945
- await browser?.close().catch(() => void 0);
2414
+ await close?.().catch(() => void 0);
1946
2415
  }
1947
2416
  });
1948
2417
  }
1949
2418
  function withScreenshotStatus(screenshots, status) {
1950
2419
  return screenshots.map((screenshot) => ({ ...screenshot, status }));
1951
2420
  }
1952
- async function executeEditedCode(page, source, testCaseId, capturedScreenshots, addLog, projectSecrets) {
2421
+ async function executeEditedCode(page, source, testCaseId, capturedScreenshots, addLog, blockedKeywords, projectSecrets) {
1953
2422
  const lines = source.split(/\r?\n/);
1954
2423
  let executed = 0;
1955
2424
  for (const rawLine of lines) {
@@ -1987,7 +2456,7 @@ async function executeEditedCode(page, source, testCaseId, capturedScreenshots,
1987
2456
  const clickMatch = line.match(/^await (page\..+)\.click\(\)$/);
1988
2457
  if (clickMatch) {
1989
2458
  const target = parseEditedLocator(page, clickMatch[1]);
1990
- await ensureSafeClick(target.locator, target.label);
2459
+ await ensureSafeClick(target.locator, target.label, blockedKeywords);
1991
2460
  addLog("info", `\u2192 Clicking ${target.label}`);
1992
2461
  await target.locator.click();
1993
2462
  continue;
@@ -2150,24 +2619,60 @@ async function captureRequestedScreenshot(page, source, testCaseId) {
2150
2619
  status: "passed"
2151
2620
  };
2152
2621
  }
2153
- var STRING_LITERAL = '"(?:\\\\.|[^"\\\\])*"';
2622
+ var STRING_LITERAL = `(?:"(?:\\\\.|[^"\\\\])*"|'(?:\\\\.|[^'\\\\])*')`;
2154
2623
  function parseStringLiteral(value) {
2155
- const parsed = JSON.parse(value);
2624
+ const quote = value[0];
2625
+ if (quote !== '"' && quote !== "'")
2626
+ throw new Error("Edited Playwright arguments must be quoted strings");
2627
+ const asJson = quote === '"' ? value : `"${value.slice(1, -1).replace(/\\'/g, "'").replace(/"/g, '\\"')}"`;
2628
+ let parsed;
2629
+ try {
2630
+ parsed = JSON.parse(asJson);
2631
+ } catch {
2632
+ throw new Error("Edited Playwright arguments must be quoted strings");
2633
+ }
2156
2634
  if (typeof parsed !== "string")
2157
2635
  throw new Error("Edited Playwright arguments must be strings");
2158
2636
  return parsed;
2159
2637
  }
2638
+ var INDEX_SUFFIX = /\.(first|last|nth)\((\d{0,4})\)$/;
2639
+ function applyIndexSuffix(expression) {
2640
+ const match = expression.match(INDEX_SUFFIX);
2641
+ if (!match)
2642
+ return { base: expression };
2643
+ const base = expression.slice(0, match.index);
2644
+ if (match[1] === "first")
2645
+ return { base, pick: (target) => target.first() };
2646
+ if (match[1] === "last")
2647
+ return { base, pick: (target) => target.last() };
2648
+ if (!match[2])
2649
+ return { base: expression };
2650
+ const index = Number(match[2]);
2651
+ return { base, pick: (target) => target.nth(index) };
2652
+ }
2160
2653
  function parseEditedLocator(page, expression) {
2654
+ debugLocator("EditedSource", { expression });
2655
+ const { base, pick } = applyIndexSuffix(expression);
2656
+ const resolved = resolveLocatorExpression(page, base);
2657
+ return pick ? { locator: pick(resolved.locator), label: resolved.label } : resolved;
2658
+ }
2659
+ function resolveLocatorExpression(page, expression) {
2161
2660
  const roleMatch = expression.match(new RegExp(`^page\\.getByRole\\((${STRING_LITERAL}),\\s*\\{\\s*name:\\s*(${STRING_LITERAL})\\s*\\}\\)$`));
2162
2661
  if (roleMatch) {
2163
2662
  const role = parseStringLiteral(roleMatch[1]);
2164
2663
  const name = parseStringLiteral(roleMatch[2]);
2165
2664
  return { locator: page.getByRole(role, { name }), label: name };
2166
2665
  }
2666
+ const roleOnlyMatch = expression.match(new RegExp(`^page\\.getByRole\\((${STRING_LITERAL})\\)$`));
2667
+ if (roleOnlyMatch) {
2668
+ const role = parseStringLiteral(roleOnlyMatch[1]);
2669
+ return { locator: page.getByRole(role), label: role };
2670
+ }
2167
2671
  for (const [method, create] of [
2168
2672
  ["getByLabel", (value) => page.getByLabel(value)],
2169
2673
  ["getByPlaceholder", (value) => page.getByPlaceholder(value)],
2170
2674
  ["getByText", (value) => page.getByText(value)],
2675
+ ["getByTestId", (value) => page.getByTestId(value)],
2171
2676
  ["locator", (value) => page.locator(value)]
2172
2677
  ]) {
2173
2678
  const match = expression.match(new RegExp(`^page\\.${method}\\((${STRING_LITERAL})\\)$`));
@@ -2176,9 +2681,10 @@ function parseEditedLocator(page, expression) {
2176
2681
  return { locator: create(value), label: value };
2177
2682
  }
2178
2683
  }
2179
- throw new Error(`Unsupported Playwright locator: ${expression.slice(0, 120)}`);
2684
+ throw new Error(`Unsupported locator: ${expression.slice(0, 120)}
2685
+ Expected page.getByRole("button", { name: "Login" }), page.getByLabel/getByPlaceholder/getByText/getByTestId("\u2026") or page.locator("css"), optionally followed by .first(), .last() or .nth(n).`);
2180
2686
  }
2181
- async function executeStep(page, step, addLog, secrets) {
2687
+ async function executeStep(page, step, addLog, blockedKeywords, secrets) {
2182
2688
  switch (step.type) {
2183
2689
  case "navigate":
2184
2690
  const checked = checkTargetUrl(step.url, config.urlPolicy);
@@ -2193,7 +2699,7 @@ async function executeStep(page, step, addLog, secrets) {
2193
2699
  case "click": {
2194
2700
  const name = step.target.name ?? step.target.text ?? step.target.cssSelector ?? "target";
2195
2701
  const target = locator(page, step.target);
2196
- await ensureSafeClick(target, name);
2702
+ await ensureSafeClick(target, name, blockedKeywords);
2197
2703
  addLog("info", "Control found: " + name);
2198
2704
  addLog("info", "\u2192 Clicking " + name);
2199
2705
  await target.click();
@@ -2250,6 +2756,12 @@ function resolveSecret(value, projectSecrets) {
2250
2756
  return secret ?? value;
2251
2757
  }
2252
2758
  function locator(page, target) {
2759
+ debugLocator("Resolver", {
2760
+ strategy: target.role && target.name ? "role" : target.label ? "label" : target.placeholder ? "placeholder" : target.text ? "text" : "css",
2761
+ role: target.role,
2762
+ name: target.name,
2763
+ cssSelector: target.cssSelector
2764
+ });
2253
2765
  if (target.role && target.name)
2254
2766
  return page.getByRole(target.role, { name: target.name });
2255
2767
  if (target.label)
@@ -2260,7 +2772,15 @@ function locator(page, target) {
2260
2772
  return page.getByText(target.text);
2261
2773
  return page.locator(target.cssSelector ?? "");
2262
2774
  }
2263
- async function ensureSafeClick(target, fallbackLabel) {
2775
+ function debugLocator(stage, detail) {
2776
+ if (!process.env.LAZYSCOUT_DEBUG_LOCATOR)
2777
+ return;
2778
+ const safe = Object.fromEntries(Object.entries(detail).filter(([, value]) => value !== void 0).map(([key, value]) => [key, typeof value === "string" ? redactSensitiveText(value) : value]));
2779
+ console.log(`[LazyScout:${stage}]`, safe);
2780
+ }
2781
+ async function ensureSafeClick(target, fallbackLabel, blockedKeywords) {
2782
+ if (blockedKeywords.length === 0)
2783
+ return;
2264
2784
  const labels = await Promise.all([
2265
2785
  target.getAttribute("aria-label").catch(() => null),
2266
2786
  target.getAttribute("title").catch(() => null),
@@ -2268,8 +2788,8 @@ async function ensureSafeClick(target, fallbackLabel) {
2268
2788
  target.getAttribute("id").catch(() => null),
2269
2789
  target.innerText().catch(() => "")
2270
2790
  ]);
2271
- if (isDestructiveLabel(fallbackLabel, ...labels.map((value) => value ?? void 0))) {
2272
- throw new Error(`Blocked destructive action: ${fallbackLabel}`);
2791
+ if (isBlockedLabel(blockedKeywords, fallbackLabel, ...labels.map((value) => value ?? void 0))) {
2792
+ throw new Error(`Blocked by the Project click filter: ${fallbackLabel}`);
2273
2793
  }
2274
2794
  }
2275
2795
 
@@ -2597,6 +3117,16 @@ function registerWorkspaceRoutes(app, root) {
2597
3117
  await deleteProject(root, request.params.projectId);
2598
3118
  return reply.send({ deleted: true });
2599
3119
  });
3120
+ app.post("/api/workspace/projects/:projectId/auth-session", async (request, reply) => {
3121
+ const body = request.body;
3122
+ if (!body?.url)
3123
+ return reply.status(400).send({ error: { code: "invalid-url", message: "A login URL is required." } });
3124
+ const profile = await browserProfileDirectory(root, request.params.projectId);
3125
+ const launched = await launchBrowser({ userDataDir: profile, headless: false });
3126
+ const page = launched.context.pages()[0] ?? await launched.context.newPage();
3127
+ await page.goto(body.url, { waitUntil: "domcontentloaded" });
3128
+ return reply.send({ opened: true });
3129
+ });
2600
3130
  app.get("/api/workspace/projects/:projectId/screenshots", async (request) => readScreenshots(root, request.params.projectId));
2601
3131
  app.post("/api/workspace/projects/:projectId/screenshots", async (request) => saveScreenshot(root, request.params.projectId, request.body));
2602
3132
  app.get("/api/workspace/projects/:projectId/screenshots/:name", async (request, reply) => {
@@ -2634,6 +3164,127 @@ function registerWorkspaceRoutes(app, root) {
2634
3164
  });
2635
3165
  }
2636
3166
 
3167
+ // ../server/dist/recorderSessions.js
3168
+ function idleRecorderState(projectId) {
3169
+ return { projectId, status: "idle", startUrl: "", startedAt: "", steps: [] };
3170
+ }
3171
+ var RecorderSessions = class {
3172
+ launch;
3173
+ sessions = /* @__PURE__ */ new Map();
3174
+ constructor(launch) {
3175
+ this.launch = launch;
3176
+ }
3177
+ isRunning(projectId) {
3178
+ const session = this.sessions.get(projectId);
3179
+ return Boolean(session && !session.closed);
3180
+ }
3181
+ state(projectId) {
3182
+ const session = this.sessions.get(projectId);
3183
+ if (!session)
3184
+ return idleRecorderState(projectId);
3185
+ return {
3186
+ projectId: session.projectId,
3187
+ status: session.closed ? "stopped" : "recording",
3188
+ startUrl: session.startUrl,
3189
+ startedAt: session.startedAt,
3190
+ browserLabel: session.browserLabel,
3191
+ steps: session.finalSteps ?? session.handle.steps()
3192
+ };
3193
+ }
3194
+ async start(projectId, startUrl) {
3195
+ const launched = await this.launch(projectId);
3196
+ const handle = await attachRecorder(launched.context, startUrl, {
3197
+ onEnded: () => {
3198
+ const current = this.sessions.get(projectId);
3199
+ if (current)
3200
+ void this.finish(current);
3201
+ }
3202
+ });
3203
+ const session = {
3204
+ projectId,
3205
+ startUrl,
3206
+ startedAt: (/* @__PURE__ */ new Date()).toISOString(),
3207
+ browserLabel: launched.label,
3208
+ handle,
3209
+ close: launched.close,
3210
+ closed: false
3211
+ };
3212
+ this.sessions.set(projectId, session);
3213
+ const page = launched.context.pages()[0] ?? await launched.context.newPage();
3214
+ await page.goto(startUrl, { waitUntil: "domcontentloaded" });
3215
+ return this.state(projectId);
3216
+ }
3217
+ async stop(projectId) {
3218
+ const session = this.sessions.get(projectId);
3219
+ if (!session)
3220
+ return idleRecorderState(projectId);
3221
+ await this.finish(session);
3222
+ return this.state(projectId);
3223
+ }
3224
+ /**
3225
+ * Forgets a session once the operator has saved or discarded it, so reopening
3226
+ * the panel starts a fresh recording instead of the previous one.
3227
+ */
3228
+ async discard(projectId) {
3229
+ const session = this.sessions.get(projectId);
3230
+ this.sessions.delete(projectId);
3231
+ if (session)
3232
+ await this.finish(session);
3233
+ return idleRecorderState(projectId);
3234
+ }
3235
+ async closeAll() {
3236
+ await Promise.all([...this.sessions.values()].map((session) => this.finish(session)));
3237
+ this.sessions.clear();
3238
+ }
3239
+ async finish(session) {
3240
+ if (session.closed)
3241
+ return;
3242
+ session.finalSteps = session.handle.finalize();
3243
+ session.closed = true;
3244
+ await session.close().catch(() => void 0);
3245
+ }
3246
+ };
3247
+
3248
+ // ../server/dist/routes/recorder.js
3249
+ function registerRecorderRoutes(app, workspaceRoot, options = {}) {
3250
+ const launch = options.launch ?? (async (projectId) => launchBrowser({ userDataDir: await browserProfileDirectory(workspaceRoot, projectId), headless: false }));
3251
+ const sessions = new RecorderSessions(launch);
3252
+ app.post("/api/recorder/:projectId/start", async (request, reply) => {
3253
+ const { projectId } = request.params;
3254
+ const body = request.body;
3255
+ if (!body?.url)
3256
+ return reply.status(400).send({ error: { code: "invalid-url", message: "A start URL is required." } });
3257
+ const check = checkTargetUrl(body.url, config.urlPolicy);
3258
+ if (!check.ok)
3259
+ return reply.status(400).send({ error: { code: check.code, message: check.message } });
3260
+ if (sessions.isRunning(projectId))
3261
+ return reply.status(409).send({
3262
+ error: {
3263
+ code: "recorder-busy",
3264
+ message: "A recording is already running for this Project.",
3265
+ hint: "Stop the current recording before starting another one."
3266
+ }
3267
+ });
3268
+ try {
3269
+ return reply.send(await sessions.start(projectId, check.url.toString()));
3270
+ } catch (error) {
3271
+ return reply.status(500).send({
3272
+ error: {
3273
+ code: "browser-error",
3274
+ message: error instanceof Error ? error.message : "The browser could not be started.",
3275
+ hint: "Close any other LazyScout browser for this Project and try again."
3276
+ }
3277
+ });
3278
+ }
3279
+ });
3280
+ app.get("/api/recorder/:projectId", async (request) => sessions.state(request.params.projectId));
3281
+ app.post("/api/recorder/:projectId/stop", async (request, reply) => reply.send(await sessions.stop(request.params.projectId)));
3282
+ app.delete("/api/recorder/:projectId", async (request, reply) => reply.send(await sessions.discard(request.params.projectId)));
3283
+ app.addHook("onClose", async () => {
3284
+ await sessions.closeAll();
3285
+ });
3286
+ }
3287
+
2637
3288
  // ../server/dist/app.js
2638
3289
  function buildApp(options = {}) {
2639
3290
  const app = Fastify({
@@ -2651,6 +3302,7 @@ function buildApp(options = {}) {
2651
3302
  registerLoadTestRoute(app);
2652
3303
  registerVersionRoutes(app, appVersion);
2653
3304
  registerWorkspaceRoutes(app, workspaceRoot);
3305
+ registerRecorderRoutes(app, workspaceRoot);
2654
3306
  if (options.staticDir) {
2655
3307
  app.register(fastifyStatic, { root: options.staticDir });
2656
3308
  app.setNotFoundHandler(async (request, reply) => {
@@ -2678,7 +3330,7 @@ async function openInBrowser(url) {
2678
3330
  }
2679
3331
 
2680
3332
  // src/version.ts
2681
- var VERSION = true ? "0.3.1" : "0.0.0-dev";
3333
+ var VERSION = true ? "0.3.3" : "0.0.0-dev";
2682
3334
 
2683
3335
  // src/commands/serve.ts
2684
3336
  var DEFAULT_PORT = 4321;
@@ -2751,7 +3403,8 @@ npx lazyscout scan https://example.com --max-pages 10 --csv report.csv
2751
3403
 
2752
3404
  Explorer Behavior
2753
3405
  LazyScout only explores URLs within the same origin.
2754
- It currently follows links only and does not click buttons or submit forms.
3406
+ It follows links and tries a small, safe set of UI controls such as tabs and dialogs.
3407
+ It never submits forms or fills credentials automatically.
2755
3408
  `;
2756
3409
  async function main() {
2757
3410
  const { values, positionals } = parseArgs({