@dream_engine/browser 0.0.0-stage → 0.1.1

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 (100) hide show
  1. package/LICENSE +21 -0
  2. package/dist/.tsbuildinfo +1 -0
  3. package/dist/adapter/playwright.d.ts +27 -0
  4. package/dist/adapter/playwright.d.ts.map +1 -0
  5. package/dist/adapter/playwright.js +1087 -0
  6. package/dist/adapter/playwright.js.map +1 -0
  7. package/dist/adapter/types.d.ts +833 -0
  8. package/dist/adapter/types.d.ts.map +1 -0
  9. package/dist/adapter/types.js +9 -0
  10. package/dist/adapter/types.js.map +1 -0
  11. package/dist/api-request.d.ts +93 -0
  12. package/dist/api-request.d.ts.map +1 -0
  13. package/dist/api-request.js +284 -0
  14. package/dist/api-request.js.map +1 -0
  15. package/dist/artifacts.d.ts +99 -0
  16. package/dist/artifacts.d.ts.map +1 -0
  17. package/dist/artifacts.js +211 -0
  18. package/dist/artifacts.js.map +1 -0
  19. package/dist/browser.d.ts +79 -0
  20. package/dist/browser.d.ts.map +1 -0
  21. package/dist/browser.js +186 -0
  22. package/dist/browser.js.map +1 -0
  23. package/dist/code-execution.d.ts +12 -0
  24. package/dist/code-execution.d.ts.map +1 -0
  25. package/dist/code-execution.js +15 -0
  26. package/dist/code-execution.js.map +1 -0
  27. package/dist/context.d.ts +174 -0
  28. package/dist/context.d.ts.map +1 -0
  29. package/dist/context.js +474 -0
  30. package/dist/context.js.map +1 -0
  31. package/dist/events.d.ts +66 -0
  32. package/dist/events.d.ts.map +1 -0
  33. package/dist/events.js +87 -0
  34. package/dist/events.js.map +1 -0
  35. package/dist/index.d.ts +24 -0
  36. package/dist/index.d.ts.map +1 -0
  37. package/dist/index.js +23 -0
  38. package/dist/index.js.map +1 -0
  39. package/dist/locator.d.ts +208 -0
  40. package/dist/locator.d.ts.map +1 -0
  41. package/dist/locator.js +402 -0
  42. package/dist/locator.js.map +1 -0
  43. package/dist/login.d.ts +76 -0
  44. package/dist/login.d.ts.map +1 -0
  45. package/dist/login.js +176 -0
  46. package/dist/login.js.map +1 -0
  47. package/dist/manager.d.ts +109 -0
  48. package/dist/manager.d.ts.map +1 -0
  49. package/dist/manager.js +320 -0
  50. package/dist/manager.js.map +1 -0
  51. package/dist/navigation.d.ts +74 -0
  52. package/dist/navigation.d.ts.map +1 -0
  53. package/dist/navigation.js +234 -0
  54. package/dist/navigation.js.map +1 -0
  55. package/dist/network.d.ts +260 -0
  56. package/dist/network.d.ts.map +1 -0
  57. package/dist/network.js +582 -0
  58. package/dist/network.js.map +1 -0
  59. package/dist/page.d.ts +512 -0
  60. package/dist/page.d.ts.map +1 -0
  61. package/dist/page.js +1493 -0
  62. package/dist/page.js.map +1 -0
  63. package/dist/selectors.d.ts +67 -0
  64. package/dist/selectors.d.ts.map +1 -0
  65. package/dist/selectors.js +137 -0
  66. package/dist/selectors.js.map +1 -0
  67. package/dist/sessions.d.ts +114 -0
  68. package/dist/sessions.d.ts.map +1 -0
  69. package/dist/sessions.js +285 -0
  70. package/dist/sessions.js.map +1 -0
  71. package/dist/smart/dom-scan.d.ts +104 -0
  72. package/dist/smart/dom-scan.d.ts.map +1 -0
  73. package/dist/smart/dom-scan.js +491 -0
  74. package/dist/smart/dom-scan.js.map +1 -0
  75. package/dist/smart/ranking.d.ts +63 -0
  76. package/dist/smart/ranking.d.ts.map +1 -0
  77. package/dist/smart/ranking.js +318 -0
  78. package/dist/smart/ranking.js.map +1 -0
  79. package/dist/smart/recovery.d.ts +106 -0
  80. package/dist/smart/recovery.d.ts.map +1 -0
  81. package/dist/smart/recovery.js +197 -0
  82. package/dist/smart/recovery.js.map +1 -0
  83. package/dist/smart/smart.d.ts +249 -0
  84. package/dist/smart/smart.d.ts.map +1 -0
  85. package/dist/smart/smart.js +840 -0
  86. package/dist/smart/smart.js.map +1 -0
  87. package/dist/trace-parser.d.ts +70 -0
  88. package/dist/trace-parser.d.ts.map +1 -0
  89. package/dist/trace-parser.js +203 -0
  90. package/dist/trace-parser.js.map +1 -0
  91. package/dist/types.d.ts +57 -0
  92. package/dist/types.d.ts.map +1 -0
  93. package/dist/types.js +2 -0
  94. package/dist/types.js.map +1 -0
  95. package/dist/visual.d.ts +185 -0
  96. package/dist/visual.d.ts.map +1 -0
  97. package/dist/visual.js +384 -0
  98. package/dist/visual.js.map +1 -0
  99. package/package.json +37 -3
  100. package/README.md +0 -3
