browser-debugger-cli 0.6.10 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (260) hide show
  1. package/README.md +10 -0
  2. package/dist/commands/cdp.d.ts.map +1 -1
  3. package/dist/commands/cdp.js +72 -16
  4. package/dist/commands/cdp.js.map +1 -1
  5. package/dist/commands/cleanup.js +1 -1
  6. package/dist/commands/cleanup.js.map +1 -1
  7. package/dist/commands/console.d.ts +4 -28
  8. package/dist/commands/console.d.ts.map +1 -1
  9. package/dist/commands/console.js +81 -187
  10. package/dist/commands/console.js.map +1 -1
  11. package/dist/commands/details.d.ts.map +1 -1
  12. package/dist/commands/details.js +8 -0
  13. package/dist/commands/details.js.map +1 -1
  14. package/dist/commands/dom/DomElementResolver.d.ts +2 -2
  15. package/dist/commands/dom/DomElementResolver.d.ts.map +1 -1
  16. package/dist/commands/dom/DomElementResolver.js +34 -13
  17. package/dist/commands/dom/DomElementResolver.js.map +1 -1
  18. package/dist/commands/dom/__tests__/screenshotResize.unit.test.d.ts +2 -0
  19. package/dist/commands/dom/__tests__/screenshotResize.unit.test.d.ts.map +1 -0
  20. package/dist/commands/dom/__tests__/screenshotResize.unit.test.js +184 -0
  21. package/dist/commands/dom/__tests__/screenshotResize.unit.test.js.map +1 -0
  22. package/dist/commands/dom/a11y.d.ts.map +1 -1
  23. package/dist/commands/dom/a11y.js +14 -10
  24. package/dist/commands/dom/a11y.js.map +1 -1
  25. package/dist/commands/dom/evalHelpers.d.ts.map +1 -1
  26. package/dist/commands/dom/evalHelpers.js +10 -7
  27. package/dist/commands/dom/evalHelpers.js.map +1 -1
  28. package/dist/commands/dom/form.d.ts +14 -0
  29. package/dist/commands/dom/form.d.ts.map +1 -0
  30. package/dist/commands/dom/form.js +439 -0
  31. package/dist/commands/dom/form.js.map +1 -0
  32. package/dist/commands/dom/formDiscovery.d.ts +26 -0
  33. package/dist/commands/dom/formDiscovery.d.ts.map +1 -0
  34. package/dist/commands/dom/formDiscovery.js +476 -0
  35. package/dist/commands/dom/formDiscovery.js.map +1 -0
  36. package/dist/commands/dom/formFillHelpers.d.ts +2 -1
  37. package/dist/commands/dom/formFillHelpers.d.ts.map +1 -1
  38. package/dist/commands/dom/formFillHelpers.js +54 -24
  39. package/dist/commands/dom/formFillHelpers.js.map +1 -1
  40. package/dist/commands/dom/formInteraction.d.ts.map +1 -1
  41. package/dist/commands/dom/formInteraction.js +26 -10
  42. package/dist/commands/dom/formInteraction.js.map +1 -1
  43. package/dist/commands/dom/formSubmitHelpers.d.ts +2 -1
  44. package/dist/commands/dom/formSubmitHelpers.d.ts.map +1 -1
  45. package/dist/commands/dom/formSubmitHelpers.js.map +1 -1
  46. package/dist/commands/dom/formTypes.d.ts +75 -0
  47. package/dist/commands/dom/formTypes.d.ts.map +1 -0
  48. package/dist/commands/dom/formTypes.js +7 -0
  49. package/dist/commands/dom/formTypes.js.map +1 -0
  50. package/dist/commands/dom/helpers.d.ts +11 -4
  51. package/dist/commands/dom/helpers.d.ts.map +1 -1
  52. package/dist/commands/dom/helpers.js +324 -40
  53. package/dist/commands/dom/helpers.js.map +1 -1
  54. package/dist/commands/dom/index.d.ts.map +1 -1
  55. package/dist/commands/dom/index.js +17 -5
  56. package/dist/commands/dom/index.js.map +1 -1
  57. package/dist/commands/dom/reactEventHelpers.d.ts +4 -4
  58. package/dist/commands/dom/reactEventHelpers.d.ts.map +1 -1
  59. package/dist/commands/dom/reactEventHelpers.js +11 -11
  60. package/dist/commands/dom/screenshotResize.d.ts +81 -0
  61. package/dist/commands/dom/screenshotResize.d.ts.map +1 -0
  62. package/dist/commands/dom/screenshotResize.js +103 -0
  63. package/dist/commands/dom/screenshotResize.js.map +1 -0
  64. package/dist/commands/helpJson.d.ts +20 -0
  65. package/dist/commands/helpJson.d.ts.map +1 -1
  66. package/dist/commands/helpJson.js +21 -29
  67. package/dist/commands/helpJson.js.map +1 -1
  68. package/dist/commands/network/har.d.ts.map +1 -1
  69. package/dist/commands/network/har.js +3 -2
  70. package/dist/commands/network/har.js.map +1 -1
  71. package/dist/commands/network/list.d.ts +0 -8
  72. package/dist/commands/network/list.d.ts.map +1 -1
  73. package/dist/commands/network/list.js +131 -201
  74. package/dist/commands/network/list.js.map +1 -1
  75. package/dist/commands/network/shared.d.ts.map +1 -1
  76. package/dist/commands/network/shared.js +6 -0
  77. package/dist/commands/network/shared.js.map +1 -1
  78. package/dist/commands/optionBehaviors.d.ts +26 -0
  79. package/dist/commands/optionBehaviors.d.ts.map +1 -0
  80. package/dist/commands/optionBehaviors.js +195 -0
  81. package/dist/commands/optionBehaviors.js.map +1 -0
  82. package/dist/commands/peek.d.ts +2 -4
  83. package/dist/commands/peek.d.ts.map +1 -1
  84. package/dist/commands/peek.js +108 -92
  85. package/dist/commands/peek.js.map +1 -1
  86. package/dist/commands/shared/CommandRunner.js +1 -1
  87. package/dist/commands/shared/CommandRunner.js.map +1 -1
  88. package/dist/commands/shared/dataFetcher.d.ts +58 -0
  89. package/dist/commands/shared/dataFetcher.d.ts.map +1 -0
  90. package/dist/commands/shared/dataFetcher.js +98 -0
  91. package/dist/commands/shared/dataFetcher.js.map +1 -0
  92. package/dist/commands/shared/optionTypes.d.ts +8 -4
  93. package/dist/commands/shared/optionTypes.d.ts.map +1 -1
  94. package/dist/commands/shared/startHelpers.d.ts.map +1 -1
  95. package/dist/commands/shared/startHelpers.js +6 -5
  96. package/dist/commands/shared/startHelpers.js.map +1 -1
  97. package/dist/commands/shared/validation.d.ts +0 -45
  98. package/dist/commands/shared/validation.d.ts.map +1 -1
  99. package/dist/commands/shared/validation.js +65 -107
  100. package/dist/commands/shared/validation.js.map +1 -1
  101. package/dist/commands/status.d.ts.map +1 -1
  102. package/dist/commands/status.js +13 -4
  103. package/dist/commands/status.js.map +1 -1
  104. package/dist/commands/stop.d.ts.map +1 -1
  105. package/dist/commands/stop.js +15 -4
  106. package/dist/commands/stop.js.map +1 -1
  107. package/dist/commands/tail.d.ts +2 -7
  108. package/dist/commands/tail.d.ts.map +1 -1
  109. package/dist/commands/tail.js +61 -64
  110. package/dist/commands/tail.js.map +1 -1
  111. package/dist/connection/cdp.d.ts.map +1 -1
  112. package/dist/connection/cdp.js +5 -3
  113. package/dist/connection/cdp.js.map +1 -1
  114. package/dist/connection/diagnostics.js +1 -1
  115. package/dist/connection/diagnostics.js.map +1 -1
  116. package/dist/connection/errors.d.ts +0 -7
  117. package/dist/connection/errors.d.ts.map +1 -1
  118. package/dist/connection/errors.js +0 -7
  119. package/dist/connection/errors.js.map +1 -1
  120. package/dist/connection/launcher/binaryResolver.d.ts.map +1 -1
  121. package/dist/connection/launcher/binaryResolver.js +2 -1
  122. package/dist/connection/launcher/binaryResolver.js.map +1 -1
  123. package/dist/connection/launcher/preferencesLoader.d.ts.map +1 -1
  124. package/dist/connection/launcher/preferencesLoader.js +2 -1
  125. package/dist/connection/launcher/preferencesLoader.js.map +1 -1
  126. package/dist/connection/launcher.d.ts.map +1 -1
  127. package/dist/connection/launcher.js +2 -1
  128. package/dist/connection/launcher.js.map +1 -1
  129. package/dist/connection/pageReadiness.d.ts.map +1 -1
  130. package/dist/connection/pageReadiness.js +2 -9
  131. package/dist/connection/pageReadiness.js.map +1 -1
  132. package/dist/daemon/handlers/BaseHandler.d.ts.map +1 -1
  133. package/dist/daemon/handlers/BaseHandler.js +1 -1
  134. package/dist/daemon/handlers/BaseHandler.js.map +1 -1
  135. package/dist/daemon/handlers/QueryHandlers.d.ts.map +1 -1
  136. package/dist/daemon/handlers/QueryHandlers.js +1 -1
  137. package/dist/daemon/handlers/QueryHandlers.js.map +1 -1
  138. package/dist/daemon/handlers/SessionHandlers.d.ts.map +1 -1
  139. package/dist/daemon/handlers/SessionHandlers.js +1 -1
  140. package/dist/daemon/handlers/SessionHandlers.js.map +1 -1
  141. package/dist/daemon/ipcServer.js +1 -1
  142. package/dist/daemon/ipcServer.js.map +1 -1
  143. package/dist/daemon/launcher.d.ts.map +1 -1
  144. package/dist/daemon/launcher.js +3 -2
  145. package/dist/daemon/launcher.js.map +1 -1
  146. package/dist/daemon/lifecycle/signalHandlers.d.ts.map +1 -1
  147. package/dist/daemon/lifecycle/signalHandlers.js +1 -1
  148. package/dist/daemon/lifecycle/signalHandlers.js.map +1 -1
  149. package/dist/daemon/lifecycle/workerCleanup.d.ts.map +1 -1
  150. package/dist/daemon/lifecycle/workerCleanup.js +4 -3
  151. package/dist/daemon/lifecycle/workerCleanup.js.map +1 -1
  152. package/dist/daemon/lifecycle/workerConfig.d.ts.map +1 -1
  153. package/dist/daemon/lifecycle/workerConfig.js +1 -1
  154. package/dist/daemon/lifecycle/workerConfig.js.map +1 -1
  155. package/dist/daemon/lifecycle/workerIpc.d.ts.map +1 -1
  156. package/dist/daemon/lifecycle/workerIpc.js +1 -1
  157. package/dist/daemon/lifecycle/workerIpc.js.map +1 -1
  158. package/dist/daemon/server/JsonlParser.d.ts.map +1 -1
  159. package/dist/daemon/server/JsonlParser.js +1 -1
  160. package/dist/daemon/server/JsonlParser.js.map +1 -1
  161. package/dist/daemon/startSession.d.ts.map +1 -1
  162. package/dist/daemon/startSession.js +1 -1
  163. package/dist/daemon/startSession.js.map +1 -1
  164. package/dist/daemon/worker/plugins.js +3 -3
  165. package/dist/daemon/worker/plugins.js.map +1 -1
  166. package/dist/index.js +23 -7
  167. package/dist/index.js.map +1 -1
  168. package/dist/ipc/protocol/messages.d.ts +2 -2
  169. package/dist/ipc/protocol/messages.d.ts.map +1 -1
  170. package/dist/ipc/utils/errors.js +1 -1
  171. package/dist/ipc/utils/errors.js.map +1 -1
  172. package/dist/session/QueryCacheManager.d.ts.map +1 -1
  173. package/dist/session/QueryCacheManager.js +1 -1
  174. package/dist/session/QueryCacheManager.js.map +1 -1
  175. package/dist/session/chrome.js +1 -1
  176. package/dist/session/chrome.js.map +1 -1
  177. package/dist/session/cleanup.js +5 -5
  178. package/dist/session/cleanup.js.map +1 -1
  179. package/dist/session/lock.js +1 -1
  180. package/dist/session/lock.js.map +1 -1
  181. package/dist/session/metadata.d.ts.map +1 -1
  182. package/dist/session/metadata.js +1 -1
  183. package/dist/session/metadata.js.map +1 -1
  184. package/dist/session/pid.js +1 -1
  185. package/dist/session/pid.js.map +1 -1
  186. package/dist/telemetry/dom.d.ts.map +1 -1
  187. package/dist/telemetry/dom.js +1 -1
  188. package/dist/telemetry/dom.js.map +1 -1
  189. package/dist/telemetry/filterPresets.d.ts.map +1 -1
  190. package/dist/telemetry/filterPresets.js +5 -2
  191. package/dist/telemetry/filterPresets.js.map +1 -1
  192. package/dist/telemetry/network.d.ts.map +1 -1
  193. package/dist/telemetry/network.js +1 -1
  194. package/dist/telemetry/network.js.map +1 -1
  195. package/dist/types.d.ts +217 -1
  196. package/dist/types.d.ts.map +1 -1
  197. package/dist/types.js +33 -1
  198. package/dist/types.js.map +1 -1
  199. package/dist/ui/OutputBuilder.d.ts +2 -44
  200. package/dist/ui/OutputBuilder.d.ts.map +1 -1
  201. package/dist/ui/OutputBuilder.js +71 -103
  202. package/dist/ui/OutputBuilder.js.map +1 -1
  203. package/dist/ui/errors/CommandError.d.ts +0 -2
  204. package/dist/ui/errors/CommandError.d.ts.map +1 -1
  205. package/dist/ui/errors/CommandError.js.map +1 -1
  206. package/dist/ui/formatters/dom.d.ts +8 -19
  207. package/dist/ui/formatters/dom.d.ts.map +1 -1
  208. package/dist/ui/formatters/dom.js +12 -68
  209. package/dist/ui/formatters/dom.js.map +1 -1
  210. package/dist/ui/formatters/form.d.ts +15 -0
  211. package/dist/ui/formatters/form.d.ts.map +1 -0
  212. package/dist/ui/formatters/form.js +314 -0
  213. package/dist/ui/formatters/form.js.map +1 -0
  214. package/dist/ui/logging/logger.d.ts +1 -1
  215. package/dist/ui/logging/logger.d.ts.map +1 -1
  216. package/dist/ui/logging/logger.js +1 -1
  217. package/dist/ui/logging/logger.js.map +1 -1
  218. package/dist/ui/messages/dom.d.ts +14 -0
  219. package/dist/ui/messages/dom.d.ts.map +1 -0
  220. package/dist/ui/messages/dom.js +28 -0
  221. package/dist/ui/messages/dom.js.map +1 -0
  222. package/dist/ui/messages/errors.d.ts +122 -10
  223. package/dist/ui/messages/errors.d.ts.map +1 -1
  224. package/dist/ui/messages/errors.js +280 -11
  225. package/dist/ui/messages/errors.js.map +1 -1
  226. package/dist/utils/__tests__/shellDetection.unit.test.d.ts +12 -0
  227. package/dist/utils/__tests__/shellDetection.unit.test.d.ts.map +1 -0
  228. package/dist/utils/__tests__/shellDetection.unit.test.js +220 -0
  229. package/dist/utils/__tests__/shellDetection.unit.test.js.map +1 -0
  230. package/dist/utils/async.d.ts +10 -0
  231. package/dist/utils/async.d.ts.map +1 -0
  232. package/dist/utils/async.js +12 -0
  233. package/dist/utils/async.js.map +1 -0
  234. package/dist/utils/atomicFile.js +1 -1
  235. package/dist/utils/atomicFile.js.map +1 -1
  236. package/dist/utils/decisionTrees.d.ts.map +1 -1
  237. package/dist/utils/decisionTrees.js +5 -0
  238. package/dist/utils/decisionTrees.js.map +1 -1
  239. package/dist/utils/errorMapping.d.ts.map +1 -1
  240. package/dist/utils/errorMapping.js +4 -1
  241. package/dist/utils/errorMapping.js.map +1 -1
  242. package/dist/utils/exitCodes.d.ts +18 -17
  243. package/dist/utils/exitCodes.d.ts.map +1 -1
  244. package/dist/utils/exitCodes.js +97 -17
  245. package/dist/utils/exitCodes.js.map +1 -1
  246. package/dist/utils/shellDetection.d.ts +34 -0
  247. package/dist/utils/shellDetection.d.ts.map +1 -0
  248. package/dist/utils/shellDetection.js +94 -0
  249. package/dist/utils/shellDetection.js.map +1 -0
  250. package/dist/utils/suggestions.d.ts +19 -0
  251. package/dist/utils/suggestions.d.ts.map +1 -0
  252. package/dist/utils/suggestions.js +34 -0
  253. package/dist/utils/suggestions.js.map +1 -0
  254. package/dist/utils/taskMappings.d.ts.map +1 -1
  255. package/dist/utils/taskMappings.js +40 -0
  256. package/dist/utils/taskMappings.js.map +1 -1
  257. package/dist/utils/url.d.ts.map +1 -1
  258. package/dist/utils/url.js +14 -0
  259. package/dist/utils/url.js.map +1 -1
  260. package/package.json +5 -5
