lazyscout 0.3.2 → 0.3.4

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
@@ -243,6 +243,40 @@ function redactUrl(value) {
243
243
  }
244
244
  }
245
245
 
246
+ // ../../packages/core/dist/safety/blocklist.js
247
+ var SESSION_ENDING_KEYWORDS = [
248
+ "log out",
249
+ "logout",
250
+ "log out",
251
+ "sign out",
252
+ "signout",
253
+ "sign out",
254
+ "\u0E2D\u0E2D\u0E01\u0E08\u0E32\u0E01\u0E23\u0E30\u0E1A\u0E1A",
255
+ "\u0E2D\u0E2D\u0E01\u0E08\u0E32\u0E01\u0E23\u0E30\u0E1A\u0E1A"
256
+ ];
257
+ function isSessionEndingLabel(...labels) {
258
+ const haystack = labels.filter(Boolean).join(" ").toLowerCase();
259
+ if (!haystack.trim())
260
+ return false;
261
+ return SESSION_ENDING_KEYWORDS.some((keyword) => haystack.includes(keyword.toLowerCase()));
262
+ }
263
+ var MAX_BLOCK_KEYWORDS = 100;
264
+ var MAX_KEYWORD_LENGTH = 80;
265
+ function normalizeBlockedKeywords(value) {
266
+ if (!Array.isArray(value))
267
+ return [];
268
+ const cleaned = value.filter((keyword) => typeof keyword === "string").map((keyword) => keyword.trim().toLowerCase().slice(0, MAX_KEYWORD_LENGTH)).filter(Boolean);
269
+ return [...new Set(cleaned)].slice(0, MAX_BLOCK_KEYWORDS);
270
+ }
271
+ function isBlockedLabel(keywords, ...labels) {
272
+ if (keywords.length === 0)
273
+ return false;
274
+ const haystack = labels.filter(Boolean).join(" ").toLowerCase();
275
+ if (!haystack.trim())
276
+ return false;
277
+ return keywords.some((keyword) => keyword && haystack.includes(keyword.toLowerCase()));
278
+ }
279
+
246
280
  // ../../packages/core/dist/testcase/describeStep.js