@@ -0,0 +1,840 @@
1
+ import { AmbiguousElementError, ElementNotFoundError, InteractionError, ValidationError, normalizeText, redactUrl, toBashirWebError, } from '@dream_engine/core';
2
+ import { classifyAction, validateUploadPath } from '@dream_engine/security';
3
+ import { scanDocument, scanForms } from './dom-scan.js';
4
+ import { describeCandidate, parseTarget, rankCandidates, resolveCandidates, textMatchScore, } from './ranking.js';
5
+ import { fingerprintOf } from './recovery.js';
6
+ let scanCounter = 0;
7
+ function toSmartElement(c, frameUrl) {
8
+ const e = c.element;
9
+ return {
10
+ ref: e.ref,
11
+ role: e.role,
12
+ name: e.name,
13
+ tag: e.tag,
14
+ type: e.type,
15
+ value: e.value,
16
+ checked: e.checked,
17
+ visible: e.visible,
18
+ enabled: e.enabled,
19
+ editable: e.editable,
20
+ bbox: e.bbox,
21
+ selector: e.cssPath,
22
+ xpath: e.xpath,
23
+ frameUrl,
24
+ landmark: e.landmark,
25
+ container: e.container,
26
+ score: c.score,
27
+ reasons: c.reasons,
28
+ options: e.options.map((o) => ({ value: o.value, label: o.label, selected: o.selected })),
29
+ };
30
+ }
31
+ function targetLabel(target) {
32
+ if (typeof target === 'string')
33
+ return target;
34
+ if ('ref' in target)
35
+ return target.name || target.ref;
36
+ return target.text;
37
+ }
38
+ function fieldKind(el) {
39
+ if (el.tag === 'select')
40
+ return el.multiple ? 'multiselect' : 'select';
41
+ if (el.tag === 'textarea')
42
+ return 'textarea';
43
+ if (el.role === 'checkbox' || el.role === 'switch')
44
+ return 'checkbox';
45
+ if (el.tag === 'input') {
46
+ switch (el.type) {
47
+ case 'email':
48
+ case 'password':
49
+ case 'number':
50
+ case 'date':
51
+ case 'time':
52
+ case 'month':
53
+ case 'week':
54
+ case 'tel':
55
+ case 'url':
56
+ case 'search':
57
+ case 'file':
58
+ case 'range':
59
+ case 'color':
60
+ return el.type;
61
+ case 'datetime-local':
62
+ return 'datetime';
63
+ default:
64
+ return 'text';
65
+ }
66
+ }
67
+ if (el.role === 'combobox' || el.role === 'listbox')
68
+ return 'select';
69
+ if (el.role === 'textbox' || el.role === 'searchbox')
70
+ return 'text';
71
+ return 'custom';
72
+ }
73
+ const FIELD_ROLES = new Set(['textbox', 'searchbox', 'combobox', 'listbox', 'checkbox', 'switch', 'radio', 'slider', 'spinbutton']);
74
+ /**
75
+ * Deterministic, AI-free smart interaction: find elements by describing them, act on them,
76
+ * inspect and fill forms. Ambiguous matches are reported, never guessed.
77
+ */
78
+ export class SmartInteraction {
79
+ host;
80
+ lastScan = null;
81
+ constructor(host) {
82
+ this.host = host;
83
+ }
84
+ get timeout() {
85
+ return this.host.services.config.browser.timeout;
86
+ }
87
+ /** Scans the page (all frames) and returns raw element descriptors. */
88
+ async scan(options = {}) {
89
+ const scanId = `s${(++scanCounter).toString(36)}`;
90
+ const frames = this.host.adapter.frames().filter((f) => !f.isDetached());
91
+ const frameMap = new Map();
92
+ const elements = [];
93
+ let main = null;
94
+ let nearAnchors = [];
95
+ for (let i = 0; i < frames.length; i++) {
96
+ const frame = frames[i];
97
+ try {
98
+ const result = await frame.evaluate(scanDocument, {
99
+ scanId: `${scanId}f${i}`,
100
+ includeHidden: options.includeHidden ?? false,
101
+ includeNonInteractive: options.includeNonInteractive ?? false,
102
+ near: options.near ?? null,
103
+ maxElements: 3000,
104
+ only: null,
105
+ });
106
+ frameMap.set(i, frame);
107
+ for (const el of result.elements) {
108
+ el.frameIndex = i;
109
+ elements.push(el);
110
+ }
111
+ if (frame.isMain()) {
112
+ main = result;
113
+ nearAnchors = result.nearAnchors;
114
+ }
115
+ }
116
+ catch (error) {
117
+ if (frame.isMain())
118
+ throw toBashirWebError(error);
119
+ this.host.services.logger.debug('frame scan skipped', { frame: redactUrl(frame.url()), error: error.message });
120
+ }
121
+ }
122
+ if (!main)
123
+ throw new InteractionError('Could not scan the main frame');
124
+ this.lastScan = { elements, frames: frameMap, main, nearAnchors };
125
+ return this.lastScan;
126
+ }
127
+ locatorFor(snapshot, el) {
128
+ const frame = snapshot.frames.get(el.frameIndex) ?? this.host.adapter.mainFrame();
129
+ return frame.locator(`[data-bw-ref="${el.ref}"]`);
130
+ }
131
+ frameUrl(snapshot, el) {
132
+ return redactUrl(snapshot.frames.get(el.frameIndex)?.url() ?? this.host.adapter.url());
133
+ }
134
+ async locate(target, action, options = {}) {
135
+ if (typeof target === 'object' && 'ref' in target) {
136
+ const snapshot = this.lastScan && this.lastScan.elements.some((e) => e.ref === target.ref) ? this.lastScan : await this.scan({ includeHidden: true });
137
+ const el = snapshot.elements.find((e) => e.ref === target.ref);
138
+ if (!el)
139
+ throw new ElementNotFoundError(`Element reference ${target.ref} is stale; find the element again`, { details: { ref: target.ref } });
140
+ return { snapshot, candidate: { element: el, score: 1, match: null, reasons: ['explicit reference'] }, spec: { text: target.name } };
141
+ }
142
+ const spec = parseTarget(target);
143
+ if (!spec.text)
144
+ throw new ValidationError('Target description must not be empty');
145
+ const deadline = Date.now() + (options.timeout ?? this.timeout);
146
+ let lastError = null;
147
+ // Poll until the element appears (dynamic pages) or the timeout elapses.
148
+ for (;;) {
149
+ const snapshot = await this.scan({ includeHidden: options.includeHidden ?? false, near: spec.near ?? null });
150
+ const ranked = rankCandidates(spec, snapshot.elements, { action, minScore: options.minScore ?? 0.45, nearAnchors: snapshot.nearAnchors });
151
+ const resolution = resolveCandidates(spec, ranked);
152
+ if (resolution.status === 'resolved' && resolution.candidate) {
153
+ const c = resolution.candidate;
154
+ this.host.services.events.emit('element:found', {
155
+ pageId: this.host.id,
156
+ query: spec.text,
157
+ ref: c.element.ref,
158
+ role: c.element.role,
159
+ name: c.element.name,
160
+ score: c.score,
161
+ });
162
+ return { snapshot, candidate: c, spec };
163
+ }
164
+ if (resolution.status === 'ambiguous') {
165
+ throw new AmbiguousElementError(resolution.reason, {
166
+ details: { target: spec.text, candidates: resolution.candidates.slice(0, 6).map(describeCandidate) },
167
+ hint: 'Refine the description, e.g. { text, within: "Login form" }, { text, role: "button" }, { text, exact: true } or { text, index: 0 }.',
168
+ });
169
+ }
170
+ lastError = new ElementNotFoundError(`No element matches "${spec.text}"${spec.role ? ` (role ${spec.role})` : ''}`, {
171
+ details: {
172
+ target: spec.text,
173
+ action,
174
+ nearMisses: rankCandidates(spec, snapshot.elements, { action, minScore: 0.2 }).slice(0, 5).map(describeCandidate),
175
+ },
176
+ hint: 'Use page.smart.inspect() to list interactive elements and their accessible names.',
177
+ });
178
+ if (Date.now() + 250 > deadline)
179
+ throw lastError;
180
+ await this.host.adapter.waitForTimeout(250);
181
+ }
182
+ }
183
+ /** Finds a single element by description. Throws ElementNotFoundError or AmbiguousElementError. */
184
+ async find(target, options = {}) {
185
+ const { snapshot, candidate } = await this.locate(target, 'any', options);
186
+ return toSmartElement(candidate, this.frameUrl(snapshot, candidate.element));
187
+ }
188
+ /** Returns every candidate ranked by score (no ambiguity error). */
189
+ async findAll(target, options = {}) {
190
+ const spec = parseTarget(target);
191
+ const snapshot = await this.scan({ includeHidden: options.includeHidden ?? false, near: spec.near ?? null });
192
+ return rankCandidates(spec, snapshot.elements, {
193
+ action: options.action ?? 'any',
194
+ minScore: options.minScore ?? 0.45,
195
+ nearAnchors: snapshot.nearAnchors,
196
+ }).map((c) => toSmartElement(c, this.frameUrl(snapshot, c.element)));
197
+ }
198
+ /** Locator diagnostics: full ranking with reasons, resolution status and near misses. */
199
+ async diagnose(target, action = 'any') {
200
+ const spec = parseTarget(target);
201
+ const snapshot = await this.scan({ includeHidden: true, near: spec.near ?? null });
202
+ const ranked = rankCandidates(spec, snapshot.elements, { action, minScore: 0.15, nearAnchors: snapshot.nearAnchors });
203
+ const visibleRanked = ranked.filter((c) => c.score >= 0.45);
204
+ const resolution = resolveCandidates(spec, visibleRanked);
205
+ return {
206
+ target: spec,
207
+ status: resolution.status,
208
+ reason: resolution.reason,
209
+ candidates: ranked.slice(0, 10).map((c) => ({ ...describeCandidate(c), reasons: c.reasons })),
210
+ };
211
+ }
212
+ async guard(action, el, extra) {
213
+ const cls = classifyAction(el.name, el.text, el.value && el.type === 'submit' ? el.value : '', extra);
214
+ if (cls.consequential) {
215
+ await this.host.services.approvals.require({
216
+ action,
217
+ target: el.name || el.text || el.cssPath,
218
+ url: redactUrl(this.host.adapter.url()),
219
+ categories: cls.categories,
220
+ reasons: cls.reasons,
221
+ });
222
+ }
223
+ return { consequential: cls.consequential, categories: cls.categories };
224
+ }
225
+ /**
226
+ * Performs an action on a located element; on failure, attempts controlled recovery by fingerprint.
227
+ */
228
+ async perform(action, target, smartAction, options, run) {
229
+ const started = Date.now();
230
+ const label = targetLabel(target);
231
+ const events = this.host.services.events;
232
+ let snapshot;
233
+ let candidate;
234
+ try {
235
+ ({ snapshot, candidate } = await this.locate(target, smartAction, options));
236
+ }
237
+ catch (error) {
238
+ events.emit('interaction:failed', { pageId: this.host.id, action, target: label, error: error.message });
239
+ throw error;
240
+ }
241
+ const el = candidate.element;
242
+ if (!el.enabled) {
243
+ const err = new InteractionError(`Element "${el.name || label}" is disabled`, { details: { target: label, element: describeCandidate(candidate) } });
244
+ events.emit('interaction:failed', { pageId: this.host.id, action, target: label, error: err.message });
245
+ throw err;
246
+ }
247
+ const { consequential } = await this.guard(action, el);
248
+ const fingerprint = fingerprintOf(el, this.host.adapter.url());
249
+ const timeout = options.timeout ?? this.timeout;
250
+ try {
251
+ const details = await run(this.locatorFor(snapshot, el), el);
252
+ return this.result(action, label, started, el, false, details ?? undefined);
253
+ }
254
+ catch (error) {
255
+ const err = toBashirWebError(error, 'INTERACTION');
256
+ if (err.code === 'APPROVAL_REQUIRED' || err.code === 'SECURITY' || err.code === 'VALIDATION')
257
+ throw err;
258
+ const recovered = await this.tryRecover(action, label, fingerprint, smartAction, consequential, timeout, run);
259
+ if (recovered)
260
+ return { ...recovered, duration: Date.now() - started };
261
+ events.emit('interaction:failed', { pageId: this.host.id, action, target: label, error: err.message });
262
+ throw new InteractionError(`${action} on "${el.name || label}" failed: ${err.message}`, {
263
+ cause: error,
264
+ details: { target: label, element: describeCandidate(candidate), recovery: this.host.services.recovery.history.at(-1) ?? null },
265
+ });
266
+ }
267
+ }
268
+ async tryRecover(action, label, fingerprint, smartAction, consequential, timeout, run) {
269
+ const cfg = this.host.services.config.recovery;
270
+ if (!cfg.enabled || cfg.maxAttempts < 1)
271
+ return null;
272
+ for (let attempt = 1; attempt <= cfg.maxAttempts; attempt++) {
273
+ const snapshot = await this.scan();
274
+ const decision = this.host.services.recovery.decide({
275
+ target: label,
276
+ action,
277
+ url: redactUrl(this.host.adapter.url()),
278
+ fingerprint,
279
+ candidates: snapshot.elements,
280
+ consequential,
281
+ });
282
+ if (!decision.accepted || !decision.element)
283
+ return null;
284
+ const el = decision.element;
285
+ try {
286
+ const details = await run(this.locatorFor(snapshot, el).nth(0), el);
287
+ this.host.services.events.emit('locator:recovered', { pageId: this.host.id, target: label, confidence: decision.confidence, strategy: 'fingerprint' });
288
+ return this.result(action, label, Date.now(), el, true, { ...(details ?? {}), recoveryConfidence: decision.confidence, attempt });
289
+ }
290
+ catch (error) {
291
+ this.host.services.logger.debug('recovery attempt failed', { attempt, error: error.message, smartAction, timeout });
292
+ }
293
+ }
294
+ return null;
295
+ }
296
+ result(action, target, started, el, recovered, details) {
297
+ const r = {
298
+ success: true,
299
+ action,
300
+ target,
301
+ url: redactUrl(this.host.adapter.url()),
302
+ duration: Date.now() - started,
303
+ error: null,
304
+ element: { ref: el.ref, role: el.role, name: el.name, selector: el.cssPath },
305
+ recovered,
306
+ };
307
+ if (details && Object.keys(details).length)
308
+ r.details = details;
309
+ return r;
310
+ }
311
+ /** Clicks the element best matching the description. Consequential targets require approval. */
312
+ async click(target, options = {}) {
313
+ const result = await this.perform('click', target, 'click', options, async (loc) => {
314
+ const opts = { timeout: options.timeout ?? this.timeout };
315
+ if (options.button)
316
+ opts.button = options.button;
317
+ if (options.clickCount)
318
+ opts.clickCount = options.clickCount;
319
+ await loc.click(opts);
320
+ });
321
+ this.host.services.events.emit('element:clicked', { pageId: this.host.id, target: targetLabel(target) });
322
+ return result;
323
+ }
324
+ async doubleClick(target, options = {}) {
325
+ return this.perform('doubleClick', target, 'click', options, async (loc) => loc.dblclick({ timeout: options.timeout ?? this.timeout }));
326
+ }
327
+ async hover(target, options = {}) {
328
+ return this.perform('hover', target, 'hover', options, async (loc) => loc.hover({ timeout: options.timeout ?? this.timeout }));
329
+ }
330
+ /** Fills a text field (clearing it first) and verifies the resulting value. */
331
+ async fill(target, value, options = {}) {
332
+ if (typeof value !== 'string')
333
+ throw new ValidationError('fill value must be a string');
334
+ const result = await this.perform('fill', target, 'fill', options, async (loc, el) => {
335
+ if (!el.editable && el.role !== 'combobox')
336
+ throw new InteractionError(`Element "${el.name}" is not editable`);
337
+ await loc.fill(value, { timeout: options.timeout ?? this.timeout });
338
+ if (el.tag === 'input' || el.tag === 'textarea') {
339
+ const actual = await loc.inputValue({ timeout: 2000 });
340
+ if (actual !== value && !['number', 'date', 'time', 'color', 'range'].includes(el.type)) {
341
+ throw new InteractionError('Value verification failed after fill (field may be reformatting input)', {
342
+ details: { expectedLength: value.length, actualLength: actual.length },
343
+ });
344
+ }
345
+ }
346
+ return { verified: true, sensitive: options.sensitive ?? el.type === 'password' };
347
+ });
348
+ this.host.services.events.emit('element:filled', { pageId: this.host.id, target: targetLabel(target) });
349
+ return result;
350
+ }
351
+ /** Types text key-by-key into an element (useful for autocomplete widgets). */
352
+ async type(target, text, options = {}) {
353
+ return this.perform('type', target, 'fill', options, async (loc) => {
354
+ await loc.type(text, { delay: options.delay ?? 0, timeout: options.timeout ?? this.timeout });
355
+ });
356
+ }
357
+ /** Presses a key with the element focused. */
358
+ async press(target, key, options = {}) {
359
+ return this.perform('press', target, 'any', options, async (loc, el) => {
360
+ if (key === 'Enter' && el.formIndex >= 0)
361
+ await this.guard('submit', el, 'submit');
362
+ await loc.press(key, { timeout: options.timeout ?? this.timeout });
363
+ });
364
+ }
365
+ /**
366
+ * Selects option(s) in a native select, an ARIA combobox/listbox, or a radio group.
367
+ * Options are matched by exact label, exact value, then unambiguous fuzzy label match.
368
+ */
369
+ async select(target, value, options = {}) {
370
+ const values = Array.isArray(value) ? value : [value];
371
+ if (!values.length)
372
+ throw new ValidationError('select requires at least one value');
373
+ const timeout = options.timeout ?? this.timeout;
374
+ try {
375
+ return await this.perform('select', target, 'select', options, async (loc, el) => {
376
+ if (el.tag === 'select') {
377
+ const chosen = values.map((v) => matchOption(el.options, v));
378
+ await loc.selectOption(chosen.map((o) => ({ value: o.value })), { timeout });
379
+ return { selected: chosen.map((o) => o.label) };
380
+ }
381
+ if (el.role === 'combobox' || el.role === 'listbox' || el.options.length) {
382
+ if (el.tag === 'input' && el.options.length) {
383
+ const o = matchOption(el.options, values[0]);
384
+ await loc.fill(o.value, { timeout });
385
+ return { selected: [o.label] };
386
+ }
387
+ await loc.click({ timeout });
388
+ const picked = [];
389
+ for (const v of values) {
390
+ const opt = await this.locate({ text: v, role: 'option' }, 'click', { timeout: Math.min(timeout, 5000) });
391
+ await this.locatorFor(opt.snapshot, opt.candidate.element).click({ timeout });
392
+ picked.push(opt.candidate.element.name);
393
+ }
394
+ return { selected: picked };
395
+ }
396
+ throw new InteractionError(`Element "${el.name}" (${el.role || el.tag}) is not selectable`);
397
+ });
398
+ }
399
+ catch (error) {
400
+ // Radio-group fallback: "Plan" → radio "Pro" inside a group labelled "Plan".
401
+ if (typeof target === 'object' && 'ref' in target)
402
+ throw error;
403
+ const err = toBashirWebError(error);
404
+ if (err.code !== 'ELEMENT_NOT_FOUND' && err.code !== 'INTERACTION')
405
+ throw error;
406
+ const spec = parseTarget(target);
407
+ const radio = await this.locate({ text: values[0], role: 'radio', within: spec.text }, 'check', { ...options, timeout: Math.min(timeout, 2000) }).catch(() => null);
408
+ if (!radio)
409
+ throw error;
410
+ await this.guard('select', radio.candidate.element);
411
+ await this.locatorFor(radio.snapshot, radio.candidate.element).check({ timeout });
412
+ return this.result('select', targetLabel(target), Date.now(), radio.candidate.element, false, {
413
+ selected: [radio.candidate.element.name],
414
+ via: 'radio-group',
415
+ });
416
+ }
417
+ }
418
+ /** Checks a checkbox, switch or radio (no-op if already checked). */
419
+ async check(target, options = {}) {
420
+ return this.setChecked(target, true, options);
421
+ }
422
+ /** Unchecks a checkbox or switch (no-op if already unchecked). */
423
+ async uncheck(target, options = {}) {
424
+ return this.setChecked(target, false, options);
425
+ }
426
+ async setChecked(target, checked, options) {
427
+ const timeout = options.timeout ?? this.timeout;
428
+ return this.perform(checked ? 'check' : 'uncheck', target, 'check', options, async (loc, el) => {
429
+ if (el.tag === 'input' && (el.type === 'checkbox' || el.type === 'radio')) {
430
+ if (checked)
431
+ await loc.check({ timeout });
432
+ else
433
+ await loc.uncheck({ timeout });
434
+ }
435
+ else {
436
+ if (el.checked !== checked)
437
+ await loc.click({ timeout });
438
+ const state = await loc.getAttribute('aria-checked', { timeout: 2000 });
439
+ if (state !== null && (state === 'true') !== checked)
440
+ throw new InteractionError('Checked state did not change');
441
+ }
442
+ return { checked };
443
+ });
444
+ }
445
+ /** Uploads files into a file input. Files must be inside security.uploads.allowedDirs. */
446
+ async uploadFile(target, files, options = {}) {
447
+ const list = (Array.isArray(files) ? files : [files]).map((f) => validateUploadPath(f, this.host.services.config.security.uploads.allowedDirs));
448
+ return this.perform('upload', target, 'click', options, async (loc, el) => {
449
+ if (el.type !== 'file')
450
+ throw new InteractionError(`Element "${el.name}" is not a file input`);
451
+ await loc.setInputFiles(list, { timeout: options.timeout ?? this.timeout });
452
+ return { files: list.length };
453
+ });
454
+ }
455
+ /** Summarises the page for humans and agents: interactive elements, headings, landmarks and forms. */
456
+ async inspect(options = {}) {
457
+ const snapshot = await this.scan({ includeHidden: options.includeHidden ?? false });
458
+ const headings = await this.host.adapter.evaluate(() => Array.from(document.querySelectorAll('h1, h2, h3, h4, h5, h6'))
459
+ .map((h) => ({ level: Number(h.tagName.slice(1)), text: (h.textContent ?? '').replace(/\s+/g, ' ').trim() }))
460
+ .filter((h) => h.text)
461
+ .slice(0, 100), null);
462
+ const forms = await this.host.adapter.evaluate(scanForms, undefined);
463
+ const els = snapshot.elements;
464
+ const limit = options.limit ?? 200;
465
+ return {
466
+ url: redactUrl(snapshot.main.url),
467
+ title: snapshot.main.title,
468
+ viewport: snapshot.main.viewport,
469
+ documentSize: snapshot.main.documentSize,
470
+ counts: {
471
+ interactive: els.length,
472
+ links: els.filter((e) => e.role === 'link').length,
473
+ buttons: els.filter((e) => e.role === 'button').length,
474
+ inputs: els.filter((e) => FIELD_ROLES.has(e.role)).length,
475
+ forms: forms.length,
476
+ frames: snapshot.frames.size,
477
+ },
478
+ elements: els.slice(0, limit).map((e) => {
479
+ const item = {
480
+ ref: e.ref,
481
+ role: e.role,
482
+ name: e.name,
483
+ tag: e.tag,
484
+ type: e.type,
485
+ visible: e.visible,
486
+ enabled: e.enabled,
487
+ inViewport: e.inViewport,
488
+ landmark: e.landmark,
489
+ selector: e.cssPath,
490
+ };
491
+ if (e.value && e.type !== 'password')
492
+ item.value = e.value;
493
+ if (e.href)
494
+ item.href = redactUrl(e.href);
495
+ return item;
496
+ }),
497
+ headings,
498
+ landmarks: [...new Set(els.map((e) => e.landmark).filter(Boolean))],
499
+ forms: forms.map((f) => ({
500
+ index: f.index,
501
+ label: f.label,
502
+ method: f.method,
503
+ fieldCount: els.filter((e) => e.formIndex === f.index && FIELD_ROLES.has(e.role)).length,
504
+ })),
505
+ };
506
+ }
507
+ /** Inspects all forms on the page. */
508
+ async inspectForms() {
509
+ const snapshot = await this.scan();
510
+ const forms = await this.host.adapter.evaluate(scanForms, undefined);
511
+ const main = snapshot.elements.filter((e) => e.frameIndex === [...snapshot.frames.entries()].find(([, f]) => f.isMain())?.[0]);
512
+ const groups = forms.map((f) => this.buildForm(f, main.filter((e) => e.formIndex === f.index)));
513
+ const loose = main.filter((e) => e.formIndex === -1 && FIELD_ROLES.has(e.role));
514
+ if (loose.length) {
515
+ groups.push(this.buildForm({ index: -1, label: 'Fields outside a <form>', name: '', id: '', action: '', method: 'none' }, main.filter((e) => e.formIndex === -1)));
516
+ }
517
+ return groups.filter((g) => g.fields.length > 0);
518
+ }
519
+ /**
520
+ * Inspects one form. With no argument, returns the form with the most fields.
521
+ * `target` may be a form index or text matching the form's label/heading.
522
+ */
523
+ async inspectForm(target) {
524
+ const forms = await this.inspectForms();
525
+ if (!forms.length)
526
+ throw new ElementNotFoundError('No form fields found on the page');
527
+ if (typeof target === 'number') {
528
+ const f = forms.find((x) => x.index === target);
529
+ if (!f)
530
+ throw new ElementNotFoundError(`Form #${target} not found`, { details: { available: forms.map((x) => x.index) } });
531
+ return f;
532
+ }
533
+ if (typeof target === 'string') {
534
+ const scored = forms
535
+ .map((f) => ({ f, s: Math.max(textMatchScore(target, f.label), textMatchScore(target, f.name), textMatchScore(target, f.id)) }))
536
+ .sort((a, b) => b.s - a.s);
537
+ const best = scored[0];
538
+ if (!best || best.s < 0.5)
539
+ throw new ElementNotFoundError(`No form matches "${target}"`, { details: { forms: forms.map((f) => f.label) } });
540
+ if (scored[1] && best.s - scored[1].s < 0.04)
541
+ throw new AmbiguousElementError(`Several forms match "${target}"`, { details: { forms: scored.slice(0, 4).map((x) => x.f.label) } });
542
+ return best.f;
543
+ }
544
+ return [...forms].sort((a, b) => b.fields.length - a.fields.length)[0];
545
+ }
546
+ buildForm(form, els) {
547
+ const fields = [];
548
+ const radios = new Map();
549
+ for (const el of els) {
550
+ if (el.role === 'radio') {
551
+ const key = el.nameAttr || el.container || 'radio';
552
+ radios.set(key, [...(radios.get(key) ?? []), el]);
553
+ continue;
554
+ }
555
+ if (!FIELD_ROLES.has(el.role) && !(el.tag === 'input' && el.type === 'file'))
556
+ continue;
557
+ fields.push({
558
+ key: el.nameAttr || el.id || el.name,
559
+ label: el.name || el.label || el.placeholder || el.nearbyText || el.nameAttr,
560
+ kind: fieldKind(el),
561
+ ref: el.ref,
562
+ name: el.nameAttr,
563
+ id: el.id,
564
+ type: el.type,
565
+ role: el.role,
566
+ required: el.required,
567
+ disabled: !el.enabled,
568
+ readonly: el.readonly,
569
+ visible: el.visible,
570
+ value: el.type === 'password' ? (el.value ? '••••' : '') : el.value,
571
+ checked: el.checked,
572
+ placeholder: el.placeholder,
573
+ autocomplete: el.autocomplete,
574
+ description: el.description,
575
+ options: el.options.map((o) => ({ value: o.value, label: o.label, selected: o.selected })),
576
+ });
577
+ }
578
+ for (const [key, group] of radios) {
579
+ const first = group[0];
580
+ fields.push({
581
+ key,
582
+ label: first.container || first.nearbyText || key,
583
+ kind: 'radio-group',
584
+ ref: first.ref,
585
+ name: first.nameAttr,
586
+ id: '',
587
+ type: 'radio',
588
+ role: 'radiogroup',
589
+ required: group.some((g) => g.required),
590
+ disabled: group.every((g) => !g.enabled),
591
+ readonly: false,
592
+ visible: group.some((g) => g.visible),
593
+ value: group.find((g) => g.checked)?.name ?? '',
594
+ checked: null,
595
+ placeholder: '',
596
+ autocomplete: '',
597
+ description: '',
598
+ options: group.map((g) => ({ value: g.value, label: g.name, selected: g.checked === true, ref: g.ref })),
599
+ });
600
+ }
601
+ fields.sort((a, b) => {
602
+ const ea = els.findIndex((e) => e.ref === a.ref);
603
+ const eb = els.findIndex((e) => e.ref === b.ref);
604
+ return ea - eb;
605
+ });
606
+ const submitButtons = els
607
+ .filter((e) => e.role === 'button' && (e.type === 'submit' || (e.tag === 'button' && (e.type === '' || e.type === 'submit')) || e.type === 'image'))
608
+ .map((e) => {
609
+ const cls = classifyAction(e.name, 'submit');
610
+ return { ref: e.ref, name: e.name, consequential: true, categories: cls.categories };
611
+ });
612
+ return { index: form.index, label: form.label, name: form.name, id: form.id, action: redactUrl(form.action), method: form.method, fields, submitButtons };
613
+ }
614
+ /**
615
+ * Maps structured data onto form fields, validates the whole mapping first, then fills fields in order.
616
+ * Submission only happens when `submit` is set AND approval is granted.
617
+ */
618
+ async fillForm(data, options = {}) {
619
+ if (!data || typeof data !== 'object' || Array.isArray(data))
620
+ throw new ValidationError('fillForm data must be an object of { label: value }');
621
+ const keys = Object.keys(data);
622
+ if (!keys.length)
623
+ throw new ValidationError('fillForm data is empty');
624
+ const form = options.form !== undefined ? await this.inspectForm(options.form) : await this.pickForm(keys);
625
+ const errors = [];
626
+ const warnings = [];
627
+ const mapping = [];
628
+ const used = new Map();
629
+ for (const key of keys) {
630
+ const scored = form.fields
631
+ .map((f) => ({
632
+ f,
633
+ s: Math.max(textMatchScore(key, f.label), textMatchScore(key, f.placeholder) * 0.92, textMatchScore(key, f.name.replace(/[_\-.]/g, ' ')) * 0.85, textMatchScore(key, f.id.replace(/[_\-.]/g, ' ')) * 0.8, f.key === key ? 1 : 0),
634
+ }))
635
+ .sort((a, b) => b.s - a.s);
636
+ const best = scored[0];
637
+ if (!best || best.s < 0.55) {
638
+ errors.push(`"${key}": no matching field (closest: ${scored
639
+ .slice(0, 3)
640
+ .map((x) => `"${x.f.label}"`)
641
+ .join(', ') || 'none'})`);
642
+ continue;
643
+ }
644
+ if (scored[1] && best.s - scored[1].s < 0.04 && scored[1].s >= 0.55) {
645
+ errors.push(`"${key}": ambiguous between "${best.f.label}" and "${scored[1].f.label}"`);
646
+ continue;
647
+ }
648
+ if (used.has(best.f.ref)) {
649
+ errors.push(`"${key}" and "${used.get(best.f.ref)}" map to the same field "${best.f.label}"`);
650
+ continue;
651
+ }
652
+ used.set(best.f.ref, key);
653
+ const problem = validateFieldValue(best.f, data[key], this.host.services.config.security.uploads.allowedDirs);
654
+ if (problem)
655
+ errors.push(`"${key}" → "${best.f.label}": ${problem}`);
656
+ if (best.f.disabled || best.f.readonly)
657
+ errors.push(`"${key}" → "${best.f.label}": field is ${best.f.disabled ? 'disabled' : 'read-only'}`);
658
+ mapping.push({ key, field: best.f.label, ref: best.f.ref, kind: best.f.kind, score: Math.round(best.s * 1000) / 1000 });
659
+ }
660
+ for (const f of form.fields) {
661
+ if (f.required && !used.has(f.ref) && !f.value && f.kind !== 'checkbox')
662
+ warnings.push(`required field "${f.label}" was not provided`);
663
+ }
664
+ if (errors.length) {
665
+ throw new ValidationError(`Form mapping validation failed:\n - ${errors.join('\n - ')}`, {
666
+ details: { errors, form: form.label, fields: form.fields.map((f) => f.label) },
667
+ });
668
+ }
669
+ const result = {
670
+ form: { index: form.index, label: form.label },
671
+ mapping,
672
+ filled: [],
673
+ warnings,
674
+ submitted: false,
675
+ dryRun: Boolean(options.dryRun),
676
+ };
677
+ if (options.dryRun)
678
+ return result;
679
+ const timeout = options.timeout ?? this.timeout;
680
+ for (const m of mapping) {
681
+ const field = form.fields.find((f) => f.ref === m.ref);
682
+ const value = data[m.key];
683
+ const ref = { ref: field.ref, name: field.label };
684
+ switch (field.kind) {
685
+ case 'checkbox':
686
+ await (toBool(value) ? this.check(ref, { timeout }) : this.uncheck(ref, { timeout }));
687
+ break;
688
+ case 'select':
689
+ case 'multiselect':
690
+ await this.select(ref, Array.isArray(value) ? value.map(String) : String(value), { timeout });
691
+ break;
692
+ case 'radio-group': {
693
+ const opt = matchOption(field.options.map((o) => ({ ...o, disabled: false })), String(value));
694
+ const radioRef = field.options.find((o) => o.value === opt.value && o.label === opt.label)?.ref;
695
+ if (!radioRef)
696
+ throw new InteractionError(`Radio option "${String(value)}" not found`);
697
+ await this.check({ ref: radioRef, name: opt.label }, { timeout });
698
+ break;
699
+ }
700
+ case 'file':
701
+ await this.uploadFile(ref, Array.isArray(value) ? value.map(String) : String(value), { timeout });
702
+ break;
703
+ default:
704
+ await this.fill(ref, String(value), { timeout, sensitive: field.kind === 'password' });
705
+ }
706
+ result.filled.push(m.key);
707
+ }
708
+ if (options.submit) {
709
+ let button;
710
+ if (options.submit === true) {
711
+ if (form.submitButtons.length > 1)
712
+ throw new AmbiguousElementError('Form has several submit buttons; pass submit: "<button text>"', {
713
+ details: { buttons: form.submitButtons.map((b) => b.name) },
714
+ });
715
+ button = form.submitButtons[0];
716
+ }
717
+ else {
718
+ const spec = parseTarget(options.submit);
719
+ button = form.submitButtons
720
+ .map((b) => ({ b, s: textMatchScore(spec.text, b.name) }))
721
+ .sort((a, b) => b.s - a.s)
722
+ .find((x) => x.s >= 0.6)?.b;
723
+ }
724
+ if (!button)
725
+ throw new ElementNotFoundError('No submit button found for the form');
726
+ const cls = classifyAction(button.name);
727
+ const categories = [...new Set(['form-submission', ...cls.categories])];
728
+ await this.host.services.approvals.require({
729
+ action: 'submit-form',
730
+ target: button.name || form.label,
731
+ url: redactUrl(this.host.adapter.url()),
732
+ categories,
733
+ reasons: [`submitting form "${form.label || form.index}"`, ...cls.reasons],
734
+ });
735
+ const snapshot = await this.scan();
736
+ const el = snapshot.elements.find((e) => e.ref === button.ref);
737
+ if (!el)
738
+ throw new ElementNotFoundError('Submit button disappeared before submission');
739
+ await this.locatorFor(snapshot, el).click({ timeout });
740
+ result.submitted = true;
741
+ }
742
+ return result;
743
+ }
744
+ async pickForm(keys) {
745
+ const forms = await this.inspectForms();
746
+ if (!forms.length)
747
+ throw new ElementNotFoundError('No form fields found on the page');
748
+ if (forms.length === 1)
749
+ return forms[0];
750
+ const scored = forms
751
+ .map((f) => ({
752
+ f,
753
+ s: keys.reduce((acc, k) => acc + (Math.max(0, ...f.fields.map((x) => Math.max(textMatchScore(k, x.label), textMatchScore(k, x.name)))) >= 0.55 ? 1 : 0), 0),
754
+ }))
755
+ .sort((a, b) => b.s - a.s);
756
+ if (scored[1] && scored[0].s === scored[1].s) {
757
+ throw new AmbiguousElementError('Several forms match the provided fields; pass { form: <index or label> }', {
758
+ details: { forms: scored.map((x) => ({ index: x.f.index, label: x.f.label, matches: x.s })) },
759
+ });
760
+ }
761
+ return scored[0].f;
762
+ }
763
+ }
764
+ function toBool(v) {
765
+ if (typeof v === 'boolean')
766
+ return v;
767
+ return /^(true|yes|on|1|checked)$/i.test(String(v));
768
+ }
769
+ function matchOption(options, wanted) {
770
+ const w = normalizeText(wanted);
771
+ const enabled = options.filter((o) => !o.disabled);
772
+ const exact = enabled.find((o) => normalizeText(o.label) === w) ?? enabled.find((o) => normalizeText(o.value) === w);
773
+ if (exact)
774
+ return exact;
775
+ const fuzzy = enabled.map((o) => ({ o, s: Math.max(textMatchScore(wanted, o.label), textMatchScore(wanted, o.value)) })).sort((a, b) => b.s - a.s);
776
+ if (fuzzy[0] && fuzzy[0].s >= 0.8 && !(fuzzy[1] && fuzzy[0].s - fuzzy[1].s < 0.05))
777
+ return fuzzy[0].o;
778
+ throw new ValidationError(`Option "${wanted}" not found`, { details: { available: enabled.slice(0, 50).map((o) => o.label) } });
779
+ }
780
+ function validateFieldValue(field, value, allowedDirs) {
781
+ const str = Array.isArray(value) ? value.join(',') : String(value);
782
+ switch (field.kind) {
783
+ case 'email':
784
+ return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(str) ? null : 'not a valid email address';
785
+ case 'number':
786
+ case 'range':
787
+ return str.trim() !== '' && Number.isFinite(Number(str)) ? null : 'not a number';
788
+ case 'date':
789
+ return /^\d{4}-\d{2}-\d{2}$/.test(str) ? null : 'dates must use YYYY-MM-DD';
790
+ case 'time':
791
+ return /^\d{2}:\d{2}(:\d{2})?$/.test(str) ? null : 'times must use HH:MM';
792
+ case 'datetime':
793
+ return /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}/.test(str) ? null : 'datetimes must use YYYY-MM-DDTHH:MM';
794
+ case 'url':
795
+ try {
796
+ new URL(str);
797
+ return null;
798
+ }
799
+ catch {
800
+ return 'not a valid URL';
801
+ }
802
+ case 'checkbox':
803
+ return typeof value === 'boolean' || /^(true|false|yes|no|on|off|1|0|checked|unchecked)$/i.test(str) ? null : 'checkbox values must be boolean';
804
+ case 'select':
805
+ case 'multiselect':
806
+ case 'radio-group': {
807
+ if (!field.options.length)
808
+ return null; // custom combobox: options load dynamically
809
+ const wanted = Array.isArray(value) ? value.map(String) : [str];
810
+ if (field.kind !== 'multiselect' && wanted.length > 1)
811
+ return 'only one option can be selected';
812
+ for (const w of wanted) {
813
+ try {
814
+ matchOption(field.options.map((o) => ({ ...o, disabled: false })), w);
815
+ }
816
+ catch {
817
+ return `option "${w}" is not available (options: ${field.options
818
+ .slice(0, 10)
819
+ .map((o) => o.label)
820
+ .join(', ')})`;
821
+ }
822
+ }
823
+ return null;
824
+ }
825
+ case 'file': {
826
+ const files = Array.isArray(value) ? value.map(String) : [str];
827
+ try {
828
+ for (const f of files)
829
+ validateUploadPath(f, allowedDirs);
830
+ return null;
831
+ }
832
+ catch (error) {
833
+ return error.message;
834
+ }
835
+ }
836
+ default:
837
+ return typeof value === 'object' && !Array.isArray(value) ? 'value must be a string' : null;
838
+ }
839
+ }
840
+ //# sourceMappingURL=smart.js.map