@@ -0,0 +1,476 @@
1
+ /**
2
+ * Form discovery script executed in page context.
3
+ *
4
+ * Discovers forms, extracts semantic labels, detects state and validation,
5
+ * and returns structured data for agent consumption.
6
+ */
7
+ /**
8
+ * Page-context script for form discovery.
9
+ *
10
+ * This script runs in the browser via Runtime.evaluate and discovers:
11
+ * - Native form elements and inputs
12
+ * - Custom components with ARIA roles
13
+ * - Labels via priority chain (label[for], aria-label, placeholder, etc.)
14
+ * - Current values and validation state
15
+ * - Form relevance scoring for multi-form pages
16
+ */
17
+ export const FORM_DISCOVERY_SCRIPT = `
18
+ (function() {
19
+ const result = { forms: [] };
20
+
21
+ function generateSelector(element) {
22
+ if (element.id) {
23
+ return '#' + CSS.escape(element.id);
24
+ }
25
+ if (element.name) {
26
+ const tag = element.tagName.toLowerCase();
27
+ return tag + '[name="' + CSS.escape(element.name) + '"]';
28
+ }
29
+ const tag = element.tagName.toLowerCase();
30
+ const parent = element.parentElement;
31
+ if (!parent) return tag;
32
+ const siblings = Array.from(parent.children).filter(c => c.tagName === element.tagName);
33
+ if (siblings.length === 1) {
34
+ const parentSelector = generateSelector(parent);
35
+ return parentSelector + ' > ' + tag;
36
+ }
37
+ const index = siblings.indexOf(element);
38
+ const parentSelector = generateSelector(parent);
39
+ return parentSelector + ' > ' + tag + ':nth-of-type(' + (index + 1) + ')';
40
+ }
41
+
42
+ function cleanLabelText(text) {
43
+ if (!text) return text;
44
+ const patterns = [
45
+ /Previous\\s*arrow/gi,
46
+ /Next\\s*arrow/gi,
47
+ /\\barrow\\b/gi,
48
+ /\\bchevron\\b/gi,
49
+ /←|→|↑|↓|▲|▼|◀|▶/g,
50
+ /\\u25C0|\\u25B6|\\u25B2|\\u25BC/g,
51
+ /Previous|Next|Back|Forward/gi,
52
+ /^\\s*[<>]\\s*/,
53
+ /\\s*[<>]\\s*$/,
54
+ ];
55
+ let cleaned = text;
56
+ for (const pattern of patterns) {
57
+ cleaned = cleaned.replace(pattern, '');
58
+ }
59
+ cleaned = cleaned.replace(/\\s{2,}/g, ' ').trim();
60
+ return cleaned || text.trim();
61
+ }
62
+
63
+ function extractLabel(element) {
64
+ if (element.id) {
65
+ const labelFor = document.querySelector('label[for="' + CSS.escape(element.id) + '"]');
66
+ if (labelFor) return cleanLabelText(labelFor.textContent);
67
+ }
68
+ const ariaLabel = element.getAttribute('aria-label');
69
+ if (ariaLabel) return cleanLabelText(ariaLabel);
70
+ const ariaLabelledBy = element.getAttribute('aria-labelledby');
71
+ if (ariaLabelledBy) {
72
+ const labelEl = document.getElementById(ariaLabelledBy);
73
+ if (labelEl) return cleanLabelText(labelEl.textContent);
74
+ }
75
+ const wrappingLabel = element.closest('label');
76
+ if (wrappingLabel) {
77
+ const clone = wrappingLabel.cloneNode(true);
78
+ const inputs = clone.querySelectorAll('input, select, textarea, button');
79
+ inputs.forEach(i => i.remove());
80
+ const text = clone.textContent.trim();
81
+ if (text) return cleanLabelText(text);
82
+ }
83
+ if (element.placeholder) return cleanLabelText(element.placeholder);
84
+ const title = element.getAttribute('title');
85
+ if (title) return cleanLabelText(title);
86
+ if (element.name) {
87
+ return element.name
88
+ .replace(/[_-]/g, ' ')
89
+ .replace(/([a-z])([A-Z])/g, '$1 $2')
90
+ .replace(/^./, s => s.toUpperCase());
91
+ }
92
+ return 'Unlabeled field';
93
+ }
94
+
95
+ function extractButtonLabel(element) {
96
+ const ariaLabel = element.getAttribute('aria-label');
97
+ if (ariaLabel) return ariaLabel.trim();
98
+ if (element.value && element.type !== 'submit') return element.value;
99
+ const text = element.textContent.trim();
100
+ if (text) return text;
101
+ if (element.value) return element.value;
102
+ const title = element.getAttribute('title');
103
+ if (title) return title;
104
+ return 'Button';
105
+ }
106
+
107
+ function getFieldValue(element) {
108
+ const tag = element.tagName.toLowerCase();
109
+ const type = element.type?.toLowerCase() || 'text';
110
+ if (tag === 'select') {
111
+ if (element.multiple) {
112
+ return Array.from(element.selectedOptions).map(o => o.value);
113
+ }
114
+ return element.value;
115
+ }
116
+ if (type === 'checkbox' || type === 'radio') {
117
+ return element.checked;
118
+ }
119
+ if (element.getAttribute('role') === 'checkbox' || element.getAttribute('role') === 'switch') {
120
+ return element.getAttribute('aria-checked') === 'true';
121
+ }
122
+ if (element.isContentEditable) {
123
+ return element.textContent || '';
124
+ }
125
+ return element.value || '';
126
+ }
127
+
128
+ function getFieldState(element, value) {
129
+ const type = element.type?.toLowerCase() || 'text';
130
+ if (type === 'checkbox' || element.getAttribute('role') === 'checkbox' || element.getAttribute('role') === 'switch') {
131
+ return value ? 'checked' : 'unchecked';
132
+ }
133
+ if (type === 'radio') {
134
+ return value ? 'checked' : 'unchecked';
135
+ }
136
+ if (Array.isArray(value)) {
137
+ return value.length > 0 ? 'filled' : 'empty';
138
+ }
139
+ if (typeof value === 'string') {
140
+ return value.length > 0 ? 'filled' : 'empty';
141
+ }
142
+ return 'empty';
143
+ }
144
+
145
+ function getFieldType(element) {
146
+ const tag = element.tagName.toLowerCase();
147
+ const role = element.getAttribute('role');
148
+ if (role === 'textbox') return 'textbox';
149
+ if (role === 'checkbox') return 'checkbox';
150
+ if (role === 'radio') return 'radio';
151
+ if (role === 'combobox') return 'combobox';
152
+ if (role === 'listbox') return 'listbox';
153
+ if (role === 'switch') return 'switch';
154
+ if (element.isContentEditable) return 'contenteditable';
155
+ if (tag === 'textarea') return 'textarea';
156
+ if (tag === 'select') return 'select';
157
+ if (tag === 'input') {
158
+ const type = element.type?.toLowerCase() || 'text';
159
+ return type;
160
+ }
161
+ return 'unknown';
162
+ }
163
+
164
+ function isNativeInput(element) {
165
+ const tag = element.tagName.toLowerCase();
166
+ return tag === 'input' || tag === 'textarea' || tag === 'select';
167
+ }
168
+
169
+ function getSelectOptions(element) {
170
+ if (element.tagName.toLowerCase() !== 'select') return undefined;
171
+ return Array.from(element.options).map(opt => ({
172
+ value: opt.value,
173
+ label: opt.textContent.trim(),
174
+ selected: opt.selected
175
+ }));
176
+ }
177
+
178
+ function findSiblingError(element) {
179
+ const next = element.nextElementSibling;
180
+ if (next) {
181
+ const isError = next.classList.contains('error') ||
182
+ next.classList.contains('invalid') ||
183
+ next.classList.contains('field-error') ||
184
+ next.classList.contains('error-message') ||
185
+ next.getAttribute('role') === 'alert';
186
+ if (isError) return next.textContent.trim();
187
+ }
188
+ const parent = element.parentElement;
189
+ if (parent) {
190
+ const errorEl = parent.querySelector('.error-message, .field-error, [role="alert"]');
191
+ if (errorEl && errorEl !== element) return errorEl.textContent.trim();
192
+ }
193
+ return undefined;
194
+ }
195
+
196
+ function calculateRelevance(formEl, fields, buttons) {
197
+ let score = 0;
198
+ const rect = formEl.getBoundingClientRect();
199
+ const viewportHeight = window.innerHeight;
200
+ const viewportWidth = window.innerWidth;
201
+ const centerX = rect.left + rect.width / 2;
202
+ const centerY = rect.top + rect.height / 2;
203
+ if (centerX > viewportWidth * 0.2 && centerX < viewportWidth * 0.8) score += 10;
204
+ if (centerY > 0 && centerY < viewportHeight) score += 5;
205
+ const isInMain = formEl.closest('main, [role="main"], article, .main-content, #main');
206
+ if (isInMain) score += 15;
207
+ const isInHeader = formEl.closest('header, [role="banner"], nav, [role="navigation"]');
208
+ if (isInHeader) score -= 10;
209
+ const isInAside = formEl.closest('aside, [role="complementary"], footer, [role="contentinfo"]');
210
+ if (isInAside) score -= 5;
211
+ score += Math.min(fields.length * 3, 30);
212
+ const hasSubmit = buttons.some(b => b.type === 'submit' || b.isPrimary);
213
+ if (hasSubmit) score += 10;
214
+ const style = window.getComputedStyle(formEl);
215
+ if (style.display === 'none' || style.visibility === 'hidden') score -= 100;
216
+ return score;
217
+ }
218
+
219
+ function detectFormStep(formEl) {
220
+ const stepIndicators = formEl.querySelectorAll('[aria-current="step"], .step.active, .wizard-step.current');
221
+ if (stepIndicators.length === 0) {
222
+ const pageSteps = document.querySelectorAll('.step, .wizard-step, [role="tablist"] [role="tab"]');
223
+ if (pageSteps.length > 1) {
224
+ const activeIndex = Array.from(pageSteps).findIndex(s =>
225
+ s.classList.contains('active') ||
226
+ s.classList.contains('current') ||
227
+ s.getAttribute('aria-selected') === 'true'
228
+ );
229
+ if (activeIndex >= 0) {
230
+ return { current: activeIndex + 1, total: pageSteps.length };
231
+ }
232
+ }
233
+ }
234
+ const ariaStep = formEl.querySelector('[aria-current="step"]');
235
+ if (ariaStep) {
236
+ const allSteps = formEl.querySelectorAll('[role="listitem"], .step');
237
+ const currentIdx = Array.from(allSteps).indexOf(ariaStep);
238
+ if (currentIdx >= 0) {
239
+ return { current: currentIdx + 1, total: allSteps.length };
240
+ }
241
+ }
242
+ return null;
243
+ }
244
+
245
+ function findNearbyHeading(formEl) {
246
+ let sibling = formEl.previousElementSibling;
247
+ let distance = 0;
248
+ while (sibling && distance < 3) {
249
+ if (sibling.matches('h1, h2, h3, h4, h5, h6, [role="heading"]')) {
250
+ return sibling.textContent.trim();
251
+ }
252
+ const heading = sibling.querySelector('h1, h2, h3, h4, h5, h6, [role="heading"]');
253
+ if (heading) return heading.textContent.trim();
254
+ sibling = sibling.previousElementSibling;
255
+ distance++;
256
+ }
257
+ const parent = formEl.parentElement;
258
+ if (parent) {
259
+ const heading = parent.querySelector(':scope > h1, :scope > h2, :scope > h3');
260
+ if (heading && heading.compareDocumentPosition(formEl) & Node.DOCUMENT_POSITION_FOLLOWING) {
261
+ return heading.textContent.trim();
262
+ }
263
+ }
264
+ return null;
265
+ }
266
+
267
+ function matchesWord(text, word) {
268
+ const pattern = new RegExp('\\\\b' + word + '\\\\b', 'i');
269
+ return pattern.test(text);
270
+ }
271
+
272
+ function inferFormType(formEl) {
273
+ const inputs = formEl.querySelectorAll('input, textarea, select');
274
+ const types = Array.from(inputs).map(i => i.type?.toLowerCase() || i.tagName.toLowerCase());
275
+ const names = Array.from(inputs).map(i => (i.name || '').toLowerCase());
276
+ const allText = (Array.from(inputs).map(i => i.name + ' ' + i.placeholder + ' ' + i.id).join(' ')).toLowerCase();
277
+ if (types.includes('password')) {
278
+ if (types.filter(t => t === 'password').length >= 2) return 'Change Password';
279
+ if (matchesWord(allText, 'register') || matchesWord(allText, 'signup') || matchesWord(allText, 'create')) return 'Registration';
280
+ return 'Login';
281
+ }
282
+ const hasSearchRole = formEl.closest('[role="search"]') || formEl.getAttribute('role') === 'search';
283
+ const hasSearchInput = formEl.querySelector('[type="search"], [aria-label*="search" i]');
284
+ if (hasSearchRole || hasSearchInput) return 'Search';
285
+ const interactiveTypes = types.filter(t => !['hidden', 'submit', 'button', 'reset', 'image'].includes(t));
286
+ if (interactiveTypes.length <= 2 && matchesWord(allText, 'search')) return 'Search';
287
+ if (matchesWord(allText, 'address') || matchesWord(allText, 'street') || matchesWord(allText, 'postcode') ||
288
+ matchesWord(allText, 'zipcode') || matchesWord(allText, 'city') || matchesWord(allText, 'county')) {
289
+ return 'Address';
290
+ }
291
+ if (matchesWord(allText, 'email') && (matchesWord(allText, 'message') || matchesWord(allText, 'subject'))) {
292
+ return 'Contact';
293
+ }
294
+ if (matchesWord(allText, 'card') || matchesWord(allText, 'cvv') || matchesWord(allText, 'expiry')) {
295
+ return 'Payment';
296
+ }
297
+ if (names.some(n => matchesWord(n, 'subscribe') || matchesWord(n, 'newsletter'))) {
298
+ return 'Newsletter';
299
+ }
300
+ return null;
301
+ }
302
+
303
+ function extractFormName(formEl) {
304
+ const ariaLabel = formEl.getAttribute('aria-label');
305
+ if (ariaLabel) return ariaLabel;
306
+ const ariaLabelledBy = formEl.getAttribute('aria-labelledby');
307
+ if (ariaLabelledBy) {
308
+ const labelEl = document.getElementById(ariaLabelledBy);
309
+ if (labelEl) return labelEl.textContent.trim();
310
+ }
311
+ const headings = formEl.querySelectorAll('h1, h2, h3, h4, h5, h6, [role="heading"]');
312
+ for (const h of headings) {
313
+ if (!h.closest('[role="dialog"], [role="alertdialog"], [aria-modal="true"]')) {
314
+ return h.textContent.trim();
315
+ }
316
+ }
317
+ const legend = formEl.querySelector('legend');
318
+ if (legend) return legend.textContent.trim();
319
+ const title = formEl.getAttribute('title');
320
+ if (title) return title;
321
+ const name = formEl.getAttribute('name');
322
+ if (name) {
323
+ return name
324
+ .replace(/[_-]/g, ' ')
325
+ .replace(/([a-z])([A-Z])/g, '$1 $2')
326
+ .replace(/^./, s => s.toUpperCase());
327
+ }
328
+ const nearbyHeading = findNearbyHeading(formEl);
329
+ if (nearbyHeading) return nearbyHeading;
330
+ const inferredType = inferFormType(formEl);
331
+ if (inferredType) return inferredType;
332
+ return null;
333
+ }
334
+
335
+ function discoverFields(container, formIndex, startIndex) {
336
+ const fields = [];
337
+ const nativeInputs = container.querySelectorAll(
338
+ 'input:not([type="hidden"]):not([type="submit"]):not([type="button"]):not([type="reset"]):not([type="image"]), ' +
339
+ 'textarea, ' +
340
+ 'select'
341
+ );
342
+ const customInputs = container.querySelectorAll(
343
+ '[role="textbox"], ' +
344
+ '[role="checkbox"]:not(input), ' +
345
+ '[role="radio"]:not(input), ' +
346
+ '[role="combobox"], ' +
347
+ '[role="listbox"], ' +
348
+ '[role="switch"], ' +
349
+ '[contenteditable="true"]'
350
+ );
351
+ const allInputs = new Set([...nativeInputs, ...customInputs]);
352
+ let idx = startIndex;
353
+ for (const el of allInputs) {
354
+ const style = window.getComputedStyle(el);
355
+ const isHidden = style.display === 'none' || style.visibility === 'hidden' || el.type === 'hidden';
356
+ const value = getFieldValue(el);
357
+ fields.push({
358
+ index: idx,
359
+ formIndex: formIndex,
360
+ selector: generateSelector(el),
361
+ type: getFieldType(el),
362
+ inputType: el.type?.toLowerCase(),
363
+ label: extractLabel(el),
364
+ name: el.name || null,
365
+ placeholder: el.placeholder || undefined,
366
+ required: el.required || el.getAttribute('aria-required') === 'true',
367
+ disabled: el.disabled || el.getAttribute('aria-disabled') === 'true',
368
+ readOnly: el.readOnly || false,
369
+ hidden: isHidden,
370
+ native: isNativeInput(el),
371
+ value: value,
372
+ checked: el.checked,
373
+ validationMessage: el.validationMessage || undefined,
374
+ isValid: el.checkValidity ? el.checkValidity() : true,
375
+ ariaInvalid: el.getAttribute('aria-invalid') === 'true',
376
+ hasErrorClass: el.classList.contains('error') || el.classList.contains('invalid'),
377
+ siblingErrorText: findSiblingError(el),
378
+ options: getSelectOptions(el)
379
+ });
380
+ idx++;
381
+ }
382
+ return fields;
383
+ }
384
+
385
+ function discoverButtons(container, startIndex) {
386
+ const buttons = [];
387
+ const buttonEls = container.querySelectorAll(
388
+ 'button, ' +
389
+ 'input[type="submit"], ' +
390
+ 'input[type="button"], ' +
391
+ 'input[type="reset"], ' +
392
+ '[role="button"]'
393
+ );
394
+ let idx = startIndex;
395
+ for (const el of buttonEls) {
396
+ const style = window.getComputedStyle(el);
397
+ if (style.display === 'none' || style.visibility === 'hidden') continue;
398
+ const type = el.type?.toLowerCase() || 'button';
399
+ const btnType = type === 'submit' ? 'submit' : type === 'reset' ? 'reset' : 'button';
400
+ const isPrimary = btnType === 'submit' ||
401
+ el.classList.contains('primary') ||
402
+ el.classList.contains('btn-primary') ||
403
+ el.classList.contains('submit');
404
+ buttons.push({
405
+ index: idx,
406
+ selector: generateSelector(el),
407
+ label: extractButtonLabel(el),
408
+ type: btnType,
409
+ disabled: el.disabled || el.getAttribute('aria-disabled') === 'true',
410
+ isPrimary: isPrimary
411
+ });
412
+ idx++;
413
+ }
414
+ return buttons;
415
+ }
416
+
417
+ const forms = document.querySelectorAll('form');
418
+ let globalIndex = 0;
419
+
420
+ if (forms.length === 0) {
421
+ const bodyFields = discoverFields(document.body, 0, 0);
422
+ const bodyButtons = discoverButtons(document.body, bodyFields.length);
423
+ if (bodyFields.length > 0) {
424
+ result.forms.push({
425
+ index: 0,
426
+ name: document.title || 'Page',
427
+ action: null,
428
+ method: 'GET',
429
+ step: null,
430
+ relevanceScore: bodyFields.length * 3,
431
+ inIframe: false,
432
+ fields: bodyFields,
433
+ buttons: bodyButtons
434
+ });
435
+ }
436
+ } else {
437
+ for (let i = 0; i < forms.length; i++) {
438
+ const formEl = forms[i];
439
+ const fields = discoverFields(formEl, i, globalIndex);
440
+ globalIndex += fields.length;
441
+ const buttons = discoverButtons(formEl, globalIndex);
442
+ globalIndex += buttons.length;
443
+ const inIframe = formEl.ownerDocument !== document;
444
+ result.forms.push({
445
+ index: i,
446
+ name: extractFormName(formEl),
447
+ action: formEl.action || null,
448
+ method: (formEl.method || 'GET').toUpperCase(),
449
+ step: detectFormStep(formEl),
450
+ relevanceScore: calculateRelevance(formEl, fields, buttons),
451
+ inIframe: inIframe,
452
+ fields: fields,
453
+ buttons: buttons
454
+ });
455
+ }
456
+ }
457
+
458
+ result.forms.sort((a, b) => b.relevanceScore - a.relevanceScore);
459
+
460
+ return result;
461
+ })()
462
+ `;
463
+ /**
464
+ * Type guard for raw form data.
465
+ *
466
+ * @param value - Unknown value to check
467
+ * @returns True if value matches RawFormData structure
468
+ */
469
+ export function isRawFormData(value) {
470
+ if (typeof value !== 'object' || value === null) {
471
+ return false;
472
+ }
473
+ const obj = value;
474
+ return Array.isArray(obj['forms']);
475
+ }
476
+ //# sourceMappingURL=formDiscovery.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"formDiscovery.js","sourceRoot":"","sources":["../../../src/commands/dom/formDiscovery.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAIH;;;;;;;;;GASG;AACH,MAAM,CAAC,MAAM,qBAAqB,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA6bpC,CAAC;AAEF;;;;;GAKG;AACH,MAAM,UAAU,aAAa,CAAC,KAAc;IAC1C,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,EAAE,CAAC;QAChD,OAAO,KAAK,CAAC;IACf,CAAC;IACD,MAAM,GAAG,GAAG,KAAgC,CAAC;IAC7C,OAAO,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC;AACrC,CAAC"}
@@ -65,7 +65,7 @@ export declare function waitForActionStability(cdp: CDPConnection): Promise<void
65
65
  * Options for pressing a key on an element.
