@qontinui/ui-bridge 0.1.1 → 0.3.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 (112) hide show
  1. package/dist/ai/index.d.mts +893 -0
  2. package/dist/ai/index.d.ts +893 -0
  3. package/dist/ai/index.js +3897 -0
  4. package/dist/ai/index.js.map +1 -0
  5. package/dist/ai/index.mjs +3839 -0
  6. package/dist/ai/index.mjs.map +1 -0
  7. package/dist/babel-plugin/index.js +515 -0
  8. package/dist/babel-plugin/index.js.map +1 -0
  9. package/dist/babel-plugin/index.mjs +499 -0
  10. package/dist/babel-plugin/index.mjs.map +1 -0
  11. package/dist/control/index.d.mts +5 -4
  12. package/dist/control/index.d.ts +5 -4
  13. package/dist/core/index.d.mts +115 -42
  14. package/dist/core/index.d.ts +115 -42
  15. package/dist/core/index.js +0 -983
  16. package/dist/core/index.js.map +1 -1
  17. package/dist/core/index.mjs +1 -972
  18. package/dist/core/index.mjs.map +1 -1
  19. package/dist/debug/index.d.mts +3 -3
  20. package/dist/debug/index.d.ts +3 -3
  21. package/dist/index.d.mts +8 -7
  22. package/dist/index.d.ts +8 -7
  23. package/dist/index.js +8249 -4163
  24. package/dist/index.js.map +1 -1
  25. package/dist/index.mjs +8193 -4152
  26. package/dist/index.mjs.map +1 -1
  27. package/dist/{metrics-QCnK0EFw.d.ts → metrics-BfiT_rhZ.d.ts} +2 -2
  28. package/dist/{metrics-BCG7z7Aq.d.mts → metrics-DTA2bwG7.d.mts} +2 -2
  29. package/dist/native/control/index.js +453 -0
  30. package/dist/native/control/index.js.map +1 -0
  31. package/dist/native/control/index.mjs +450 -0
  32. package/dist/native/control/index.mjs.map +1 -0
  33. package/dist/native/core/index.js +486 -0
  34. package/dist/native/core/index.js.map +1 -0
  35. package/dist/native/core/index.mjs +475 -0
  36. package/dist/native/core/index.mjs.map +1 -0
  37. package/dist/native/debug/index.js +451 -0
  38. package/dist/native/debug/index.js.map +1 -0
  39. package/dist/native/debug/index.mjs +449 -0
  40. package/dist/native/debug/index.mjs.map +1 -0
  41. package/dist/native/index.js +2274 -0
  42. package/dist/native/index.js.map +1 -0
  43. package/dist/native/index.mjs +2246 -0
  44. package/dist/native/index.mjs.map +1 -0
  45. package/dist/native/react/index.js +1401 -0
  46. package/dist/native/react/index.js.map +1 -0
  47. package/dist/native/react/index.mjs +1389 -0
  48. package/dist/native/react/index.mjs.map +1 -0
  49. package/dist/native/server/index.js +415 -0
  50. package/dist/native/server/index.js.map +1 -0
  51. package/dist/native/server/index.mjs +410 -0
  52. package/dist/native/server/index.mjs.map +1 -0
  53. package/dist/react/index.d.mts +20 -6
  54. package/dist/react/index.d.ts +20 -6
  55. package/dist/react/index.js +629 -14
  56. package/dist/react/index.js.map +1 -1
  57. package/dist/react/index.mjs +629 -14
  58. package/dist/react/index.mjs.map +1 -1
  59. package/dist/{registry-CT6BVVKr.d.mts → registry-BKLEm-yk.d.ts} +29 -14
  60. package/dist/{registry-D4mQ01B3.d.ts → registry-BmZgyCz8.d.mts} +29 -14
  61. package/dist/render-log/index.d.mts +1 -1
  62. package/dist/render-log/index.d.ts +1 -1
  63. package/dist/server/express.d.mts +36 -0
  64. package/dist/server/express.d.ts +36 -0
  65. package/dist/server/express.js +196 -0
  66. package/dist/server/express.js.map +1 -0
  67. package/dist/server/express.mjs +192 -0
  68. package/dist/server/express.mjs.map +1 -0
  69. package/dist/server/handlers.d.mts +93 -0
  70. package/dist/server/handlers.d.ts +93 -0
  71. package/dist/server/handlers.js +4278 -0
  72. package/dist/server/handlers.js.map +1 -0
  73. package/dist/server/handlers.mjs +4275 -0
  74. package/dist/server/handlers.mjs.map +1 -0
  75. package/dist/server/index.d.mts +10 -0
  76. package/dist/server/index.d.ts +10 -0
  77. package/dist/server/index.js +5352 -0
  78. package/dist/server/index.js.map +1 -0
  79. package/dist/server/index.mjs +5337 -0
  80. package/dist/server/index.mjs.map +1 -0
  81. package/dist/server/nextjs.d.mts +126 -0
  82. package/dist/server/nextjs.d.ts +126 -0
  83. package/dist/server/nextjs.js +287 -0
  84. package/dist/server/nextjs.js.map +1 -0
  85. package/dist/server/nextjs.mjs +282 -0
  86. package/dist/server/nextjs.mjs.map +1 -0
  87. package/dist/server/standalone.d.mts +6 -0
  88. package/dist/server/standalone.d.ts +6 -0
  89. package/dist/server/standalone.js +719 -0
  90. package/dist/server/standalone.js.map +1 -0
  91. package/dist/server/standalone.mjs +715 -0
  92. package/dist/server/standalone.mjs.map +1 -0
  93. package/dist/standalone-BURj8J3G.d.ts +212 -0
  94. package/dist/standalone-Dwmel29d.d.mts +212 -0
  95. package/dist/swc-plugin/index.d.mts +79 -0
  96. package/dist/swc-plugin/index.d.ts +79 -0
  97. package/dist/swc-plugin/index.js +15 -0
  98. package/dist/swc-plugin/index.js.map +1 -0
  99. package/dist/swc-plugin/index.mjs +9 -0
  100. package/dist/swc-plugin/index.mjs.map +1 -0
  101. package/dist/types-B5Q0GVo0.d.mts +646 -0
  102. package/dist/{types-DdJD9yw5.d.mts → types-B7J7noLK.d.mts} +1 -1
  103. package/dist/{types-BDkXy5si.d.ts → types-BkNRILUa.d.ts} +1 -1
  104. package/dist/types-CEQLnFMv.d.mts +156 -0
  105. package/dist/types-CHnlwiTK.d.ts +156 -0
  106. package/dist/types-DfPqwU-i.d.ts +646 -0
  107. package/dist/{types-BpvpStn3.d.mts → types-jKVgTI6_.d.mts} +364 -160
  108. package/dist/{types-BpvpStn3.d.ts → types-jKVgTI6_.d.ts} +364 -160
  109. package/package.json +111 -3
  110. package/swc-plugin-wasm/ui_bridge_swc_plugin.wasm +0 -0
  111. package/dist/websocket-client-B2LC9CYc.d.mts +0 -124
  112. package/dist/websocket-client-DupH0X7B.d.ts +0 -124