247
281
  function describeTarget(target) {
248
282
  const name = target.name || target.label || target.text || target.placeholder;
@@ -489,90 +523,37 @@ function collectPageData() {
489
523
  }
490
524
 
491
525
  // ../../packages/explorer/dist/safety.js
492
- var DESTRUCTIVE_KEYWORDS = [
493
- "delete",
494
- "remove",
495
- "destroy",
496
- "erase",
497
- "drop",
498
- "reset",
499
- "purchase",
500
- "buy",
501
- "checkout",
502
- "pay",
503
- "payment",
504
- "transfer",
505
- "withdraw",
506
- "refund",
507
- "send",
508
- "submit order",
509
- "place order",
510
- "confirm payment",
511
- "confirm order",
512
- "logout",
513
- "log out",
514
- "sign out",
515
- "signout",
516
- "deactivate",
517
- "disable account",
518
- "delete account",
519
- "close account",
520
- "unsubscribe",
521
- "cancel subscription",
522
- "archive",
523
- "publish",
524
- "approve",
525
- "reject",
526
- "\u0E25\u0E1A",
527
- "\u0E22\u0E01\u0E40\u0E25\u0E34\u0E01",
528
- "\u0E0A\u0E33\u0E23\u0E30\u0E40\u0E07\u0E34\u0E19",
529
- "\u0E08\u0E48\u0E32\u0E22",
530
- "\u0E42\u0E2D\u0E19",
531
- "\u0E0B\u0E37\u0E49\u0E2D",
532
- "\u0E2A\u0E31\u0E48\u0E07\u0E0B\u0E37\u0E49\u0E2D",
533
- "\u0E22\u0E37\u0E19\u0E22\u0E31\u0E19\u0E01\u0E32\u0E23\u0E0A\u0E33\u0E23\u0E30",
534
- "\u0E2D\u0E2D\u0E01\u0E08\u0E32\u0E01\u0E23\u0E30\u0E1A\u0E1A",
535
- "\u0E2A\u0E48\u0E07\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25",
536
- "\u0E1A\u0E31\u0E19\u0E17\u0E36\u0E01"
537
- ];
538
- function isDestructiveLabel(...labels) {
539
- const haystack = labels.filter(Boolean).join(" ").toLowerCase();
540
- if (!haystack.trim())
541
- return false;
542
- return DESTRUCTIVE_KEYWORDS.some((keyword) => haystack.includes(keyword));
543
- }
544
- function canFollowLink(href, accessibleName) {
526
+ function canFollowLink(href, accessibleName, keywords = []) {
545
527
  if (!href)
546
528
  return false;
547
- if (isDestructiveLabel(accessibleName, href))
548
- return false;
549
- return true;
529
+ return !isBlockedLabel(keywords, accessibleName, href);
550
530
  }
551
531
 
552
532
  // ../../packages/explorer/dist/mapToPageModel.js
553
- function toUIElement(raw) {
533
+ function toUIElement(raw, keywords) {
554
534
  return {
555
535
  ...raw,
556
- destructive: isDestructiveLabel(raw.accessibleName, raw.text, raw.name, raw.id)
536
+ destructive: isBlockedLabel(keywords, raw.accessibleName, raw.text, raw.name, raw.id)
557
537
  };
558
538
  }
559
- function toFormInfo(raw) {
539
+ function toFormInfo(raw, keywords) {
560
540
  return {
561
541
  id: raw.id,
562
542
  name: raw.name,
563
543
  action: raw.action,
564
544
  method: raw.method,
565
545
  accessibleName: raw.accessibleName,
566
- fields: raw.fields.map(toUIElement),
567
- submitButtons: raw.submitButtons.map(toUIElement)
546
+ fields: raw.fields.map((field) => toUIElement(field, keywords)),
547
+ submitButtons: raw.submitButtons.map((button) => toUIElement(button, keywords))
568
548
  };
569
549
  }
570
- function mapToPageModel(raw, meta) {
571
- const links = raw.links.map(toUIElement);
572
- const buttons = raw.buttons.map(toUIElement);
573
- const inputs = raw.inputs.map(toUIElement);
574
- const textareas = raw.textareas.map(toUIElement);
575
- const selects = raw.selects.map(toUIElement);
550
+ function mapToPageModel(raw, meta, blockedKeywords = []) {
551
+ const toElement = (element) => toUIElement(element, blockedKeywords);
552
+ const links = raw.links.map(toElement);
553
+ const buttons = raw.buttons.map(toElement);
554
+ const inputs = raw.inputs.map(toElement);
555
+ const textareas = raw.textareas.map(toElement);
556
+ const selects = raw.selects.map(toElement);
576
557
  const controls = [...links, ...buttons, ...inputs, ...textareas, ...selects];
577
558
  const state = createPageState(raw, meta.finalUrl, controls);
578
559
  return {
@@ -587,7 +568,7 @@ function mapToPageModel(raw, meta) {
587
568
  inputs,
588
569
  textareas,
589
570
  selects,
590
- forms: raw.forms.map(toFormInfo),
571
+ forms: raw.forms.map((form) => toFormInfo(form, blockedKeywords)),
591
572
  apiRequests: meta.apiRequests ?? [],
592
573
  state
593
574
  };
@@ -698,7 +679,7 @@ async function launchBrowser(options = {}) {
698
679
  void error;
699
680
  }
700
681
  }
701
- throw new ExplorerError("browser-error", `unable to launch a browser (tried: ${failures.join(", ")})`, 'Please install Google Chrome or Microsoft Edge or run "npx playwright install chromium" and try again');
682
+ 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');
702
683
  }
703
684
 
704
685
  // ../../packages/explorer/dist/exploreWebsite.js
@@ -712,7 +693,9 @@ var DEFAULT_EXPLORE_OPTIONS = {
712
693
  maxActionsPerState: 8,
713
694
  maxTotalStates: 80,
714
695
  actionTimeoutMs: 2e3,
715
- stateDiscoveryTimeoutMs: 350
696
+ stateDiscoveryTimeoutMs: 350,
697
+ blockedKeywords: [],
698
+ maxNavigationProbesPerPage: 6
716
699
  };
717
700
  async function exploreWebsite(startUrl, options = {}, policy = LOCAL_QA_POLICY) {
718
701
  const config2 = { ...DEFAULT_EXPLORE_OPTIONS, ...options };
@@ -736,19 +719,19 @@ async function exploreWebsite(startUrl, options = {}, policy = LOCAL_QA_POLICY)
736
719
  };
737
720
  let urlsSkipped = 0;
738
721
  let limitReached = "none";
739
- const launched = await launchBrowser();
722
+ const launched = await launchBrowser(config2.browserProfileDir ? { userDataDir: config2.browserProfileDir } : {});
740
723
  const { context, label: browserLabel } = launched;
741
724
  try {
742
725
  context.setDefaultTimeout(config2.pageTimeoutMs);
743
726
  const page = await context.newPage();
744
727
  while (queue.length > 0) {
745
728
  if (pages.length >= config2.maxPages) {
746
- limitReached = "max-pages";
729
+ limitReached = "max-pages-reached";
747
730
  urlsSkipped += queue.length;
748
731
  break;
749
732
  }
750
733
  if (Date.now() - startedAt > config2.totalTimeoutMs) {
751
- limitReached = "total-timeout";
734
+ limitReached = "timeout-reached";
752
735
  urlsSkipped += queue.length;
753
736
  break;
754
737
  }
@@ -756,7 +739,7 @@ async function exploreWebsite(startUrl, options = {}, policy = LOCAL_QA_POLICY)
756
739
  if (visited.has(item.url))
757
740
  continue;
758
741
  visited.add(item.url);
759
- const result = await visitPage(page, item, config2);
742
+ const result = await visitPage(page, item, config2, config2.blockedKeywords);
760
743
  if (result.kind === "issue") {
761
744
  issues.push(result.issue);
762
745
  continue;
@@ -772,26 +755,32 @@ async function exploreWebsite(startUrl, options = {}, policy = LOCAL_QA_POLICY)
772
755
  await discoverSafeStates(page, result.page, config2, origin, actionGraph);
773
756
  if (item.depth >= config2.maxDepth) {
774
757
  if (result.page.links.length > 0)
775
- limitReached = limitReached === "none" ? "max-depth" : limitReached;
758
+ limitReached = limitReached === "none" ? "max-depth-reached" : limitReached;
776
759
  continue;
777
760
  }
778
- for (const link of result.page.links) {
779
- if (!canFollowLink(link.href, link.accessibleName))
780
- continue;
781
- if (!isSameOrigin(link.href, origin) || !isCrawlableUrl(link.href)) {
761
+ const enqueue = (href) => {
762
+ if (!href)
763
+ return;
764
+ if (!isSameOrigin(href, origin) || !isCrawlableUrl(href)) {
782
765
  urlsSkipped++;
783
- continue;
766
+ return;
784
767
  }
785
- const next = normalizeUrl(link.href);
768
+ const next = normalizeUrl(href);
786
769
  if (visited.has(next) || queue.some((queued) => queued.url === next))
787
- continue;
770
+ return;
788
771
  queue.push({ url: next, depth: item.depth + 1 });
772
+ };
773
+ for (const link of result.page.links) {
774
+ if (!canFollowLink(link.href, link.accessibleName, config2.blockedKeywords))
775
+ continue;
776
+ enqueue(link.href);
789
777
  }
778
+ await probeNavigationControls(page, result.page, config2, origin, actionGraph, enqueue, () => Date.now() - startedAt > config2.totalTimeoutMs);
790
779
  }
791
780
  } finally {
792
781
  await launched.close().catch(() => void 0);
793
782
  }
794
- addNavigationEdges(pages, actionGraph);
783
+ addNavigationEdges(pages, actionGraph, config2.blockedKeywords);
795
784
  return {
796
785
  startUrl: entryUrl,
797
786
  origin,
@@ -807,7 +796,7 @@ async function exploreWebsite(startUrl, options = {}, policy = LOCAL_QA_POLICY)
807
796
  actionGraph
808
797
  };
809
798
  }
810
- function addNavigationEdges(pages, graph) {
799
+ function addNavigationEdges(pages, graph, keywords) {
811
800
  for (const page of pages) {
812
801
  const source = page.state;
813
802
  if (!source)
@@ -815,7 +804,7 @@ function addNavigationEdges(pages, graph) {
815
804
  for (const link of page.links) {
816
805
  if (!link.href || !link.accessibleName)
817
806
  continue;
818
- const safe = canFollowLink(link.href, link.accessibleName);
807
+ const safe = canFollowLink(link.href, link.accessibleName, keywords);
819
808
  const target = pages.find((candidate) => candidate.finalUrl === link.href || candidate.url === link.href)?.state;
820
809
  const action = {
821
810
  id: `${source.id}|navigate|${link.cssSelector}`,
@@ -825,7 +814,7 @@ function addNavigationEdges(pages, graph) {
825
814
  selector: link.cssSelector,
826
815
  locator: { role: link.role, name: link.accessibleName },
827
816
  safe,
828
- reason: safe ? void 0 : "Unsafe link was discovered but not opened"
817
+ reason: safe ? void 0 : "Link matched the Project click filter and was not opened"
829
818
  };
830
819
  addEdge(graph, source.id, target?.id, action, safe && target ? "visited" : safe ? "discovered" : "blocked");
831
820
  if (!safe)
@@ -849,7 +838,7 @@ async function discoverSafeStates(page, source, config2, origin, graph) {
849
838
  for (const interaction of interactions) {
850
839
  if (statesForPage >= config2.maxStatesPerPage || graph.states.length >= config2.maxTotalStates)
851
840
  break;
852
- const action = actionFromInteraction(initial.id, interaction);
841
+ const action = actionFromInteraction(initial.id, interaction, config2.blockedKeywords);
853
842
  const actionKey = action.id;
854
843
  if (graph.visitedActionKeys.includes(actionKey) || graph.failedActionKeys.includes(actionKey))
855
844
  continue;
@@ -872,7 +861,7 @@ async function discoverSafeStates(page, source, config2, origin, graph) {
872
861
  finalUrl: page.url(),
873
862
  depth: source.depth,
874
863
  statusCode: source.statusCode
875
- }).state;
864
+ }, config2.blockedKeywords).state;
876
865
  if (!observed)
877
866
  continue;
878
867
  addState(graph, observed);
@@ -889,9 +878,59 @@ async function discoverSafeStates(page, source, config2, origin, graph) {
889
878
  }
890
879
  }
891
880
  }
892
- function actionFromInteraction(stateId2, interaction) {
881
+ async function probeNavigationControls(page, source, config2, origin, graph, enqueue, outOfTime) {
882
+ if (config2.maxNavigationProbesPerPage <= 0)
883
+ return;
884
+ const sourceUrl = source.finalUrl;
885
+ const sourceKey = normalizeUrl(sourceUrl);
886
+ const stateId2 = source.state?.id;
887
+ const candidates = source.buttons.filter((button) => button.accessibleName && !button.destructive && !button.disabled).slice(0, config2.maxNavigationProbesPerPage);
888
+ for (const candidate of candidates) {
889
+ if (outOfTime())
890
+ break;
891
+ const action = {
892
+ id: `${stateId2 ?? sourceKey}|navigate|${candidate.cssSelector}`,
893
+ type: "navigate",
894
+ description: `Navigate by clicking \u201C${candidate.accessibleName}\u201D`,
895
+ target: candidate.accessibleName,
896
+ selector: candidate.cssSelector,
897
+ locator: { role: candidate.role, name: candidate.accessibleName },
898
+ safe: true
899
+ };
900
+ if (graph.visitedActionKeys.includes(action.id) || graph.failedActionKeys.includes(action.id))
901
+ continue;
902
+ try {
903
+ if (normalizeUrl(page.url()) !== sourceKey) {
904
+ await page.goto(sourceUrl, { waitUntil: "domcontentloaded", timeout: config2.pageTimeoutMs });
905
+ }
906
+ await page.locator(candidate.cssSelector).click({ timeout: config2.actionTimeoutMs });
907
+ await page.waitForTimeout(config2.stateDiscoveryTimeoutMs);
908
+ const reached = page.url();
909
+ if (normalizeUrl(reached) === sourceKey)
910
+ continue;
911
+ if (!isSameOrigin(reached, origin)) {
912
+ if (stateId2)
913
+ addEdge(graph, stateId2, void 0, { ...action, safe: false, reason: "Action left the approved origin" }, "blocked");
914
+ graph.blockedActionKeys.push(action.id);
915
+ continue;
916
+ }
917
+ enqueue(reached);
918
+ if (stateId2)
919
+ addEdge(graph, stateId2, void 0, action, "discovered");
920
+ graph.visitedActionKeys.push(action.id);
921
+ } catch {
922
+ if (stateId2)
923
+ addEdge(graph, stateId2, void 0, action, "failed");
924
+ graph.failedActionKeys.push(action.id);
925
+ }
926
+ }
927
+ if (normalizeUrl(page.url()) !== sourceKey) {
928
+ await page.goto(sourceUrl, { waitUntil: "domcontentloaded", timeout: config2.pageTimeoutMs }).catch(() => void 0);
929
+ }
930
+ }
931
+ function actionFromInteraction(stateId2, interaction, keywords) {
893
932
  const type = interaction.kind === "tab" ? "selectTab" : interaction.kind === "accordion" ? "expandAccordion" : interaction.kind === "dropdown" ? "openDropdown" : interaction.expanded ? "closeDialog" : "openModal";
894
- const destructive = isDestructiveLabel(interaction.name);
933
+ const blocked = isBlockedLabel(keywords, interaction.name);
895
934
  const description = `${type === "selectTab" ? "Select" : type === "expandAccordion" ? "Expand" : "Open"} \u201C${interaction.name}\u201D`;
896
935
  return {
897
936
  id: `${stateId2}|${type}|${interaction.cssSelector}`,
@@ -900,8 +939,8 @@ function actionFromInteraction(stateId2, interaction) {
900
939
  target: interaction.name,
901
940
  selector: interaction.cssSelector,
902
941
  locator: { role: interaction.role, name: interaction.name },
903
- safe: !destructive,
904
- reason: destructive ? "Destructive action was discovered but not executed" : void 0
942
+ safe: !blocked,
943
+ reason: blocked ? "Action matched the Project click filter and was not executed" : void 0
905
944
  };
906
945
  }
907
946
  function addEdge(graph, fromStateId, toStateId, action, status) {
@@ -910,7 +949,7 @@ function addEdge(graph, fromStateId, toStateId, action, status) {
910
949
  return;
911
950
  graph.edges.push({ id, fromStateId, toStateId, action, status });
912
951
  }
913
- async function visitPage(page, item, config2) {
952
+ async function visitPage(page, item, config2, keywords) {
914
953
  try {
915
954
  const apiRequests = [];
916
955
  const requestStarted = /* @__PURE__ */ new Map();
@@ -971,13 +1010,817 @@ async function visitPage(page, item, config2) {
971
1010
  depth: item.depth,
972
1011
  statusCode: status,
973
1012
  apiRequests
974
- })
1013
+ }, keywords)
975
1014
  };
976
1015
  } catch (error) {
977
1016
  return { kind: "issue", issue: toExploreIssue(item.url, error) };
978
1017
  }
979
1018
  }
980
1019
 
1020
+ // ../../packages/explorer/dist/scopedExplorer.js
1021
+ var DEFAULT_LIMITS = {
1022
+ maxPages: 20,
1023
+ maxStates: 80,
1024
+ maxDepth: 3,
1025
+ maxActionsPerState: 8,
1026
+ maxTotalActions: 200,
1027
+ maxActionRetries: 2,
1028
+ explorationTimeoutMs: 3e5
1029
+ };
1030
+ var DEFAULT_CONFIG = {
1031
+ mode: "site",
1032
+ debug: false,
1033
+ limits: DEFAULT_LIMITS,
1034
+ continueAfterLogin: true
1035
+ };
1036
+ async function exploreWithScope(startUrl, explorationConfig = {}, exploreOptions = {}) {
1037
+ const config2 = {
1038
+ ...DEFAULT_CONFIG,
1039
+ ...explorationConfig,
1040
+ limits: { ...DEFAULT_LIMITS, ...explorationConfig.limits }
1041
+ };
1042
+ const legacyOptions = {
1043
+ maxPages: config2.limits.maxPages,
1044
+ maxDepth: config2.limits.maxDepth,
1045
+ maxStatesPerPage: config2.limits.maxActionsPerState,
1046
+ maxActionsPerState: config2.limits.maxActionsPerState,
1047
+ maxTotalStates: config2.limits.maxStates,
1048
+ actionTimeoutMs: 3e3,
1049
+ stateDiscoveryTimeoutMs: 500,
1050
+ pageTimeoutMs: 25e3,
1051
+ totalTimeoutMs: config2.limits.explorationTimeoutMs,
1052
+ waitAfterNavigationMs: 750,
1053
+ blockedKeywords: [],
1054
+ maxNavigationProbesPerPage: 8,
1055
+ ...exploreOptions
1056
+ };
1057
+ const startedAt = Date.now();
1058
+ const logs = [];
1059
+ const debug = (message, context2) => {
1060
+ if (config2.debug) {
1061
+ logs.push({ timestamp: (/* @__PURE__ */ new Date()).toISOString(), level: "debug", message, context: context2 });
1062
+ }
1063
+ logs.push({ timestamp: (/* @__PURE__ */ new Date()).toISOString(), level: "info", message, context: context2 });
1064
+ };
1065
+ const check = checkTargetUrl(startUrl, LOCAL_QA_POLICY);
1066
+ if (!check.ok)
1067
+ throw new ExplorerError(check.code, check.message);
1068
+ const origin = check.url.origin;
1069
+ const entryUrl = normalizeUrl(check.url.toString());
1070
+ const pages = [];
1071
+ const issues = [];
1072
+ const visitedStates = /* @__PURE__ */ new Set();
1073
+ const visitedUrls = /* @__PURE__ */ new Set();
1074
+ const stateQueue = [];
1075
+ const actionGraph = {
1076
+ states: [],
1077
+ edges: [],
1078
+ visitedStateIds: [],
1079
+ visitedActionKeys: [],
1080
+ failedActionKeys: [],
1081
+ blockedActionKeys: []
1082
+ };
1083
+ let totalActionsExecuted = 0;
1084
+ let totalActionsBlocked = 0;
1085
+ let totalActionsFailed = 0;
1086
+ let totalActionsRetried = 0;
1087
+ let urlsSkippedByScope = 0;
1088
+ let endReason = "queue-exhausted";
1089
+ function isWithinScope(url) {
1090
+ if (!config2.scopePath)
1091
+ return true;
1092
+ try {
1093
+ const path = new URL(url).pathname;
1094
+ const scope = config2.scopePath.replace(/\/$/, "");
1095
+ return path === scope || path.startsWith(scope + "/");
1096
+ } catch {
1097
+ return false;
1098
+ }
1099
+ }
1100
+ function isSessionEnding(name, text) {
1101
+ return isSessionEndingLabel(name, text);
1102
+ }
1103
+ async function discoverNavigationRegions(page) {
1104
+ const candidates = [];
1105
+ try {
1106
+ const navItems = await page.evaluate(() => {
1107
+ const results = [];
1108
+ const navRegions = document.querySelectorAll('nav a[href], aside a[href], [role="navigation"] a[href], [role="menu"] [role="menuitem"], [role="menubar"] [role="menuitem"]');
1109
+ navRegions.forEach((el) => {
1110
+ const anchor = el;
1111
+ const name = el.getAttribute("aria-label") || el.textContent?.replace(/\s+/g, " ").trim() || "";
1112
+ if (!name || name.length > 80)
1113
+ return;
1114
+ const cssSel = el.id ? `#${CSS.escape(el.id)}` : `${el.tagName.toLowerCase()}[href="${anchor.getAttribute("href") || ""}"]`;
1115
+ results.push({
1116
+ name: name.slice(0, 80),
1117
+ role: el.getAttribute("role") || "link",
1118
+ href: anchor.href || null,
1119
+ cssSelector: cssSel
1120
+ });
1121
+ });
1122
+ return results.slice(0, 40);
1123
+ });
1124
+ for (const item of navItems) {
1125
+ if (!item.href)
1126
+ continue;
1127
+ const action = {
1128
+ id: `nav|${item.cssSelector}`,
1129
+ type: "navigate",
1130
+ description: `Navigate to \u201C${item.name}\u201D via sidebar`,
1131
+ target: item.name,
1132
+ selector: item.cssSelector,
1133
+ locator: { role: item.role, name: item.name },
1134
+ safe: true
1135
+ };
1136
+ if (isSessionEnding(item.name, void 0)) {
1137
+ action.safe = false;
1138
+ action.reason = "session-ending action";
1139
+ }
1140
+ if (isBlockedLabel(legacyOptions.blockedKeywords, item.name, item.href)) {
1141
+ action.safe = false;
1142
+ action.reason = "Action matched the Project click filter";
1143
+ }
1144
+ candidates.push({
1145
+ priority: 2,
1146
+ action,
1147
+ locator: { role: item.role, name: item.name },
1148
+ kind: "sidebar-nav",
1149
+ restoreStrategy: "goto"
1150
+ });
1151
+ }
1152
+ } catch {
1153
+ }
1154
+ return candidates;
1155
+ }
1156
+ async function discoverSafeCandidates(page, currentState) {
1157
+ const candidates = [];
1158
+ for (const link of currentState.controls.filter((c) => c.kind === "link" && c.href)) {
1159
+ if (isSessionEnding(link.accessibleName, link.text)) {
1160
+ candidates.push({
1161
+ priority: 10,
1162
+ action: {
1163
+ id: `${currentState.id}|navigate|${link.cssSelector}`,
1164
+ type: "navigate",
1165
+ description: `Navigate to \u201C${link.accessibleName}\u201D`,
1166
+ target: link.accessibleName,
1167
+ selector: link.cssSelector,
1168
+ locator: { role: link.role, name: link.accessibleName },
1169
+ safe: false,
1170
+ reason: "session-ending action"
1171
+ },
1172
+ locator: { role: link.role, name: link.accessibleName },
1173
+ kind: "navigation-link",
1174
+ restoreStrategy: "goto"
1175
+ });
1176
+ continue;
1177
+ }
1178
+ const blocked = isBlockedLabel(legacyOptions.blockedKeywords, link.accessibleName, link.href, link.text);
1179
+ candidates.push({
1180
+ priority: blocked ? 10 : 1,
1181
+ action: {
1182
+ id: `${currentState.id}|navigate|${link.cssSelector}`,
1183
+ type: "navigate",
1184
+ description: `Navigate to \u201C${link.accessibleName}\u201D`,
1185
+ target: link.accessibleName,
1186
+ selector: link.cssSelector,
1187
+ locator: { role: link.role, name: link.accessibleName },
1188
+ safe: !blocked,
1189
+ reason: blocked ? "Action matched the Project click filter" : void 0
1190
+ },
1191
+ locator: { role: link.role, name: link.accessibleName },
1192
+ kind: "navigation-link",
1193
+ restoreStrategy: "goto"
1194
+ });
1195
+ }
1196
+ try {
1197
+ const navCandidates = await discoverNavigationRegions(page);
1198
+ candidates.push(...navCandidates);
1199
+ } catch {
1200
+ }
1201
+ for (const interaction of currentState.interactions.filter((i) => i.kind === "tab")) {
1202
+ const blocked = isBlockedLabel(legacyOptions.blockedKeywords, interaction.name);
1203
+ candidates.push({
1204
+ priority: blocked ? 10 : 3,
1205
+ action: {
1206
+ id: `${currentState.id}|selectTab|${interaction.cssSelector}`,
1207
+ type: "selectTab",
1208
+ description: `Select tab \u201C${interaction.name}\u201D`,
1209
+ target: interaction.name,
1210
+ selector: interaction.cssSelector,
1211
+ locator: { role: interaction.role, name: interaction.name },
1212
+ safe: !blocked,
1213
+ reason: blocked ? "Action matched the Project click filter" : void 0
1214
+ },
1215
+ locator: { role: interaction.role, name: interaction.name },
1216
+ kind: "tab",
1217
+ restoreStrategy: "select-tab"
1218
+ });
1219
+ }
1220
+ const paginationSelectors = '[aria-label*="page" i], [aria-label*="\u0E2B\u0E19\u0E49\u0E32" i], .pagination a, .pager a, [rel="next"], [rel="prev"]';
1221
+ try {
1222
+ const pagItems = await page.evaluate((sel) => {
1223
+ return Array.from(document.querySelectorAll(sel)).filter((el) => {
1224
+ const htmlEl = el;
1225
+ return htmlEl.offsetParent !== null;
1226
+ }).slice(0, 10).map((el) => ({
1227
+ name: el.getAttribute("aria-label") || el.textContent?.replace(/\s+/g, " ").trim() || "",
1228
+ role: el.getAttribute("role") || "link",
1229
+ href: el.href || null,
1230
+ cssSelector: el.id ? `#${CSS.escape(el.id)}` : el.tagName.toLowerCase()
1231
+ }));
1232
+ }, paginationSelectors);
1233
+ for (const item of pagItems) {
1234
+ if (!item.name)
1235
+ continue;
1236
+ const blocked = isSessionEnding(item.name, void 0);
1237
+ candidates.push({
1238
+ priority: blocked ? 10 : 4,
1239
+ action: {
1240
+ id: `${currentState.id}|pagination|${item.cssSelector}`,
1241
+ type: "pagination",
1242
+ description: `Go to page \u201C${item.name}\u201D`,
1243
+ target: item.name,
1244
+ selector: item.cssSelector,
1245
+ locator: { role: item.role, name: item.name },
1246
+ safe: !blocked,
1247
+ reason: blocked ? "session-ending action" : void 0
1248
+ },
1249
+ locator: { role: item.role, name: item.name },
1250
+ kind: "pagination",
1251
+ restoreStrategy: "goto"
1252
+ });
1253
+ }
1254
+ } catch {
1255
+ }
1256
+ for (const interaction of currentState.interactions.filter((i) => i.kind === "dialog" || i.kind === "drawer" || i.kind === "popover")) {
1257
+ const blocked = isBlockedLabel(legacyOptions.blockedKeywords, interaction.name);
1258
+ candidates.push({
1259
+ priority: blocked ? 10 : 5,
1260
+ action: {
1261
+ id: `${currentState.id}|openModal|${interaction.cssSelector}`,
1262
+ type: "openModal",
1263
+ description: `Open \u201C${interaction.name}\u201D`,
1264
+ target: interaction.name,
1265
+ selector: interaction.cssSelector,
1266
+ locator: { role: interaction.role, name: interaction.name },
1267
+ safe: !blocked,
1268
+ reason: blocked ? "Action matched the Project click filter" : void 0
1269
+ },
1270
+ locator: { role: interaction.role, name: interaction.name },
1271
+ kind: "modal-opener",
1272
+ restoreStrategy: "close-dialog"
1273
+ });
1274
+ }
1275
+ for (const interaction of currentState.interactions.filter((i) => i.kind === "dropdown")) {
1276
+ const blocked = isBlockedLabel(legacyOptions.blockedKeywords, interaction.name);
1277
+ candidates.push({
1278
+ priority: blocked ? 10 : 6,
1279
+ action: {
1280
+ id: `${currentState.id}|openDropdown|${interaction.cssSelector}`,
1281
+ type: "openDropdown",
1282
+ description: `Open dropdown \u201C${interaction.name}\u201D`,
1283
+ target: interaction.name,
1284
+ selector: interaction.cssSelector,
1285
+ locator: { role: interaction.role, name: interaction.name },
1286
+ safe: !blocked,
1287
+ reason: blocked ? "Action matched the Project click filter" : void 0
1288
+ },
1289
+ locator: { role: interaction.role, name: interaction.name },
1290
+ kind: "dropdown",
1291
+ restoreStrategy: "goto"
1292
+ });
1293
+ }
1294
+ for (const interaction of currentState.interactions.filter((i) => i.kind === "accordion")) {
1295
+ const blocked = isBlockedLabel(legacyOptions.blockedKeywords, interaction.name);
1296
+ candidates.push({
1297
+ priority: blocked ? 10 : 7,
1298
+ action: {
1299
+ id: `${currentState.id}|expandAccordion|${interaction.cssSelector}`,
1300
+ type: "expandAccordion",
1301
+ description: `Expand \u201C${interaction.name}\u201D`,
1302
+ target: interaction.name,
1303
+ selector: interaction.cssSelector,
1304
+ locator: { role: interaction.role, name: interaction.name },
1305
+ safe: !blocked,
1306
+ reason: blocked ? "Action matched the Project click filter" : void 0
1307
+ },
1308
+ locator: { role: interaction.role, name: interaction.name },
1309
+ kind: "accordion",
1310
+ restoreStrategy: "goto"
1311
+ });
1312
+ }
1313
+ try {
1314
+ const bcItems = await page.evaluate(() => {
1315
+ return Array.from(document.querySelectorAll('nav[aria-label*="breadcrumb" i] a, .breadcrumb a, [role="navigation"] ol a')).filter((el) => el.offsetParent !== null).slice(0, 10).map((el) => ({
1316
+ name: el.textContent?.replace(/\s+/g, " ").trim() || "",
1317
+ href: el.href || null,
1318
+ cssSelector: el.id ? `#${CSS.escape(el.id)}` : "a"
1319
+ }));
1320
+ });
1321
+ for (const item of bcItems) {
1322
+ if (!item.name || !item.href)
1323
+ continue;
1324
+ candidates.push({
1325
+ priority: 8,
1326
+ action: {
1327
+ id: `${currentState.id}|breadcrumb|${item.cssSelector}`,
1328
+ type: "breadcrumb",
1329
+ description: `Navigate breadcrumb \u201C${item.name}\u201D`,
1330
+ target: item.name,
1331
+ selector: item.cssSelector,
1332
+ locator: { name: item.name },
1333
+ safe: true
1334
+ },
1335
+ locator: { name: item.name },
1336
+ kind: "breadcrumb",
1337
+ restoreStrategy: "goto"
1338
+ });
1339
+ }
1340
+ } catch {
1341
+ }
1342
+ for (const button of currentState.controls.filter((c) => c.kind === "button" && !c.disabled && !c.destructive && c.accessibleName)) {
1343
+ if (isSessionEnding(button.accessibleName, button.text)) {
1344
+ candidates.push({
1345
+ priority: 10,
1346
+ action: {
1347
+ id: `${currentState.id}|navigate|${button.cssSelector}`,
1348
+ type: "navigate",
1349
+ description: `Navigate by clicking \u201C${button.accessibleName}\u201D`,
1350
+ target: button.accessibleName,
1351
+ selector: button.cssSelector,
1352
+ locator: { role: button.role, name: button.accessibleName },
1353
+ safe: false,
1354
+ reason: "session-ending action"
1355
+ },
1356
+ locator: { role: button.role, name: button.accessibleName },
1357
+ kind: "other-safe",
1358
+ restoreStrategy: "goto"
1359
+ });
1360
+ continue;
1361
+ }
1362
+ const blocked = isBlockedLabel(legacyOptions.blockedKeywords, button.accessibleName, button.text);
1363
+ candidates.push({
1364
+ priority: blocked ? 10 : 9,
1365
+ action: {
1366
+ id: `${currentState.id}|navigate|${button.cssSelector}`,
1367
+ type: "navigate",
1368
+ description: `Navigate by clicking \u201C${button.accessibleName}\u201D`,
1369
+ target: button.accessibleName,
1370
+ selector: button.cssSelector,
1371
+ locator: { role: button.role, name: button.accessibleName },
1372
+ safe: !blocked,
1373
+ reason: blocked ? "Action matched the Project click filter" : void 0
1374
+ },
1375
+ locator: { role: button.role, name: button.accessibleName },
1376
+ kind: "other-safe",
1377
+ restoreStrategy: "goto"
1378
+ });
1379
+ }
1380
+ candidates.sort((a, b) => a.priority - b.priority);
1381
+ return candidates;
1382
+ }
1383
+ async function restoreState(page, targetUrl, strategy, _entryFlow) {
1384
+ switch (strategy) {
1385
+ case "goto":
1386
+ await page.goto(targetUrl, { waitUntil: "domcontentloaded", timeout: legacyOptions.pageTimeoutMs }).catch(() => void 0);
1387
+ await page.waitForTimeout(legacyOptions.waitAfterNavigationMs);
1388
+ break;
1389
+ case "reload":
1390
+ await page.reload({ waitUntil: "domcontentloaded", timeout: legacyOptions.pageTimeoutMs }).catch(() => void 0);
1391
+ await page.waitForTimeout(legacyOptions.waitAfterNavigationMs);
1392
+ break;
1393
+ case "close-dialog":
1394
+ try {
1395
+ await page.keyboard.press("Escape");
1396
+ await page.waitForTimeout(300);
1397
+ } catch {
1398
+ }
1399
+ break;
1400
+ case "select-tab":
1401
+ await page.waitForTimeout(legacyOptions.stateDiscoveryTimeoutMs);
1402
+ break;
1403
+ case "entry-replay":
1404
+ for (const step of _entryFlow) {
1405
+ try {
1406
+ if (step.action.selector) {
1407
+ await page.locator(step.action.selector).click({ timeout: legacyOptions.actionTimeoutMs }).catch(() => void 0);
1408
+ await page.waitForTimeout(legacyOptions.stateDiscoveryTimeoutMs);
1409
+ }
1410
+ } catch {
1411
+ }
1412
+ }
1413
+ break;
1414
+ case "none":
1415
+ default:
1416
+ break;
1417
+ }
1418
+ }
1419
+ function isAuthLost(currentUrl, page) {
1420
+ try {
1421
+ const path = new URL(currentUrl).pathname.toLowerCase();
1422
+ return path.includes("/login") || path.includes("/signin") || path.includes("/auth");
1423
+ } catch {
1424
+ return false;
1425
+ }
1426
+ }
1427
+ async function executeWithRetry(page, candidate, currentUrl, entryFlow, maxRetries) {
1428
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
1429
+ try {
1430
+ let locator2;
1431
+ if (candidate.locator.cssSelector) {
1432
+ locator2 = page.locator(candidate.locator.cssSelector).first();
1433
+ } else if (candidate.locator.role && candidate.locator.name) {
1434
+ locator2 = page.getByRole(candidate.locator.role, {
1435
+ name: candidate.locator.name
1436
+ });
1437
+ } else if (candidate.locator.testId) {
1438
+ locator2 = page.getByTestId(candidate.locator.testId);
1439
+ } else {
1440
+ return { success: false };
1441
+ }
1442
+ await locator2.click({ timeout: legacyOptions.actionTimeoutMs });
1443
+ await page.waitForTimeout(legacyOptions.stateDiscoveryTimeoutMs);
1444
+ const newUrl = page.url();
1445
+ return { success: true, newUrl };
1446
+ } catch (_error) {
1447
+ if (attempt < maxRetries) {
1448
+ totalActionsRetried++;
1449
+ debug(`Retrying action: ${candidate.action.description} (attempt ${attempt + 1}/${maxRetries})`, {
1450
+ actionId: candidate.action.id,
1451
+ retryCount: attempt + 1
1452
+ });
1453
+ await restoreState(page, currentUrl, candidate.restoreStrategy, entryFlow);
1454
+ await page.waitForTimeout(500);
1455
+ }
1456
+ }
1457
+ }
1458
+ return { success: false };
1459
+ }
1460
+ async function exploreModal(page, parentState, _sourceUrl, entryFlow) {
1461
+ try {
1462
+ const hasDialog = await page.evaluate(() => {
1463
+ return !!(document.querySelector('[role="dialog"]') || document.querySelector("dialog[open]") || document.querySelector('[aria-modal="true"]'));
1464
+ });
1465
+ if (!hasDialog)
1466
+ return { candidates: [] };
1467
+ const raw = await page.evaluate(collectPageData);
1468
+ const pageModel = mapToPageModel(raw, { url: page.url(), finalUrl: page.url(), depth: parentState.depth ?? 0, statusCode: 200 }, legacyOptions.blockedKeywords);
1469
+ const modalState = pageModel.state;
1470
+ if (!modalState)
1471
+ return { candidates: [] };
1472
+ if (visitedStates.has(modalState.id))
1473
+ return { candidates: [] };
1474
+ visitedStates.add(modalState.id);
1475
+ addState2(actionGraph, modalState);
1476
+ debug(`State discovered: ${modalState.name} (modal)`, { stateId: modalState.id, url: page.url() });
1477
+ const modalCandidates = await discoverSafeCandidates(page, modalState);
1478
+ const safeCandidates = modalCandidates.filter((c) => c.action.safe).slice(0, legacyOptions.maxActionsPerState);
1479
+ for (const mc of safeCandidates) {
1480
+ if (actionGraph.visitedActionKeys.includes(mc.action.id) || actionGraph.failedActionKeys.includes(mc.action.id))
1481
+ continue;
1482
+ if (!mc.action.safe) {
1483
+ addEdge2(actionGraph, modalState.id, void 0, mc.action, "blocked");
1484
+ actionGraph.blockedActionKeys.push(mc.action.id);
1485
+ totalActionsBlocked++;
1486
+ debug(`Blocked: ${mc.action.target} (${mc.action.reason || "unsafe"})`, {
1487
+ actionId: mc.action.id,
1488
+ stateId: modalState.id
1489
+ });
1490
+ continue;
1491
+ }
1492
+ const result = await executeWithRetry(page, mc, page.url(), entryFlow, config2.limits.maxActionRetries);
1493
+ totalActionsExecuted++;
1494
+ if (!result.success) {
1495
+ totalActionsFailed++;
1496
+ addEdge2(actionGraph, modalState.id, void 0, mc.action, "failed");
1497
+ actionGraph.failedActionKeys.push(mc.action.id);
1498
+ debug(`Failed: ${mc.action.target}`, { actionId: mc.action.id, stateId: modalState.id });
1499
+ continue;
1500
+ }
1501
+ actionGraph.visitedActionKeys.push(mc.action.id);
1502
+ const newRaw = await page.evaluate(collectPageData);
1503
+ const newModel = mapToPageModel(newRaw, { url: page.url(), finalUrl: page.url(), depth: parentState.depth ?? 0, statusCode: 200 }, legacyOptions.blockedKeywords);
1504
+ const newState = newModel.state;
1505
+ if (newState && !visitedStates.has(newState.id)) {
1506
+ visitedStates.add(newState.id);
1507
+ addState2(actionGraph, newState);
1508
+ addEdge2(actionGraph, modalState.id, newState.id, mc.action, "visited");
1509
+ debug(`New state in modal: ${newState.name}`, { stateId: newState.id });
1510
+ }
1511
+ }
1512
+ try {
1513
+ await page.keyboard.press("Escape");
1514
+ await page.waitForTimeout(300);
1515
+ } catch {
1516
+ }
1517
+ return { state: modalState, candidates: modalCandidates };
1518
+ } catch {
1519
+ return { candidates: [] };
1520
+ }
1521
+ }
1522
+ const launched = await launchBrowser(legacyOptions.browserProfileDir ? { userDataDir: legacyOptions.browserProfileDir } : {});
1523
+ const { context, label: browserLabel } = launched;
1524
+ let targetStartUrl = entryUrl;
1525
+ if (config2.startPath) {
1526
+ try {
1527
+ targetStartUrl = new URL(config2.startPath, entryUrl).toString();
1528
+ debug(`Start path resolved: ${targetStartUrl}`);
1529
+ } catch {
1530
+ debug(`Invalid start path: ${config2.startPath}, using base URL`);
1531
+ }
1532
+ }
1533
+ try {
1534
+ context.setDefaultTimeout(legacyOptions.pageTimeoutMs);
1535
+ const page = await context.newPage();
1536
+ debug(`Navigating to: ${redactUrl(targetStartUrl)}`);
1537
+ const response = await page.goto(targetStartUrl, {
1538
+ waitUntil: "domcontentloaded",
1539
+ timeout: legacyOptions.pageTimeoutMs
1540
+ });
1541
+ if (!response || response.status() >= 400 && response.status() < 600) {
1542
+ const status = response?.status();
1543
+ if (status && status >= 400) {
1544
+ issues.push({
1545
+ url: targetStartUrl,
1546
+ code: "http-error",
1547
+ message: `The server returned HTTP ${status}.`
1548
+ });
1549
+ endReason = "queue-exhausted";
1550
+ }
1551
+ } else {
1552
+ await page.waitForLoadState("networkidle", { timeout: Math.min(legacyOptions.pageTimeoutMs, 5e3) }).catch(() => void 0);
1553
+ await page.waitForTimeout(legacyOptions.waitAfterNavigationMs);
1554
+ const raw = await page.evaluate(collectPageData);
1555
+ const initialPage = mapToPageModel(raw, { url: targetStartUrl, finalUrl: page.url(), depth: 0, statusCode: response.status() }, legacyOptions.blockedKeywords);
1556
+ pages.push(initialPage);
1557
+ visitedUrls.add(normalizeUrl(initialPage.finalUrl));
1558
+ if (initialPage.state) {
1559
+ visitedStates.add(initialPage.state.id);
1560
+ addState2(actionGraph, initialPage.state);
1561
+ debug(`State discovered: ${initialPage.state.name}`, {
1562
+ stateId: initialPage.state.id,
1563
+ url: redactUrl(initialPage.finalUrl)
1564
+ });
1565
+ }
1566
+ const entryFlow = [];
1567
+ if (config2.startPath && config2.startPath !== "/") {
1568
+ entryFlow.push({
1569
+ url: targetStartUrl,
1570
+ action: {
1571
+ id: "entry|start-path",
1572
+ type: "navigate",
1573
+ description: `Navigate to start path: ${config2.startPath}`,
1574
+ target: config2.startPath,
1575
+ safe: true
1576
+ },
1577
+ stateId: initialPage.state?.id
1578
+ });
1579
+ }
1580
+ stateQueue.push({
1581
+ url: initialPage.finalUrl,
1582
+ stateId: initialPage.state?.id,
1583
+ depth: 0,
1584
+ entryFlow
1585
+ });
1586
+ while (stateQueue.length > 0) {
1587
+ if (pages.length >= config2.limits.maxPages) {
1588
+ endReason = "max-pages-reached";
1589
+ debug(`Limit reached: max pages (${config2.limits.maxPages})`);
1590
+ break;
1591
+ }
1592
+ if (actionGraph.states.length >= config2.limits.maxStates) {
1593
+ endReason = "max-states-reached";
1594
+ debug(`Limit reached: max states (${config2.limits.maxStates})`);
1595
+ break;
1596
+ }
1597
+ if (totalActionsExecuted >= config2.limits.maxTotalActions) {
1598
+ endReason = "max-total-actions-reached";
1599
+ debug(`Limit reached: max total actions (${config2.limits.maxTotalActions})`);
1600
+ break;
1601
+ }
1602
+ if (Date.now() - startedAt > config2.limits.explorationTimeoutMs) {
1603
+ endReason = "timeout-reached";
1604
+ debug(`Limit reached: timeout (${config2.limits.explorationTimeoutMs}ms)`);
1605
+ break;
1606
+ }
1607
+ const item = stateQueue.shift();
1608
+ if (item.depth > config2.limits.maxDepth)
1609
+ continue;
1610
+ const currentUrl = normalizeUrl(page.url());
1611
+ const targetUrl = normalizeUrl(item.url);
1612
+ if (currentUrl !== targetUrl) {
1613
+ try {
1614
+ await page.goto(item.url, { waitUntil: "domcontentloaded", timeout: legacyOptions.pageTimeoutMs });
1615
+ await page.waitForTimeout(legacyOptions.waitAfterNavigationMs);
1616
+ } catch (error) {
1617
+ issues.push(toExploreIssue(item.url, error));
1618
+ continue;
1619
+ }
1620
+ }
1621
+ if (isAuthLost(page.url(), page)) {
1622
+ debug(`Auth lost, attempting recovery`, { url: redactUrl(page.url()) });
1623
+ try {
1624
+ await page.goto(item.url, { waitUntil: "domcontentloaded", timeout: legacyOptions.pageTimeoutMs });
1625
+ await page.waitForTimeout(legacyOptions.waitAfterNavigationMs);
1626
+ if (isAuthLost(page.url(), page)) {
1627
+ debug(`Auth recovery failed`, { url: redactUrl(page.url()) });
1628
+ issues.push({
1629
+ url: item.url,
1630
+ code: "auth-lost",
1631
+ message: "Authentication was lost during exploration and could not be recovered."
1632
+ });
1633
+ endReason = "auth-lost-unrecoverable";
1634
+ break;
1635
+ }
1636
+ debug(`Auth recovered`);
1637
+ } catch {
1638
+ endReason = "auth-lost-unrecoverable";
1639
+ break;
1640
+ }
1641
+ }
1642
+ const raw2 = await page.evaluate(collectPageData);
1643
+ const currentModel = mapToPageModel(raw2, { url: item.url, finalUrl: page.url(), depth: item.depth, statusCode: 200 }, legacyOptions.blockedKeywords);
1644
+ const currentState = currentModel.state;
1645
+ if (!currentState)
1646
+ continue;
1647
+ if (!visitedStates.has(currentState.id)) {
1648
+ visitedStates.add(currentState.id);
1649
+ addState2(actionGraph, currentState);
1650
+ }
1651
+ if (config2.mode === "current-page")
1652
+ continue;
1653
+ const candidates = await discoverSafeCandidates(page, currentState);
1654
+ 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);
1655
+ debug(`State: ${currentState.name} \u2014 Found ${candidates.length} candidates, ${safeActions.length} safe`, {
1656
+ stateId: currentState.id,
1657
+ url: redactUrl(page.url()),
1658
+ queueSize: stateQueue.length
1659
+ });
1660
+ for (const candidate of candidates) {
1661
+ if (!candidate.action.safe && candidate.action.reason) {
1662
+ totalActionsBlocked++;
1663
+ addEdge2(actionGraph, currentState.id, void 0, candidate.action, "blocked");
1664
+ actionGraph.blockedActionKeys.push(candidate.action.id);
1665
+ const blockReason = isSessionEnding(candidate.action.target, void 0) ? "session-ending action" : candidate.action.reason;
1666
+ debug(`Blocked: ${candidate.action.target} (${blockReason})`, {
1667
+ actionId: candidate.action.id,
1668
+ stateId: currentState.id
1669
+ });
1670
+ }
1671
+ }
1672
+ for (const candidate of safeActions) {
1673
+ if (totalActionsExecuted >= config2.limits.maxTotalActions)
1674
+ break;
1675
+ if (Date.now() - startedAt > config2.limits.explorationTimeoutMs)
1676
+ break;
1677
+ actionGraph.visitedActionKeys.push(candidate.action.id);
1678
+ const beforeUrl = page.url();
1679
+ if (candidate.kind === "navigation-link" || candidate.kind === "sidebar-nav" || candidate.kind === "breadcrumb") {
1680
+ const href = candidate.action.target;
1681
+ if (href && !isWithinScope(href)) {
1682
+ urlsSkippedByScope++;
1683
+ debug(`Skipped: ${candidate.action.target} (outside scope ${config2.scopePath || "root"})`, {
1684
+ actionId: candidate.action.id,
1685
+ reason: `outside scope ${config2.scopePath || "root"}`
1686
+ });
1687
+ continue;
1688
+ }
1689
+ }
1690
+ const result = await executeWithRetry(page, candidate, beforeUrl, item.entryFlow, config2.limits.maxActionRetries);
1691
+ totalActionsExecuted++;
1692
+ if (!result.success) {
1693
+ totalActionsFailed++;
1694
+ addEdge2(actionGraph, currentState.id, void 0, candidate.action, "failed");
1695
+ actionGraph.failedActionKeys.push(candidate.action.id);
1696
+ debug(`Failed: ${candidate.action.target}`, { actionId: candidate.action.id });
1697
+ await restoreState(page, beforeUrl, candidate.restoreStrategy, item.entryFlow);
1698
+ continue;
1699
+ }
1700
+ const afterUrl = page.url();
1701
+ const normalizedAfter = normalizeUrl(afterUrl);
1702
+ if (!isWithinScope(afterUrl)) {
1703
+ urlsSkippedByScope++;
1704
+ debug(`Skipped (after navigation): ${redactUrl(afterUrl)} (outside scope)`, {
1705
+ url: redactUrl(afterUrl),
1706
+ reason: "outside scope"
1707
+ });
1708
+ await restoreState(page, beforeUrl, candidate.restoreStrategy, item.entryFlow);
1709
+ continue;
1710
+ }
1711
+ if (isAuthLost(afterUrl, page)) {
1712
+ debug(`Auth lost after action: ${candidate.action.target}`, { url: redactUrl(afterUrl) });
1713
+ await restoreState(page, beforeUrl, "goto", item.entryFlow);
1714
+ continue;
1715
+ }
1716
+ const newRaw = await page.evaluate(collectPageData);
1717
+ const newModel = mapToPageModel(newRaw, { url: beforeUrl, finalUrl: afterUrl, depth: item.depth + 1, statusCode: 200 }, legacyOptions.blockedKeywords);
1718
+ const newState = newModel.state;
1719
+ if (newState && !visitedStates.has(newState.id)) {
1720
+ visitedStates.add(newState.id);
1721
+ addState2(actionGraph, newState);
1722
+ addEdge2(actionGraph, currentState.id, newState.id, candidate.action, "visited");
1723
+ debug(`New state: ${newState.name}`, { stateId: newState.id, url: redactUrl(afterUrl) });
1724
+ if (!visitedUrls.has(normalizedAfter)) {
1725
+ visitedUrls.add(normalizedAfter);
1726
+ if (isSameOrigin(afterUrl, origin) && isCrawlableUrl(afterUrl)) {
1727
+ pages.push(newModel);
1728
+ }
1729
+ }
1730
+ await exploreModal(page, newState, afterUrl, item.entryFlow);
1731
+ const newEntryFlow = [...item.entryFlow, { url: afterUrl, action: candidate.action, stateId: newState.id }];
1732
+ stateQueue.push({
1733
+ url: afterUrl,
1734
+ stateId: newState.id,
1735
+ depth: item.depth + 1,
1736
+ entryFlow: newEntryFlow
1737
+ });
1738
+ } else if (newState) {
1739
+ addEdge2(actionGraph, currentState.id, newState.id, candidate.action, "visited");
1740
+ } else {
1741
+ addEdge2(actionGraph, currentState.id, void 0, candidate.action, "visited");
1742
+ }
1743
+ if (normalizedAfter !== normalizeUrl(beforeUrl)) {
1744
+ await restoreState(page, beforeUrl, candidate.restoreStrategy, item.entryFlow);
1745
+ }
1746
+ }
1747
+ }
1748
+ }
1749
+ } catch (error) {
1750
+ issues.push(toExploreIssue(targetStartUrl || entryUrl, error));
1751
+ if (endReason === "queue-exhausted") {
1752
+ endReason = "browser-crash";
1753
+ }
1754
+ } finally {
1755
+ await launched.close().catch(() => void 0);
1756
+ }
1757
+ const summary = {
1758
+ pagesDiscovered: pages.length,
1759
+ statesDiscovered: actionGraph.states.length,
1760
+ transitions: actionGraph.edges.filter((e) => e.status === "visited").length,
1761
+ actionsExecuted: totalActionsExecuted,
1762
+ actionsBlocked: totalActionsBlocked,
1763
+ actionsFailed: totalActionsFailed,
1764
+ actionsRetried: totalActionsRetried,
1765
+ urlsSkippedByScope,
1766
+ endReason,
1767
+ endReasonDetail: getEndReasonDetail(endReason, config2)
1768
+ };
1769
+ const stats = {
1770
+ browser: browserLabel,
1771
+ pagesVisited: pages.length,
1772
+ urlsSkipped: urlsSkippedByScope,
1773
+ durationMs: Date.now() - startedAt,
1774
+ limitReached: endReason,
1775
+ summary,
1776
+ discoveryLogs: logs
1777
+ };
1778
+ return {
1779
+ startUrl: entryUrl,
1780
+ origin,
1781
+ pages,
1782
+ issues,
1783
+ stats,
1784
+ actionGraph
1785
+ };
1786
+ }
1787
+ function addState2(graph, state) {
1788
+ if (!state || graph.states.some((s) => s.id === state.id))
1789
+ return;
1790
+ graph.states.push(state);
1791
+ graph.visitedStateIds.push(state.id);
1792
+ }
1793
+ function addEdge2(graph, fromStateId, toStateId, action, status) {
1794
+ const id = `${fromStateId}|${action.id}|${toStateId ?? status}`;
1795
+ if (graph.edges.some((edge) => edge.id === id))
1796
+ return;
1797
+ graph.edges.push({ id, fromStateId, toStateId, action, status });
1798
+ }
1799
+ function getEndReasonDetail(reason, config2) {
1800
+ switch (reason) {
1801
+ case "queue-exhausted":
1802
+ return "All discoverable states have been explored within the configured scope.";
1803
+ case "max-pages-reached":
1804
+ return `Maximum page limit (${config2.limits.maxPages}) reached.`;
1805
+ case "max-states-reached":
1806
+ return `Maximum state limit (${config2.limits.maxStates}) reached.`;
1807
+ case "max-depth-reached":
1808
+ return `Maximum depth limit (${config2.limits.maxDepth}) reached.`;
1809
+ case "max-total-actions-reached":
1810
+ return `Maximum total actions limit (${config2.limits.maxTotalActions}) reached.`;
1811
+ case "timeout-reached":
1812
+ return `Exploration timeout (${config2.limits.explorationTimeoutMs}ms) reached.`;
1813
+ case "no-safe-actions-remaining":
1814
+ return "No safe actions remain to explore.";
1815
+ case "auth-lost-unrecoverable":
1816
+ return "Authentication was lost and could not be recovered.";
1817
+ case "browser-crash":
1818
+ return "Browser crashed or became unresponsive.";
1819
+ default:
1820
+ return "Exploration ended.";
1821
+ }
1822
+ }
1823
+
981
1824
  // ../../packages/explorer/dist/recorder/recorderScript.js
982
1825
  function recorderInitScript() {
983
1826
  const scope = window;
@@ -1757,7 +2600,22 @@ function exportTestCasesToCsv(testCases, testData = []) {
1757
2600
  // src/commands/scan.ts
1758
2601
  async function runScan(options) {
1759
2602
  console.log(`checking scan ${redactUrl(options.url)} ...`);
1760
- const result = await exploreWebsite(options.url, {
2603
+ const useScoped = options.startPath || options.scopePath || options.mode || options.debug;
2604
+ const result = useScoped ? await exploreWithScope(options.url, {
2605
+ startPath: options.startPath,
2606
+ scopePath: options.scopePath,
2607
+ mode: options.mode ?? "site",
2608
+ debug: options.debug ?? false,
2609
+ limits: {
2610
+ maxPages: options.maxPages ?? 20,
2611
+ maxDepth: options.maxDepth ?? 3,
2612
+ maxStates: 80,
2613
+ maxActionsPerState: 8,
2614
+ maxTotalActions: 200,
2615
+ maxActionRetries: 2,
2616
+ explorationTimeoutMs: 3e5
2617
+ }
2618
+ }) : await exploreWebsite(options.url, {
1761
2619
  ...options.maxPages !== void 0 ? { maxPages: options.maxPages } : {},
1762
2620
  ...options.maxDepth !== void 0 ? { maxDepth: options.maxDepth } : {}
1763
2621
  });
@@ -1769,10 +2627,31 @@ async function runScan(options) {
1769
2627
  for (const issue of result.issues) {
1770
2628
  console.log(` ! ${issue.url} \u2014 ${issue.message}`);
1771
2629
  }
2630
+ const summary = result.stats.summary;
2631
+ if (summary) {
2632
+ console.log(`
2633
+ Exploration Summary:`);
2634
+ console.log(` Pages discovered: ${summary.pagesDiscovered}`);
2635
+ console.log(` UI states discovered: ${summary.statesDiscovered}`);
2636
+ console.log(` Transitions: ${summary.transitions}`);
2637
+ console.log(
2638
+ ` Actions \u2014 Executed: ${summary.actionsExecuted} | Blocked: ${summary.actionsBlocked} | Failed: ${summary.actionsFailed} | Retried: ${summary.actionsRetried}`
2639
+ );
2640
+ console.log(` URLs skipped by scope: ${summary.urlsSkippedByScope}`);
2641
+ console.log(` End reason: ${summary.endReason}${summary.endReasonDetail ? ` \u2014 ${summary.endReasonDetail}` : ""}`);
2642
+ }
1772
2643
  console.log(
1773
2644
  `
1774
2645
  Summary: ${result.pages.length} pages \xB7 ${testCases.length} test cases \xB7 ${testData.length} test data \xB7 ${(result.stats.durationMs / 1e3).toFixed(1)} seconds \xB7 Using ${result.stats.browser}`
1775
2646
  );
2647
+ if (result.stats.discoveryLogs && result.stats.discoveryLogs.length > 0) {
2648
+ console.log(`
2649
+ Discovery Logs:`);
2650
+ for (const log of result.stats.discoveryLogs) {
2651
+ const prefix = log.level === "blocked" ? "\u{1F6AB}" : log.level === "skipped" ? "\u23ED\uFE0F" : log.level === "error" ? "\u274C" : log.level === "retry" ? "\u{1F504}" : log.level === "debug" ? "\u{1F50D}" : " ";
2652
+ console.log(`${prefix} ${log.message}`);
2653
+ }
2654
+ }
1776
2655
  if (result.pages.length === 0) {
1777
2656
  console.error("Failed to open the website, no data to save");
1778
2657
  process.exitCode = 1;
@@ -1780,7 +2659,8 @@ Summary: ${result.pages.length} pages \xB7 ${testCases.length} test cases \xB7 $
1780
2659
  }
1781
2660
  const csvPath = resolve(options.csvPath ?? "lazyscout-testcases.csv");
1782
2661
  await writeFile(csvPath, exportTestCasesToCsv(testCases, testData), "utf8");
1783
- console.log(`Saved CSV: ${csvPath}`);
2662
+ console.log(`
2663
+ Saved CSV: ${csvPath}`);
1784
2664
  if (options.jsonPath) {
1785
2665
  const jsonPath = resolve(options.jsonPath);
1786
2666
  await writeFile(jsonPath, JSON.stringify({ ...result, testCases, testData }, null, 2), "utf8");
@@ -1803,236 +2683,40 @@ var config = {
1803
2683
  urlPolicy: process.env.LAZYSCOUT_MODE === "public" ? PUBLIC_SAAS_POLICY : LOCAL_QA_POLICY,
1804
2684
  limits: {
1805
2685
  maxPages: 20,
1806
- maxDepth: 3
1807
- }
1808
- };
1809
- function clamp(value, min, max, fallback) {
1810
- if (value === void 0 || Number.isNaN(value))
1811
- return fallback;
1812
- return Math.min(Math.max(Math.trunc(value), min), max);
1813
- }
1814
-
1815
- // ../server/dist/toApiError.js
1816
- function toApiError(error) {
1817
- if (error instanceof ExplorerError) {
1818
- const status = error.code === "invalid-url" || error.code === "blocked-url" ? 400 : 502;
1819
- return {
1820
- status,
1821
- body: {
1822
- error: {
1823
- code: error.code,
1824
- message: redactSensitiveText(error.message),
1825
- hint: error.hint ? redactSensitiveText(error.hint) : void 0
1826
- }
1827
- }
1828
- };
1829
- }
1830
- return {
1831
- status: 500,
1832
- body: {
1833
- error: {
1834
- code: "internal-error",
1835
- message: "An internal error occurred while analyzing the website.",
1836
- hint: "Try again, or review the server logs for more details."
1837
- }
1838
- }
1839
- };
1840
- }
1841
-
1842
- // ../server/dist/routes/analyze.js
1843
- function registerAnalyzeRoute(app) {
1844
- app.post("/api/analyze", async (request, reply) => {
1845
- const body = request.body ?? {};
1846
- if (typeof body.url !== "string" || !body.url.trim()) {
1847
- return reply.status(400).send({
1848
- error: { code: "invalid-url", message: "Provide a URL to analyze." }
1849
- });
1850
- }
1851
- const check = checkTargetUrl(body.url, config.urlPolicy);
1852
- if (!check.ok) {
1853
- return reply.status(400).send({ error: { code: check.code, message: check.message } });
1854
- }
1855
- try {
1856
- const result = await exploreWebsite(check.url.toString(), {
1857
- maxPages: clamp(body.maxPages, 1, config.limits.maxPages, config.limits.maxPages),
1858
- maxDepth: clamp(body.maxDepth, 0, config.limits.maxDepth, config.limits.maxDepth),
1859
- waitAfterNavigationMs: clamp(body.waitAfterNavigationMs, 0, 5e3, 750)
1860
- }, config.urlPolicy);
1861
- if (result.pages.length === 0) {
1862
- const firstIssue = result.issues[0];
1863
- 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.");
1864
- }
1865
- const testCases = [
1866
- ...generateTestCases(result.pages, { language: body.language ?? "en" }),
1867
- ...generateStateFlowTestCases(result.actionGraph)
1868
- ];
1869
- const runEvents = [
1870
- {
1871
- timestamp: new Date(Date.now() - result.stats.durationMs).toISOString(),
1872
- eventType: "run-started",
1873
- result: "running",
1874
- message: "Explorer run started"
1875
- },
1876
- ...result.pages.flatMap((page) => [
1877
- {
1878
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1879
- eventType: "page-discovered",
1880
- currentUrl: page.finalUrl,
1881
- currentStateId: page.state?.id,
1882
- result: "passed",
1883
- message: `Page discovered: ${page.title || page.finalUrl}`
1884
- },
1885
- ...(page.state?.interactions ?? []).map((interaction) => ({
1886
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1887
- eventType: result.actionGraph.blockedActionKeys.some((key) => key.endsWith(`|${interaction.cssSelector}`)) ? "action-blocked" : "action-discovered",
1888
- currentUrl: page.finalUrl,
1889
- currentStateId: page.state?.id,
1890
- result: result.actionGraph.blockedActionKeys.some((key) => key.endsWith(`|${interaction.cssSelector}`)) ? "blocked" : "warning",
1891
- message: `${interaction.kind}: ${interaction.name}`
1892
- }))
1893
- ]),
1894
- ...result.actionGraph.states.map((state) => ({
1895
- timestamp: state.discoveredAt,
1896
- eventType: "state-discovered",
1897
- currentUrl: state.url,
1898
- currentStateId: state.id,
1899
- result: "passed",
1900
- message: `State observed: ${state.name || state.title || state.url}`
1901
- })),
1902
- ...result.actionGraph.edges.map((edge) => ({
1903
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1904
- eventType: edge.status === "blocked" ? "action-blocked" : edge.status === "failed" ? "action-failed" : edge.status === "visited" ? "action-executed" : "transition-discovered",
1905
- currentUrl: result.actionGraph.states.find((state) => state.id === edge.fromStateId)?.url,
1906
- currentStateId: edge.fromStateId,
1907
- action: edge.action,
1908
- result: edge.status === "blocked" ? "blocked" : edge.status === "failed" ? "failed" : edge.status === "visited" ? "passed" : "warning",
1909
- message: edge.action.description
1910
- })),
1911
- ...result.issues.map((issue) => ({
1912
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1913
- eventType: "error",
1914
- currentUrl: issue.url,
1915
- result: "failed",
1916
- error: issue.message,
1917
- message: issue.message
1918
- })),
1919
- {
1920
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1921
- eventType: "run-completed",
1922
- result: result.issues.length ? "warning" : "passed",
1923
- durationMs: result.stats.durationMs,
1924
- message: "Analysis completed"
1925
- }
1926
- ];
1927
- const response = {
1928
- startUrl: result.startUrl,
1929
- origin: result.origin,
1930
- pages: result.pages,
1931
- testCases,
1932
- testData: generateTestData(result.pages),
1933
- issues: result.issues,
1934
- stats: result.stats,
1935
- actionGraph: result.actionGraph,
1936
- runEvents,
1937
- apiChecks: body.includeApiChecks ? buildApiChecks(result.pages) : []
1938
- };
1939
- return reply.send(response);
1940
- } catch (error) {
1941
- request.log.error({ message: redactSensitiveText(error instanceof Error ? error.message : String(error)) }, "analyze failed");
1942
- const { status, body: errorBody } = toApiError(error);
1943
- return reply.status(status).send(errorBody);
1944
- }
1945
- });
1946
- }
1947
- function generateStateFlowTestCases(graph) {
1948
- const states = new Map(graph.states.map((state) => [state.id, state]));
1949
- let sequence = 1;
1950
- return graph.edges.flatMap((edge) => {
1951
- if (edge.status !== "visited" || !edge.toStateId || edge.fromStateId === edge.toStateId)
1952
- return [];
1953
- const target = states.get(edge.toStateId);
1954
- const source = states.get(edge.fromStateId);
1955
- if (!target || !source)
1956
- return [];
1957
- const observation = expectedObservation(target);
1958
- const id = `TC-FLOW-${String(sequence).padStart(3, "0")}`;
1959
- sequence += 1;
1960
- return [
1961
- {
1962
- id,
1963
- module: "FLOW",
1964
- tags: ["state-flow"],
1965
- title: `${edge.action.description} reaches ${target.name}`,
1966
- preconditions: [`The application is available at ${source.url}`],
1967
- steps: [
1968
- { type: "navigate", url: source.url },
1969
- {
1970
- type: "click",
1971
- target: {
1972
- role: edge.action.locator?.role,
1973
- name: edge.action.locator?.name,
1974
- cssSelector: edge.action.selector
1975
- }
1976
- }
1977
- ],
1978
- expectedResult: observation ?? "Observed state requires tester review before automation.",
1979
- type: target.type === "validation" || target.type === "error" ? "validation" : "positive",
1980
- priority: "medium",
1981
- automationStatus: observation ? "ready" : "needs-review",
1982
- sourceUrl: source.url,
1983
- notes: observation ? "Generated from an observed UI state transition." : "Explorer observed a new UI state but no stable assertion text."
1984
- }
1985
- ];
1986
- });
1987
- }
1988
- function expectedObservation(state) {
1989
- if (state.visibleDialogs[0])
1990
- return `Dialog "${state.visibleDialogs[0]}" is visible.`;
1991
- if (state.validationMessages[0])
1992
- return `Validation message "${state.validationMessages[0]}" is visible.`;
1993
- if (state.headings[0])
1994
- return `Heading "${state.headings[0]}" is visible.`;
1995
- return void 0;
1996
- }
1997
- function buildApiChecks(pages) {
1998
- const seen = /* @__PURE__ */ new Set();
1999
- const checks = [];
2000
- for (const page of pages)
2001
- for (const request of page.apiRequests) {
2002
- const key = `${request.method}:${request.url}`;
2003
- if (seen.has(key))
2004
- continue;
2005
- seen.add(key);
2006
- const authRequired = request.status === 401 || request.status === 403;
2007
- const safeMethod = ["GET", "HEAD", "OPTIONS"].includes(request.method.toUpperCase());
2008
- checks.push({
2009
- id: `API-${String(checks.length + 1).padStart(3, "0")}`,
2010
- method: request.method,
2011
- url: request.url,
2012
- observedStatus: request.status,
2013
- expectedStatus: authRequired ? void 0 : request.status && request.status < 400 ? 200 : void 0,
2014
- sourceUrl: request.sourceUrl,
2015
- durationMs: request.durationMs,
2016
- status: !safeMethod ? "needs-review" : authRequired ? "needs-auth" : request.status && request.status >= 400 ? "needs-review" : "observed",
2017
- note: !safeMethod ? "Observation only. LazyScout does not replay state-changing API methods automatically." : authRequired ? "Requires auth profile or token before execution." : void 0
2018
- });
2019
- }
2020
- return checks;
2686
+ maxDepth: 3
2687
+ }
2688
+ };
2689
+ function clamp(value, min, max, fallback) {
2690
+ if (value === void 0 || Number.isNaN(value))
2691
+ return fallback;
2692
+ return Math.min(Math.max(Math.trunc(value), min), max);
2021
2693
  }
2022
2694
 
2023
- // ../server/dist/routes/exportCsv.js
2024
- function registerExportCsvRoute(app) {
2025
- app.post("/api/export/csv", async (request, reply) => {
2026
- const body = request.body ?? {};
2027
- if (!Array.isArray(body.testCases) || body.testCases.length === 0) {
2028
- return reply.status(400).send({
2029
- error: { code: "empty-export", message: "There are no Test Cases to export." }
2030
- });
2695
+ // ../server/dist/toApiError.js
2696
+ function toApiError(error) {
2697
+ if (error instanceof ExplorerError) {
2698
+ const status = error.code === "invalid-url" || error.code === "blocked-url" ? 400 : 502;
2699
+ return {
2700
+ status,
2701
+ body: {
2702
+ error: {
2703
+ code: error.code,
2704
+ message: redactSensitiveText(error.message),
2705
+ hint: error.hint ? redactSensitiveText(error.hint) : void 0
2706
+ }
2707
+ }
2708
+ };
2709
+ }
2710
+ return {
2711
+ status: 500,
2712
+ body: {
2713
+ error: {
2714
+ code: "internal-error",
2715
+ message: "An internal error occurred while analyzing the website.",
2716
+ hint: "Try again, or review the server logs for more details."
2717
+ }
2031
2718
  }
2032
- const csv = exportTestCasesToCsv(body.testCases, Array.isArray(body.testData) ? body.testData : []);
2033
- const filename = `lazyscout-testcases-${(/* @__PURE__ */ new Date()).toISOString().slice(0, 10)}.csv`;
2034
- return reply.header("Content-Type", "text/csv; charset=utf-8").header("Content-Disposition", `attachment; filename="${filename}"`).send(csv);
2035
- });
2719
+ };
2036
2720
  }
2037
2721
 
2038
2722
  // ../server/dist/workspace.js
@@ -2312,6 +2996,205 @@ function enqueueMutation(key, action) {
2312
2996
  });
2313
2997
  }
2314
2998
 
2999
+ // ../server/dist/routes/analyze.js
3000
+ function registerAnalyzeRoute(app, workspaceRoot) {
3001
+ app.post("/api/analyze", async (request, reply) => {
3002
+ const body = request.body ?? {};
3003
+ if (typeof body.url !== "string" || !body.url.trim()) {
3004
+ return reply.status(400).send({
3005
+ error: { code: "invalid-url", message: "Provide a URL to analyze." }
3006
+ });
3007
+ }
3008
+ const check = checkTargetUrl(body.url, config.urlPolicy);
3009
+ if (!check.ok) {
3010
+ return reply.status(400).send({ error: { code: check.code, message: check.message } });
3011
+ }
3012
+ const browserProfileDir = body.projectId ? await browserProfileDirectory(workspaceRoot, body.projectId).catch(() => void 0) : void 0;
3013
+ try {
3014
+ const result = await exploreWebsite(check.url.toString(), {
3015
+ maxPages: clamp(body.maxPages, 1, config.limits.maxPages, config.limits.maxPages),
3016
+ maxDepth: clamp(body.maxDepth, 0, config.limits.maxDepth, config.limits.maxDepth),
3017
+ waitAfterNavigationMs: clamp(body.waitAfterNavigationMs, 0, 5e3, 750),
3018
+ blockedKeywords: normalizeBlockedKeywords(body.blockedKeywords),
3019
+ ...browserProfileDir ? { browserProfileDir } : {}
3020
+ }, config.urlPolicy);
3021
+ if (result.pages.length === 0) {
3022
+ const firstIssue = result.issues[0];
3023
+ 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.");
3024
+ }
3025
+ const testCases = [
3026
+ ...generateTestCases(result.pages, { language: body.language ?? "en" }),
3027
+ ...generateStateFlowTestCases(result.actionGraph)
3028
+ ];
3029
+ const runEvents = [
3030
+ {
3031
+ timestamp: new Date(Date.now() - result.stats.durationMs).toISOString(),
3032
+ eventType: "run-started",
3033
+ result: "running",
3034
+ message: "Explorer run started"
3035
+ },
3036
+ ...result.pages.flatMap((page) => [
3037
+ {
3038
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
3039
+ eventType: "page-discovered",
3040
+ currentUrl: page.finalUrl,
3041
+ currentStateId: page.state?.id,
3042
+ result: "passed",
3043
+ message: `Page discovered: ${page.title || page.finalUrl}`
3044
+ },
3045
+ ...(page.state?.interactions ?? []).map((interaction) => ({
3046
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
3047
+ eventType: result.actionGraph.blockedActionKeys.some((key) => key.endsWith(`|${interaction.cssSelector}`)) ? "action-blocked" : "action-discovered",
3048
+ currentUrl: page.finalUrl,
3049
+ currentStateId: page.state?.id,
3050
+ result: result.actionGraph.blockedActionKeys.some((key) => key.endsWith(`|${interaction.cssSelector}`)) ? "blocked" : "warning",
3051
+ message: `${interaction.kind}: ${interaction.name}`
3052
+ }))
3053
+ ]),
3054
+ ...result.actionGraph.states.map((state) => ({
3055
+ timestamp: state.discoveredAt,
3056
+ eventType: "state-discovered",
3057
+ currentUrl: state.url,
3058
+ currentStateId: state.id,
3059
+ result: "passed",
3060
+ message: `State observed: ${state.name || state.title || state.url}`
3061
+ })),
3062
+ ...result.actionGraph.edges.map((edge) => ({
3063
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
3064
+ eventType: edge.status === "blocked" ? "action-blocked" : edge.status === "failed" ? "action-failed" : edge.status === "visited" ? "action-executed" : "transition-discovered",
3065
+ currentUrl: result.actionGraph.states.find((state) => state.id === edge.fromStateId)?.url,
3066
+ currentStateId: edge.fromStateId,
3067
+ action: edge.action,
3068
+ result: edge.status === "blocked" ? "blocked" : edge.status === "failed" ? "failed" : edge.status === "visited" ? "passed" : "warning",
3069
+ message: edge.action.description
3070
+ })),
3071
+ ...result.issues.map((issue) => ({
3072
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
3073
+ eventType: "error",
3074
+ currentUrl: issue.url,
3075
+ result: "failed",
3076
+ error: issue.message,
3077
+ message: issue.message
3078
+ })),
3079
+ {
3080
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
3081
+ eventType: "run-completed",
3082
+ result: result.issues.length ? "warning" : "passed",
3083
+ durationMs: result.stats.durationMs,
3084
+ message: "Analysis completed"
3085
+ }
3086
+ ];
3087
+ const response = {
3088
+ startUrl: result.startUrl,
3089
+ origin: result.origin,
3090
+ pages: result.pages,
3091
+ testCases,
3092
+ testData: generateTestData(result.pages),
3093
+ issues: result.issues,
3094
+ stats: result.stats,
3095
+ actionGraph: result.actionGraph,
3096
+ runEvents,
3097
+ apiChecks: body.includeApiChecks ? buildApiChecks(result.pages) : []
3098
+ };
3099
+ return reply.send(response);
3100
+ } catch (error) {
3101
+ request.log.error({ message: redactSensitiveText(error instanceof Error ? error.message : String(error)) }, "analyze failed");
3102
+ const { status, body: errorBody } = toApiError(error);
3103
+ return reply.status(status).send(errorBody);
3104
+ }
3105
+ });
3106
+ }
3107
+ function generateStateFlowTestCases(graph) {
3108
+ const states = new Map(graph.states.map((state) => [state.id, state]));
3109
+ let sequence = 1;
3110
+ return graph.edges.flatMap((edge) => {
3111
+ if (edge.status !== "visited" || !edge.toStateId || edge.fromStateId === edge.toStateId)
3112
+ return [];
3113
+ const target = states.get(edge.toStateId);
3114
+ const source = states.get(edge.fromStateId);
3115
+ if (!target || !source)
3116
+ return [];
3117
+ const observation = expectedObservation(target);
3118
+ const id = `TC-FLOW-${String(sequence).padStart(3, "0")}`;
3119
+ sequence += 1;
3120
+ return [
3121
+ {
3122
+ id,
3123
+ module: "FLOW",
3124
+ tags: ["state-flow"],
3125
+ title: `${edge.action.description} reaches ${target.name}`,
3126
+ preconditions: [`The application is available at ${source.url}`],
3127
+ steps: [
3128
+ { type: "navigate", url: source.url },
3129
+ {
3130
+ type: "click",
3131
+ target: {
3132
+ role: edge.action.locator?.role,
3133
+ name: edge.action.locator?.name,
3134
+ cssSelector: edge.action.selector
3135
+ }
3136
+ }
3137
+ ],
3138
+ expectedResult: observation ?? "Observed state requires tester review before automation.",
3139
+ type: target.type === "validation" || target.type === "error" ? "validation" : "positive",
3140
+ priority: "medium",
3141
+ automationStatus: observation ? "ready" : "needs-review",
3142
+ sourceUrl: source.url,
3143
+ notes: observation ? "Generated from an observed UI state transition." : "Explorer observed a new UI state but no stable assertion text."
3144
+ }
3145
+ ];
3146
+ });
3147
+ }
3148
+ function expectedObservation(state) {
3149
+ if (state.visibleDialogs[0])
3150
+ return `Dialog "${state.visibleDialogs[0]}" is visible.`;
3151
+ if (state.validationMessages[0])
3152
+ return `Validation message "${state.validationMessages[0]}" is visible.`;
3153
+ if (state.headings[0])
3154
+ return `Heading "${state.headings[0]}" is visible.`;
3155
+ return void 0;
3156
+ }
3157
+ function buildApiChecks(pages) {
3158
+ const seen = /* @__PURE__ */ new Set();
3159
+ const checks = [];
3160
+ for (const page of pages)
3161
+ for (const request of page.apiRequests) {
3162
+ const key = `${request.method}:${request.url}`;
3163
+ if (seen.has(key))
3164
+ continue;
3165
+ seen.add(key);
3166
+ const authRequired = request.status === 401 || request.status === 403;
3167
+ const safeMethod = ["GET", "HEAD", "OPTIONS"].includes(request.method.toUpperCase());
3168
+ checks.push({
3169
+ id: `API-${String(checks.length + 1).padStart(3, "0")}`,
3170
+ method: request.method,
3171
+ url: request.url,
3172
+ observedStatus: request.status,
3173
+ expectedStatus: authRequired ? void 0 : request.status && request.status < 400 ? 200 : void 0,
3174
+ sourceUrl: request.sourceUrl,
3175
+ durationMs: request.durationMs,
3176
+ status: !safeMethod ? "needs-review" : authRequired ? "needs-auth" : request.status && request.status >= 400 ? "needs-review" : "observed",
3177
+ note: !safeMethod ? "Observation only. LazyScout does not replay state-changing API methods automatically." : authRequired ? "Requires auth profile or token before execution." : void 0
3178
+ });
3179
+ }
3180
+ return checks;
3181
+ }
3182
+
3183
+ // ../server/dist/routes/exportCsv.js
3184
+ function registerExportCsvRoute(app) {
3185
+ app.post("/api/export/csv", async (request, reply) => {
3186
+ const body = request.body ?? {};
3187
+ if (!Array.isArray(body.testCases) || body.testCases.length === 0) {
3188
+ return reply.status(400).send({
3189
+ error: { code: "empty-export", message: "There are no Test Cases to export." }
3190
+ });
3191
+ }
3192
+ const csv = exportTestCasesToCsv(body.testCases, Array.isArray(body.testData) ? body.testData : []);
3193
+ const filename = `lazyscout-testcases-${(/* @__PURE__ */ new Date()).toISOString().slice(0, 10)}.csv`;
3194
+ return reply.header("Content-Type", "text/csv; charset=utf-8").header("Content-Disposition", `attachment; filename="${filename}"`).send(csv);
3195
+ });
3196
+ }
3197
+
2315
3198
  // ../server/dist/routes/automationRun.js
2316
3199
  var MAX_STEPS = 100;
2317
3200
  var MAX_LOGS = 250;
@@ -2334,6 +3217,7 @@ function registerAutomationRunRoute(app, workspaceRoot) {
2334
3217
  const body = request.body;
2335
3218
  const testCase = body.testCase;
2336
3219
  const secrets = body.secrets;
3220
+ const blockedKeywords = normalizeBlockedKeywords(body.blockedKeywords);
2337
3221
  const framework = body.framework ?? "playwright";
2338
3222
  const runId = body.runId || crypto.randomUUID();
2339
3223
  if (!testCase || !Array.isArray(testCase.steps))
@@ -2398,7 +3282,7 @@ function registerAutomationRunRoute(app, workspaceRoot) {
2398
3282
  page = await context.newPage();
2399
3283
  if (typeof body.code === "string" && body.code.trim()) {
2400
3284
  addLog("info", "Running edited automation source");
2401
- await executeEditedCode(page, body.code, testCase.id, capturedScreenshots, addLog, secrets);
3285
+ await executeEditedCode(page, body.code, testCase.id, capturedScreenshots, addLog, blockedKeywords, secrets);
2402
3286
  if (active.stopped)
2403
3287
  throw new Error("Run stopped by user");
2404
3288
  addLog("pass", "\u2713 edited source completed");
@@ -2407,7 +3291,7 @@ function registerAutomationRunRoute(app, workspaceRoot) {
2407
3291
  if (active.stopped)
2408
3292
  throw new Error("Run stopped by user");
2409
3293
  const stepStarted = Date.now();
2410
- await executeStep(page, step, addLog, secrets);
3294
+ await executeStep(page, step, addLog, blockedKeywords, secrets);
2411
3295
  if (active.stopped)
2412
3296
  throw new Error("Run stopped by user");
2413
3297
  addLog("pass", `\u2713 ${step.type}`, Date.now() - stepStarted);
@@ -2424,6 +3308,7 @@ function registerAutomationRunRoute(app, workspaceRoot) {
2424
3308
  });
2425
3309
  } catch (error) {
2426
3310
  const message = redactSensitiveText(error instanceof Error ? error.message : String(error), secretValues);
3311
+ debugLocator("StepFailed", { testCaseId: testCase.id, url: page?.url(), error: message });
2427
3312
  if (active.stopped) {
2428
3313
  addLog("warn", "Run stopped by user", Date.now() - started);
2429
3314
  await persistLog("stopped");
@@ -2449,7 +3334,7 @@ function registerAutomationRunRoute(app, workspaceRoot) {
2449
3334
  function withScreenshotStatus(screenshots, status) {
2450
3335
  return screenshots.map((screenshot) => ({ ...screenshot, status }));
2451
3336
  }
2452
- async function executeEditedCode(page, source, testCaseId, capturedScreenshots, addLog, projectSecrets) {
3337
+ async function executeEditedCode(page, source, testCaseId, capturedScreenshots, addLog, blockedKeywords, projectSecrets) {
2453
3338
  const lines = source.split(/\r?\n/);
2454
3339
  let executed = 0;
2455
3340
  for (const rawLine of lines) {
@@ -2487,7 +3372,7 @@ async function executeEditedCode(page, source, testCaseId, capturedScreenshots,
2487
3372
  const clickMatch = line.match(/^await (page\..+)\.click\(\)$/);
2488
3373
  if (clickMatch) {
2489
3374
  const target = parseEditedLocator(page, clickMatch[1]);
2490
- await ensureSafeClick(target.locator, target.label);
3375
+ await ensureSafeClick(target.locator, target.label, blockedKeywords);
2491
3376
  addLog("info", `\u2192 Clicking ${target.label}`);
2492
3377
  await target.locator.click();
2493
3378
  continue;
@@ -2650,14 +3535,44 @@ async function captureRequestedScreenshot(page, source, testCaseId) {
2650
3535
  status: "passed"
2651
3536
  };
2652
3537
  }
2653
- var STRING_LITERAL = '"(?:\\\\.|[^"\\\\])*"';
3538
+ var STRING_LITERAL = `(?:"(?:\\\\.|[^"\\\\])*"|'(?:\\\\.|[^'\\\\])*')`;
2654
3539
  function parseStringLiteral(value) {
2655
- const parsed = JSON.parse(value);
3540
+ const quote = value[0];
3541
+ if (quote !== '"' && quote !== "'")
3542
+ throw new Error("Edited Playwright arguments must be quoted strings");
3543
+ const asJson = quote === '"' ? value : `"${value.slice(1, -1).replace(/\\'/g, "'").replace(/"/g, '\\"')}"`;
3544
+ let parsed;
3545
+ try {
3546
+ parsed = JSON.parse(asJson);
3547
+ } catch {
3548
+ throw new Error("Edited Playwright arguments must be quoted strings");
3549
+ }
2656
3550
  if (typeof parsed !== "string")
2657
3551
  throw new Error("Edited Playwright arguments must be strings");
2658
3552
  return parsed;
2659
3553
  }
3554
+ var INDEX_SUFFIX = /\.(first|last|nth)\((\d{0,4})\)$/;
3555
+ function applyIndexSuffix(expression) {
3556
+ const match = expression.match(INDEX_SUFFIX);
3557
+ if (!match)
3558
+ return { base: expression };
3559
+ const base = expression.slice(0, match.index);
3560
+ if (match[1] === "first")
3561
+ return { base, pick: (target) => target.first() };
3562
+ if (match[1] === "last")
3563
+ return { base, pick: (target) => target.last() };
3564
+ if (!match[2])
3565
+ return { base: expression };
3566
+ const index = Number(match[2]);
3567
+ return { base, pick: (target) => target.nth(index) };
3568
+ }
2660
3569
  function parseEditedLocator(page, expression) {
3570
+ debugLocator("EditedSource", { expression });
3571
+ const { base, pick } = applyIndexSuffix(expression);
3572
+ const resolved = resolveLocatorExpression(page, base);
3573
+ return pick ? { locator: pick(resolved.locator), label: resolved.label } : resolved;
3574
+ }
3575
+ function resolveLocatorExpression(page, expression) {
2661
3576
  const roleMatch = expression.match(new RegExp(`^page\\.getByRole\\((${STRING_LITERAL}),\\s*\\{\\s*name:\\s*(${STRING_LITERAL})\\s*\\}\\)$`));
2662
3577
  if (roleMatch) {
2663
3578
  const role = parseStringLiteral(roleMatch[1]);
@@ -2673,6 +3588,7 @@ function parseEditedLocator(page, expression) {
2673
3588
  ["getByLabel", (value) => page.getByLabel(value)],
2674
3589
  ["getByPlaceholder", (value) => page.getByPlaceholder(value)],
2675
3590
  ["getByText", (value) => page.getByText(value)],
3591
+ ["getByTestId", (value) => page.getByTestId(value)],
2676
3592
  ["locator", (value) => page.locator(value)]
2677
3593
  ]) {
2678
3594
  const match = expression.match(new RegExp(`^page\\.${method}\\((${STRING_LITERAL})\\)$`));
@@ -2681,9 +3597,10 @@ function parseEditedLocator(page, expression) {
2681
3597
  return { locator: create(value), label: value };
2682
3598
  }
2683
3599
  }
2684
- throw new Error(`Unsupported Playwright locator: ${expression.slice(0, 120)}`);
3600
+ throw new Error(`Unsupported locator: ${expression.slice(0, 120)}
3601
+ Expected page.getByRole("button", { name: "Login" }), page.getByLabel/getByPlaceholder/getByText/getByTestId("\u2026") or page.locator("css"), optionally followed by .first(), .last() or .nth(n).`);
2685
3602
  }
2686
- async function executeStep(page, step, addLog, secrets) {
3603
+ async function executeStep(page, step, addLog, blockedKeywords, secrets) {
2687
3604
  switch (step.type) {
2688
3605
  case "navigate":
2689
3606
  const checked = checkTargetUrl(step.url, config.urlPolicy);
@@ -2698,7 +3615,7 @@ async function executeStep(page, step, addLog, secrets) {
2698
3615
  case "click": {
2699
3616
  const name = step.target.name ?? step.target.text ?? step.target.cssSelector ?? "target";
2700
3617
  const target = locator(page, step.target);
2701
- await ensureSafeClick(target, name);
3618
+ await ensureSafeClick(target, name, blockedKeywords);
2702
3619
  addLog("info", "Control found: " + name);
2703
3620
  addLog("info", "\u2192 Clicking " + name);
2704
3621
  await target.click();
@@ -2755,6 +3672,12 @@ function resolveSecret(value, projectSecrets) {
2755
3672
  return secret ?? value;
2756
3673
  }
2757
3674
  function locator(page, target) {
3675
+ debugLocator("Resolver", {
3676
+ strategy: target.role && target.name ? "role" : target.label ? "label" : target.placeholder ? "placeholder" : target.text ? "text" : "css",
3677
+ role: target.role,
3678
+ name: target.name,
3679
+ cssSelector: target.cssSelector
3680
+ });
2758
3681
  if (target.role && target.name)
2759
3682
  return page.getByRole(target.role, { name: target.name });
2760
3683
  if (target.label)
@@ -2765,7 +3688,15 @@ function locator(page, target) {
2765
3688
  return page.getByText(target.text);
2766
3689
  return page.locator(target.cssSelector ?? "");
2767
3690
  }
2768
- async function ensureSafeClick(target, fallbackLabel) {
3691
+ function debugLocator(stage, detail) {
3692
+ if (!process.env.LAZYSCOUT_DEBUG_LOCATOR)
3693
+ return;
3694
+ const safe = Object.fromEntries(Object.entries(detail).filter(([, value]) => value !== void 0).map(([key, value]) => [key, typeof value === "string" ? redactSensitiveText(value) : value]));
3695
+ console.log(`[LazyScout:${stage}]`, safe);
3696
+ }
3697
+ async function ensureSafeClick(target, fallbackLabel, blockedKeywords) {
3698
+ if (blockedKeywords.length === 0)
3699
+ return;
2769
3700
  const labels = await Promise.all([
2770
3701
  target.getAttribute("aria-label").catch(() => null),
2771
3702
  target.getAttribute("title").catch(() => null),
@@ -2773,8 +3704,8 @@ async function ensureSafeClick(target, fallbackLabel) {
2773
3704
  target.getAttribute("id").catch(() => null),
2774
3705
  target.innerText().catch(() => "")
2775
3706
  ]);
2776
- if (isDestructiveLabel(fallbackLabel, ...labels.map((value) => value ?? void 0))) {
2777
- throw new Error(`Blocked destructive action: ${fallbackLabel}`);
3707
+ if (isBlockedLabel(blockedKeywords, fallbackLabel, ...labels.map((value) => value ?? void 0))) {
3708
+ throw new Error(`Blocked by the Project click filter: ${fallbackLabel}`);
2778
3709
  }
2779
3710
  }
2780
3711
 
@@ -3206,6 +4137,17 @@ var RecorderSessions = class {
3206
4137
  await this.finish(session);
3207
4138
  return this.state(projectId);
3208
4139
  }
4140
+ /**
4141
+ * Forgets a session once the operator has saved or discarded it, so reopening
4142
+ * the panel starts a fresh recording instead of the previous one.
4143
+ */
4144
+ async discard(projectId) {
4145
+ const session = this.sessions.get(projectId);
4146
+ this.sessions.delete(projectId);
4147
+ if (session)
4148
+ await this.finish(session);
4149
+ return idleRecorderState(projectId);
4150
+ }
3209
4151
  async closeAll() {
3210
4152
  await Promise.all([...this.sessions.values()].map((session) => this.finish(session)));
3211
4153
  this.sessions.clear();
@@ -3253,6 +4195,7 @@ function registerRecorderRoutes(app, workspaceRoot, options = {}) {
3253
4195
  });
3254
4196
  app.get("/api/recorder/:projectId", async (request) => sessions.state(request.params.projectId));
3255
4197
  app.post("/api/recorder/:projectId/stop", async (request, reply) => reply.send(await sessions.stop(request.params.projectId)));
4198
+ app.delete("/api/recorder/:projectId", async (request, reply) => reply.send(await sessions.discard(request.params.projectId)));
3256
4199
  app.addHook("onClose", async () => {
3257
4200
  await sessions.closeAll();
3258
4201
  });
@@ -3268,7 +4211,7 @@ function buildApp(options = {}) {
3268
4211
  const appVersion = options.appVersion ?? process.env.npm_package_version ?? "0.0.0-dev";
3269
4212
  const workspaceRoot = resolveWorkspaceRoot(options.workspaceRoot);
3270
4213
  app.get("/api/health", async () => ({ status: "ok", version: appVersion, workspaceRoot }));
3271
- registerAnalyzeRoute(app);
4214
+ registerAnalyzeRoute(app, workspaceRoot);
3272
4215
  registerExportCsvRoute(app);
3273
4216
  registerAutomationRunRoute(app, workspaceRoot);
3274
4217
  registerApiCheckRunRoute(app);
@@ -3303,7 +4246,7 @@ async function openInBrowser(url) {
3303
4246
  }
3304
4247
 
3305
4248
  // src/version.ts
3306
- var VERSION = true ? "0.3.2" : "0.0.0-dev";
4249
+ var VERSION = true ? "0.3.4" : "0.0.0-dev";
3307
4250
 
3308
4251
  // src/commands/serve.ts
3309
4252
  var DEFAULT_PORT = 4321;
@@ -3356,6 +4299,17 @@ Default: 20
3356
4299
  --max-depth <n> Maximum crawl depth.
3357
4300
  Default: 3
3358
4301
 
4302
+ --start-path <path> Continue exploration from this path after login.
4303
+ Example: /admin/users
4304
+
4305
+ --scope-path <path> Limit exploration to this section.
4306
+ Example: /admin
4307
+
4308
+ --mode <mode> Exploration mode: current-page, scope, site.
4309
+ Default: site
4310
+
4311
+ --debug Show detailed exploration logs.
4312
+
3359
4313
  Web Interface Options
3360
4314
  --port <port> Port used by the LazyScout web interface.
3361
4315
  Default: 4321
@@ -3374,6 +4328,8 @@ npx lazyscout scan http://localhost:5173
3374
4328
 
3375
4329
  npx lazyscout scan https://example.com --max-pages 10 --csv report.csv
3376
4330
 
4331
+ npx lazyscout scan https://example.com --start-path /admin --scope-path /admin --mode scope --debug
4332
+
3377
4333
  Explorer Behavior
3378
4334
  LazyScout only explores URLs within the same origin.
3379
4335
  It follows links and tries a small, safe set of UI controls such as tabs and dialogs.
@@ -3391,7 +4347,11 @@ async function main() {
3391
4347
  "max-depth": { type: "string" },
3392
4348
  port: { type: "string" },
3393
4349
  workspace: { type: "string" },
3394
- "no-open": { type: "boolean", default: false }
4350
+ "no-open": { type: "boolean", default: false },
4351
+ "start-path": { type: "string" },
4352
+ "scope-path": { type: "string" },
4353
+ mode: { type: "string" },
4354
+ debug: { type: "boolean", default: false }
3395
4355
  }
3396
4356
  });
3397
4357
  if (values.version) {
@@ -3419,12 +4379,22 @@ async function main() {
3419
4379
  process.exitCode = 1;
3420
4380
  return;
3421
4381
  }
4382
+ const mode = values.mode;
4383
+ if (mode && mode !== "current-page" && mode !== "scope" && mode !== "site") {
4384
+ console.error(`Invalid mode "${mode}". Use: current-page, scope, or site`);
4385
+ process.exitCode = 1;
4386
+ return;
4387
+ }
3422
4388
  await runScan({
3423
4389
  url,
3424
4390
  csvPath: values.csv,
3425
4391
  jsonPath: values.json,
3426
4392
  maxPages: values["max-pages"] ? Number(values["max-pages"]) : void 0,
3427
- maxDepth: values["max-depth"] ? Number(values["max-depth"]) : void 0
4393
+ maxDepth: values["max-depth"] ? Number(values["max-depth"]) : void 0,
4394
+ startPath: values["start-path"],
4395
+ scopePath: values["scope-path"],
4396
+ mode,
4397
+ debug: values.debug
3428
4398
  });
3429
4399
  return;
3430
4400
  }