66
66
  */
67
67
  export interface PressKeyOptions {
68
- /** Element index if selector matches multiple (1-based) */
68
+ /** Element index if selector matches multiple (0-based) */
69
69
  index?: number;
70
70
  /** Number of times to press the key (default: 1) */
71
71
  times?: number;
@@ -83,6 +83,7 @@ export interface PressKeyResult {
83
83
  times?: number;
84
84
  modifiers?: number;
85
85
  elementType?: string | undefined;
86
+ suggestion?: string;
86
87
  }
87
88
  /**
88
89
  * Press a key on an element.
@@ -1 +1 @@
1
- {"version":3,"file":"formFillHelpers.d.ts","sourceRoot":"","sources":["../../../src/commands/dom/formFillHelpers.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAOzD,OAAO,EAKL,KAAK,WAAW,EAChB,KAAK,UAAU,EACf,KAAK,WAAW,EACjB,MAAM,wBAAwB,CAAC;AA8ChC;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAsB,WAAW,CAC/B,GAAG,EAAE,aAAa,EAClB,QAAQ,EAAE,MAAM,EAChB,KAAK,EAAE,MAAM,EACb,OAAO,GAAE,WAAgB,GACxB,OAAO,CAAC,UAAU,CAAC,CAiDrB;AAED;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAsB,YAAY,CAChC,GAAG,EAAE,aAAa,EAClB,QAAQ,EAAE,MAAM,EAChB,OAAO,GAAE;IAAE,KAAK,CAAC,EAAE,MAAM,CAAA;CAAO,GAC/B,OAAO,CAAC,WAAW,CAAC,CA6CtB;AA8BD;;;;;;;;;;;;;;;GAeG;AACH,wBAAsB,sBAAsB,CAAC,GAAG,EAAE,aAAa,GAAG,OAAO,CAAC,IAAI,CAAC,CA2C9E;AAWD;;GAEG;AACH,MAAM,WAAW,eAAe;IAC9B,2DAA2D;IAC3D,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,oDAAoD;IACpD,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,6DAA6D;IAC7D,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB;AAED;;GAEG;AACH,MAAM,WAAW,cAAc;IAC7B,OAAO,EAAE,OAAO,CAAC;IACjB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,WAAW,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;CAClC;AAqCD;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,wBAAsB,eAAe,CACnC,GAAG,EAAE,aAAa,EAClB,QAAQ,EAAE,MAAM,EAChB,OAAO,EAAE,MAAM,EACf,OAAO,GAAE,eAAoB,GAC5B,OAAO,CAAC,cAAc,CAAC,CAwEzB"}
1
+ {"version":3,"file":"formFillHelpers.d.ts","sourceRoot":"","sources":["../../../src/commands/dom/formFillHelpers.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAgBzD,OAAO,EAKL,KAAK,WAAW,EAChB,KAAK,UAAU,EACf,KAAK,WAAW,EACjB,MAAM,wBAAwB,CAAC;AA8EhC;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAsB,WAAW,CAC/B,GAAG,EAAE,aAAa,EAClB,QAAQ,EAAE,MAAM,EAChB,KAAK,EAAE,MAAM,EACb,OAAO,GAAE,WAAgB,GACxB,OAAO,CAAC,UAAU,CAAC,CAiDrB;AAED;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAsB,YAAY,CAChC,GAAG,EAAE,aAAa,EAClB,QAAQ,EAAE,MAAM,EAChB,OAAO,GAAE;IAAE,KAAK,CAAC,EAAE,MAAM,CAAA;CAAO,GAC/B,OAAO,CAAC,WAAW,CAAC,CA6CtB;AA8BD;;;;;;;;;;;;;;;GAeG;AACH,wBAAsB,sBAAsB,CAAC,GAAG,EAAE,aAAa,GAAG,OAAO,CAAC,IAAI,CAAC,CA2C9E;AAED;;GAEG;AACH,MAAM,WAAW,eAAe;IAC9B,2DAA2D;IAC3D,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,oDAAoD;IACpD,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,6DAA6D;IAC7D,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB;AAED;;GAEG;AACH,MAAM,WAAW,cAAc;IAC7B,OAAO,EAAE,OAAO,CAAC;IACjB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,WAAW,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IACjC,UAAU,CAAC,EAAE,MAAM,CAAC;CACrB;AAqCD;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,wBAAsB,eAAe,CACnC,GAAG,EAAE,aAAa,EAClB,QAAQ,EAAE,MAAM,EAChB,OAAO,EAAE,MAAM,EACf,OAAO,GAAE,eAAoB,GAC5B,OAAO,CAAC,cAAc,CAAC,CAsEzB"}
@@ -3,7 +3,10 @@
3
3
  */
4
4
  import { CommandError } from '../../ui/errors/index.js';
5
5
  import { createLogger } from '../../ui/logging/index.js';
6
+ import { fillableElementNotFoundError, clickableElementNotFoundError, keyPressFailedError, unexpectedResponseFormatError, operationFailedError, } from '../../ui/messages/errors.js';
7
+ import { delay } from '../../utils/async.js';
6
8
  import { EXIT_CODES } from '../../utils/exitCodes.js';
9
+ import { detectSelectorQuoteDamage } from '../../utils/shellDetection.js';
7
10
  import { getKeyDefinition, parseModifiers } from './keyMapping.js';
8
11
  import { REACT_FILL_SCRIPT, CLICK_ELEMENT_SCRIPT, isFillResult, isClickResult, } from './reactEventHelpers.js';
9
12
  const log = createLogger('dom');
@@ -16,16 +19,40 @@ const STABILITY_CHECK_INTERVAL_MS = 50;
16
19
  /**
17
20
  * Format exception details into a user-friendly error message with troubleshooting hints.
18
21
  *
22
+ * Shows the actual expression sent to CDP to help diagnose escaping issues.
23
+ * Detects shell quote damage patterns and provides specific recovery suggestions.
24
+ *
19
25
  * @param exceptionDetails - CDP exception details
20
26
  * @param selector - CSS selector that was used
21
27
  * @param operationType - Type of operation (fill or click) for tailored hints
28
+ * @param expression - The actual JavaScript expression sent to CDP
22
29
  * @returns Formatted error message with context
23
30
  */
24
- function formatScriptExecutionError(exceptionDetails, selector, operationType = 'fill') {
31
+ function formatScriptExecutionError(exceptionDetails, selector, operationType = 'fill', expression) {
25
32
  const errorText = exceptionDetails.text || 'Unknown error';
26
33
  const location = exceptionDetails.lineNumber !== undefined && exceptionDetails.columnNumber !== undefined
27
34
  ? ` at line ${exceptionDetails.lineNumber + 1}, column ${exceptionDetails.columnNumber + 1}`
28
35
  : '';
36
+ const lines = [];
37
+ lines.push(`Script execution failed: ${errorText}${location}`);
38
+ if (expression) {
39
+ const truncated = expression.length > 150 ? expression.slice(0, 150) + '...' : expression;
40
+ lines.push('');
41
+ lines.push(`Expression received: ${truncated}`);
42
+ const selectorCheck = detectSelectorQuoteDamage(selector);
43
+ if (selectorCheck.damaged) {
44
+ lines.push('');
45
+ lines.push('Shell quote damage detected in selector:');
46
+ if (selectorCheck.details) {
47
+ lines.push(` ${selectorCheck.details}`);
48
+ }
49
+ lines.push('');
50
+ lines.push('Try using the two-step pattern:');
51
+ lines.push(` 1. bdg dom query '${selector}'`);
52
+ lines.push(` 2. bdg dom ${operationType} 0${operationType === 'fill' ? ' "value"' : ''}`);
53
+ return lines.join('\n');
54
+ }
55
+ }
29
56
  const troubleshootingSteps = operationType === 'fill'
30
57
  ? [
31
58
  `1. Verify element exists: bdg dom query "${selector}"`,
@@ -37,7 +64,10 @@ function formatScriptExecutionError(exceptionDetails, selector, operationType =
37
64
  '2. Check element is visible and clickable',
38
65
  `3. Try direct eval: bdg dom eval "document.querySelector('${escapeSelectorForJS(selector)}').click()"`,
39
66
  ];
40
- return `Script execution failed: ${errorText}${location}\n\nTroubleshooting:\n ${troubleshootingSteps.join('\n ')}`;
67
+ lines.push('');
68
+ lines.push('Troubleshooting:');
69
+ lines.push(` ${troubleshootingSteps.join('\n ')}`);
70
+ return lines.join('\n');
41
71
  }
42
72
  /**
43
73
  * Fill a form element with a value in a React-compatible way.
@@ -72,20 +102,23 @@ export async function fillElement(cdp, selector, value, options = {}) {
72
102
  });
73
103
  const cdpResponse = response;
74
104
  if (cdpResponse.exceptionDetails) {
75
- const errorMessage = formatScriptExecutionError(cdpResponse.exceptionDetails, selector, 'fill');
76
- throw new CommandError(errorMessage, {}, EXIT_CODES.SOFTWARE_ERROR);
105
+ const errorMessage = formatScriptExecutionError(cdpResponse.exceptionDetails, selector, 'fill', expression);
106
+ const err = fillableElementNotFoundError(selector);
107
+ throw new CommandError(errorMessage, { suggestion: err.suggestion }, EXIT_CODES.SOFTWARE_ERROR);
77
108
  }
78
109
  if (cdpResponse.result?.value && isFillResult(cdpResponse.result.value)) {
79
110
  return cdpResponse.result.value;
80
111
  }
81
- throw new CommandError('Unexpected response format', { note: 'CDP response missing result.value or invalid FillResult structure' }, EXIT_CODES.SOFTWARE_ERROR);
112
+ const err = unexpectedResponseFormatError('FillResult');
113
+ throw new CommandError(err.message, { suggestion: err.suggestion }, EXIT_CODES.SOFTWARE_ERROR);
82
114
  }
83
115
  catch (error) {
84
116
  if (error instanceof CommandError) {
85
117
  throw error;
86
118
  }
87
119
  const errorMessage = error instanceof Error ? error.message : String(error);
88
- throw new CommandError('Failed to fill element', { note: errorMessage }, EXIT_CODES.SOFTWARE_ERROR);
120
+ const err = operationFailedError('fill element', errorMessage);
121
+ throw new CommandError(err.message, { suggestion: err.suggestion }, EXIT_CODES.SOFTWARE_ERROR);
89
122
  }
90
123
  }
91
124
  /**
@@ -117,20 +150,23 @@ export async function clickElement(cdp, selector, options = {}) {
117
150
  });
118
151
  const cdpResponse = response;
119
152
  if (cdpResponse.exceptionDetails) {
120
- const errorMessage = formatScriptExecutionError(cdpResponse.exceptionDetails, selector, 'click');
121
- throw new CommandError(errorMessage, {}, EXIT_CODES.SOFTWARE_ERROR);
153
+ const errorMessage = formatScriptExecutionError(cdpResponse.exceptionDetails, selector, 'click', expression);
154
+ const err = clickableElementNotFoundError(selector);
155
+ throw new CommandError(errorMessage, { suggestion: err.suggestion }, EXIT_CODES.SOFTWARE_ERROR);
122
156
  }
123
157
  if (cdpResponse.result?.value && isClickResult(cdpResponse.result.value)) {
124
158
  return cdpResponse.result.value;
125
159
  }
126
- throw new CommandError('Unexpected response format', { note: 'CDP response missing result.value or invalid ClickResult structure' }, EXIT_CODES.SOFTWARE_ERROR);
160
+ const err = unexpectedResponseFormatError('ClickResult');
161
+ throw new CommandError(err.message, { suggestion: err.suggestion }, EXIT_CODES.SOFTWARE_ERROR);
127
162
  }
128
163
  catch (error) {
129
164
  if (error instanceof CommandError) {
130
165
  throw error;
131
166
  }
132
167
  const errorMessage = error instanceof Error ? error.message : String(error);
133
- throw new CommandError('Failed to click element', { note: errorMessage }, EXIT_CODES.SOFTWARE_ERROR);
168
+ const err = operationFailedError('click element', errorMessage);
169
+ throw new CommandError(err.message, { suggestion: err.suggestion }, EXIT_CODES.SOFTWARE_ERROR);
134
170
  }
135
171
  }
136
172
  /**
@@ -212,14 +248,6 @@ export async function waitForActionStability(cdp) {
212
248
  cleanupFailed();
213
249
  }
214
250
  }
215
- /**
216
- * Delay utility.
217
- *
218
- * @param ms - Milliseconds to delay
219
- */
220
- function delay(ms) {
221
- return new Promise((resolve) => setTimeout(resolve, ms));
222
- }
223
251
  /**
224
252
  * Script to focus an element by selector and optional index.
225
253
  *
@@ -233,14 +261,14 @@ const FOCUS_ELEMENT_SCRIPT = `
233
261
  }
234
262
 
235
263
  let el;
236
- if (typeof index === 'number' && index > 0) {
237
- if (index > allMatches.length) {
264
+ if (typeof index === 'number' && index >= 0) {
265
+ if (index >= allMatches.length) {
238
266
  return {
239
267
  success: false,
240
- error: 'Index ' + index + ' out of range (found ' + allMatches.length + ' nodes)'
268
+ error: 'Index ' + index + ' out of range (found ' + allMatches.length + ' nodes, use 0-' + (allMatches.length - 1) + ')'
241
269
  };
242
270
  }
243
- el = allMatches[index - 1];
271
+ el = allMatches[index];
244
272
  } else {
245
273
  el = allMatches[0];
246
274
  }
@@ -298,7 +326,8 @@ export async function pressKeyElement(cdp, selector, keyName, options = {}) {
298
326
  });
299
327
  const focusCdpResponse = focusResponse;
300
328
  if (focusCdpResponse.exceptionDetails) {
301
- throw new CommandError(`Failed to focus element: ${focusCdpResponse.exceptionDetails.text}`, { note: `Selector: ${selector}` }, EXIT_CODES.SOFTWARE_ERROR);
329
+ const err = keyPressFailedError(`focus: ${focusCdpResponse.exceptionDetails.text}`);
330
+ throw new CommandError(err.message, { suggestion: err.suggestion }, EXIT_CODES.SOFTWARE_ERROR);
302
331
  }
303
332
  const focusResult = focusCdpResponse.result?.value;
304
333
  if (!focusResult?.success) {
@@ -327,7 +356,8 @@ export async function pressKeyElement(cdp, selector, keyName, options = {}) {
327
356
  throw error;
328
357
  }
329
358
  const errorMessage = error instanceof Error ? error.message : String(error);
330
- throw new CommandError('Failed to press key', { note: errorMessage }, EXIT_CODES.SOFTWARE_ERROR);
359
+ const err = operationFailedError('press key', errorMessage);
360
+ throw new CommandError(err.message, { suggestion: err.suggestion }, EXIT_CODES.SOFTWARE_ERROR);
331
361
  }
332
362
  }
333
363
  /**