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