@@ -0,0 +1,3839 @@
1
+ // src/ai/fuzzy-matcher.ts
2
+ var DEFAULT_FUZZY_CONFIG = {
3
+ threshold: 0.7,
4
+ levenshteinWeight: 0.3,
5
+ jaroWinklerWeight: 0.4,
6
+ ngramWeight: 0.3,
7
+ ngramSize: 2,
8
+ caseSensitive: false,
9
+ ignoreWhitespace: true
10
+ };
11
+ function levenshteinDistance(s1, s2) {
12
+ const len1 = s1.length;
13
+ const len2 = s2.length;
14
+ const matrix = Array(len1 + 1).fill(null).map(() => Array(len2 + 1).fill(0));
15
+ for (let i = 0; i <= len1; i++) matrix[i][0] = i;
16
+ for (let j = 0; j <= len2; j++) matrix[0][j] = j;
17
+ for (let i = 1; i <= len1; i++) {
18
+ for (let j = 1; j <= len2; j++) {
19
+ const cost = s1[i - 1] === s2[j - 1] ? 0 : 1;
20
+ matrix[i][j] = Math.min(
21
+ matrix[i - 1][j] + 1,
22
+ // deletion
23
+ matrix[i][j - 1] + 1,
24
+ // insertion
25
+ matrix[i - 1][j - 1] + cost
26
+ // substitution
27
+ );
28
+ }
29
+ }
30
+ return matrix[len1][len2];
31
+ }
32
+ function levenshteinSimilarity(s1, s2) {
33
+ if (s1.length === 0 && s2.length === 0) return 1;
34
+ if (s1.length === 0 || s2.length === 0) return 0;
35
+ const distance = levenshteinDistance(s1, s2);
36
+ const maxLength = Math.max(s1.length, s2.length);
37
+ return 1 - distance / maxLength;
38
+ }
39
+ function jaroSimilarity(s1, s2) {
40
+ if (s1.length === 0 && s2.length === 0) return 1;
41
+ if (s1.length === 0 || s2.length === 0) return 0;
42
+ const matchDistance = Math.floor(Math.max(s1.length, s2.length) / 2) - 1;
43
+ const s1Matches = new Array(s1.length).fill(false);
44
+ const s2Matches = new Array(s2.length).fill(false);
45
+ let matches = 0;
46
+ let transpositions = 0;
47
+ for (let i = 0; i < s1.length; i++) {
48
+ const start = Math.max(0, i - matchDistance);
49
+ const end = Math.min(i + matchDistance + 1, s2.length);
50
+ for (let j = start; j < end; j++) {
51
+ if (s2Matches[j] || s1[i] !== s2[j]) continue;
52
+ s1Matches[i] = true;
53
+ s2Matches[j] = true;
54
+ matches++;
55
+ break;
56
+ }
57
+ }
58
+ if (matches === 0) return 0;
59
+ let k = 0;
60
+ for (let i = 0; i < s1.length; i++) {
61
+ if (!s1Matches[i]) continue;
62
+ while (!s2Matches[k]) k++;
63
+ if (s1[i] !== s2[k]) transpositions++;
64
+ k++;
65
+ }
66
+ return (matches / s1.length + matches / s2.length + (matches - transpositions / 2) / matches) / 3;
67
+ }
68
+ function jaroWinklerSimilarity(s1, s2, prefixScale = 0.1) {
69
+ const jaroSim = jaroSimilarity(s1, s2);
70
+ let prefixLength = 0;
71
+ const maxPrefix = Math.min(4, Math.min(s1.length, s2.length));
72
+ for (let i = 0; i < maxPrefix; i++) {
73
+ if (s1[i] === s2[i]) {
74
+ prefixLength++;
75
+ } else {
76
+ break;
77
+ }
78
+ }
79
+ return jaroSim + prefixLength * prefixScale * (1 - jaroSim);
80
+ }
81
+ function generateNgrams(s, n) {
82
+ const ngrams = /* @__PURE__ */ new Set();
83
+ if (s.length < n) {
84
+ ngrams.add(s);
85
+ return ngrams;
86
+ }
87
+ for (let i = 0; i <= s.length - n; i++) {
88
+ ngrams.add(s.substring(i, i + n));
89
+ }
90
+ return ngrams;
91
+ }
92
+ function ngramSimilarity(s1, s2, n = 2) {
93
+ if (s1.length === 0 && s2.length === 0) return 1;
94
+ if (s1.length === 0 || s2.length === 0) return 0;
95
+ const ngrams1 = generateNgrams(s1, n);
96
+ const ngrams2 = generateNgrams(s2, n);
97
+ let intersection = 0;
98
+ for (const ngram of ngrams1) {
99
+ if (ngrams2.has(ngram)) {
100
+ intersection++;
101
+ }
102
+ }
103
+ const union = ngrams1.size + ngrams2.size - intersection;
104
+ return union === 0 ? 0 : intersection / union;
105
+ }
106
+ function normalizeString(s, config = {}) {
107
+ let normalized = s;
108
+ if (!config.caseSensitive) {
109
+ normalized = normalized.toLowerCase();
110
+ }
111
+ if (config.ignoreWhitespace !== false) {
112
+ normalized = normalized.replace(/\s+/g, " ").trim();
113
+ }
114
+ return normalized;
115
+ }
116
+ function fuzzyMatch(source, target, config = {}) {
117
+ const finalConfig = { ...DEFAULT_FUZZY_CONFIG, ...config };
118
+ const normalizedSource = normalizeString(source, finalConfig);
119
+ const normalizedTarget = normalizeString(target, finalConfig);
120
+ const levenshteinScore = levenshteinSimilarity(normalizedSource, normalizedTarget);
121
+ const jaroWinklerScore = jaroWinklerSimilarity(normalizedSource, normalizedTarget);
122
+ const ngramScore = ngramSimilarity(normalizedSource, normalizedTarget, finalConfig.ngramSize);
123
+ const similarity = levenshteinScore * finalConfig.levenshteinWeight + jaroWinklerScore * finalConfig.jaroWinklerWeight + ngramScore * finalConfig.ngramWeight;
124
+ return {
125
+ similarity,
126
+ isMatch: similarity >= finalConfig.threshold,
127
+ scores: {
128
+ levenshtein: levenshteinScore,
129
+ jaroWinkler: jaroWinklerScore,
130
+ ngram: ngramScore
131
+ },
132
+ normalizedSource,
133
+ normalizedTarget
134
+ };
135
+ }
136
+ function findBestMatch(source, candidates, config = {}) {
137
+ if (candidates.length === 0) {
138
+ return { match: null, index: -1, result: null };
139
+ }
140
+ let bestMatch = null;
141
+ let bestIndex = -1;
142
+ let bestResult = null;
143
+ for (let i = 0; i < candidates.length; i++) {
144
+ const result = fuzzyMatch(source, candidates[i], config);
145
+ if (result.isMatch && (!bestResult || result.similarity > bestResult.similarity)) {
146
+ bestMatch = candidates[i];
147
+ bestIndex = i;
148
+ bestResult = result;
149
+ }
150
+ }
151
+ return { match: bestMatch, index: bestIndex, result: bestResult };
152
+ }
153
+ function findAllMatches(source, candidates, config = {}) {
154
+ const matches = [];
155
+ for (let i = 0; i < candidates.length; i++) {
156
+ const result = fuzzyMatch(source, candidates[i], config);
157
+ if (result.isMatch) {
158
+ matches.push({ candidate: candidates[i], index: i, result });
159
+ }
160
+ }
161
+ matches.sort((a, b) => b.result.similarity - a.result.similarity);
162
+ return matches;
163
+ }
164
+ function fuzzyContains(source, target, config = {}) {
165
+ const finalConfig = { ...DEFAULT_FUZZY_CONFIG, ...config };
166
+ const normalizedSource = normalizeString(source, finalConfig);
167
+ const normalizedTarget = normalizeString(target, finalConfig);
168
+ if (normalizedSource.includes(normalizedTarget)) {
169
+ return true;
170
+ }
171
+ const sourceWords = normalizedSource.split(/\s+/);
172
+ const targetWords = normalizedTarget.split(/\s+/);
173
+ for (const targetWord of targetWords) {
174
+ const hasMatch = sourceWords.some((sourceWord) => {
175
+ const result = fuzzyMatch(sourceWord, targetWord, { ...finalConfig, threshold: 0.8 });
176
+ return result.isMatch;
177
+ });
178
+ if (!hasMatch) {
179
+ return false;
180
+ }
181
+ }
182
+ return true;
183
+ }
184
+ function wordSimilarity(s1, s2, config = {}) {
185
+ const finalConfig = { ...DEFAULT_FUZZY_CONFIG, ...config };
186
+ const words1 = normalizeString(s1, finalConfig).split(/\s+/);
187
+ const words2 = normalizeString(s2, finalConfig).split(/\s+/);
188
+ if (words1.length === 0 && words2.length === 0) return 1;
189
+ if (words1.length === 0 || words2.length === 0) return 0;
190
+ let totalSimilarity = 0;
191
+ let matchCount = 0;
192
+ for (const word1 of words1) {
193
+ let bestSim = 0;
194
+ for (const word2 of words2) {
195
+ const result = fuzzyMatch(word1, word2, finalConfig);
196
+ if (result.similarity > bestSim) {
197
+ bestSim = result.similarity;
198
+ }
199
+ }
200
+ totalSimilarity += bestSim;
201
+ if (bestSim >= finalConfig.threshold) {
202
+ matchCount++;
203
+ }
204
+ }
205
+ const avgSimilarity = totalSimilarity / words1.length;
206
+ const matchRatio = matchCount / Math.max(words1.length, words2.length);
207
+ return avgSimilarity * 0.5 + matchRatio * 0.5;
208
+ }
209
+ function tokenize(s) {
210
+ return s.replace(/([a-z])([A-Z])/g, "$1 $2").replace(/[_-]/g, " ").replace(/\s+/g, " ").trim().toLowerCase().split(" ").filter((token) => token.length > 0);
211
+ }
212
+ function tokenSimilarity(s1, s2) {
213
+ const tokens1 = tokenize(s1);
214
+ const tokens2 = tokenize(s2);
215
+ if (tokens1.length === 0 && tokens2.length === 0) return 1;
216
+ if (tokens1.length === 0 || tokens2.length === 0) return 0;
217
+ const set1 = new Set(tokens1);
218
+ const set2 = new Set(tokens2);
219
+ let intersection = 0;
220
+ for (const token of set1) {
221
+ if (set2.has(token)) {
222
+ intersection++;
223
+ }
224
+ }
225
+ const union = set1.size + set2.size - intersection;
226
+ return union === 0 ? 0 : intersection / union;
227
+ }
228
+
229
+ // src/ai/alias-generator.ts
230
+ var DEFAULT_ALIAS_CONFIG = {
231
+ includeText: true,
232
+ includeAriaLabel: true,
233
+ includePlaceholder: true,
234
+ includeTitle: true,
235
+ includeSynonyms: true,
236
+ maxAliases: 20,
237
+ minLength: 2,
238
+ maxLength: 50
239
+ };
240
+ var SYNONYMS = {
241
+ // Submit-related
242
+ submit: ["send", "go", "confirm", "ok", "apply", "save", "done", "finish"],
243
+ send: ["submit", "deliver", "post"],
244
+ save: ["submit", "store", "keep", "apply"],
245
+ cancel: ["close", "dismiss", "abort", "back", "exit", "quit", "nevermind"],
246
+ close: ["cancel", "dismiss", "exit", "x"],
247
+ delete: ["remove", "trash", "erase", "clear", "destroy"],
248
+ remove: ["delete", "clear", "discard"],
249
+ edit: ["modify", "change", "update", "alter"],
250
+ update: ["edit", "modify", "save", "refresh"],
251
+ add: ["create", "new", "plus", "insert"],
252
+ create: ["add", "new", "make"],
253
+ search: ["find", "lookup", "query", "filter"],
254
+ find: ["search", "locate", "lookup"],
255
+ login: ["signin", "sign in", "log in", "authenticate", "enter"],
256
+ logout: ["signout", "sign out", "log out", "exit"],
257
+ register: ["signup", "sign up", "join", "create account"],
258
+ next: ["continue", "forward", "proceed", "advance"],
259
+ previous: ["back", "backward", "return", "prior"],
260
+ back: ["previous", "return", "backward"],
261
+ start: ["begin", "launch", "initiate", "run", "execute"],
262
+ stop: ["end", "halt", "pause", "terminate"],
263
+ enable: ["activate", "turn on", "switch on"],
264
+ disable: ["deactivate", "turn off", "switch off"],
265
+ show: ["display", "reveal", "view", "open"],
266
+ hide: ["conceal", "collapse", "close"],
267
+ expand: ["open", "show", "unfold", "reveal"],
268
+ collapse: ["close", "hide", "fold", "minimize"],
269
+ yes: ["ok", "confirm", "agree", "accept"],
270
+ no: ["cancel", "decline", "reject", "deny"],
271
+ help: ["support", "assistance", "info", "information", "faq"],
272
+ settings: ["preferences", "options", "config", "configuration"],
273
+ profile: ["account", "user", "me"],
274
+ download: ["export", "save", "get"],
275
+ upload: ["import", "load", "attach"],
276
+ refresh: ["reload", "update", "sync"],
277
+ copy: ["duplicate", "clone"],
278
+ paste: ["insert"],
279
+ select: ["choose", "pick"],
280
+ toggle: ["switch", "flip"],
281
+ // Form fields
282
+ email: ["e-mail", "mail"],
283
+ password: ["pass", "pwd", "secret"],
284
+ username: ["user", "login", "account", "name"],
285
+ firstname: ["first name", "given name", "forename"],
286
+ lastname: ["last name", "surname", "family name"],
287
+ fullname: ["full name", "name", "complete name"],
288
+ phone: ["telephone", "tel", "mobile", "cell"],
289
+ address: ["location", "street"],
290
+ city: ["town"],
291
+ country: ["nation"],
292
+ zip: ["zipcode", "postal", "postal code", "postcode"],
293
+ // Navigation
294
+ home: ["main", "start", "dashboard"],
295
+ menu: ["navigation", "nav"],
296
+ sidebar: ["side bar", "side panel", "side menu"]
297
+ };
298
+ var ELEMENT_ACTION_WORDS = {
299
+ button: ["button", "btn", "click"],
300
+ input: ["input", "field", "textbox", "box"],
301
+ textarea: ["textarea", "text area", "text field", "multiline"],
302
+ select: ["select", "dropdown", "combo", "picker", "chooser"],
303
+ checkbox: ["checkbox", "check", "tick"],
304
+ radio: ["radio", "option", "choice"],
305
+ link: ["link", "anchor", "href"],
306
+ form: ["form"],
307
+ menu: ["menu"],
308
+ menuitem: ["menu item", "option"],
309
+ tab: ["tab"],
310
+ dialog: ["dialog", "modal", "popup"],
311
+ switch: ["switch", "toggle"],
312
+ slider: ["slider", "range"]
313
+ };
314
+ function normalizeAlias(text) {
315
+ return text.toLowerCase().replace(/[^\w\s]/g, " ").replace(/\s+/g, " ").trim();
316
+ }
317
+ function extractWords(text) {
318
+ const tokens = tokenize(text);
319
+ return tokens.filter((t) => t.length >= 2);
320
+ }
321
+ function generateTextAliases(text, config) {
322
+ if (!text || !config.includeText) return [];
323
+ const aliases = [];
324
+ const normalized = normalizeAlias(text);
325
+ if (normalized.length >= config.minLength && normalized.length <= config.maxLength) {
326
+ aliases.push(normalized);
327
+ }
328
+ const words = extractWords(text);
329
+ for (const word of words) {
330
+ if (word.length >= config.minLength) {
331
+ aliases.push(word);
332
+ }
333
+ }
334
+ if (words.length >= 2 && words.length <= 4) {
335
+ const twoWords = words.slice(0, 2).join(" ");
336
+ if (twoWords.length <= config.maxLength) {
337
+ aliases.push(twoWords);
338
+ }
339
+ if (words.length > 2) {
340
+ const lastTwo = words.slice(-2).join(" ");
341
+ if (lastTwo.length <= config.maxLength) {
342
+ aliases.push(lastTwo);
343
+ }
344
+ }
345
+ }
346
+ return aliases;
347
+ }
348
+ function generateSynonyms(aliases, config) {
349
+ if (!config.includeSynonyms) return [];
350
+ const synonyms = [];
351
+ for (const alias of aliases) {
352
+ const words = alias.toLowerCase().split(/\s+/);
353
+ for (const word of words) {
354
+ if (SYNONYMS[word]) {
355
+ for (const synonym of SYNONYMS[word]) {
356
+ const newAlias = alias.toLowerCase().replace(word, synonym);
357
+ if (newAlias !== alias.toLowerCase()) {
358
+ synonyms.push(newAlias);
359
+ }
360
+ if (synonym.length >= config.minLength) {
361
+ synonyms.push(synonym);
362
+ }
363
+ }
364
+ }
365
+ }
366
+ }
367
+ return synonyms;
368
+ }
369
+ function generateTypeAliases(elementType) {
370
+ const type = elementType.toLowerCase();
371
+ return ELEMENT_ACTION_WORDS[type] || [type];
372
+ }
373
+ function generateAliases(input, config = {}) {
374
+ const finalConfig = { ...DEFAULT_ALIAS_CONFIG, ...config };
375
+ const aliasSet = /* @__PURE__ */ new Set();
376
+ const addAlias = (alias) => {
377
+ const normalized = normalizeAlias(alias);
378
+ if (normalized.length >= finalConfig.minLength && normalized.length <= finalConfig.maxLength) {
379
+ aliasSet.add(normalized);
380
+ }
381
+ };
382
+ const addAliases = (aliases2) => {
383
+ for (const alias of aliases2) {
384
+ addAlias(alias);
385
+ }
386
+ };
387
+ if (finalConfig.includeText && input.textContent) {
388
+ addAliases(generateTextAliases(input.textContent, finalConfig));
389
+ }
390
+ if (finalConfig.includeAriaLabel && input.ariaLabel) {
391
+ addAliases(generateTextAliases(input.ariaLabel, finalConfig));
392
+ }
393
+ if (finalConfig.includeAriaLabel && input.ariaLabelledBy) {
394
+ addAliases(generateTextAliases(input.ariaLabelledBy, finalConfig));
395
+ }
396
+ if (finalConfig.includePlaceholder && input.placeholder) {
397
+ addAliases(generateTextAliases(input.placeholder, finalConfig));
398
+ }
399
+ if (finalConfig.includeTitle && input.title) {
400
+ addAliases(generateTextAliases(input.title, finalConfig));
401
+ }
402
+ if (input.labelText) {
403
+ addAliases(generateTextAliases(input.labelText, finalConfig));
404
+ }
405
+ if (input.id) {
406
+ addAliases(extractWords(input.id));
407
+ }
408
+ if (input.name) {
409
+ addAliases(extractWords(input.name));
410
+ }
411
+ if (input.value && (input.elementType === "button" || input.inputType === "submit" || input.inputType === "button")) {
412
+ addAliases(generateTextAliases(input.value, finalConfig));
413
+ }
414
+ if (input.elementType) {
415
+ addAliases(generateTypeAliases(input.elementType));
416
+ }
417
+ if (input.inputType) {
418
+ addAlias(input.inputType);
419
+ if (input.inputType === "email") {
420
+ addAliases(["email", "e-mail", "email address"]);
421
+ } else if (input.inputType === "password") {
422
+ addAliases(["password", "pass", "pwd"]);
423
+ } else if (input.inputType === "tel") {
424
+ addAliases(["phone", "telephone", "mobile"]);
425
+ } else if (input.inputType === "url") {
426
+ addAliases(["url", "website", "link", "address"]);
427
+ } else if (input.inputType === "search") {
428
+ addAliases(["search", "find", "query"]);
429
+ }
430
+ }
431
+ if (finalConfig.includeSynonyms) {
432
+ const currentAliases = Array.from(aliasSet);
433
+ addAliases(generateSynonyms(currentAliases, finalConfig));
434
+ }
435
+ let aliases = Array.from(aliasSet);
436
+ aliases.sort((a, b) => a.length - b.length);
437
+ if (aliases.length > finalConfig.maxAliases) {
438
+ aliases = aliases.slice(0, finalConfig.maxAliases);
439
+ }
440
+ return aliases;
441
+ }
442
+ function generateDescription(input) {
443
+ const parts = [];
444
+ let name = input.ariaLabel || input.labelText || input.textContent || input.placeholder || input.title || input.id || input.name;
445
+ if (name) {
446
+ name = name.trim();
447
+ if (name.length > 30) {
448
+ name = name.substring(0, 27) + "...";
449
+ }
450
+ parts.push(`"${name}"`);
451
+ }
452
+ const typeWords = ELEMENT_ACTION_WORDS[input.elementType || ""] || [input.elementType || "element"];
453
+ parts.push(typeWords[0]);
454
+ if (input.inputType && input.inputType !== "text") {
455
+ parts.push(`(${input.inputType})`);
456
+ }
457
+ return parts.join(" ");
458
+ }
459
+ function generatePurpose(input) {
460
+ const text = (input.textContent || input.ariaLabel || input.title || "").toLowerCase();
461
+ const type = input.elementType?.toLowerCase() || "";
462
+ const inputType = input.inputType?.toLowerCase() || "";
463
+ if (type === "button" || inputType === "submit") {
464
+ if (text.match(/submit|send|save|confirm|ok|done|finish|apply/)) {
465
+ return "Submits the form";
466
+ }
467
+ if (text.match(/cancel|close|dismiss|back|exit/)) {
468
+ return "Cancels or closes the current action";
469
+ }
470
+ if (text.match(/delete|remove|trash|clear/)) {
471
+ return "Deletes or removes an item";
472
+ }
473
+ if (text.match(/edit|modify|change|update/)) {
474
+ return "Edits or modifies an item";
475
+ }
476
+ if (text.match(/add|create|new|\+/)) {
477
+ return "Creates or adds a new item";
478
+ }
479
+ if (text.match(/search|find|lookup/)) {
480
+ return "Performs a search";
481
+ }
482
+ if (text.match(/login|sign.?in/)) {
483
+ return "Signs the user in";
484
+ }
485
+ if (text.match(/logout|sign.?out/)) {
486
+ return "Signs the user out";
487
+ }
488
+ if (text.match(/register|sign.?up|join/)) {
489
+ return "Creates a new account";
490
+ }
491
+ if (text.match(/next|continue|proceed/)) {
492
+ return "Proceeds to the next step";
493
+ }
494
+ if (text.match(/previous|back|return/)) {
495
+ return "Returns to the previous step";
496
+ }
497
+ }
498
+ if (type === "input" || type === "textarea") {
499
+ if (inputType === "email") return "Accepts email address input";
500
+ if (inputType === "password") return "Accepts password input";
501
+ if (inputType === "search") return "Accepts search query input";
502
+ if (inputType === "tel") return "Accepts phone number input";
503
+ if (inputType === "url") return "Accepts URL input";
504
+ if (inputType === "number") return "Accepts numeric input";
505
+ if (inputType === "date") return "Accepts date input";
506
+ if (inputType === "file") return "Accepts file upload";
507
+ }
508
+ if (type === "checkbox") {
509
+ return "Toggles an option on or off";
510
+ }
511
+ if (type === "radio") {
512
+ return "Selects one option from a group";
513
+ }
514
+ if (type === "select") {
515
+ return "Selects an option from a dropdown";
516
+ }
517
+ if (type === "link") {
518
+ return "Navigates to another page";
519
+ }
520
+ return void 0;
521
+ }
522
+ function generateSuggestedActions(input) {
523
+ const type = input.elementType?.toLowerCase() || "";
524
+ const inputType = input.inputType?.toLowerCase() || "";
525
+ const text = (input.textContent || input.ariaLabel || "").toLowerCase();
526
+ const actions = [];
527
+ switch (type) {
528
+ case "button":
529
+ actions.push(`click "${text || "this button"}"`);
530
+ break;
531
+ case "input":
532
+ if (inputType === "checkbox") {
533
+ actions.push("check to enable", "uncheck to disable");
534
+ } else if (inputType === "radio") {
535
+ actions.push("select this option");
536
+ } else {
537
+ actions.push(`type into "${text || "this field"}"`);
538
+ actions.push("clear the field");
539
+ }
540
+ break;
541
+ case "textarea":
542
+ actions.push(`type into "${text || "this text area"}"`);
543
+ actions.push("clear the content");
544
+ break;
545
+ case "select":
546
+ actions.push(`select an option from "${text || "this dropdown"}"`);
547
+ break;
548
+ case "checkbox":
549
+ actions.push("check to enable", "uncheck to disable");
550
+ break;
551
+ case "radio":
552
+ actions.push("select this option");
553
+ break;
554
+ case "link":
555
+ actions.push(`click to navigate to "${text || "the linked page"}"`);
556
+ break;
557
+ case "switch":
558
+ actions.push("toggle on", "toggle off");
559
+ break;
560
+ default:
561
+ actions.push("click");
562
+ }
563
+ return actions;
564
+ }
565
+ function getSynonyms(word) {
566
+ const normalized = word.toLowerCase().trim();
567
+ return SYNONYMS[normalized] || [];
568
+ }
569
+ function areSynonyms(word1, word2) {
570
+ const w1 = word1.toLowerCase().trim();
571
+ const w2 = word2.toLowerCase().trim();
572
+ if (w1 === w2) return true;
573
+ const synonyms1 = SYNONYMS[w1] || [];
574
+ const synonyms2 = SYNONYMS[w2] || [];
575
+ return synonyms1.includes(w2) || synonyms2.includes(w1);
576
+ }
577
+
578
+ // src/ai/search-engine.ts
579
+ var DEFAULT_SEARCH_CONFIG = {
580
+ fuzzyThreshold: 0.7,
581
+ textWeight: 0.35,
582
+ accessibilityWeight: 0.25,
583
+ roleWeight: 0.15,
584
+ spatialWeight: 0.1,
585
+ aliasWeight: 0.15,
586
+ maxResults: 20,
587
+ includeHidden: false
588
+ };
589
+ var SearchEngine = class {
590
+ // Cache valid for 100ms
591
+ constructor(config = {}) {
592
+ this.cachedElements = [];
593
+ this.cacheTimestamp = 0;
594
+ this.cacheValidityMs = 100;
595
+ this.config = { ...DEFAULT_SEARCH_CONFIG, ...config };
596
+ }
597
+ /**
598
+ * Update cached elements from various sources
599
+ */
600
+ updateElements(elements, getState) {
601
+ this.cachedElements = elements.map((el) => this.toSearchable(el, getState));
602
+ this.cacheTimestamp = Date.now();
603
+ }
604
+ /**
605
+ * Convert an element to searchable format
606
+ */
607
+ toSearchable(element, getState) {
608
+ let state;
609
+ let textContent;
610
+ let tagName;
611
+ let role;
612
+ let ariaLabel;
613
+ let placeholder;
614
+ let title;
615
+ let labelText;
616
+ let value;
617
+ if ("getState" in element && typeof element.getState === "function") {
618
+ state = getState ? getState(element) : element.getState();
619
+ textContent = state.textContent || void 0;
620
+ tagName = element.element.tagName.toLowerCase();
621
+ role = element.element.getAttribute("role") || void 0;
622
+ ariaLabel = element.element.getAttribute("aria-label") || void 0;
623
+ placeholder = element.element.getAttribute("placeholder") || void 0;
624
+ title = element.element.getAttribute("title") || void 0;
625
+ if (element.element.id) {
626
+ const labelEl = document.querySelector(`label[for="${element.element.id}"]`);
627
+ labelText = labelEl?.textContent?.trim() || void 0;
628
+ }
629
+ if (element.element instanceof HTMLInputElement || element.element instanceof HTMLTextAreaElement || element.element instanceof HTMLSelectElement) {
630
+ value = element.element.value || void 0;
631
+ }
632
+ } else {
633
+ const discovered = element;
634
+ state = discovered.state;
635
+ textContent = state.textContent || void 0;
636
+ tagName = discovered.tagName;
637
+ role = discovered.role || void 0;
638
+ ariaLabel = discovered.accessibleName || void 0;
639
+ }
640
+ const aliases = generateAliases({
641
+ textContent,
642
+ ariaLabel,
643
+ placeholder,
644
+ title,
645
+ elementType: element.type,
646
+ id: element.id,
647
+ labelText,
648
+ value
649
+ });
650
+ const description = generateDescription({
651
+ textContent,
652
+ ariaLabel,
653
+ placeholder,
654
+ title,
655
+ elementType: element.type,
656
+ id: element.id,
657
+ labelText
658
+ });
659
+ return {
660
+ id: element.id,
661
+ element,
662
+ state,
663
+ textContent,
664
+ ariaLabel,
665
+ placeholder,
666
+ title,
667
+ role,
668
+ tagName,
669
+ type: element.type,
670
+ aliases,
671
+ description,
672
+ rect: state.rect,
673
+ labelText,
674
+ value
675
+ };
676
+ }
677
+ /**
678
+ * Search for elements matching the criteria
679
+ */
680
+ search(criteria, elements) {
681
+ const startTime = performance.now();
682
+ if (elements) {
683
+ this.updateElements(elements);
684
+ }
685
+ let searchableElements = this.cachedElements;
686
+ if (!this.config.includeHidden && !criteria.fuzzy) {
687
+ searchableElements = searchableElements.filter((el) => el.state.visible);
688
+ }
689
+ const results = [];
690
+ for (const searchable of searchableElements) {
691
+ const result = this.scoreElement(searchable, criteria);
692
+ if (result.confidence >= (criteria.fuzzyThreshold ?? this.config.fuzzyThreshold)) {
693
+ results.push(result);
694
+ }
695
+ }
696
+ results.sort((a, b) => b.confidence - a.confidence);
697
+ const limitedResults = results.slice(0, this.config.maxResults);
698
+ return {
699
+ results: limitedResults,
700
+ bestMatch: limitedResults.length > 0 ? limitedResults[0] : null,
701
+ scannedCount: searchableElements.length,
702
+ durationMs: performance.now() - startTime,
703
+ criteria,
704
+ timestamp: Date.now()
705
+ };
706
+ }
707
+ /**
708
+ * Find the best matching element
709
+ */
710
+ findBest(criteria, elements) {
711
+ const response = this.search(criteria, elements);
712
+ return response.bestMatch;
713
+ }
714
+ /**
715
+ * Find elements by text content
716
+ */
717
+ findByText(text, fuzzy = true, elements) {
718
+ return this.search({ text, fuzzy }, elements).results;
719
+ }
720
+ /**
721
+ * Find elements by role
722
+ */
723
+ findByRole(role, name, elements) {
724
+ const criteria = { role };
725
+ if (name) {
726
+ criteria.accessibleName = name;
727
+ }
728
+ return this.search(criteria, elements).results;
729
+ }
730
+ /**
731
+ * Find elements by accessible name
732
+ */
733
+ findByAccessibleName(name, elements) {
734
+ return this.search({ accessibleName: name, fuzzy: true }, elements).results;
735
+ }
736
+ /**
737
+ * Find elements near another element
738
+ */
739
+ findNear(referenceId, criteria, elements) {
740
+ return this.search({ ...criteria, near: referenceId }, elements).results;
741
+ }
742
+ /**
743
+ * Find elements within a container
744
+ */
745
+ findWithin(containerId, criteria, elements) {
746
+ return this.search({ ...criteria, within: containerId }, elements).results;
747
+ }
748
+ /**
749
+ * Score an element against search criteria
750
+ */
751
+ scoreElement(searchable, criteria) {
752
+ const scores = {};
753
+ const matchReasons = [];
754
+ let totalWeight = 0;
755
+ let weightedScore = 0;
756
+ const fuzzyConfig = {
757
+ ...DEFAULT_FUZZY_CONFIG,
758
+ threshold: criteria.fuzzyThreshold ?? this.config.fuzzyThreshold
759
+ };
760
+ if (criteria.text) {
761
+ const textScore = this.scoreTextMatch(searchable, criteria.text, criteria.fuzzy !== false, fuzzyConfig.threshold);
762
+ scores.text = textScore.score;
763
+ if (textScore.score > 0) {
764
+ matchReasons.push(...textScore.reasons);
765
+ }
766
+ weightedScore += textScore.score * this.config.textWeight;
767
+ totalWeight += this.config.textWeight;
768
+ }
769
+ if (criteria.textContains) {
770
+ const containsScore = this.scoreContainsMatch(searchable, criteria.textContains, criteria.fuzzy !== false);
771
+ scores.text = Math.max(scores.text || 0, containsScore.score);
772
+ if (containsScore.score > 0 && containsScore.reasons.length > 0) {
773
+ matchReasons.push(...containsScore.reasons);
774
+ }
775
+ weightedScore += containsScore.score * this.config.textWeight;
776
+ totalWeight += this.config.textWeight;
777
+ }
778
+ if (criteria.accessibleName) {
779
+ const accessibilityScore = this.scoreAccessibilityMatch(
780
+ searchable,
781
+ criteria.accessibleName,
782
+ criteria.fuzzy !== false,
783
+ fuzzyConfig.threshold
784
+ );
785
+ scores.accessibility = accessibilityScore.score;
786
+ if (accessibilityScore.score > 0) {
787
+ matchReasons.push(...accessibilityScore.reasons);
788
+ }
789
+ weightedScore += accessibilityScore.score * this.config.accessibilityWeight;
790
+ totalWeight += this.config.accessibilityWeight;
791
+ }
792
+ if (criteria.role) {
793
+ const roleScore = this.scoreRoleMatch(searchable, criteria.role);
794
+ scores.role = roleScore.score;
795
+ if (roleScore.score > 0) {
796
+ matchReasons.push(...roleScore.reasons);
797
+ }
798
+ weightedScore += roleScore.score * this.config.roleWeight;
799
+ totalWeight += this.config.roleWeight;
800
+ }
801
+ if (criteria.type) {
802
+ const typeMatch = searchable.type.toLowerCase() === criteria.type.toLowerCase();
803
+ if (typeMatch) {
804
+ matchReasons.push(`type: ${criteria.type}`);
805
+ weightedScore += 1 * this.config.roleWeight;
806
+ totalWeight += this.config.roleWeight;
807
+ }
808
+ }
809
+ if (criteria.near) {
810
+ const spatialScore = this.scoreSpatialMatch(searchable, criteria.near);
811
+ scores.spatial = spatialScore.score;
812
+ if (spatialScore.score > 0) {
813
+ matchReasons.push(...spatialScore.reasons);
814
+ }
815
+ weightedScore += spatialScore.score * this.config.spatialWeight;
816
+ totalWeight += this.config.spatialWeight;
817
+ }
818
+ if (criteria.placeholder && searchable.placeholder) {
819
+ const placeholderResult = fuzzyMatch(searchable.placeholder, criteria.placeholder, fuzzyConfig);
820
+ if (placeholderResult.isMatch) {
821
+ matchReasons.push(`placeholder matches`);
822
+ weightedScore += placeholderResult.similarity * this.config.textWeight;
823
+ totalWeight += this.config.textWeight;
824
+ }
825
+ }
826
+ if (criteria.title && searchable.title) {
827
+ const titleResult = fuzzyMatch(searchable.title, criteria.title, fuzzyConfig);
828
+ if (titleResult.isMatch) {
829
+ matchReasons.push(`title matches`);
830
+ weightedScore += titleResult.similarity * this.config.textWeight;
831
+ totalWeight += this.config.textWeight;
832
+ }
833
+ }
834
+ if (criteria.idPattern) {
835
+ const idMatch = this.matchPattern(searchable.id, criteria.idPattern);
836
+ if (idMatch) {
837
+ matchReasons.push(`id matches pattern`);
838
+ weightedScore += 1 * this.config.textWeight;
839
+ totalWeight += this.config.textWeight;
840
+ }
841
+ }
842
+ const aliasScore = this.scoreAliasMatch(searchable, criteria, fuzzyConfig.threshold);
843
+ if (aliasScore.score > 0) {
844
+ scores.fuzzy = aliasScore.score;
845
+ matchReasons.push(...aliasScore.reasons);
846
+ weightedScore += aliasScore.score * this.config.aliasWeight;
847
+ totalWeight += this.config.aliasWeight;
848
+ }
849
+ const confidence = totalWeight > 0 ? weightedScore / totalWeight : 0;
850
+ const aiElement = this.toAIDiscoveredElement(searchable);
851
+ return {
852
+ element: aiElement,
853
+ confidence,
854
+ matchReasons,
855
+ scores
856
+ };
857
+ }
858
+ /**
859
+ * Score text match
860
+ */
861
+ scoreTextMatch(searchable, text, fuzzy, threshold) {
862
+ const reasons = [];
863
+ let maxScore = 0;
864
+ const textsToMatch = [
865
+ searchable.textContent,
866
+ searchable.labelText,
867
+ searchable.value
868
+ ].filter(Boolean);
869
+ for (const targetText of textsToMatch) {
870
+ if (targetText.toLowerCase() === text.toLowerCase()) {
871
+ maxScore = Math.max(maxScore, 1);
872
+ reasons.push("exact text match");
873
+ continue;
874
+ }
875
+ if (fuzzy) {
876
+ const result = fuzzyMatch(targetText, text, { threshold });
877
+ if (result.isMatch && result.similarity > maxScore) {
878
+ maxScore = result.similarity;
879
+ reasons.push(`text similarity: ${(result.similarity * 100).toFixed(0)}%`);
880
+ }
881
+ const wordSim = wordSimilarity(targetText, text, { threshold });
882
+ if (wordSim > maxScore && wordSim >= threshold) {
883
+ maxScore = wordSim;
884
+ reasons.push(`word match: ${(wordSim * 100).toFixed(0)}%`);
885
+ }
886
+ }
887
+ }
888
+ return { score: maxScore, reasons };
889
+ }
890
+ /**
891
+ * Score contains match
892
+ */
893
+ scoreContainsMatch(searchable, text, fuzzy) {
894
+ const reasons = [];
895
+ let maxScore = 0;
896
+ const textsToMatch = [
897
+ searchable.textContent,
898
+ searchable.labelText,
899
+ searchable.ariaLabel
900
+ ].filter(Boolean);
901
+ for (const targetText of textsToMatch) {
902
+ if (targetText.toLowerCase().includes(text.toLowerCase())) {
903
+ maxScore = Math.max(maxScore, 0.9);
904
+ reasons.push("text contains match");
905
+ continue;
906
+ }
907
+ if (fuzzy && fuzzyContains(targetText, text)) {
908
+ maxScore = Math.max(maxScore, 0.7);
909
+ reasons.push("fuzzy contains match");
910
+ }
911
+ }
912
+ return { score: maxScore, reasons };
913
+ }
914
+ /**
915
+ * Score accessibility match
916
+ */
917
+ scoreAccessibilityMatch(searchable, name, fuzzy, threshold) {
918
+ const reasons = [];
919
+ let maxScore = 0;
920
+ const accessibleNames = [
921
+ searchable.ariaLabel,
922
+ searchable.ariaLabelledBy,
923
+ searchable.labelText,
924
+ searchable.title
925
+ ].filter(Boolean);
926
+ for (const accessibleName of accessibleNames) {
927
+ if (accessibleName.toLowerCase() === name.toLowerCase()) {
928
+ maxScore = Math.max(maxScore, 1);
929
+ reasons.push("exact accessible name match");
930
+ continue;
931
+ }
932
+ if (fuzzy) {
933
+ const result = fuzzyMatch(accessibleName, name, { threshold });
934
+ if (result.isMatch && result.similarity > maxScore) {
935
+ maxScore = result.similarity;
936
+ reasons.push(`accessible name similarity: ${(result.similarity * 100).toFixed(0)}%`);
937
+ }
938
+ }
939
+ }
940
+ return { score: maxScore, reasons };
941
+ }
942
+ /**
943
+ * Score role match
944
+ */
945
+ scoreRoleMatch(searchable, role) {
946
+ const reasons = [];
947
+ const normalizedRole = role.toLowerCase();
948
+ if (searchable.role?.toLowerCase() === normalizedRole) {
949
+ return { score: 1, reasons: [`role: ${role}`] };
950
+ }
951
+ const tagRoleMap = {
952
+ button: ["button", "input[type=button]", "input[type=submit]"],
953
+ textbox: ["input", "textarea"],
954
+ checkbox: ["input[type=checkbox]"],
955
+ radio: ["input[type=radio]"],
956
+ link: ["a"],
957
+ listbox: ["select"],
958
+ combobox: ["select", "input[list]"],
959
+ navigation: ["nav"],
960
+ main: ["main"],
961
+ heading: ["h1", "h2", "h3", "h4", "h5", "h6"]
962
+ };
963
+ const inferredRoles = tagRoleMap[normalizedRole] || [];
964
+ if (inferredRoles.some((r) => searchable.tagName === r || searchable.type.toLowerCase() === normalizedRole)) {
965
+ return { score: 0.8, reasons: [`inferred role: ${role}`] };
966
+ }
967
+ return { score: 0, reasons };
968
+ }
969
+ /**
970
+ * Score spatial match (proximity to another element)
971
+ */
972
+ scoreSpatialMatch(searchable, nearId) {
973
+ const reference = this.cachedElements.find((el) => el.id === nearId);
974
+ if (!reference) {
975
+ return { score: 0, reasons: [] };
976
+ }
977
+ const distance = this.calculateDistance(searchable.rect, reference.rect);
978
+ const nearThreshold = 200;
979
+ if (distance > nearThreshold * 3) {
980
+ return { score: 0, reasons: [] };
981
+ }
982
+ const score = Math.max(0, 1 - distance / (nearThreshold * 3));
983
+ return {
984
+ score,
985
+ reasons: [`${distance.toFixed(0)}px from ${nearId}`]
986
+ };
987
+ }
988
+ /**
989
+ * Calculate distance between two element rectangles
990
+ */
991
+ calculateDistance(rect1, rect2) {
992
+ const center1 = {
993
+ x: rect1.x + rect1.width / 2,
994
+ y: rect1.y + rect1.height / 2
995
+ };
996
+ const center2 = {
997
+ x: rect2.x + rect2.width / 2,
998
+ y: rect2.y + rect2.height / 2
999
+ };
1000
+ return Math.sqrt(Math.pow(center1.x - center2.x, 2) + Math.pow(center1.y - center2.y, 2));
1001
+ }
1002
+ /**
1003
+ * Score alias match
1004
+ */
1005
+ scoreAliasMatch(searchable, criteria, threshold) {
1006
+ const reasons = [];
1007
+ let maxScore = 0;
1008
+ const searchTerms = [];
1009
+ if (criteria.text) searchTerms.push(criteria.text);
1010
+ if (criteria.textContains) searchTerms.push(criteria.textContains);
1011
+ if (criteria.accessibleName) searchTerms.push(criteria.accessibleName);
1012
+ for (const searchTerm of searchTerms) {
1013
+ const termLower = searchTerm.toLowerCase();
1014
+ for (const alias of searchable.aliases) {
1015
+ if (alias === termLower) {
1016
+ maxScore = Math.max(maxScore, 1);
1017
+ reasons.push(`alias match: "${alias}"`);
1018
+ continue;
1019
+ }
1020
+ const searchWords = termLower.split(/\s+/);
1021
+ const aliasWords = alias.split(/\s+/);
1022
+ for (const searchWord of searchWords) {
1023
+ for (const aliasWord of aliasWords) {
1024
+ if (areSynonyms(searchWord, aliasWord)) {
1025
+ maxScore = Math.max(maxScore, 0.85);
1026
+ reasons.push(`synonym match: "${searchWord}" ~ "${aliasWord}"`);
1027
+ }
1028
+ }
1029
+ }
1030
+ const result = fuzzyMatch(alias, termLower, { threshold });
1031
+ if (result.isMatch && result.similarity > maxScore) {
1032
+ maxScore = result.similarity;
1033
+ reasons.push(`fuzzy alias: "${alias}" (${(result.similarity * 100).toFixed(0)}%)`);
1034
+ }
1035
+ const tokenSim = tokenSimilarity(alias, termLower);
1036
+ if (tokenSim > maxScore && tokenSim >= threshold) {
1037
+ maxScore = tokenSim;
1038
+ reasons.push(`token match: "${alias}"`);
1039
+ }
1040
+ }
1041
+ }
1042
+ return { score: maxScore, reasons };
1043
+ }
1044
+ /**
1045
+ * Match a string against a pattern (supports * wildcard)
1046
+ */
1047
+ matchPattern(str, pattern) {
1048
+ const regexPattern = pattern.replace(/[.*+?^${}()|[\]\\]/g, "\\$&").replace(/\\\*/g, ".*");
1049
+ return new RegExp(`^${regexPattern}$`, "i").test(str);
1050
+ }
1051
+ /**
1052
+ * Convert searchable element to AI discovered element
1053
+ */
1054
+ toAIDiscoveredElement(searchable) {
1055
+ const discoveredBase = "getState" in searchable.element ? {
1056
+ id: searchable.id,
1057
+ type: searchable.type,
1058
+ label: searchable.element.label,
1059
+ tagName: searchable.tagName,
1060
+ role: searchable.role,
1061
+ accessibleName: searchable.ariaLabel,
1062
+ actions: searchable.element.actions,
1063
+ state: searchable.state,
1064
+ registered: true
1065
+ } : searchable.element;
1066
+ return {
1067
+ ...discoveredBase,
1068
+ description: searchable.description,
1069
+ aliases: searchable.aliases,
1070
+ purpose: generatePurpose({
1071
+ textContent: searchable.textContent,
1072
+ ariaLabel: searchable.ariaLabel,
1073
+ elementType: searchable.type,
1074
+ tagName: searchable.tagName
1075
+ }),
1076
+ parentContext: void 0,
1077
+ // Would need DOM traversal
1078
+ suggestedActions: generateSuggestedActions({
1079
+ textContent: searchable.textContent,
1080
+ ariaLabel: searchable.ariaLabel,
1081
+ elementType: searchable.type,
1082
+ tagName: searchable.tagName
1083
+ }),
1084
+ semanticType: this.inferSemanticType(searchable),
1085
+ labelText: searchable.labelText,
1086
+ placeholder: searchable.placeholder,
1087
+ title: searchable.title
1088
+ };
1089
+ }
1090
+ /**
1091
+ * Infer a semantic type for the element
1092
+ */
1093
+ inferSemanticType(searchable) {
1094
+ const text = (searchable.textContent || searchable.ariaLabel || "").toLowerCase();
1095
+ const type = searchable.type.toLowerCase();
1096
+ if (type === "input" || type === "textarea") {
1097
+ if (searchable.placeholder?.toLowerCase().includes("email") || text.includes("email")) {
1098
+ return "email-input";
1099
+ }
1100
+ if (searchable.placeholder?.toLowerCase().includes("password") || text.includes("password")) {
1101
+ return "password-input";
1102
+ }
1103
+ if (searchable.placeholder?.toLowerCase().includes("search") || text.includes("search")) {
1104
+ return "search-input";
1105
+ }
1106
+ return "text-input";
1107
+ }
1108
+ if (type === "button") {
1109
+ if (text.match(/submit|save|confirm|ok|done|apply/)) return "submit-button";
1110
+ if (text.match(/cancel|close|dismiss/)) return "cancel-button";
1111
+ if (text.match(/delete|remove|trash/)) return "delete-button";
1112
+ if (text.match(/add|create|new|\+/)) return "add-button";
1113
+ if (text.match(/edit|modify/)) return "edit-button";
1114
+ if (text.match(/next|continue/)) return "next-button";
1115
+ if (text.match(/back|previous/)) return "back-button";
1116
+ return "action-button";
1117
+ }
1118
+ if (type === "link") {
1119
+ if (text.match(/home|dashboard/)) return "home-link";
1120
+ if (text.match(/login|sign.?in/)) return "login-link";
1121
+ if (text.match(/logout|sign.?out/)) return "logout-link";
1122
+ return "navigation-link";
1123
+ }
1124
+ return type;
1125
+ }
1126
+ };
1127
+ function createSearchEngine(config) {
1128
+ return new SearchEngine(config);
1129
+ }
1130
+
1131
+ // src/ai/summary-generator.ts
1132
+ var DEFAULT_SUMMARY_CONFIG = {
1133
+ maxLength: 2e3,
1134
+ includeForms: true,
1135
+ includeElementCounts: true,
1136
+ includeModals: true,
1137
+ includeFocused: true,
1138
+ verbosity: "normal"
1139
+ };
1140
+ function generatePageSummary(elements, pageContext, config = {}) {
1141
+ const finalConfig = { ...DEFAULT_SUMMARY_CONFIG, ...config };
1142
+ const lines = [];
1143
+ if (pageContext) {
1144
+ if (pageContext.title) {
1145
+ lines.push(`Page: "${pageContext.title}"`);
1146
+ }
1147
+ if (pageContext.pageType && pageContext.pageType !== "unknown") {
1148
+ lines.push(`Type: ${formatPageType(pageContext.pageType)}`);
1149
+ }
1150
+ }
1151
+ if (finalConfig.includeElementCounts) {
1152
+ const counts = countElementTypes(elements);
1153
+ const countParts = [];
1154
+ if (counts.button > 0) countParts.push(`${counts.button} button${counts.button > 1 ? "s" : ""}`);
1155
+ if (counts.input > 0) countParts.push(`${counts.input} input${counts.input > 1 ? "s" : ""}`);
1156
+ if (counts.link > 0) countParts.push(`${counts.link} link${counts.link > 1 ? "s" : ""}`);
1157
+ if (counts.select > 0) countParts.push(`${counts.select} dropdown${counts.select > 1 ? "s" : ""}`);
1158
+ if (counts.checkbox > 0) countParts.push(`${counts.checkbox} checkbox${counts.checkbox > 1 ? "es" : ""}`);
1159
+ if (countParts.length > 0) {
1160
+ lines.push(`Contains: ${countParts.join(", ")}`);
1161
+ }
1162
+ }
1163
+ if (finalConfig.includeForms) {
1164
+ const forms = detectForms(elements);
1165
+ if (forms.length > 0) {
1166
+ lines.push("");
1167
+ lines.push("Forms:");
1168
+ for (const form of forms) {
1169
+ lines.push(generateFormSummary(form, finalConfig.verbosity));
1170
+ }
1171
+ }
1172
+ }
1173
+ if (finalConfig.includeModals && pageContext?.activeModals && pageContext.activeModals.length > 0) {
1174
+ lines.push("");
1175
+ lines.push(`Active modals: ${pageContext.activeModals.join(", ")}`);
1176
+ }
1177
+ if (finalConfig.includeFocused && pageContext?.focusedElement) {
1178
+ lines.push(`Focus: ${pageContext.focusedElement}`);
1179
+ }
1180
+ const keyElements = getKeyElements(elements);
1181
+ if (keyElements.length > 0) {
1182
+ lines.push("");
1183
+ lines.push("Key elements:");
1184
+ for (const el of keyElements) {
1185
+ lines.push(` - ${el.description}${el.state.enabled ? "" : " (disabled)"}`);
1186
+ }
1187
+ }
1188
+ let summary = lines.join("\n");
1189
+ if (summary.length > finalConfig.maxLength) {
1190
+ summary = summary.substring(0, finalConfig.maxLength - 3) + "...";
1191
+ }
1192
+ return summary;
1193
+ }
1194
+ function generateElementDescription(element) {
1195
+ const parts = [];
1196
+ const name = element.accessibleName || element.label || element.state.textContent?.trim();
1197
+ if (name) {
1198
+ parts.push(`"${truncate(name, 30)}"`);
1199
+ }
1200
+ parts.push(formatElementType(element.type));
1201
+ const stateIndicators = [];
1202
+ if (!element.state.visible) stateIndicators.push("hidden");
1203
+ if (!element.state.enabled) stateIndicators.push("disabled");
1204
+ if (element.state.focused) stateIndicators.push("focused");
1205
+ if (element.state.checked) stateIndicators.push("checked");
1206
+ if (stateIndicators.length > 0) {
1207
+ parts.push(`(${stateIndicators.join(", ")})`);
1208
+ }
1209
+ if (element.state.value && element.type !== "button") {
1210
+ const valuePreview = truncate(element.state.value, 20);
1211
+ parts.push(`value: "${valuePreview}"`);
1212
+ }
1213
+ return parts.join(" ");
1214
+ }
1215
+ function generateFormSummary(form, verbosity) {
1216
+ const lines = [];
1217
+ const formName = form.name || form.purpose || form.id;
1218
+ lines.push(` ${formName}:`);
1219
+ if (verbosity === "brief") {
1220
+ const fieldCount = form.fields.length;
1221
+ const filledCount = form.fields.filter((f) => f.value).length;
1222
+ lines.push(` ${filledCount}/${fieldCount} fields filled, ${form.isValid ? "valid" : "has errors"}`);
1223
+ } else {
1224
+ for (const field of form.fields) {
1225
+ let fieldLine = ` - ${field.label || field.id}`;
1226
+ if (field.value) {
1227
+ fieldLine += ` = "${truncate(field.value, 15)}"`;
1228
+ } else if (field.placeholder) {
1229
+ fieldLine += ` (${field.placeholder})`;
1230
+ } else {
1231
+ fieldLine += " (empty)";
1232
+ }
1233
+ if (!field.valid && field.error) {
1234
+ fieldLine += ` [ERROR: ${field.error}]`;
1235
+ } else if (field.required && !field.value) {
1236
+ fieldLine += " [required]";
1237
+ }
1238
+ lines.push(fieldLine);
1239
+ }
1240
+ if (form.submitButton) {
1241
+ lines.push(` Submit: ${form.submitButton}`);
1242
+ }
1243
+ }
1244
+ return lines.join("\n");
1245
+ }
1246
+ function generateSnapshotSummary(snapshot, config = {}) {
1247
+ const finalConfig = { ...DEFAULT_SUMMARY_CONFIG, ...config };
1248
+ const lines = [];
1249
+ lines.push(`Page: "${snapshot.page.title}"`);
1250
+ lines.push(`URL: ${snapshot.page.url}`);
1251
+ if (snapshot.page.pageType) {
1252
+ lines.push(`Type: ${formatPageType(snapshot.page.pageType)}`);
1253
+ }
1254
+ if (finalConfig.includeElementCounts) {
1255
+ const countParts = [];
1256
+ for (const [type, count] of Object.entries(snapshot.elementCounts)) {
1257
+ if (count > 0) {
1258
+ countParts.push(`${count} ${type}${count > 1 ? "s" : ""}`);
1259
+ }
1260
+ }
1261
+ if (countParts.length > 0) {
1262
+ lines.push(`Elements: ${countParts.join(", ")}`);
1263
+ }
1264
+ }
1265
+ if (finalConfig.includeForms && snapshot.forms.length > 0) {
1266
+ lines.push("");
1267
+ lines.push("Forms:");
1268
+ for (const form of snapshot.forms) {
1269
+ lines.push(generateFormStateSummary(form));
1270
+ }
1271
+ }
1272
+ if (finalConfig.includeModals && snapshot.activeModals.length > 0) {
1273
+ lines.push("");
1274
+ lines.push("Active dialogs:");
1275
+ for (const modal of snapshot.activeModals) {
1276
+ lines.push(` - ${modal.title || modal.id} (${modal.type})`);
1277
+ }
1278
+ }
1279
+ if (finalConfig.includeFocused && snapshot.focusedElement) {
1280
+ const focused = snapshot.elements.find((e) => e.id === snapshot.focusedElement);
1281
+ if (focused) {
1282
+ lines.push(`Focused: ${generateElementDescription(focused)}`);
1283
+ }
1284
+ }
1285
+ return lines.join("\n");
1286
+ }
1287
+ function generateFormStateSummary(form) {
1288
+ const lines = [];
1289
+ const formName = form.name || form.purpose || form.id;
1290
+ const filledCount = form.fields.filter((f) => f.value).length;
1291
+ const errorCount = form.fields.filter((f) => !f.valid).length;
1292
+ let statusLine = ` ${formName}: ${filledCount}/${form.fields.length} filled`;
1293
+ if (errorCount > 0) {
1294
+ statusLine += `, ${errorCount} error${errorCount > 1 ? "s" : ""}`;
1295
+ }
1296
+ if (form.isDirty) {
1297
+ statusLine += " (modified)";
1298
+ }
1299
+ lines.push(statusLine);
1300
+ for (const field of form.fields) {
1301
+ if (!field.valid && field.error) {
1302
+ lines.push(` ERROR: ${field.label}: ${field.error}`);
1303
+ }
1304
+ }
1305
+ return lines.join("\n");
1306
+ }
1307
+ function generateDiffSummary(appeared, disappeared, modified) {
1308
+ const lines = [];
1309
+ if (appeared.length > 0) {
1310
+ lines.push(`Appeared: ${appeared.join(", ")}`);
1311
+ }
1312
+ if (disappeared.length > 0) {
1313
+ lines.push(`Disappeared: ${disappeared.join(", ")}`);
1314
+ }
1315
+ if (modified.length > 0) {
1316
+ lines.push("Changed:");
1317
+ for (const mod of modified.slice(0, 5)) {
1318
+ lines.push(` - ${mod.description}: ${mod.property} changed from "${mod.from}" to "${mod.to}"`);
1319
+ }
1320
+ if (modified.length > 5) {
1321
+ lines.push(` ... and ${modified.length - 5} more changes`);
1322
+ }
1323
+ }
1324
+ if (lines.length === 0) {
1325
+ return "No changes detected";
1326
+ }
1327
+ return lines.join("\n");
1328
+ }
1329
+ function countElementTypes(elements) {
1330
+ const counts = {};
1331
+ for (const el of elements) {
1332
+ const type = el.type.toLowerCase();
1333
+ counts[type] = (counts[type] || 0) + 1;
1334
+ }
1335
+ return counts;
1336
+ }
1337
+ function detectForms(elements) {
1338
+ const formElements = elements.filter(
1339
+ (el) => el.type === "input" || el.type === "textarea" || el.type === "select" || el.type === "checkbox"
1340
+ );
1341
+ if (formElements.length === 0) return [];
1342
+ const forms = [];
1343
+ const submitButtons = elements.filter(
1344
+ (el) => el.type === "button" && (el.state.textContent?.toLowerCase().includes("submit") || el.state.textContent?.toLowerCase().includes("save") || el.state.textContent?.toLowerCase().includes("send") || el.semanticType === "submit-button")
1345
+ );
1346
+ const defaultForm = {
1347
+ id: "detected-form",
1348
+ purpose: inferFormPurpose(formElements),
1349
+ fields: formElements.map((el) => ({
1350
+ id: el.id,
1351
+ label: el.labelText || el.accessibleName || el.placeholder || el.id,
1352
+ type: el.type,
1353
+ value: el.state.value || "",
1354
+ valid: true,
1355
+ // Can't determine without validation state
1356
+ required: false,
1357
+ // Can't determine without DOM access
1358
+ placeholder: el.placeholder
1359
+ })),
1360
+ isValid: true,
1361
+ submitButton: submitButtons[0]?.id
1362
+ };
1363
+ if (defaultForm.fields.length > 0) {
1364
+ forms.push(defaultForm);
1365
+ }
1366
+ return forms;
1367
+ }
1368
+ function inferFormPurpose(fields) {
1369
+ const labels = fields.map(
1370
+ (f) => (f.labelText || f.accessibleName || f.placeholder || "").toLowerCase()
1371
+ );
1372
+ const allLabels = labels.join(" ");
1373
+ if (allLabels.includes("email") && allLabels.includes("password")) {
1374
+ if (allLabels.includes("confirm") || allLabels.includes("name")) {
1375
+ return "Registration form";
1376
+ }
1377
+ return "Login form";
1378
+ }
1379
+ if (allLabels.includes("search")) {
1380
+ return "Search form";
1381
+ }
1382
+ if (allLabels.includes("address") || allLabels.includes("city") || allLabels.includes("zip")) {
1383
+ return "Address form";
1384
+ }
1385
+ if (allLabels.includes("card") || allLabels.includes("cvv") || allLabels.includes("expir")) {
1386
+ return "Payment form";
1387
+ }
1388
+ if (allLabels.includes("contact") || allLabels.includes("message")) {
1389
+ return "Contact form";
1390
+ }
1391
+ return "Form";
1392
+ }
1393
+ function getKeyElements(elements) {
1394
+ const keyElements = [];
1395
+ const actionButtons = elements.filter(
1396
+ (el) => el.type === "button" && el.state.visible && (el.semanticType?.includes("submit") || el.semanticType?.includes("action") || el.semanticType?.includes("next"))
1397
+ );
1398
+ keyElements.push(...actionButtons.slice(0, 2));
1399
+ const primaryInputs = elements.filter(
1400
+ (el) => (el.type === "input" || el.type === "textarea") && el.state.visible
1401
+ );
1402
+ keyElements.push(...primaryInputs.slice(0, 3));
1403
+ const links = elements.filter((el) => el.type === "link" && el.state.visible);
1404
+ keyElements.push(...links.slice(0, 2));
1405
+ const unique = [...new Map(keyElements.map((e) => [e.id, e])).values()];
1406
+ return unique.slice(0, 8);
1407
+ }
1408
+ function formatPageType(pageType) {
1409
+ const typeLabels = {
1410
+ login: "Login page",
1411
+ dashboard: "Dashboard",
1412
+ form: "Form page",
1413
+ list: "List/table page",
1414
+ detail: "Detail page",
1415
+ search: "Search page",
1416
+ checkout: "Checkout page",
1417
+ settings: "Settings page",
1418
+ unknown: "Unknown"
1419
+ };
1420
+ return typeLabels[pageType || "unknown"] || "Page";
1421
+ }
1422
+ function formatElementType(type) {
1423
+ const typeLabels = {
1424
+ button: "button",
1425
+ input: "input field",
1426
+ textarea: "text area",
1427
+ select: "dropdown",
1428
+ checkbox: "checkbox",
1429
+ radio: "radio button",
1430
+ link: "link",
1431
+ form: "form",
1432
+ menu: "menu",
1433
+ menuitem: "menu item",
1434
+ tab: "tab",
1435
+ dialog: "dialog",
1436
+ switch: "switch",
1437
+ slider: "slider"
1438
+ };
1439
+ return typeLabels[type.toLowerCase()] || type;
1440
+ }
1441
+ function truncate(str, maxLength) {
1442
+ if (str.length <= maxLength) return str;
1443
+ return str.substring(0, maxLength - 3) + "...";
1444
+ }
1445
+ function inferPageType(url, title, elements) {
1446
+ const urlLower = url.toLowerCase();
1447
+ const titleLower = title.toLowerCase();
1448
+ if (urlLower.includes("login") || urlLower.includes("signin")) return "login";
1449
+ if (urlLower.includes("dashboard")) return "dashboard";
1450
+ if (urlLower.includes("search")) return "search";
1451
+ if (urlLower.includes("checkout") || urlLower.includes("payment")) return "checkout";
1452
+ if (urlLower.includes("settings") || urlLower.includes("preferences")) return "settings";
1453
+ if (titleLower.includes("login") || titleLower.includes("sign in")) return "login";
1454
+ if (titleLower.includes("dashboard")) return "dashboard";
1455
+ if (titleLower.includes("search")) return "search";
1456
+ const hasLoginForm = elements.some((el) => el.type === "input" && el.semanticType === "email-input") && elements.some((el) => el.type === "input" && el.semanticType === "password-input");
1457
+ if (hasLoginForm) return "login";
1458
+ const hasSearchInput = elements.some(
1459
+ (el) => el.type === "input" && el.semanticType === "search-input"
1460
+ );
1461
+ if (hasSearchInput) return "search";
1462
+ const inputCount = elements.filter(
1463
+ (el) => el.type === "input" || el.type === "textarea" || el.type === "select"
1464
+ ).length;
1465
+ if (inputCount >= 3) return "form";
1466
+ const hasTable = elements.some((el) => el.tagName === "table");
1467
+ const hasMany = elements.length > 20;
1468
+ if (hasTable || hasMany) return "list";
1469
+ return "unknown";
1470
+ }
1471
+
1472
+ // src/ai/nl-action-parser.ts
1473
+ var ACTION_PATTERNS = [
1474
+ // Click patterns
1475
+ {
1476
+ regex: /^click\s+(?:on\s+)?(?:the\s+)?(.+?)(?:\s+button)?$/i,
1477
+ action: "click",
1478
+ targetGroup: 1,
1479
+ confidence: 0.95
1480
+ },
1481
+ {
1482
+ regex: /^press\s+(?:the\s+)?(.+?)(?:\s+button)?$/i,
1483
+ action: "click",
1484
+ targetGroup: 1,
1485
+ confidence: 0.9
1486
+ },
1487
+ {
1488
+ regex: /^tap\s+(?:on\s+)?(?:the\s+)?(.+)$/i,
1489
+ action: "click",
1490
+ targetGroup: 1,
1491
+ confidence: 0.85
1492
+ },
1493
+ {
1494
+ regex: /^activate\s+(?:the\s+)?(.+)$/i,
1495
+ action: "click",
1496
+ targetGroup: 1,
1497
+ confidence: 0.8
1498
+ },
1499
+ // Double click patterns
1500
+ {
1501
+ regex: /^double[\s-]?click\s+(?:on\s+)?(?:the\s+)?(.+)$/i,
1502
+ action: "doubleClick",
1503
+ targetGroup: 1,
1504
+ confidence: 0.95
1505
+ },
1506
+ // Right click patterns
1507
+ {
1508
+ regex: /^right[\s-]?click\s+(?:on\s+)?(?:the\s+)?(.+)$/i,
1509
+ action: "rightClick",
1510
+ targetGroup: 1,
1511
+ confidence: 0.95
1512
+ },
1513
+ {
1514
+ regex: /^context\s+click\s+(?:on\s+)?(?:the\s+)?(.+)$/i,
1515
+ action: "rightClick",
1516
+ targetGroup: 1,
1517
+ confidence: 0.9
1518
+ },
1519
+ // Type patterns - "type X in Y"
1520
+ {
1521
+ regex: /^type\s+["'](.+?)["']\s+(?:in(?:to)?|on)\s+(?:the\s+)?(.+)$/i,
1522
+ action: "type",
1523
+ targetGroup: 2,
1524
+ valueGroup: 1,
1525
+ confidence: 0.95
1526
+ },
1527
+ {
1528
+ regex: /^type\s+(.+?)\s+(?:in(?:to)?|on)\s+(?:the\s+)?(.+)$/i,
1529
+ action: "type",
1530
+ targetGroup: 2,
1531
+ valueGroup: 1,
1532
+ confidence: 0.85
1533
+ },
1534
+ // Type patterns - "enter X in Y"
1535
+ {
1536
+ regex: /^enter\s+["'](.+?)["']\s+(?:in(?:to)?|on)\s+(?:the\s+)?(.+)$/i,
1537
+ action: "type",
1538
+ targetGroup: 2,
1539
+ valueGroup: 1,
1540
+ confidence: 0.95
1541
+ },
1542
+ {
1543
+ regex: /^enter\s+(.+?)\s+(?:in(?:to)?|on)\s+(?:the\s+)?(.+)$/i,
1544
+ action: "type",
1545
+ targetGroup: 2,
1546
+ valueGroup: 1,
1547
+ confidence: 0.85
1548
+ },
1549
+ // Type patterns - "input X into Y"
1550
+ {
1551
+ regex: /^input\s+["'](.+?)["']\s+(?:in(?:to)?)\s+(?:the\s+)?(.+)$/i,
1552
+ action: "type",
1553
+ targetGroup: 2,
1554
+ valueGroup: 1,
1555
+ confidence: 0.9
1556
+ },
1557
+ // Type patterns - "fill Y with X"
1558
+ {
1559
+ regex: /^fill\s+(?:in\s+)?(?:the\s+)?(.+?)\s+with\s+["'](.+?)["']$/i,
1560
+ action: "type",
1561
+ targetGroup: 1,
1562
+ valueGroup: 2,
1563
+ confidence: 0.95
1564
+ },
1565
+ {
1566
+ regex: /^fill\s+(?:in\s+)?(?:the\s+)?(.+?)\s+with\s+(.+)$/i,
1567
+ action: "type",
1568
+ targetGroup: 1,
1569
+ valueGroup: 2,
1570
+ confidence: 0.85
1571
+ },
1572
+ // Type patterns - "set Y to X"
1573
+ {
1574
+ regex: /^set\s+(?:the\s+)?(.+?)\s+to\s+["'](.+?)["']$/i,
1575
+ action: "type",
1576
+ targetGroup: 1,
1577
+ valueGroup: 2,
1578
+ confidence: 0.9
1579
+ },
1580
+ // Select patterns
1581
+ {
1582
+ regex: /^select\s+["'](.+?)["']\s+(?:from|in)\s+(?:the\s+)?(.+)$/i,
1583
+ action: "select",
1584
+ targetGroup: 2,
1585
+ valueGroup: 1,
1586
+ confidence: 0.95
1587
+ },
1588
+ {
1589
+ regex: /^choose\s+["'](.+?)["']\s+(?:from|in)\s+(?:the\s+)?(.+)$/i,
1590
+ action: "select",
1591
+ targetGroup: 2,
1592
+ valueGroup: 1,
1593
+ confidence: 0.9
1594
+ },
1595
+ {
1596
+ regex: /^pick\s+["'](.+?)["']\s+(?:from|in)\s+(?:the\s+)?(.+)$/i,
1597
+ action: "select",
1598
+ targetGroup: 2,
1599
+ valueGroup: 1,
1600
+ confidence: 0.85
1601
+ },
1602
+ // Check patterns
1603
+ {
1604
+ regex: /^check\s+(?:the\s+)?(.+?)(?:\s+checkbox)?$/i,
1605
+ action: "check",
1606
+ targetGroup: 1,
1607
+ confidence: 0.9
1608
+ },
1609
+ {
1610
+ regex: /^enable\s+(?:the\s+)?(.+)$/i,
1611
+ action: "check",
1612
+ targetGroup: 1,
1613
+ confidence: 0.8
1614
+ },
1615
+ {
1616
+ regex: /^tick\s+(?:the\s+)?(.+)$/i,
1617
+ action: "check",
1618
+ targetGroup: 1,
1619
+ confidence: 0.85
1620
+ },
1621
+ // Uncheck patterns
1622
+ {
1623
+ regex: /^uncheck\s+(?:the\s+)?(.+?)(?:\s+checkbox)?$/i,
1624
+ action: "uncheck",
1625
+ targetGroup: 1,
1626
+ confidence: 0.9
1627
+ },
1628
+ {
1629
+ regex: /^disable\s+(?:the\s+)?(.+)$/i,
1630
+ action: "uncheck",
1631
+ targetGroup: 1,
1632
+ confidence: 0.8
1633
+ },
1634
+ {
1635
+ regex: /^untick\s+(?:the\s+)?(.+)$/i,
1636
+ action: "uncheck",
1637
+ targetGroup: 1,
1638
+ confidence: 0.85
1639
+ },
1640
+ // Clear patterns
1641
+ {
1642
+ regex: /^clear\s+(?:the\s+)?(.+)$/i,
1643
+ action: "clear",
1644
+ targetGroup: 1,
1645
+ confidence: 0.9
1646
+ },
1647
+ {
1648
+ regex: /^erase\s+(?:the\s+)?(.+)$/i,
1649
+ action: "clear",
1650
+ targetGroup: 1,
1651
+ confidence: 0.85
1652
+ },
1653
+ {
1654
+ regex: /^empty\s+(?:the\s+)?(.+)$/i,
1655
+ action: "clear",
1656
+ targetGroup: 1,
1657
+ confidence: 0.8
1658
+ },
1659
+ // Hover patterns
1660
+ {
1661
+ regex: /^hover\s+(?:over\s+)?(?:the\s+)?(.+)$/i,
1662
+ action: "hover",
1663
+ targetGroup: 1,
1664
+ confidence: 0.9
1665
+ },
1666
+ {
1667
+ regex: /^mouse\s+over\s+(?:the\s+)?(.+)$/i,
1668
+ action: "hover",
1669
+ targetGroup: 1,
1670
+ confidence: 0.85
1671
+ },
1672
+ // Focus patterns
1673
+ {
1674
+ regex: /^focus\s+(?:on\s+)?(?:the\s+)?(.+)$/i,
1675
+ action: "focus",
1676
+ targetGroup: 1,
1677
+ confidence: 0.9
1678
+ },
1679
+ // Scroll patterns
1680
+ {
1681
+ regex: /^scroll\s+(up|down|left|right)$/i,
1682
+ action: "scroll",
1683
+ targetGroup: 1,
1684
+ confidence: 0.9
1685
+ },
1686
+ {
1687
+ regex: /^scroll\s+(?:the\s+)?(.+?)\s+(up|down|left|right)$/i,
1688
+ action: "scroll",
1689
+ targetGroup: 1,
1690
+ confidence: 0.85
1691
+ },
1692
+ {
1693
+ regex: /^scroll\s+to\s+(?:the\s+)?(.+)$/i,
1694
+ action: "scroll",
1695
+ targetGroup: 1,
1696
+ confidence: 0.85
1697
+ },
1698
+ // Wait patterns
1699
+ {
1700
+ regex: /^wait\s+(?:for\s+)?(?:the\s+)?(.+?)(?:\s+to\s+(?:be\s+)?(.+))?$/i,
1701
+ action: "wait",
1702
+ targetGroup: 1,
1703
+ confidence: 0.85
1704
+ },
1705
+ {
1706
+ regex: /^wait\s+until\s+(?:the\s+)?(.+?)(?:\s+(?:is|becomes)\s+(.+))?$/i,
1707
+ action: "wait",
1708
+ targetGroup: 1,
1709
+ confidence: 0.85
1710
+ },
1711
+ // Assert patterns
1712
+ {
1713
+ regex: /^(?:assert|verify|check)\s+(?:that\s+)?(?:the\s+)?(.+?)\s+(?:is\s+)?(visible|hidden|enabled|disabled|checked|unchecked|focused)$/i,
1714
+ action: "assert",
1715
+ targetGroup: 1,
1716
+ confidence: 0.9
1717
+ },
1718
+ {
1719
+ regex: /^(?:assert|verify|check)\s+(?:that\s+)?(?:the\s+)?(.+?)\s+(?:contains|has)\s+["'](.+?)["']$/i,
1720
+ action: "assert",
1721
+ targetGroup: 1,
1722
+ valueGroup: 2,
1723
+ confidence: 0.9
1724
+ },
1725
+ {
1726
+ regex: /^(?:the\s+)?(.+?)\s+should\s+(?:be\s+)?(visible|hidden|enabled|disabled|checked|unchecked|focused)$/i,
1727
+ action: "assert",
1728
+ targetGroup: 1,
1729
+ confidence: 0.85
1730
+ }
1731
+ ];
1732
+ var ASSERTION_TYPE_MAP = {
1733
+ visible: "visible",
1734
+ hidden: "hidden",
1735
+ enabled: "enabled",
1736
+ disabled: "disabled",
1737
+ checked: "checked",
1738
+ unchecked: "unchecked",
1739
+ focused: "focused",
1740
+ contains: "containsText",
1741
+ has: "hasText"
1742
+ };
1743
+ function parseNLInstruction(instruction) {
1744
+ const trimmed = instruction.trim();
1745
+ if (!trimmed) return null;
1746
+ for (const pattern of ACTION_PATTERNS) {
1747
+ const match = trimmed.match(pattern.regex);
1748
+ if (match) {
1749
+ const parsed = {
1750
+ action: pattern.action,
1751
+ targetDescription: cleanTargetDescription(match[pattern.targetGroup] || ""),
1752
+ rawInstruction: instruction,
1753
+ parseConfidence: pattern.confidence
1754
+ };
1755
+ if (pattern.valueGroup && match[pattern.valueGroup]) {
1756
+ parsed.value = match[pattern.valueGroup];
1757
+ }
1758
+ if (pattern.modifierExtractor) {
1759
+ parsed.modifiers = pattern.modifierExtractor(match);
1760
+ }
1761
+ if (pattern.action === "scroll") {
1762
+ const directionMatch = trimmed.match(/(up|down|left|right)/i);
1763
+ if (directionMatch) {
1764
+ parsed.scrollDirection = directionMatch[1].toLowerCase();
1765
+ }
1766
+ }
1767
+ if (pattern.action === "assert") {
1768
+ const assertMatch = trimmed.match(/(visible|hidden|enabled|disabled|checked|unchecked|focused|contains|has)/i);
1769
+ if (assertMatch) {
1770
+ parsed.assertionType = ASSERTION_TYPE_MAP[assertMatch[1].toLowerCase()];
1771
+ }
1772
+ }
1773
+ if (pattern.action === "wait") {
1774
+ const waitCondition = match[2];
1775
+ if (waitCondition) {
1776
+ parsed.waitCondition = waitCondition;
1777
+ }
1778
+ }
1779
+ return parsed;
1780
+ }
1781
+ }
1782
+ return inferAction(trimmed);
1783
+ }
1784
+ function cleanTargetDescription(target) {
1785
+ return target.trim().replace(/^(the|a|an)\s+/i, "").replace(/\s+(button|field|input|link|dropdown|checkbox|radio)$/i, "").trim();
1786
+ }
1787
+ function inferAction(instruction) {
1788
+ const lower = instruction.toLowerCase();
1789
+ if (lower.includes("click") || lower.includes("press") || lower.includes("tap")) {
1790
+ const target = instruction.replace(/click|press|tap|on|the/gi, "").trim();
1791
+ if (target) {
1792
+ return {
1793
+ action: "click",
1794
+ targetDescription: cleanTargetDescription(target),
1795
+ rawInstruction: instruction,
1796
+ parseConfidence: 0.6
1797
+ };
1798
+ }
1799
+ }
1800
+ if (lower.includes("type") || lower.includes("enter") || lower.includes("input")) {
1801
+ const quotedMatch = instruction.match(/["'](.+?)["']/);
1802
+ if (quotedMatch) {
1803
+ const target = instruction.replace(/type|enter|input|into|in|the|["'].*?["']/gi, "").trim();
1804
+ return {
1805
+ action: "type",
1806
+ targetDescription: cleanTargetDescription(target),
1807
+ value: quotedMatch[1],
1808
+ rawInstruction: instruction,
1809
+ parseConfidence: 0.5
1810
+ };
1811
+ }
1812
+ }
1813
+ return null;
1814
+ }
1815
+ function parseNLInstructions(instructions) {
1816
+ const parsed = [];
1817
+ for (const instruction of instructions) {
1818
+ const result = parseNLInstruction(instruction);
1819
+ if (result) {
1820
+ parsed.push(result);
1821
+ }
1822
+ }
1823
+ return parsed;
1824
+ }
1825
+ function splitCompoundInstruction(instruction) {
1826
+ const parts = instruction.split(/\s+(?:and|then|,\s*then|,\s*and|,)\s+/i);
1827
+ return parts.map((p) => p.trim()).filter((p) => p.length > 0);
1828
+ }
1829
+ function extractModifiers(instruction) {
1830
+ const modifiers = [];
1831
+ const lower = instruction.toLowerCase();
1832
+ if (lower.includes("shift") || lower.includes("with shift")) {
1833
+ modifiers.push("shift");
1834
+ }
1835
+ if (lower.includes("ctrl") || lower.includes("control") || lower.includes("with ctrl")) {
1836
+ modifiers.push("ctrl");
1837
+ }
1838
+ if (lower.includes("alt") || lower.includes("with alt") || lower.includes("option")) {
1839
+ modifiers.push("alt");
1840
+ }
1841
+ if (lower.includes("meta") || lower.includes("command") || lower.includes("cmd") || lower.includes("windows")) {
1842
+ modifiers.push("meta");
1843
+ }
1844
+ return modifiers.length > 0 ? modifiers : void 0;
1845
+ }
1846
+ function validateParsedAction(action) {
1847
+ const errors = [];
1848
+ if (!action.targetDescription && action.action !== "scroll") {
1849
+ errors.push("No target element specified");
1850
+ }
1851
+ if ((action.action === "type" || action.action === "select") && !action.value) {
1852
+ errors.push(`No value specified for ${action.action} action`);
1853
+ }
1854
+ if (action.parseConfidence < 0.5) {
1855
+ errors.push("Low confidence parsing - instruction may be ambiguous");
1856
+ }
1857
+ return {
1858
+ valid: errors.length === 0,
1859
+ errors
1860
+ };
1861
+ }
1862
+ function describeAction(action) {
1863
+ switch (action.action) {
1864
+ case "click":
1865
+ return `Click on "${action.targetDescription}"`;
1866
+ case "doubleClick":
1867
+ return `Double-click on "${action.targetDescription}"`;
1868
+ case "rightClick":
1869
+ return `Right-click on "${action.targetDescription}"`;
1870
+ case "type":
1871
+ return `Type "${action.value}" into "${action.targetDescription}"`;
1872
+ case "select":
1873
+ return `Select "${action.value}" from "${action.targetDescription}"`;
1874
+ case "check":
1875
+ return `Check "${action.targetDescription}"`;
1876
+ case "uncheck":
1877
+ return `Uncheck "${action.targetDescription}"`;
1878
+ case "clear":
1879
+ return `Clear "${action.targetDescription}"`;
1880
+ case "hover":
1881
+ return `Hover over "${action.targetDescription}"`;
1882
+ case "focus":
1883
+ return `Focus on "${action.targetDescription}"`;
1884
+ case "scroll":
1885
+ if (action.scrollDirection) {
1886
+ return `Scroll ${action.scrollDirection}`;
1887
+ }
1888
+ return `Scroll to "${action.targetDescription}"`;
1889
+ case "wait":
1890
+ return `Wait for "${action.targetDescription}"${action.waitCondition ? ` to be ${action.waitCondition}` : ""}`;
1891
+ case "assert":
1892
+ return `Assert "${action.targetDescription}" is ${action.assertionType || "valid"}`;
1893
+ default:
1894
+ return `${action.action} on "${action.targetDescription}"`;
1895
+ }
1896
+ }
1897
+
1898
+ // src/ai/error-context.ts
1899
+ function getElementState(el) {
1900
+ if ("state" in el && el.state) {
1901
+ return el.state;
1902
+ }
1903
+ if ("getState" in el && typeof el.getState === "function") {
1904
+ try {
1905
+ return el.getState();
1906
+ } catch {
1907
+ return void 0;
1908
+ }
1909
+ }
1910
+ return void 0;
1911
+ }
1912
+ var ErrorCodes = {
1913
+ // Parsing errors
1914
+ PARSE_ERROR: "PARSE_ERROR",
1915
+ VALIDATION_ERROR: "VALIDATION_ERROR",
1916
+ // Element errors
1917
+ ELEMENT_NOT_FOUND: "ELEMENT_NOT_FOUND",
1918
+ ELEMENT_NOT_VISIBLE: "ELEMENT_NOT_VISIBLE",
1919
+ ELEMENT_DISABLED: "ELEMENT_DISABLED",
1920
+ ELEMENT_BLOCKED: "ELEMENT_BLOCKED",
1921
+ MULTIPLE_ELEMENTS: "MULTIPLE_ELEMENTS",
1922
+ // Search errors
1923
+ LOW_CONFIDENCE: "LOW_CONFIDENCE",
1924
+ AMBIGUOUS_MATCH: "AMBIGUOUS_MATCH",
1925
+ // Action errors
1926
+ ACTION_FAILED: "ACTION_FAILED",
1927
+ ACTION_TIMEOUT: "ACTION_TIMEOUT",
1928
+ UNSUPPORTED_ACTION: "UNSUPPORTED_ACTION",
1929
+ // State errors
1930
+ UNEXPECTED_STATE: "UNEXPECTED_STATE",
1931
+ STALE_ELEMENT: "STALE_ELEMENT",
1932
+ // Page errors
1933
+ PAGE_LOAD_ERROR: "PAGE_LOAD_ERROR",
1934
+ NAVIGATION_ERROR: "NAVIGATION_ERROR"
1935
+ };
1936
+ var ERROR_MESSAGES = {
1937
+ PARSE_ERROR: "Could not parse the natural language instruction",
1938
+ VALIDATION_ERROR: "The parsed action failed validation",
1939
+ ELEMENT_NOT_FOUND: "No element matching the description could be found",
1940
+ ELEMENT_NOT_VISIBLE: "The element exists but is not visible",
1941
+ ELEMENT_DISABLED: "The element is disabled and cannot be interacted with",
1942
+ ELEMENT_BLOCKED: "The element is blocked by another element",
1943
+ MULTIPLE_ELEMENTS: "Multiple elements match the description",
1944
+ LOW_CONFIDENCE: "The best match has low confidence",
1945
+ AMBIGUOUS_MATCH: "Multiple elements match with similar confidence",
1946
+ ACTION_FAILED: "The action could not be completed",
1947
+ ACTION_TIMEOUT: "The action timed out waiting for a condition",
1948
+ UNSUPPORTED_ACTION: "The requested action is not supported",
1949
+ UNEXPECTED_STATE: "The element is in an unexpected state",
1950
+ STALE_ELEMENT: "The element is no longer attached to the DOM",
1951
+ PAGE_LOAD_ERROR: "The page failed to load correctly",
1952
+ NAVIGATION_ERROR: "Navigation to the target page failed"
1953
+ };
1954
+ var ERROR_SUGGESTIONS = {
1955
+ PARSE_ERROR: [
1956
+ {
1957
+ action: 'Use a simpler instruction format like "click Submit button"',
1958
+ confidence: 0.8,
1959
+ priority: 1
1960
+ },
1961
+ {
1962
+ action: "Use specific element names visible on the page",
1963
+ confidence: 0.7,
1964
+ priority: 2
1965
+ }
1966
+ ],
1967
+ VALIDATION_ERROR: [
1968
+ {
1969
+ action: "Provide required parameters for the action",
1970
+ confidence: 0.9,
1971
+ priority: 1
1972
+ },
1973
+ {
1974
+ action: "Check the instruction format",
1975
+ confidence: 0.7,
1976
+ priority: 2
1977
+ }
1978
+ ],
1979
+ ELEMENT_NOT_FOUND: [
1980
+ {
1981
+ action: "Wait for the page to fully load",
1982
+ command: "wait for page to load",
1983
+ confidence: 0.7,
1984
+ priority: 1
1985
+ },
1986
+ {
1987
+ action: "Use a different description for the element",
1988
+ confidence: 0.8,
1989
+ priority: 2
1990
+ },
1991
+ {
1992
+ action: "Scroll the page to reveal the element",
1993
+ command: "scroll down",
1994
+ confidence: 0.6,
1995
+ priority: 3
1996
+ }
1997
+ ],
1998
+ ELEMENT_NOT_VISIBLE: [
1999
+ {
2000
+ action: "Scroll to make the element visible",
2001
+ command: "scroll to element",
2002
+ confidence: 0.9,
2003
+ priority: 1
2004
+ },
2005
+ {
2006
+ action: "Close any overlaying elements",
2007
+ confidence: 0.7,
2008
+ priority: 2
2009
+ },
2010
+ {
2011
+ action: "Wait for loading to complete",
2012
+ command: "wait for loading",
2013
+ confidence: 0.6,
2014
+ priority: 3
2015
+ }
2016
+ ],
2017
+ ELEMENT_DISABLED: [
2018
+ {
2019
+ action: "Fill in required fields first",
2020
+ confidence: 0.8,
2021
+ priority: 1
2022
+ },
2023
+ {
2024
+ action: "Complete prerequisite steps",
2025
+ confidence: 0.7,
2026
+ priority: 2
2027
+ },
2028
+ {
2029
+ action: "Wait for the element to become enabled",
2030
+ command: "wait for element to be enabled",
2031
+ confidence: 0.6,
2032
+ priority: 3
2033
+ }
2034
+ ],
2035
+ ELEMENT_BLOCKED: [
2036
+ {
2037
+ action: "Close the modal or popup",
2038
+ command: "click close button",
2039
+ confidence: 0.9,
2040
+ priority: 1
2041
+ },
2042
+ {
2043
+ action: "Dismiss the overlay",
2044
+ confidence: 0.8,
2045
+ priority: 2
2046
+ },
2047
+ {
2048
+ action: "Wait for the blocking element to disappear",
2049
+ confidence: 0.6,
2050
+ priority: 3
2051
+ }
2052
+ ],
2053
+ MULTIPLE_ELEMENTS: [
2054
+ {
2055
+ action: "Use a more specific description",
2056
+ confidence: 0.9,
2057
+ priority: 1
2058
+ },
2059
+ {
2060
+ action: "Include the element position (first, second, etc.)",
2061
+ confidence: 0.8,
2062
+ priority: 2
2063
+ },
2064
+ {
2065
+ action: "Use the element ID directly",
2066
+ confidence: 0.7,
2067
+ priority: 3
2068
+ }
2069
+ ],
2070
+ LOW_CONFIDENCE: [
2071
+ {
2072
+ action: "Use the exact text shown on the element",
2073
+ confidence: 0.9,
2074
+ priority: 1
2075
+ },
2076
+ {
2077
+ action: "Lower the confidence threshold if the match is correct",
2078
+ confidence: 0.7,
2079
+ priority: 2
2080
+ },
2081
+ {
2082
+ action: "Try a different way to describe the element",
2083
+ confidence: 0.6,
2084
+ priority: 3
2085
+ }
2086
+ ],
2087
+ AMBIGUOUS_MATCH: [
2088
+ {
2089
+ action: "Be more specific about which element you mean",
2090
+ confidence: 0.9,
2091
+ priority: 1
2092
+ },
2093
+ {
2094
+ action: "Include the section or form name",
2095
+ confidence: 0.8,
2096
+ priority: 2
2097
+ }
2098
+ ],
2099
+ ACTION_FAILED: [
2100
+ {
2101
+ action: "Check if the element is interactable",
2102
+ confidence: 0.7,
2103
+ priority: 1
2104
+ },
2105
+ {
2106
+ action: "Wait and retry the action",
2107
+ command: "wait 1 second then retry",
2108
+ confidence: 0.6,
2109
+ priority: 2
2110
+ }
2111
+ ],
2112
+ ACTION_TIMEOUT: [
2113
+ {
2114
+ action: "Increase the timeout duration",
2115
+ confidence: 0.8,
2116
+ priority: 1
2117
+ },
2118
+ {
2119
+ action: "Check if the condition can ever be met",
2120
+ confidence: 0.7,
2121
+ priority: 2
2122
+ }
2123
+ ],
2124
+ UNSUPPORTED_ACTION: [
2125
+ {
2126
+ action: "Use a different action type",
2127
+ confidence: 0.9,
2128
+ priority: 1
2129
+ },
2130
+ {
2131
+ action: "Break down into simpler actions",
2132
+ confidence: 0.7,
2133
+ priority: 2
2134
+ }
2135
+ ],
2136
+ UNEXPECTED_STATE: [
2137
+ {
2138
+ action: "Refresh the page state",
2139
+ command: "refresh",
2140
+ confidence: 0.7,
2141
+ priority: 1
2142
+ },
2143
+ {
2144
+ action: "Wait for state to stabilize",
2145
+ command: "wait 2 seconds",
2146
+ confidence: 0.6,
2147
+ priority: 2
2148
+ }
2149
+ ],
2150
+ STALE_ELEMENT: [
2151
+ {
2152
+ action: "Re-find the element",
2153
+ confidence: 0.9,
2154
+ priority: 1
2155
+ },
2156
+ {
2157
+ action: "Wait for page to stabilize",
2158
+ command: "wait 1 second",
2159
+ confidence: 0.7,
2160
+ priority: 2
2161
+ }
2162
+ ],
2163
+ PAGE_LOAD_ERROR: [
2164
+ {
2165
+ action: "Refresh the page",
2166
+ command: "refresh page",
2167
+ confidence: 0.8,
2168
+ priority: 1
2169
+ },
2170
+ {
2171
+ action: "Check network connectivity",
2172
+ confidence: 0.6,
2173
+ priority: 2
2174
+ }
2175
+ ],
2176
+ NAVIGATION_ERROR: [
2177
+ {
2178
+ action: "Try the navigation again",
2179
+ confidence: 0.7,
2180
+ priority: 1
2181
+ },
2182
+ {
2183
+ action: "Check if the URL is correct",
2184
+ confidence: 0.6,
2185
+ priority: 2
2186
+ }
2187
+ ]
2188
+ };
2189
+ function createErrorContext(errorCode, attemptedAction, availableElements, searchCriteria, nearestMatch) {
2190
+ const message = ERROR_MESSAGES[errorCode] || "An unknown error occurred";
2191
+ const baseSuggestions = ERROR_SUGGESTIONS[errorCode] || [];
2192
+ const possibleBlockers = detectPossibleBlockers(availableElements);
2193
+ const visibleElements = availableElements.filter((el) => {
2194
+ const state = getElementState(el);
2195
+ return state?.visible ?? false;
2196
+ }).length;
2197
+ const suggestions = enhanceSuggestions(
2198
+ baseSuggestions,
2199
+ errorCode,
2200
+ nearestMatch,
2201
+ possibleBlockers
2202
+ );
2203
+ return {
2204
+ code: errorCode,
2205
+ message,
2206
+ attemptedAction,
2207
+ searchCriteria,
2208
+ searchResults: {
2209
+ candidatesFound: availableElements.length,
2210
+ nearestMatch: nearestMatch ? {
2211
+ element: nearestMatch.element,
2212
+ confidence: nearestMatch.confidence,
2213
+ whyNotSelected: determineWhyNotSelected(errorCode, nearestMatch)
2214
+ } : void 0
2215
+ },
2216
+ pageContext: {
2217
+ url: typeof window !== "undefined" ? window.location.href : "",
2218
+ title: typeof document !== "undefined" ? document.title : "",
2219
+ visibleElements,
2220
+ possibleBlockers
2221
+ },
2222
+ suggestions,
2223
+ timestamp: Date.now()
2224
+ };
2225
+ }
2226
+ function detectPossibleBlockers(elements) {
2227
+ const blockers = [];
2228
+ for (const el of elements) {
2229
+ const state = getElementState(el);
2230
+ if (!state) continue;
2231
+ if (el.type === "dialog" && state.visible) {
2232
+ blockers.push(`Modal dialog: ${el.id}`);
2233
+ }
2234
+ if (state.computedStyles?.pointerEvents === "none") {
2235
+ continue;
2236
+ }
2237
+ }
2238
+ return blockers;
2239
+ }
2240
+ function enhanceSuggestions(baseSuggestions, errorCode, nearestMatch, possibleBlockers) {
2241
+ const suggestions = [...baseSuggestions];
2242
+ if (possibleBlockers && possibleBlockers.length > 0) {
2243
+ suggestions.unshift({
2244
+ action: `Close the blocking element: ${possibleBlockers[0]}`,
2245
+ command: "click close button",
2246
+ confidence: 0.85,
2247
+ priority: 0
2248
+ });
2249
+ }
2250
+ if (nearestMatch && errorCode === "LOW_CONFIDENCE") {
2251
+ suggestions.unshift({
2252
+ action: `Did you mean: "${nearestMatch.element.description}"?`,
2253
+ command: `click "${nearestMatch.element.description}"`,
2254
+ confidence: nearestMatch.confidence,
2255
+ priority: 0
2256
+ });
2257
+ }
2258
+ suggestions.sort((a, b) => a.priority - b.priority);
2259
+ return suggestions;
2260
+ }
2261
+ function determineWhyNotSelected(errorCode, nearestMatch) {
2262
+ switch (errorCode) {
2263
+ case "LOW_CONFIDENCE":
2264
+ return `Confidence (${(nearestMatch.confidence * 100).toFixed(0)}%) below threshold`;
2265
+ case "ELEMENT_NOT_VISIBLE":
2266
+ return "Element is not visible";
2267
+ case "ELEMENT_DISABLED":
2268
+ return "Element is disabled";
2269
+ case "AMBIGUOUS_MATCH":
2270
+ return "Multiple elements with similar confidence";
2271
+ default:
2272
+ return "Did not meet selection criteria";
2273
+ }
2274
+ }
2275
+ function formatErrorContext(context) {
2276
+ const lines = [];
2277
+ lines.push(`Error: ${context.code}`);
2278
+ lines.push(`Message: ${context.message}`);
2279
+ lines.push(`Attempted: ${context.attemptedAction}`);
2280
+ lines.push("");
2281
+ if (context.searchResults.nearestMatch) {
2282
+ const match = context.searchResults.nearestMatch;
2283
+ lines.push(`Nearest match: "${match.element.description}" (${(match.confidence * 100).toFixed(0)}% confidence)`);
2284
+ lines.push(`Why not used: ${match.whyNotSelected}`);
2285
+ lines.push("");
2286
+ }
2287
+ lines.push(`Page: ${context.pageContext.title || context.pageContext.url}`);
2288
+ lines.push(`Visible elements: ${context.pageContext.visibleElements}`);
2289
+ if (context.pageContext.possibleBlockers.length > 0) {
2290
+ lines.push(`Possible blockers: ${context.pageContext.possibleBlockers.join(", ")}`);
2291
+ }
2292
+ lines.push("");
2293
+ lines.push("Suggestions:");
2294
+ for (const suggestion of context.suggestions.slice(0, 3)) {
2295
+ lines.push(` - ${suggestion.action}`);
2296
+ if (suggestion.command) {
2297
+ lines.push(` Command: ${suggestion.command}`);
2298
+ }
2299
+ }
2300
+ return lines.join("\n");
2301
+ }
2302
+ function createSimpleError(code, message) {
2303
+ return {
2304
+ code,
2305
+ message: message || ERROR_MESSAGES[code] || "Unknown error"
2306
+ };
2307
+ }
2308
+ function isRecoverableError(code) {
2309
+ const unrecoverableErrors = [
2310
+ "UNSUPPORTED_ACTION",
2311
+ "PAGE_LOAD_ERROR",
2312
+ "NAVIGATION_ERROR"
2313
+ ];
2314
+ return !unrecoverableErrors.includes(code);
2315
+ }
2316
+ function getBestRecoverySuggestion(context) {
2317
+ if (context.suggestions.length === 0) return null;
2318
+ const sorted = [...context.suggestions].sort((a, b) => b.confidence - a.confidence);
2319
+ return sorted[0];
2320
+ }
2321
+
2322
+ // src/ai/nl-action-executor.ts
2323
+ var DEFAULT_EXECUTOR_CONFIG = {
2324
+ defaultConfidenceThreshold: 0.7,
2325
+ defaultTimeout: 5e3,
2326
+ maxAlternatives: 3,
2327
+ verbose: false
2328
+ };
2329
+ var NLActionExecutor = class {
2330
+ constructor(config = {}) {
2331
+ this.actionExecutor = null;
2332
+ this.elements = [];
2333
+ this.config = { ...DEFAULT_EXECUTOR_CONFIG, ...config };
2334
+ this.searchEngine = new SearchEngine(this.config.searchConfig);
2335
+ }
2336
+ /**
2337
+ * Set the action executor for performing DOM actions
2338
+ */
2339
+ setActionExecutor(executor) {
2340
+ this.actionExecutor = executor;
2341
+ }
2342
+ /**
2343
+ * Update available elements for search
2344
+ */
2345
+ updateElements(elements) {
2346
+ this.elements = elements;
2347
+ this.searchEngine.updateElements(elements);
2348
+ }
2349
+ /**
2350
+ * Execute a natural language instruction
2351
+ */
2352
+ async execute(request) {
2353
+ const startTime = performance.now();
2354
+ const threshold = request.confidenceThreshold ?? this.config.defaultConfidenceThreshold;
2355
+ const parsed = parseNLInstruction(request.instruction);
2356
+ if (!parsed) {
2357
+ return this.createFailureResponse(
2358
+ startTime,
2359
+ "PARSE_ERROR",
2360
+ `Could not parse instruction: "${request.instruction}"`,
2361
+ request.instruction,
2362
+ [],
2363
+ threshold
2364
+ );
2365
+ }
2366
+ const validation = validateParsedAction(parsed);
2367
+ if (!validation.valid) {
2368
+ return this.createFailureResponse(
2369
+ startTime,
2370
+ "VALIDATION_ERROR",
2371
+ validation.errors.join("; "),
2372
+ request.instruction,
2373
+ [],
2374
+ threshold
2375
+ );
2376
+ }
2377
+ const searchCriteria = this.buildSearchCriteria(parsed);
2378
+ const searchResponse = this.searchEngine.search(searchCriteria);
2379
+ if (!searchResponse.bestMatch) {
2380
+ return this.createFailureResponse(
2381
+ startTime,
2382
+ "ELEMENT_NOT_FOUND",
2383
+ `Could not find element matching: "${parsed.targetDescription}"`,
2384
+ request.instruction,
2385
+ searchResponse.results,
2386
+ threshold,
2387
+ searchCriteria
2388
+ );
2389
+ }
2390
+ if (searchResponse.bestMatch.confidence < threshold) {
2391
+ const alternatives = searchResponse.results.slice(0, this.config.maxAlternatives);
2392
+ return this.createFailureResponse(
2393
+ startTime,
2394
+ "LOW_CONFIDENCE",
2395
+ `Best match confidence (${(searchResponse.bestMatch.confidence * 100).toFixed(0)}%) is below threshold (${(threshold * 100).toFixed(0)}%)`,
2396
+ request.instruction,
2397
+ alternatives,
2398
+ threshold,
2399
+ searchCriteria,
2400
+ searchResponse.bestMatch
2401
+ );
2402
+ }
2403
+ try {
2404
+ const result = await this.performAction(
2405
+ parsed,
2406
+ searchResponse.bestMatch.element,
2407
+ request.timeout ?? this.config.defaultTimeout
2408
+ );
2409
+ return {
2410
+ success: true,
2411
+ executedAction: describeAction(parsed),
2412
+ elementUsed: searchResponse.bestMatch.element,
2413
+ confidence: searchResponse.bestMatch.confidence,
2414
+ elementState: result.elementState,
2415
+ durationMs: performance.now() - startTime,
2416
+ timestamp: Date.now()
2417
+ };
2418
+ } catch (error) {
2419
+ const errorMessage = error instanceof Error ? error.message : String(error);
2420
+ const alternatives = searchResponse.results.filter((r) => r !== searchResponse.bestMatch).slice(0, this.config.maxAlternatives);
2421
+ return this.createFailureResponse(
2422
+ startTime,
2423
+ "ACTION_FAILED",
2424
+ errorMessage,
2425
+ request.instruction,
2426
+ alternatives,
2427
+ threshold,
2428
+ searchCriteria,
2429
+ searchResponse.bestMatch
2430
+ );
2431
+ }
2432
+ }
2433
+ /**
2434
+ * Execute a parsed action directly (skip parsing)
2435
+ */
2436
+ async executeParsed(parsed, threshold) {
2437
+ const startTime = performance.now();
2438
+ const confidenceThreshold = threshold ?? this.config.defaultConfidenceThreshold;
2439
+ const searchCriteria = this.buildSearchCriteria(parsed);
2440
+ const searchResponse = this.searchEngine.search(searchCriteria);
2441
+ if (!searchResponse.bestMatch) {
2442
+ return this.createFailureResponse(
2443
+ startTime,
2444
+ "ELEMENT_NOT_FOUND",
2445
+ `Could not find element: "${parsed.targetDescription}"`,
2446
+ parsed.rawInstruction,
2447
+ [],
2448
+ confidenceThreshold,
2449
+ searchCriteria
2450
+ );
2451
+ }
2452
+ if (searchResponse.bestMatch.confidence < confidenceThreshold) {
2453
+ return this.createFailureResponse(
2454
+ startTime,
2455
+ "LOW_CONFIDENCE",
2456
+ `Best match confidence too low`,
2457
+ parsed.rawInstruction,
2458
+ searchResponse.results.slice(0, this.config.maxAlternatives),
2459
+ confidenceThreshold,
2460
+ searchCriteria,
2461
+ searchResponse.bestMatch
2462
+ );
2463
+ }
2464
+ try {
2465
+ const result = await this.performAction(
2466
+ parsed,
2467
+ searchResponse.bestMatch.element,
2468
+ this.config.defaultTimeout
2469
+ );
2470
+ return {
2471
+ success: true,
2472
+ executedAction: describeAction(parsed),
2473
+ elementUsed: searchResponse.bestMatch.element,
2474
+ confidence: searchResponse.bestMatch.confidence,
2475
+ elementState: result.elementState,
2476
+ durationMs: performance.now() - startTime,
2477
+ timestamp: Date.now()
2478
+ };
2479
+ } catch (error) {
2480
+ return this.createFailureResponse(
2481
+ startTime,
2482
+ "ACTION_FAILED",
2483
+ error instanceof Error ? error.message : String(error),
2484
+ parsed.rawInstruction,
2485
+ searchResponse.results.filter((r) => r !== searchResponse.bestMatch).slice(0, this.config.maxAlternatives),
2486
+ confidenceThreshold,
2487
+ searchCriteria,
2488
+ searchResponse.bestMatch
2489
+ );
2490
+ }
2491
+ }
2492
+ /**
2493
+ * Build search criteria from a parsed action
2494
+ */
2495
+ buildSearchCriteria(parsed) {
2496
+ const criteria = {
2497
+ text: parsed.targetDescription,
2498
+ fuzzy: true,
2499
+ fuzzyThreshold: this.config.defaultConfidenceThreshold
2500
+ };
2501
+ switch (parsed.action) {
2502
+ case "click":
2503
+ case "doubleClick":
2504
+ case "rightClick":
2505
+ break;
2506
+ case "type":
2507
+ case "clear":
2508
+ criteria.type = "input";
2509
+ break;
2510
+ case "select":
2511
+ criteria.type = "select";
2512
+ break;
2513
+ case "check":
2514
+ case "uncheck":
2515
+ criteria.type = "checkbox";
2516
+ break;
2517
+ }
2518
+ return criteria;
2519
+ }
2520
+ /**
2521
+ * Perform the actual action on an element
2522
+ */
2523
+ async performAction(parsed, element, timeout) {
2524
+ if (!this.actionExecutor) {
2525
+ throw new Error("No action executor configured");
2526
+ }
2527
+ const actionMap = {
2528
+ click: "click",
2529
+ doubleClick: "doubleClick",
2530
+ rightClick: "rightClick",
2531
+ type: "type",
2532
+ select: "select",
2533
+ check: "check",
2534
+ uncheck: "uncheck",
2535
+ scroll: "scroll",
2536
+ wait: null,
2537
+ // Special handling
2538
+ assert: null,
2539
+ // Special handling
2540
+ hover: "hover",
2541
+ focus: "focus",
2542
+ clear: "clear"
2543
+ };
2544
+ const standardAction = actionMap[parsed.action];
2545
+ if (!standardAction) {
2546
+ if (parsed.action === "wait") {
2547
+ const waitResult = await this.actionExecutor.waitFor(element.id, {
2548
+ visible: true,
2549
+ timeout
2550
+ });
2551
+ if (!waitResult.met) {
2552
+ throw new Error(waitResult.error || "Wait condition not met");
2553
+ }
2554
+ return { elementState: waitResult.state };
2555
+ }
2556
+ if (parsed.action === "assert") {
2557
+ throw new Error("Use the assertions module for assert actions");
2558
+ }
2559
+ throw new Error(`Unsupported action: ${parsed.action}`);
2560
+ }
2561
+ const actionRequest = {
2562
+ action: standardAction,
2563
+ waitOptions: {
2564
+ visible: true,
2565
+ enabled: true,
2566
+ timeout
2567
+ }
2568
+ };
2569
+ if (standardAction === "type" && parsed.value) {
2570
+ actionRequest.params = { text: parsed.value };
2571
+ } else if (standardAction === "select" && parsed.value) {
2572
+ actionRequest.params = { value: parsed.value };
2573
+ } else if (standardAction === "scroll" && parsed.scrollDirection) {
2574
+ actionRequest.params = { direction: parsed.scrollDirection };
2575
+ }
2576
+ const response = await this.actionExecutor.executeAction(element.id, actionRequest);
2577
+ if (!response.success) {
2578
+ throw new Error(response.error || "Action failed");
2579
+ }
2580
+ return { elementState: response.elementState };
2581
+ }
2582
+ /**
2583
+ * Create a failure response with suggestions
2584
+ */
2585
+ createFailureResponse(startTime, errorCode, errorMessage, instruction, alternatives, threshold, searchCriteria, nearestMatch) {
2586
+ const suggestions = this.generateSuggestions(
2587
+ errorCode,
2588
+ instruction,
2589
+ alternatives,
2590
+ nearestMatch
2591
+ );
2592
+ const dummyElement = nearestMatch?.element || {
2593
+ id: "not-found",
2594
+ type: "unknown",
2595
+ tagName: "unknown",
2596
+ actions: [],
2597
+ state: {
2598
+ visible: false,
2599
+ enabled: false,
2600
+ focused: false,
2601
+ rect: { x: 0, y: 0, width: 0, height: 0, top: 0, right: 0, bottom: 0, left: 0 }
2602
+ },
2603
+ registered: false,
2604
+ description: "Element not found",
2605
+ aliases: [],
2606
+ suggestedActions: []
2607
+ };
2608
+ return {
2609
+ success: false,
2610
+ executedAction: instruction,
2611
+ elementUsed: dummyElement,
2612
+ confidence: nearestMatch?.confidence || 0,
2613
+ elementState: dummyElement.state,
2614
+ durationMs: performance.now() - startTime,
2615
+ timestamp: Date.now(),
2616
+ error: errorMessage,
2617
+ errorCode,
2618
+ suggestions,
2619
+ alternatives: alternatives.slice(0, this.config.maxAlternatives)
2620
+ };
2621
+ }
2622
+ /**
2623
+ * Generate recovery suggestions
2624
+ */
2625
+ generateSuggestions(errorCode, instruction, alternatives, nearestMatch) {
2626
+ const suggestions = [];
2627
+ switch (errorCode) {
2628
+ case "PARSE_ERROR":
2629
+ suggestions.push('Try using a simpler phrase like "click Submit button"');
2630
+ suggestions.push('Ensure the instruction follows patterns like "click X" or "type Y into X"');
2631
+ break;
2632
+ case "ELEMENT_NOT_FOUND":
2633
+ if (alternatives.length > 0) {
2634
+ suggestions.push(`Did you mean: "${alternatives[0].element.description}"?`);
2635
+ }
2636
+ suggestions.push("Check if the element is visible on the page");
2637
+ suggestions.push("Try using a more specific description");
2638
+ break;
2639
+ case "LOW_CONFIDENCE":
2640
+ if (nearestMatch) {
2641
+ suggestions.push(
2642
+ `Found "${nearestMatch.element.description}" with ${(nearestMatch.confidence * 100).toFixed(0)}% confidence`
2643
+ );
2644
+ }
2645
+ suggestions.push("Try using the exact text shown on the element");
2646
+ suggestions.push("Lower the confidence threshold if this match is correct");
2647
+ break;
2648
+ case "ACTION_FAILED":
2649
+ suggestions.push("Check if the element is enabled");
2650
+ suggestions.push("Wait for any loading to complete");
2651
+ suggestions.push("Ensure no modal or overlay is blocking the element");
2652
+ break;
2653
+ default:
2654
+ suggestions.push("Try a different approach or check the page state");
2655
+ }
2656
+ return suggestions;
2657
+ }
2658
+ /**
2659
+ * Get rich error context for debugging
2660
+ */
2661
+ getErrorContext(errorCode, instruction, searchCriteria, nearestMatch) {
2662
+ return createErrorContext(
2663
+ errorCode,
2664
+ instruction,
2665
+ this.elements,
2666
+ searchCriteria,
2667
+ nearestMatch
2668
+ );
2669
+ }
2670
+ };
2671
+ function createNLActionExecutor(config) {
2672
+ return new NLActionExecutor(config);
2673
+ }
2674
+
2675
+ // src/ai/assertions.ts
2676
+ var DEFAULT_ASSERTION_CONFIG = {
2677
+ defaultTimeout: 5e3,
2678
+ pollInterval: 100,
2679
+ fuzzyThreshold: 0.7,
2680
+ includeSuggestions: true
2681
+ };
2682
+ var AssertionExecutor = class {
2683
+ constructor(config = {}) {
2684
+ this.elements = [];
2685
+ this.config = { ...DEFAULT_ASSERTION_CONFIG, ...config };
2686
+ this.searchEngine = new SearchEngine({ fuzzyThreshold: this.config.fuzzyThreshold });
2687
+ }
2688
+ /**
2689
+ * Update available elements for assertions
2690
+ */
2691
+ updateElements(elements) {
2692
+ this.elements = elements;
2693
+ this.searchEngine.updateElements(elements);
2694
+ }
2695
+ /**
2696
+ * Execute a single assertion
2697
+ */
2698
+ async assert(request) {
2699
+ const startTime = performance.now();
2700
+ const timeout = request.timeout ?? this.config.defaultTimeout;
2701
+ const element = await this.findElement(request.target, request.fuzzy !== false);
2702
+ if (!element && request.type !== "notExists") {
2703
+ return this.createResult(
2704
+ false,
2705
+ typeof request.target === "string" ? request.target : JSON.stringify(request.target),
2706
+ "element not found",
2707
+ request.type === "exists" ? true : request.expected,
2708
+ null,
2709
+ "Element could not be found",
2710
+ this.config.includeSuggestions ? "Check if the element exists and is properly labeled" : void 0,
2711
+ startTime
2712
+ );
2713
+ }
2714
+ return this.executeAssertion(request, element, timeout, startTime);
2715
+ }
2716
+ /**
2717
+ * Execute multiple assertions
2718
+ */
2719
+ async assertBatch(request) {
2720
+ const startTime = performance.now();
2721
+ const results = [];
2722
+ let passedCount = 0;
2723
+ let failedCount = 0;
2724
+ for (const assertion of request.assertions) {
2725
+ const result = await this.assert(assertion);
2726
+ results.push(result);
2727
+ if (result.passed) {
2728
+ passedCount++;
2729
+ } else {
2730
+ failedCount++;
2731
+ if (request.stopOnFailure) {
2732
+ break;
2733
+ }
2734
+ }
2735
+ }
2736
+ const passed = request.mode === "all" ? failedCount === 0 : passedCount > 0;
2737
+ return {
2738
+ passed,
2739
+ results,
2740
+ passedCount,
2741
+ failedCount,
2742
+ durationMs: performance.now() - startTime,
2743
+ timestamp: Date.now()
2744
+ };
2745
+ }
2746
+ /**
2747
+ * Convenience method: assert element is visible
2748
+ */
2749
+ async assertVisible(target, timeout) {
2750
+ return this.assert({ target, type: "visible", timeout });
2751
+ }
2752
+ /**
2753
+ * Convenience method: assert element is hidden
2754
+ */
2755
+ async assertHidden(target, timeout) {
2756
+ return this.assert({ target, type: "hidden", timeout });
2757
+ }
2758
+ /**
2759
+ * Convenience method: assert element is enabled
2760
+ */
2761
+ async assertEnabled(target, timeout) {
2762
+ return this.assert({ target, type: "enabled", timeout });
2763
+ }
2764
+ /**
2765
+ * Convenience method: assert element is disabled
2766
+ */
2767
+ async assertDisabled(target, timeout) {
2768
+ return this.assert({ target, type: "disabled", timeout });
2769
+ }
2770
+ /**
2771
+ * Convenience method: assert element has text
2772
+ */
2773
+ async assertHasText(target, text, timeout) {
2774
+ return this.assert({ target, type: "hasText", expected: text, timeout });
2775
+ }
2776
+ /**
2777
+ * Convenience method: assert element contains text
2778
+ */
2779
+ async assertContainsText(target, text, timeout) {
2780
+ return this.assert({ target, type: "containsText", expected: text, timeout });
2781
+ }
2782
+ /**
2783
+ * Convenience method: assert element has value
2784
+ */
2785
+ async assertHasValue(target, value, timeout) {
2786
+ return this.assert({ target, type: "hasValue", expected: value, timeout });
2787
+ }
2788
+ /**
2789
+ * Convenience method: assert element exists
2790
+ */
2791
+ async assertExists(target, timeout) {
2792
+ return this.assert({ target, type: "exists", timeout });
2793
+ }
2794
+ /**
2795
+ * Convenience method: assert element does not exist
2796
+ */
2797
+ async assertNotExists(target, timeout) {
2798
+ return this.assert({ target, type: "notExists", timeout });
2799
+ }
2800
+ /**
2801
+ * Convenience method: assert checkbox is checked
2802
+ */
2803
+ async assertChecked(target, timeout) {
2804
+ return this.assert({ target, type: "checked", timeout });
2805
+ }
2806
+ /**
2807
+ * Convenience method: assert checkbox is unchecked
2808
+ */
2809
+ async assertUnchecked(target, timeout) {
2810
+ return this.assert({ target, type: "unchecked", timeout });
2811
+ }
2812
+ /**
2813
+ * Convenience method: assert element count
2814
+ */
2815
+ async assertCount(target, expectedCount, timeout) {
2816
+ return this.assert({ target, type: "count", expected: expectedCount, timeout });
2817
+ }
2818
+ /**
2819
+ * Find element by target (string or criteria)
2820
+ */
2821
+ async findElement(target, fuzzy = true) {
2822
+ const criteria = typeof target === "string" ? { text: target, fuzzy } : { ...target, fuzzy };
2823
+ const searchResult = this.searchEngine.findBest(criteria);
2824
+ if (searchResult && searchResult.confidence >= this.config.fuzzyThreshold) {
2825
+ return searchResult.element;
2826
+ }
2827
+ return null;
2828
+ }
2829
+ /**
2830
+ * Execute the actual assertion
2831
+ */
2832
+ async executeAssertion(request, element, timeout, startTime) {
2833
+ const targetStr = typeof request.target === "string" ? request.target : JSON.stringify(request.target);
2834
+ const elementDescription = element?.description || targetStr;
2835
+ switch (request.type) {
2836
+ case "visible":
2837
+ return this.assertVisibility(element, true, elementDescription, request.message, startTime);
2838
+ case "hidden":
2839
+ return this.assertVisibility(element, false, elementDescription, request.message, startTime);
2840
+ case "enabled":
2841
+ return this.assertEnabledState(element, true, elementDescription, request.message, startTime);
2842
+ case "disabled":
2843
+ return this.assertEnabledState(element, false, elementDescription, request.message, startTime);
2844
+ case "focused":
2845
+ return this.assertFocused(element, elementDescription, request.message, startTime);
2846
+ case "checked":
2847
+ return this.assertCheckedState(element, true, elementDescription, request.message, startTime);
2848
+ case "unchecked":
2849
+ return this.assertCheckedState(element, false, elementDescription, request.message, startTime);
2850
+ case "hasText":
2851
+ return this.assertTextMatch(
2852
+ element,
2853
+ request.expected,
2854
+ true,
2855
+ elementDescription,
2856
+ request.message,
2857
+ startTime
2858
+ );
2859
+ case "containsText":
2860
+ return this.assertTextMatch(
2861
+ element,
2862
+ request.expected,
2863
+ false,
2864
+ elementDescription,
2865
+ request.message,
2866
+ startTime
2867
+ );
2868
+ case "hasValue":
2869
+ return this.assertValue(
2870
+ element,
2871
+ request.expected,
2872
+ elementDescription,
2873
+ request.message,
2874
+ startTime
2875
+ );
2876
+ case "exists":
2877
+ return this.createResult(
2878
+ element !== null,
2879
+ targetStr,
2880
+ elementDescription,
2881
+ true,
2882
+ element !== null,
2883
+ element === null ? "Element does not exist" : void 0,
2884
+ void 0,
2885
+ startTime,
2886
+ element?.state
2887
+ );
2888
+ case "notExists":
2889
+ return this.createResult(
2890
+ element === null,
2891
+ targetStr,
2892
+ elementDescription,
2893
+ false,
2894
+ element === null,
2895
+ element !== null ? "Element exists but should not" : void 0,
2896
+ void 0,
2897
+ startTime,
2898
+ element?.state
2899
+ );
2900
+ case "count":
2901
+ return this.assertElementCount(
2902
+ request.target,
2903
+ request.expected,
2904
+ targetStr,
2905
+ request.message,
2906
+ startTime
2907
+ );
2908
+ case "attribute":
2909
+ return this.assertAttribute(
2910
+ element,
2911
+ request.attributeName,
2912
+ request.expected,
2913
+ elementDescription,
2914
+ request.message,
2915
+ startTime
2916
+ );
2917
+ case "hasClass":
2918
+ return this.assertHasClass(
2919
+ element,
2920
+ request.expected,
2921
+ elementDescription,
2922
+ request.message,
2923
+ startTime
2924
+ );
2925
+ case "cssProperty":
2926
+ return this.assertCssProperty(
2927
+ element,
2928
+ request.propertyName,
2929
+ request.expected,
2930
+ elementDescription,
2931
+ request.message,
2932
+ startTime
2933
+ );
2934
+ default:
2935
+ return this.createResult(
2936
+ false,
2937
+ targetStr,
2938
+ elementDescription,
2939
+ void 0,
2940
+ void 0,
2941
+ `Unknown assertion type: ${request.type}`,
2942
+ void 0,
2943
+ startTime
2944
+ );
2945
+ }
2946
+ }
2947
+ /**
2948
+ * Assert visibility state
2949
+ */
2950
+ assertVisibility(element, expectedVisible, description, message, startTime = performance.now()) {
2951
+ const isVisible = element.state.visible;
2952
+ const passed = isVisible === expectedVisible;
2953
+ return this.createResult(
2954
+ passed,
2955
+ element.id,
2956
+ description,
2957
+ expectedVisible,
2958
+ isVisible,
2959
+ passed ? void 0 : message || `Element is ${isVisible ? "visible" : "hidden"} but expected ${expectedVisible ? "visible" : "hidden"}`,
2960
+ passed ? void 0 : "Check if element is covered by another element or has display:none",
2961
+ startTime,
2962
+ element.state
2963
+ );
2964
+ }
2965
+ /**
2966
+ * Assert enabled state
2967
+ */
2968
+ assertEnabledState(element, expectedEnabled, description, message, startTime = performance.now()) {
2969
+ const isEnabled = element.state.enabled;
2970
+ const passed = isEnabled === expectedEnabled;
2971
+ return this.createResult(
2972
+ passed,
2973
+ element.id,
2974
+ description,
2975
+ expectedEnabled,
2976
+ isEnabled,
2977
+ passed ? void 0 : message || `Element is ${isEnabled ? "enabled" : "disabled"} but expected ${expectedEnabled ? "enabled" : "disabled"}`,
2978
+ passed ? void 0 : "Check if the element has a disabled attribute or aria-disabled",
2979
+ startTime,
2980
+ element.state
2981
+ );
2982
+ }
2983
+ /**
2984
+ * Assert focused state
2985
+ */
2986
+ assertFocused(element, description, message, startTime = performance.now()) {
2987
+ const isFocused = element.state.focused;
2988
+ return this.createResult(
2989
+ isFocused,
2990
+ element.id,
2991
+ description,
2992
+ true,
2993
+ isFocused,
2994
+ isFocused ? void 0 : message || "Element is not focused",
2995
+ isFocused ? void 0 : "Click or focus the element first",
2996
+ startTime,
2997
+ element.state
2998
+ );
2999
+ }
3000
+ /**
3001
+ * Assert checked state
3002
+ */
3003
+ assertCheckedState(element, expectedChecked, description, message, startTime = performance.now()) {
3004
+ const isChecked = element.state.checked ?? false;
3005
+ const passed = isChecked === expectedChecked;
3006
+ return this.createResult(
3007
+ passed,
3008
+ element.id,
3009
+ description,
3010
+ expectedChecked,
3011
+ isChecked,
3012
+ passed ? void 0 : message || `Element is ${isChecked ? "checked" : "unchecked"} but expected ${expectedChecked ? "checked" : "unchecked"}`,
3013
+ passed ? void 0 : "Click the checkbox to change its state",
3014
+ startTime,
3015
+ element.state
3016
+ );
3017
+ }
3018
+ /**
3019
+ * Assert text content
3020
+ */
3021
+ assertTextMatch(element, expectedText, exact, description, message, startTime = performance.now()) {
3022
+ const actualText = element.state.textContent || "";
3023
+ const passed = exact ? actualText === expectedText : actualText.includes(expectedText);
3024
+ return this.createResult(
3025
+ passed,
3026
+ element.id,
3027
+ description,
3028
+ expectedText,
3029
+ actualText,
3030
+ passed ? void 0 : message || (exact ? `Text "${actualText}" does not match expected "${expectedText}"` : `Text "${actualText}" does not contain "${expectedText}"`),
3031
+ passed ? void 0 : "Verify the element contains the expected text",
3032
+ startTime,
3033
+ element.state
3034
+ );
3035
+ }
3036
+ /**
3037
+ * Assert input value
3038
+ */
3039
+ assertValue(element, expectedValue, description, message, startTime = performance.now()) {
3040
+ const actualValue = element.state.value || "";
3041
+ const passed = actualValue === expectedValue;
3042
+ return this.createResult(
3043
+ passed,
3044
+ element.id,
3045
+ description,
3046
+ expectedValue,
3047
+ actualValue,
3048
+ passed ? void 0 : message || `Value "${actualValue}" does not match expected "${expectedValue}"`,
3049
+ passed ? void 0 : "Type the expected value into the input",
3050
+ startTime,
3051
+ element.state
3052
+ );
3053
+ }
3054
+ /**
3055
+ * Assert element count
3056
+ */
3057
+ assertElementCount(criteria, expectedCount, targetStr, message, startTime = performance.now()) {
3058
+ const searchResponse = this.searchEngine.search(criteria);
3059
+ const actualCount = searchResponse.results.length;
3060
+ const passed = actualCount === expectedCount;
3061
+ return this.createResult(
3062
+ passed,
3063
+ targetStr,
3064
+ `${actualCount} elements matching criteria`,
3065
+ expectedCount,
3066
+ actualCount,
3067
+ passed ? void 0 : message || `Found ${actualCount} elements but expected ${expectedCount}`,
3068
+ passed ? void 0 : "Adjust search criteria or wait for elements to load",
3069
+ startTime
3070
+ );
3071
+ }
3072
+ /**
3073
+ * Assert attribute value (placeholder for DOM attribute assertions)
3074
+ */
3075
+ assertAttribute(element, attributeName, expectedValue, description, message, startTime = performance.now()) {
3076
+ let actualValue;
3077
+ switch (attributeName.toLowerCase()) {
3078
+ case "placeholder":
3079
+ actualValue = element.placeholder;
3080
+ break;
3081
+ case "title":
3082
+ actualValue = element.title;
3083
+ break;
3084
+ default:
3085
+ return this.createResult(
3086
+ false,
3087
+ element.id,
3088
+ description,
3089
+ expectedValue,
3090
+ void 0,
3091
+ `Cannot check attribute "${attributeName}" without DOM access`,
3092
+ "Use the server API to check element attributes",
3093
+ startTime,
3094
+ element.state
3095
+ );
3096
+ }
3097
+ const passed = actualValue === expectedValue;
3098
+ return this.createResult(
3099
+ passed,
3100
+ element.id,
3101
+ description,
3102
+ expectedValue,
3103
+ actualValue,
3104
+ passed ? void 0 : message || `Attribute "${attributeName}" is "${actualValue}" but expected "${expectedValue}"`,
3105
+ void 0,
3106
+ startTime,
3107
+ element.state
3108
+ );
3109
+ }
3110
+ /**
3111
+ * Assert element has CSS class
3112
+ */
3113
+ assertHasClass(element, className, description, message, startTime = performance.now()) {
3114
+ return this.createResult(
3115
+ false,
3116
+ element.id,
3117
+ description,
3118
+ className,
3119
+ void 0,
3120
+ "Cannot check CSS classes without DOM access",
3121
+ "Use the server API to check element classes",
3122
+ startTime,
3123
+ element.state
3124
+ );
3125
+ }
3126
+ /**
3127
+ * Assert CSS property value
3128
+ */
3129
+ assertCssProperty(element, propertyName, expectedValue, description, message, startTime = performance.now()) {
3130
+ const computedStyles = element.state.computedStyles;
3131
+ if (!computedStyles) {
3132
+ return this.createResult(
3133
+ false,
3134
+ element.id,
3135
+ description,
3136
+ expectedValue,
3137
+ void 0,
3138
+ "Computed styles not available",
3139
+ "Request element state with computed styles",
3140
+ startTime,
3141
+ element.state
3142
+ );
3143
+ }
3144
+ const styleKey = propertyName;
3145
+ const actualValue = computedStyles[styleKey];
3146
+ const passed = actualValue === expectedValue;
3147
+ return this.createResult(
3148
+ passed,
3149
+ element.id,
3150
+ description,
3151
+ expectedValue,
3152
+ actualValue,
3153
+ passed ? void 0 : message || `CSS property "${propertyName}" is "${actualValue}" but expected "${expectedValue}"`,
3154
+ void 0,
3155
+ startTime,
3156
+ element.state
3157
+ );
3158
+ }
3159
+ /**
3160
+ * Create an assertion result
3161
+ */
3162
+ createResult(passed, target, targetDescription, expected, actual, failureReason, suggestion, startTime = performance.now(), elementState) {
3163
+ return {
3164
+ passed,
3165
+ target,
3166
+ targetDescription,
3167
+ expected,
3168
+ actual,
3169
+ failureReason,
3170
+ suggestion: this.config.includeSuggestions ? suggestion : void 0,
3171
+ elementState,
3172
+ durationMs: performance.now() - startTime,
3173
+ timestamp: Date.now()
3174
+ };
3175
+ }
3176
+ };
3177
+ function createAssertionExecutor(config) {
3178
+ return new AssertionExecutor(config);
3179
+ }
3180
+
3181
+ // src/ai/semantic-snapshot.ts
3182
+ var DEFAULT_SNAPSHOT_CONFIG = {
3183
+ analyzeForms: true,
3184
+ detectModals: true,
3185
+ inferPageType: true,
3186
+ generateDescriptions: true,
3187
+ maxElements: 500
3188
+ };
3189
+ var SemanticSnapshotManager = class {
3190
+ constructor(config = {}) {
3191
+ this.history = [];
3192
+ this.maxHistorySize = 10;
3193
+ this.snapshotCounter = 0;
3194
+ this.config = { ...DEFAULT_SNAPSHOT_CONFIG, ...config };
3195
+ this.searchEngine = new SearchEngine();
3196
+ }
3197
+ /**
3198
+ * Create a semantic snapshot from a control snapshot
3199
+ */
3200
+ createSnapshot(controlSnapshot, pageContext) {
3201
+ const snapshotId = `snapshot-${++this.snapshotCounter}-${Date.now()}`;
3202
+ const aiElements = this.convertElements(controlSnapshot.elements);
3203
+ this.searchEngine.updateElements(aiElements);
3204
+ const fullPageContext = this.buildPageContext(aiElements, pageContext);
3205
+ const forms = this.config.analyzeForms ? this.analyzeForms(aiElements) : [];
3206
+ const modals = this.config.detectModals ? this.detectModals(aiElements) : [];
3207
+ const elementCounts = this.countElementTypes(aiElements);
3208
+ const summary = generatePageSummary(aiElements, fullPageContext);
3209
+ const focusedElement = aiElements.find((el) => el.state.focused)?.id;
3210
+ const snapshot = {
3211
+ timestamp: Date.now(),
3212
+ snapshotId,
3213
+ page: fullPageContext,
3214
+ elements: aiElements.slice(0, this.config.maxElements),
3215
+ forms,
3216
+ activeModals: modals,
3217
+ focusedElement,
3218
+ summary,
3219
+ elementCounts
3220
+ };
3221
+ this.addToHistory(snapshot);
3222
+ return snapshot;
3223
+ }
3224
+ /**
3225
+ * Get the last snapshot
3226
+ */
3227
+ getLastSnapshot() {
3228
+ if (this.history.length === 0) return null;
3229
+ return this.history[this.history.length - 1].snapshot;
3230
+ }
3231
+ /**
3232
+ * Get snapshot by ID
3233
+ */
3234
+ getSnapshot(snapshotId) {
3235
+ const entry = this.history.find((h) => h.snapshot.snapshotId === snapshotId);
3236
+ return entry?.snapshot || null;
3237
+ }
3238
+ /**
3239
+ * Get snapshot history
3240
+ */
3241
+ getHistory() {
3242
+ return this.history.map((h) => h.snapshot);
3243
+ }
3244
+ /**
3245
+ * Clear history
3246
+ */
3247
+ clearHistory() {
3248
+ this.history = [];
3249
+ }
3250
+ /**
3251
+ * Convert control snapshot elements to AI elements
3252
+ */
3253
+ convertElements(elements) {
3254
+ return elements.map((el) => this.convertElement(el));
3255
+ }
3256
+ /**
3257
+ * Convert a single element to AI element
3258
+ */
3259
+ convertElement(element) {
3260
+ const aliases = generateAliases({
3261
+ textContent: element.state.textContent,
3262
+ elementType: element.type,
3263
+ id: element.id,
3264
+ labelText: element.label
3265
+ });
3266
+ const description = this.config.generateDescriptions ? generateDescription({
3267
+ textContent: element.state.textContent,
3268
+ elementType: element.type,
3269
+ id: element.id,
3270
+ labelText: element.label
3271
+ }) : element.label || element.id;
3272
+ const purpose = generatePurpose({
3273
+ textContent: element.state.textContent,
3274
+ elementType: element.type
3275
+ });
3276
+ const suggestedActions = generateSuggestedActions({
3277
+ textContent: element.state.textContent,
3278
+ elementType: element.type
3279
+ });
3280
+ return {
3281
+ id: element.id,
3282
+ type: element.type,
3283
+ label: element.label,
3284
+ tagName: this.inferTagName(element.type),
3285
+ role: this.inferRole(element.type),
3286
+ accessibleName: element.label || element.state.textContent?.trim(),
3287
+ actions: element.actions,
3288
+ state: element.state,
3289
+ registered: true,
3290
+ description,
3291
+ aliases,
3292
+ purpose,
3293
+ suggestedActions,
3294
+ semanticType: this.inferSemanticType(element)
3295
+ };
3296
+ }
3297
+ /**
3298
+ * Build full page context
3299
+ */
3300
+ buildPageContext(elements, partial) {
3301
+ const url = partial?.url || (typeof window !== "undefined" ? window.location.href : "");
3302
+ const title = partial?.title || (typeof document !== "undefined" ? document.title : "");
3303
+ const pageType = this.config.inferPageType ? inferPageType(url, title, elements) : partial?.pageType || "unknown";
3304
+ const activeModals = elements.filter((el) => el.type === "dialog" && el.state.visible).map((el) => el.id);
3305
+ return {
3306
+ url,
3307
+ title,
3308
+ pageType,
3309
+ activeModals: partial?.activeModals || activeModals,
3310
+ focusedElement: partial?.focusedElement || elements.find((el) => el.state.focused)?.id,
3311
+ navigation: partial?.navigation
3312
+ };
3313
+ }
3314
+ /**
3315
+ * Analyze forms in the snapshot
3316
+ */
3317
+ analyzeForms(elements) {
3318
+ const forms = [];
3319
+ const formElements = elements.filter((el) => el.type === "form");
3320
+ if (formElements.length === 0) {
3321
+ const implicitForm = this.detectImplicitForm(elements);
3322
+ if (implicitForm) {
3323
+ forms.push(implicitForm);
3324
+ }
3325
+ } else {
3326
+ for (const form of formElements) {
3327
+ const formState = this.analyzeForm(form, elements);
3328
+ if (formState) {
3329
+ forms.push(formState);
3330
+ }
3331
+ }
3332
+ }
3333
+ return forms;
3334
+ }
3335
+ /**
3336
+ * Detect implicit form from inputs
3337
+ */
3338
+ detectImplicitForm(elements) {
3339
+ const inputs = elements.filter(
3340
+ (el) => el.type === "input" || el.type === "textarea" || el.type === "select" || el.type === "checkbox"
3341
+ );
3342
+ if (inputs.length === 0) return null;
3343
+ const submitButton = elements.find(
3344
+ (el) => el.type === "button" && el.state.visible && (el.semanticType === "submit-button" || el.state.textContent?.toLowerCase().match(/submit|save|send|continue/))
3345
+ );
3346
+ const fields = this.analyzeFormFields(inputs);
3347
+ const hasErrors = fields.some((f) => !f.valid);
3348
+ return {
3349
+ id: "implicit-form",
3350
+ purpose: this.inferFormPurpose(inputs),
3351
+ fields,
3352
+ isValid: !hasErrors,
3353
+ submitButton: submitButton?.id,
3354
+ isDirty: fields.some((f) => f.value !== "" && f.touched)
3355
+ };
3356
+ }
3357
+ /**
3358
+ * Analyze a specific form
3359
+ */
3360
+ analyzeForm(form, allElements) {
3361
+ const inputs = allElements.filter(
3362
+ (el) => (el.type === "input" || el.type === "textarea" || el.type === "select") && el.state.visible
3363
+ );
3364
+ const fields = this.analyzeFormFields(inputs);
3365
+ const hasErrors = fields.some((f) => !f.valid);
3366
+ const submitButton = allElements.find(
3367
+ (el) => el.type === "button" && el.state.visible && el.semanticType === "submit-button"
3368
+ );
3369
+ return {
3370
+ id: form.id,
3371
+ name: form.label,
3372
+ purpose: form.purpose,
3373
+ fields,
3374
+ isValid: !hasErrors,
3375
+ submitButton: submitButton?.id,
3376
+ isDirty: fields.some((f) => f.value !== "")
3377
+ };
3378
+ }
3379
+ /**
3380
+ * Analyze form fields
3381
+ */
3382
+ analyzeFormFields(inputs) {
3383
+ return inputs.map((input) => ({
3384
+ id: input.id,
3385
+ label: input.accessibleName || input.label || input.id,
3386
+ type: input.type,
3387
+ value: input.state.value || "",
3388
+ valid: true,
3389
+ // Would need validation state
3390
+ required: false,
3391
+ // Would need DOM access
3392
+ touched: input.state.focused || (input.state.value?.length || 0) > 0
3393
+ }));
3394
+ }
3395
+ /**
3396
+ * Detect modal dialogs
3397
+ */
3398
+ detectModals(elements) {
3399
+ const modals = [];
3400
+ const dialogElements = elements.filter(
3401
+ (el) => el.type === "dialog" && el.state.visible
3402
+ );
3403
+ for (const dialog of dialogElements) {
3404
+ const closeButton = elements.find(
3405
+ (el) => el.type === "button" && el.state.visible && (el.semanticType === "cancel-button" || el.state.textContent?.toLowerCase().match(/close|cancel|x|dismiss/))
3406
+ );
3407
+ const primaryAction = elements.find(
3408
+ (el) => el.type === "button" && el.state.visible && el.semanticType === "submit-button"
3409
+ );
3410
+ modals.push({
3411
+ id: dialog.id,
3412
+ title: dialog.accessibleName || dialog.label,
3413
+ type: this.inferModalType(dialog),
3414
+ blocking: true,
3415
+ // Assume dialogs are blocking
3416
+ closeButton: closeButton?.id,
3417
+ primaryAction: primaryAction?.id
3418
+ });
3419
+ }
3420
+ return modals;
3421
+ }
3422
+ /**
3423
+ * Infer modal type
3424
+ */
3425
+ inferModalType(dialog) {
3426
+ const text = (dialog.accessibleName || dialog.state.textContent || "").toLowerCase();
3427
+ if (text.includes("alert") || text.includes("warning") || text.includes("error")) {
3428
+ return "alert";
3429
+ }
3430
+ if (text.includes("confirm") || text.includes("are you sure")) {
3431
+ return "confirm";
3432
+ }
3433
+ if (text.includes("prompt") || text.includes("enter")) {
3434
+ return "prompt";
3435
+ }
3436
+ return "dialog";
3437
+ }
3438
+ /**
3439
+ * Count elements by type
3440
+ */
3441
+ countElementTypes(elements) {
3442
+ const counts = {};
3443
+ for (const el of elements) {
3444
+ const type = el.type.toLowerCase();
3445
+ counts[type] = (counts[type] || 0) + 1;
3446
+ }
3447
+ return counts;
3448
+ }
3449
+ /**
3450
+ * Infer form purpose from fields
3451
+ */
3452
+ inferFormPurpose(fields) {
3453
+ const labels = fields.map(
3454
+ (f) => (f.accessibleName || f.label || "").toLowerCase()
3455
+ );
3456
+ const allLabels = labels.join(" ");
3457
+ if (allLabels.includes("email") && allLabels.includes("password")) {
3458
+ if (allLabels.includes("confirm") || allLabels.includes("name")) {
3459
+ return "Registration";
3460
+ }
3461
+ return "Login";
3462
+ }
3463
+ if (allLabels.includes("search")) return "Search";
3464
+ if (allLabels.includes("address") || allLabels.includes("city")) return "Address";
3465
+ if (allLabels.includes("card") || allLabels.includes("payment")) return "Payment";
3466
+ if (allLabels.includes("contact") || allLabels.includes("message")) return "Contact";
3467
+ return "Form";
3468
+ }
3469
+ /**
3470
+ * Infer tag name from element type
3471
+ */
3472
+ inferTagName(type) {
3473
+ const typeMap = {
3474
+ button: "button",
3475
+ input: "input",
3476
+ textarea: "textarea",
3477
+ select: "select",
3478
+ checkbox: "input",
3479
+ radio: "input",
3480
+ link: "a",
3481
+ form: "form",
3482
+ dialog: "dialog"
3483
+ };
3484
+ return typeMap[type] || "div";
3485
+ }
3486
+ /**
3487
+ * Infer ARIA role from element type
3488
+ */
3489
+ inferRole(type) {
3490
+ const roleMap = {
3491
+ button: "button",
3492
+ input: "textbox",
3493
+ textarea: "textbox",
3494
+ select: "combobox",
3495
+ checkbox: "checkbox",
3496
+ radio: "radio",
3497
+ link: "link",
3498
+ dialog: "dialog",
3499
+ menu: "menu",
3500
+ menuitem: "menuitem",
3501
+ tab: "tab"
3502
+ };
3503
+ return roleMap[type];
3504
+ }
3505
+ /**
3506
+ * Infer semantic type
3507
+ */
3508
+ inferSemanticType(element) {
3509
+ const text = (element.state.textContent || element.label || "").toLowerCase();
3510
+ const type = element.type.toLowerCase();
3511
+ if (type === "button") {
3512
+ if (text.match(/submit|save|confirm|ok|done|apply/)) return "submit-button";
3513
+ if (text.match(/cancel|close|dismiss/)) return "cancel-button";
3514
+ if (text.match(/delete|remove|trash/)) return "delete-button";
3515
+ if (text.match(/add|create|new|\+/)) return "add-button";
3516
+ if (text.match(/edit|modify/)) return "edit-button";
3517
+ if (text.match(/next|continue/)) return "next-button";
3518
+ if (text.match(/back|previous/)) return "back-button";
3519
+ return "action-button";
3520
+ }
3521
+ if (type === "input") {
3522
+ if (text.includes("email") || element.id.includes("email")) return "email-input";
3523
+ if (text.includes("password") || element.id.includes("password")) return "password-input";
3524
+ if (text.includes("search") || element.id.includes("search")) return "search-input";
3525
+ return "text-input";
3526
+ }
3527
+ return type;
3528
+ }
3529
+ /**
3530
+ * Add snapshot to history
3531
+ */
3532
+ addToHistory(snapshot) {
3533
+ this.history.push({
3534
+ snapshot,
3535
+ timestamp: Date.now()
3536
+ });
3537
+ if (this.history.length > this.maxHistorySize) {
3538
+ this.history = this.history.slice(-this.maxHistorySize);
3539
+ }
3540
+ }
3541
+ };
3542
+ function createSnapshotManager(config) {
3543
+ return new SemanticSnapshotManager(config);
3544
+ }
3545
+
3546
+ // src/ai/semantic-diff.ts
3547
+ var DEFAULT_DIFF_CONFIG = {
3548
+ ignoreInsignificant: true,
3549
+ trackedProperties: ["visible", "enabled", "focused", "checked", "value", "textContent"],
3550
+ generateSuggestions: true,
3551
+ maxModifications: 20
3552
+ };
3553
+ var INSIGNIFICANT_PROPERTIES = /* @__PURE__ */ new Set(["rect", "computedStyles", "innerHTML"]);
3554
+ function computeDiff(fromSnapshot, toSnapshot, config = {}) {
3555
+ const startTime = performance.now();
3556
+ const finalConfig = { ...DEFAULT_DIFF_CONFIG, ...config };
3557
+ const fromElements = new Map(fromSnapshot.elements.map((el) => [el.id, el]));
3558
+ const toElements = new Map(toSnapshot.elements.map((el) => [el.id, el]));
3559
+ const appeared = [];
3560
+ for (const [id, element] of toElements) {
3561
+ if (!fromElements.has(id)) {
3562
+ appeared.push({
3563
+ elementId: id,
3564
+ description: element.description,
3565
+ type: element.type,
3566
+ semanticType: element.semanticType
3567
+ });
3568
+ }
3569
+ }
3570
+ const disappeared = [];
3571
+ for (const [id, element] of fromElements) {
3572
+ if (!toElements.has(id)) {
3573
+ disappeared.push({
3574
+ elementId: id,
3575
+ description: element.description,
3576
+ type: element.type,
3577
+ semanticType: element.semanticType
3578
+ });
3579
+ }
3580
+ }
3581
+ const modified = [];
3582
+ for (const [id, toElement] of toElements) {
3583
+ const fromElement = fromElements.get(id);
3584
+ if (fromElement) {
3585
+ const modifications = compareElements(fromElement, toElement, finalConfig);
3586
+ modified.push(...modifications);
3587
+ }
3588
+ }
3589
+ const limitedModifications = modified.slice(0, finalConfig.maxModifications);
3590
+ const probableTrigger = detectTrigger(appeared, disappeared, limitedModifications);
3591
+ const suggestedActions = finalConfig.generateSuggestions ? generateSuggestedActionsFromDiff(appeared, disappeared, limitedModifications, probableTrigger) : void 0;
3592
+ const pageChanges = detectPageChanges(fromSnapshot, toSnapshot);
3593
+ const summary = generateDiffSummary(
3594
+ appeared.map((e) => e.description),
3595
+ disappeared.map((e) => e.description),
3596
+ limitedModifications
3597
+ );
3598
+ return {
3599
+ summary,
3600
+ fromSnapshotId: fromSnapshot.snapshotId,
3601
+ toSnapshotId: toSnapshot.snapshotId,
3602
+ changes: {
3603
+ appeared,
3604
+ disappeared,
3605
+ modified: limitedModifications
3606
+ },
3607
+ probableTrigger,
3608
+ suggestedActions,
3609
+ pageChanges,
3610
+ durationMs: performance.now() - startTime,
3611
+ timestamp: Date.now()
3612
+ };
3613
+ }
3614
+ function compareElements(fromElement, toElement, config) {
3615
+ const modifications = [];
3616
+ for (const property of config.trackedProperties) {
3617
+ const fromValue = getPropertyValue(fromElement, property);
3618
+ const toValue = getPropertyValue(toElement, property);
3619
+ if (fromValue !== toValue) {
3620
+ const isSignificant = isSignificantChange(property, fromValue, toValue);
3621
+ if (!config.ignoreInsignificant || isSignificant) {
3622
+ modifications.push({
3623
+ elementId: toElement.id,
3624
+ description: toElement.description,
3625
+ property,
3626
+ from: formatValue(fromValue),
3627
+ to: formatValue(toValue),
3628
+ significant: isSignificant
3629
+ });
3630
+ }
3631
+ }
3632
+ }
3633
+ return modifications;
3634
+ }
3635
+ function getPropertyValue(element, property) {
3636
+ if (property in element.state) {
3637
+ return element.state[property];
3638
+ }
3639
+ return element[property];
3640
+ }
3641
+ function isSignificantChange(property, fromValue, toValue) {
3642
+ if (INSIGNIFICANT_PROPERTIES.has(property)) {
3643
+ return false;
3644
+ }
3645
+ if (property === "visible") {
3646
+ return true;
3647
+ }
3648
+ if (property === "enabled") {
3649
+ return true;
3650
+ }
3651
+ if (property === "focused") {
3652
+ return true;
3653
+ }
3654
+ if (property === "checked") {
3655
+ return true;
3656
+ }
3657
+ if (property === "value") {
3658
+ return Boolean(fromValue) || Boolean(toValue);
3659
+ }
3660
+ if (property === "textContent") {
3661
+ const fromText = String(fromValue || "");
3662
+ const toText = String(toValue || "");
3663
+ return fromText.trim() !== toText.trim();
3664
+ }
3665
+ return true;
3666
+ }
3667
+ function formatValue(value) {
3668
+ if (value === void 0) return "undefined";
3669
+ if (value === null) return "null";
3670
+ if (typeof value === "boolean") return value ? "true" : "false";
3671
+ if (typeof value === "string") {
3672
+ if (value.length > 50) {
3673
+ return value.substring(0, 47) + "...";
3674
+ }
3675
+ return value;
3676
+ }
3677
+ if (typeof value === "object") {
3678
+ return JSON.stringify(value);
3679
+ }
3680
+ return String(value);
3681
+ }
3682
+ function detectTrigger(appeared, disappeared, modified) {
3683
+ const hasNewErrors = appeared.some(
3684
+ (e) => e.description.toLowerCase().includes("error") || e.type === "error"
3685
+ );
3686
+ if (hasNewErrors) {
3687
+ return "Form validation";
3688
+ }
3689
+ const hasNewModal = appeared.some(
3690
+ (e) => e.type === "dialog" || e.semanticType?.includes("dialog")
3691
+ );
3692
+ if (hasNewModal) {
3693
+ return "Modal opened";
3694
+ }
3695
+ const hasModalDismissed = disappeared.some(
3696
+ (e) => e.type === "dialog" || e.semanticType?.includes("dialog")
3697
+ );
3698
+ if (hasModalDismissed) {
3699
+ return "Modal closed";
3700
+ }
3701
+ const hasLoading = modified.some((m) => m.description.toLowerCase().includes("loading"));
3702
+ if (hasLoading) {
3703
+ return "Loading state change";
3704
+ }
3705
+ const hasFocusChange = modified.some((m) => m.property === "focused");
3706
+ if (hasFocusChange && modified.length <= 2) {
3707
+ return "Focus changed";
3708
+ }
3709
+ const hasValueChange = modified.some((m) => m.property === "value");
3710
+ if (hasValueChange && modified.length <= 2) {
3711
+ return "User input";
3712
+ }
3713
+ const visibilityChanges = modified.filter((m) => m.property === "visible");
3714
+ if (visibilityChanges.length > 0 && visibilityChanges.length <= 5) {
3715
+ return "UI expansion/collapse";
3716
+ }
3717
+ if (appeared.length > 5) {
3718
+ return "Page navigation";
3719
+ }
3720
+ return void 0;
3721
+ }
3722
+ function detectPageChanges(fromSnapshot, toSnapshot) {
3723
+ const urlChanged = fromSnapshot.page.url !== toSnapshot.page.url;
3724
+ const titleChanged = fromSnapshot.page.title !== toSnapshot.page.title;
3725
+ if (!urlChanged && !titleChanged) {
3726
+ return void 0;
3727
+ }
3728
+ return {
3729
+ urlChanged,
3730
+ titleChanged,
3731
+ newUrl: urlChanged ? toSnapshot.page.url : void 0,
3732
+ newTitle: titleChanged ? toSnapshot.page.title : void 0
3733
+ };
3734
+ }
3735
+ function generateSuggestedActionsFromDiff(appeared, disappeared, modified, trigger) {
3736
+ const suggestions = [];
3737
+ if (trigger === "Form validation") {
3738
+ suggestions.push("Fix the validation errors before submitting");
3739
+ }
3740
+ if (trigger === "Modal opened") {
3741
+ const modal = appeared.find(
3742
+ (e) => e.type === "dialog" || e.semanticType?.includes("dialog")
3743
+ );
3744
+ if (modal) {
3745
+ suggestions.push(`Interact with the "${modal.description}" dialog`);
3746
+ }
3747
+ }
3748
+ if (trigger === "Modal closed") {
3749
+ suggestions.push("Continue with the main page interaction");
3750
+ }
3751
+ for (const element of appeared.slice(0, 3)) {
3752
+ if (element.type === "button" && element.semanticType === "submit-button") {
3753
+ suggestions.push(`Click the "${element.description}" to proceed`);
3754
+ }
3755
+ if (element.description.toLowerCase().includes("error")) {
3756
+ suggestions.push(`Address the error: ${element.description}`);
3757
+ }
3758
+ }
3759
+ for (const mod of modified.slice(0, 3)) {
3760
+ if (mod.property === "enabled" && mod.to === "true") {
3761
+ suggestions.push(`"${mod.description}" is now enabled`);
3762
+ }
3763
+ if (mod.property === "visible" && mod.to === "true") {
3764
+ suggestions.push(`"${mod.description}" is now visible`);
3765
+ }
3766
+ }
3767
+ return suggestions.slice(0, 5);
3768
+ }
3769
+ var SemanticDiffManager = class {
3770
+ constructor(config = {}) {
3771
+ this.lastSnapshot = null;
3772
+ this.config = { ...DEFAULT_DIFF_CONFIG, ...config };
3773
+ }
3774
+ /**
3775
+ * Update with new snapshot and get diff
3776
+ */
3777
+ update(newSnapshot) {
3778
+ if (!this.lastSnapshot) {
3779
+ this.lastSnapshot = newSnapshot;
3780
+ return null;
3781
+ }
3782
+ const diff = computeDiff(this.lastSnapshot, newSnapshot, this.config);
3783
+ this.lastSnapshot = newSnapshot;
3784
+ return diff;
3785
+ }
3786
+ /**
3787
+ * Get diff from a specific snapshot to current
3788
+ */
3789
+ diffFrom(fromSnapshot) {
3790
+ if (!this.lastSnapshot) return null;
3791
+ return computeDiff(fromSnapshot, this.lastSnapshot, this.config);
3792
+ }
3793
+ /**
3794
+ * Reset the manager
3795
+ */
3796
+ reset() {
3797
+ this.lastSnapshot = null;
3798
+ }
3799
+ /**
3800
+ * Get the last known snapshot
3801
+ */
3802
+ getLastSnapshot() {
3803
+ return this.lastSnapshot;
3804
+ }
3805
+ };
3806
+ function createDiffManager(config) {
3807
+ return new SemanticDiffManager(config);
3808
+ }
3809
+ function hasSignificantChanges(diff) {
3810
+ if (diff.changes.appeared.length > 0) return true;
3811
+ if (diff.changes.disappeared.length > 0) return true;
3812
+ if (diff.changes.modified.some((m) => m.significant)) return true;
3813
+ if (diff.pageChanges?.urlChanged) return true;
3814
+ return false;
3815
+ }
3816
+ function describeDiff(diff) {
3817
+ const parts = [];
3818
+ if (diff.changes.appeared.length > 0) {
3819
+ parts.push(`${diff.changes.appeared.length} elements appeared`);
3820
+ }
3821
+ if (diff.changes.disappeared.length > 0) {
3822
+ parts.push(`${diff.changes.disappeared.length} elements disappeared`);
3823
+ }
3824
+ const significantMods = diff.changes.modified.filter((m) => m.significant);
3825
+ if (significantMods.length > 0) {
3826
+ parts.push(`${significantMods.length} elements modified`);
3827
+ }
3828
+ if (diff.pageChanges?.urlChanged) {
3829
+ parts.push("URL changed");
3830
+ }
3831
+ if (parts.length === 0) {
3832
+ return "No significant changes";
3833
+ }
3834
+ return parts.join(", ");
3835
+ }
3836
+
3837
+ export { AssertionExecutor, DEFAULT_ALIAS_CONFIG, DEFAULT_ASSERTION_CONFIG, DEFAULT_DIFF_CONFIG, DEFAULT_EXECUTOR_CONFIG, DEFAULT_FUZZY_CONFIG, DEFAULT_SEARCH_CONFIG, DEFAULT_SNAPSHOT_CONFIG, ErrorCodes, NLActionExecutor, SearchEngine, SemanticDiffManager, SemanticSnapshotManager, areSynonyms, computeDiff, createAssertionExecutor, createDiffManager, createErrorContext, createNLActionExecutor, createSearchEngine, createSimpleError, createSnapshotManager, describeAction, describeDiff, extractModifiers, findAllMatches, findBestMatch, formatErrorContext, fuzzyContains, fuzzyMatch, generateAliases, generateDescription, generateDiffSummary, generateElementDescription, generateNgrams, generatePageSummary, generatePurpose, generateSnapshotSummary, generateSuggestedActions, getBestRecoverySuggestion, getSynonyms, hasSignificantChanges, inferPageType, isRecoverableError, jaroSimilarity, jaroWinklerSimilarity, levenshteinDistance, levenshteinSimilarity, ngramSimilarity, normalizeString, parseNLInstruction, parseNLInstructions, splitCompoundInstruction, tokenSimilarity, tokenize, validateParsedAction, wordSimilarity };
3838
+ //# sourceMappingURL=index.mjs.map
3839
+ //# sourceMappingURL=index.mjs.map