mcp-browser-dev-tools 0.0.6 → 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.
package/src/wait-for.mjs CHANGED
@@ -34,6 +34,152 @@ function normalizeInteger(value, fallback) {
34
34
  return Number.isInteger(value) && value > 0 ? value : fallback;
35
35
  }
36
36
 
37
+ function normalizeText(value) {
38
+ return typeof value === "string" ? value.replace(/\s+/g, " ").trim() : "";
39
+ }
40
+
41
+ // Text conditions compare whitespace-normalized visible text, which the page
42
+ // context clips to 400 characters and marks with a trailing "...".
43
+ const PAGE_TEXT_LIMIT = 400;
44
+ const CLIP_MARKER = "...";
45
+
46
+ function readElementText(result) {
47
+ const raw = result?.node?.innerText ?? result?.node?.textContent;
48
+ const clipped =
49
+ typeof raw === "string" &&
50
+ raw.length === PAGE_TEXT_LIMIT + CLIP_MARKER.length &&
51
+ raw.endsWith(CLIP_MARKER);
52
+ return {
53
+ text: normalizeText(clipped ? raw.slice(0, PAGE_TEXT_LIMIT) : raw),
54
+ clipped,
55
+ };
56
+ }
57
+
58
+ function elementText(result) {
59
+ return readElementText(result).text;
60
+ }
61
+
62
+ function hasTextCondition(options) {
63
+ return (
64
+ options.textEquals !== null ||
65
+ options.textIncludes !== null ||
66
+ options.textExcludes !== null
67
+ );
68
+ }
69
+
70
+ function textChecksFor(condition) {
71
+ return {
72
+ textEquals: condition.textEquals,
73
+ textIncludes: condition.textIncludes,
74
+ textExcludes: condition.textExcludes,
75
+ };
76
+ }
77
+
78
+ function textMatches(result, options, checkIndex) {
79
+ if (!hasTextCondition(options)) {
80
+ return true;
81
+ }
82
+
83
+ if (!result?.found) {
84
+ return false;
85
+ }
86
+
87
+ // The page compares the full text when it supports textChecks.
88
+ if (Array.isArray(result.textMatches)) {
89
+ return result.textMatches[checkIndex] === true;
90
+ }
91
+
92
+ // Clipped text is only a prefix, so it can never prove equality or that a
93
+ // string is absent.
94
+ const { text, clipped } = readElementText(result);
95
+ return (
96
+ (options.textEquals === null ||
97
+ (!clipped && text === options.textEquals)) &&
98
+ (options.textIncludes === null || text.includes(options.textIncludes)) &&
99
+ (options.textExcludes === null ||
100
+ (!clipped && !text.includes(options.textExcludes)))
101
+ );
102
+ }
103
+
104
+ // Expression conditions evaluate in the page's main world and hold when the
105
+ // result, awaited if it is a promise, is truthy.
106
+ export const DEFAULT_EXPRESSION_TIMEOUT_MS = 5_000;
107
+ const EXPRESSION_TIMEOUT = "EXPRESSION_TIMEOUT";
108
+
109
+ // The page gives up on its own after timeoutMs, so a promise that never
110
+ // settles does not leave the evaluation pending in the browser. Node waits a
111
+ // little longer as a backstop, since hidden tabs can run timers late.
112
+ const EXPRESSION_PAGE_TIMEOUT = "__mcpExpressionTimeout";
113
+ const EXPRESSION_BACKSTOP_GRACE_MS = 2_000;
114
+
115
+ // The expression is passed in as a function defined at the top level, so it
116
+ // sees only page globals, never the wrapper's own variables. Only the wrapper
117
+ // can produce the timeout marker, since the expression's result is converted
118
+ // to a boolean.
119
+ function conditionExpression(expression, timeoutMs) {
120
+ return `(async (check, timeoutMs) => {
121
+ const timedOut = {};
122
+ const value = await Promise.race([
123
+ check(),
124
+ new Promise((resolve) => {
125
+ setTimeout(() => resolve(timedOut), timeoutMs);
126
+ }),
127
+ ]);
128
+ return value === timedOut ? ${JSON.stringify(EXPRESSION_PAGE_TIMEOUT)} : Boolean(value);
129
+ })(async () => (
130
+ ${expression}
131
+ ), ${timeoutMs})`;
132
+ }
133
+
134
+ function exceptionMessage(details) {
135
+ const description = details?.exception?.description;
136
+ if (typeof description === "string" && description.trim()) {
137
+ return description.split("\n")[0];
138
+ }
139
+ if (typeof details?.text === "string" && details.text.trim()) {
140
+ return details.text;
141
+ }
142
+ const value = details?.exception?.value;
143
+ return value === undefined ? "unknown error" : String(value);
144
+ }
145
+
146
+ async function evaluateCondition(evaluate, expression, timeoutMs) {
147
+ if (typeof evaluate !== "function") {
148
+ throw new Error("expression conditions are not available here");
149
+ }
150
+ const unsettled = () => {
151
+ const error = new Error(
152
+ `expression ${JSON.stringify(expression)} did not settle within ${timeoutMs}ms`,
153
+ );
154
+ error.code = EXPRESSION_TIMEOUT;
155
+ return error;
156
+ };
157
+ let timer;
158
+ const backstop = new Promise((_, reject) => {
159
+ timer = setTimeout(
160
+ () => reject(unsettled()),
161
+ timeoutMs + EXPRESSION_BACKSTOP_GRACE_MS,
162
+ );
163
+ });
164
+ try {
165
+ const result = await Promise.race([
166
+ evaluate(conditionExpression(expression, timeoutMs)),
167
+ backstop,
168
+ ]);
169
+ if (result?.exceptionDetails) {
170
+ throw new Error(
171
+ `expression ${JSON.stringify(expression)} threw: ${exceptionMessage(result.exceptionDetails)}`,
172
+ );
173
+ }
174
+ if (result?.result === EXPRESSION_PAGE_TIMEOUT) {
175
+ throw unsettled();
176
+ }
177
+ return result?.result === true;
178
+ } finally {
179
+ clearTimeout(timer);
180
+ }
181
+ }
182
+
37
183
  function readyStateMatches(current, expected) {
38
184
  const currentRank = READY_STATE_ORDER[current] ?? -1;
39
185
  const expectedRank = READY_STATE_ORDER[expected] ?? -1;
@@ -56,7 +202,7 @@ function selectorMatches(result, state) {
56
202
  return result.node?.visible === true;
57
203
  }
58
204
 
59
- function buildTimeoutMessage(options, lastPage, lastElement) {
205
+ function describeWanted(options) {
60
206
  const conditions = [];
61
207
  if (options.selector) {
62
208
  conditions.push(
@@ -72,7 +218,24 @@ function buildTimeoutMessage(options, lastPage, lastElement) {
72
218
  if (options.readyState) {
73
219
  conditions.push(`readyState to reach ${options.readyState}`);
74
220
  }
221
+ if (options.textEquals !== null) {
222
+ conditions.push(`text to equal ${JSON.stringify(options.textEquals)}`);
223
+ }
224
+ if (options.textIncludes !== null) {
225
+ conditions.push(`text to include ${JSON.stringify(options.textIncludes)}`);
226
+ }
227
+ if (options.textExcludes !== null) {
228
+ conditions.push(`text to exclude ${JSON.stringify(options.textExcludes)}`);
229
+ }
230
+ if (options.expression) {
231
+ conditions.push(
232
+ `expression ${JSON.stringify(options.expression)} to be truthy`,
233
+ );
234
+ }
235
+ return conditions.join(", ");
236
+ }
75
237
 
238
+ function describeObserved(options, lastPage, lastElement, lastExpression) {
76
239
  const observed = [];
77
240
  if (lastPage?.url) {
78
241
  observed.push(`last url=${JSON.stringify(lastPage.url)}`);
@@ -85,104 +248,347 @@ function buildTimeoutMessage(options, lastPage, lastElement) {
85
248
  `last selector found=${Boolean(lastElement.found)} visible=${lastElement.node?.visible === true}`,
86
249
  );
87
250
  }
251
+ if (hasTextCondition(options) && lastElement?.found) {
252
+ observed.push(`last text=${JSON.stringify(elementText(lastElement))}`);
253
+ }
254
+ if (options.expression && typeof lastExpression === "boolean") {
255
+ observed.push(`last expression=${lastExpression}`);
256
+ }
257
+ return observed;
258
+ }
259
+
260
+ function buildTimeoutMessage(normalized, lastCheck) {
261
+ const prefix = `Timed out after ${normalized.timeoutMs}ms waiting for `;
262
+ if (!normalized.anyOf) {
263
+ const observed = describeObserved(
264
+ normalized,
265
+ lastCheck?.page,
266
+ lastCheck?.element,
267
+ lastCheck?.expression,
268
+ );
269
+ return `${prefix}${describeWanted(normalized)}${
270
+ observed.length > 0 ? `; ${observed.join("; ")}` : ""
271
+ }`;
272
+ }
273
+
274
+ const alternatives = normalized.anyOf.map((condition, index) => {
275
+ const check = lastCheck?.alternatives?.[index];
276
+ const observed = describeObserved(
277
+ condition,
278
+ check?.page,
279
+ check?.element,
280
+ check?.expression,
281
+ );
282
+ return `anyOf[${index}] ${describeWanted(condition)}${
283
+ observed.length > 0 ? ` (${observed.join("; ")})` : ""
284
+ }`;
285
+ });
286
+ return `${prefix}any of: ${alternatives.join("; or ")}`;
287
+ }
88
288
 
89
- return `Timed out after ${options.timeoutMs}ms waiting for ${conditions.join(
90
- ", ",
91
- )}${observed.length > 0 ? `; ${observed.join("; ")}` : ""}`;
289
+ const CONDITION_KEYS = [
290
+ "selector",
291
+ "state",
292
+ "url",
293
+ "urlIncludes",
294
+ "readyState",
295
+ "textEquals",
296
+ "textIncludes",
297
+ "textExcludes",
298
+ "expression",
299
+ ];
300
+
301
+ function normalizeOptionalText(value) {
302
+ return typeof value === "string" ? normalizeText(value) : null;
92
303
  }
93
304
 
94
- export function normalizeWaitForOptions(options = {}) {
305
+ function normalizeCondition(options, label) {
306
+ if (options.anyOf !== undefined) {
307
+ throw new Error(`${label} cannot nest anyOf`);
308
+ }
309
+
95
310
  const normalized = {
96
311
  selector: normalizeOptionalString(options.selector),
97
312
  state: normalizeSelectorState(options.state),
98
313
  url: normalizeOptionalString(options.url),
99
314
  urlIncludes: normalizeOptionalString(options.urlIncludes),
100
315
  readyState: normalizeReadyState(options.readyState),
101
- timeoutMs: normalizeInteger(options.timeoutMs, 10_000),
102
- pollIntervalMs: normalizeInteger(options.pollIntervalMs, 100),
316
+ textEquals: normalizeOptionalText(options.textEquals),
317
+ textIncludes: normalizeOptionalText(options.textIncludes),
318
+ textExcludes: normalizeOptionalText(options.textExcludes),
319
+ expression: normalizeOptionalString(options.expression),
103
320
  };
104
321
 
105
322
  if (
106
323
  !normalized.selector &&
107
324
  !normalized.url &&
108
325
  !normalized.urlIncludes &&
109
- !normalized.readyState
326
+ !normalized.readyState &&
327
+ !normalized.expression
110
328
  ) {
111
329
  throw new Error(
112
- "wait_for requires at least one of selector, url, urlIncludes, or readyState",
330
+ `${label} requires at least one of selector, url, urlIncludes, readyState, or expression`,
113
331
  );
114
332
  }
115
333
 
116
334
  if (!normalized.selector && options.state !== undefined) {
117
- throw new Error("wait_for state requires selector");
335
+ throw new Error(`${label} state requires selector`);
336
+ }
337
+
338
+ if (hasTextCondition(normalized) && !normalized.selector) {
339
+ throw new Error(
340
+ `${label} textEquals, textIncludes, and textExcludes require selector`,
341
+ );
342
+ }
343
+
344
+ if (hasTextCondition(normalized) && normalized.state === "hidden") {
345
+ throw new Error(
346
+ `${label} textEquals, textIncludes, and textExcludes cannot be combined with state hidden`,
347
+ );
118
348
  }
119
349
 
120
350
  return normalized;
121
351
  }
122
352
 
353
+ // Returns either one condition or { anyOf: [conditions] }, plus timing.
354
+ export function normalizeWaitForOptions(options = {}, label = "wait_for") {
355
+ const timing = {
356
+ timeoutMs: normalizeInteger(options.timeoutMs, 10_000),
357
+ pollIntervalMs: normalizeInteger(options.pollIntervalMs, 100),
358
+ };
359
+ if (options.anyOf === undefined) {
360
+ return { ...normalizeCondition(options, label), ...timing };
361
+ }
362
+
363
+ if (!Array.isArray(options.anyOf) || options.anyOf.length === 0) {
364
+ throw new Error(`${label} anyOf must list at least one condition`);
365
+ }
366
+ const mixed = CONDITION_KEYS.filter((key) => options[key] !== undefined);
367
+ if (mixed.length > 0) {
368
+ throw new Error(
369
+ `${label} anyOf cannot be combined with ${mixed.join(", ")}; put them inside each anyOf condition`,
370
+ );
371
+ }
372
+ return {
373
+ anyOf: options.anyOf.map((condition, index) =>
374
+ normalizeCondition(condition ?? {}, `${label}.anyOf[${index}]`),
375
+ ),
376
+ ...timing,
377
+ };
378
+ }
379
+
380
+ async function checkOneCondition(
381
+ condition,
382
+ readPage,
383
+ readElement,
384
+ readExpression,
385
+ ) {
386
+ let checkIndex = -1;
387
+ const page =
388
+ condition.url || condition.urlIncludes || condition.readyState
389
+ ? await readPage()
390
+ : null;
391
+ let element = null;
392
+ if (condition.selector) {
393
+ let textChecks;
394
+ ({ element, textChecks } = await readElement(condition.selector));
395
+ checkIndex = textChecks.indexOf(JSON.stringify(textChecksFor(condition)));
396
+ if (element?.error) {
397
+ throw new Error(element.error);
398
+ }
399
+ }
400
+
401
+ const matched =
402
+ (condition.selector
403
+ ? selectorMatches(element, condition.state) &&
404
+ textMatches(element, condition, checkIndex)
405
+ : true) &&
406
+ (condition.url ? page?.url === condition.url : true) &&
407
+ (condition.urlIncludes
408
+ ? page?.url?.includes(condition.urlIncludes) === true
409
+ : true) &&
410
+ (condition.readyState
411
+ ? readyStateMatches(page?.readyState, condition.readyState)
412
+ : true);
413
+ const expression = condition.expression
414
+ ? await readExpression(condition.expression)
415
+ : null;
416
+
417
+ return {
418
+ matched: matched && (condition.expression ? expression : true),
419
+ page,
420
+ element,
421
+ text: element?.found ? elementText(element) : null,
422
+ expression,
423
+ };
424
+ }
425
+
426
+ // Checks normalized conditions once against the current page. For anyOf, the
427
+ // alternatives are checked in order until one holds, reading the page state
428
+ // and each selector at most once. Expressions must settle by deadline.
429
+ export async function checkPageCondition({
430
+ getPageState,
431
+ inspectElement,
432
+ evaluate,
433
+ normalized,
434
+ deadline = Date.now() + DEFAULT_EXPRESSION_TIMEOUT_MS,
435
+ }) {
436
+ let pagePromise = null;
437
+ const readPage = () => {
438
+ pagePromise ??= getPageState();
439
+ return pagePromise;
440
+ };
441
+ const expressions = new Map();
442
+ const readExpression = (expression) => {
443
+ if (!expressions.has(expression)) {
444
+ expressions.set(
445
+ expression,
446
+ evaluateCondition(
447
+ evaluate,
448
+ expression,
449
+ Math.max(1, deadline - Date.now()),
450
+ ),
451
+ );
452
+ }
453
+ return expressions.get(expression);
454
+ };
455
+ // Gather every text check per selector first, so one inspection per
456
+ // selector answers all of them.
457
+ const conditions = normalized.anyOf ?? [normalized];
458
+ const textChecks = new Map();
459
+ for (const condition of conditions) {
460
+ if (!condition.selector || !hasTextCondition(condition)) {
461
+ continue;
462
+ }
463
+ const checks = textChecks.get(condition.selector) ?? [];
464
+ const key = JSON.stringify(textChecksFor(condition));
465
+ if (!checks.includes(key)) {
466
+ checks.push(key);
467
+ }
468
+ textChecks.set(condition.selector, checks);
469
+ }
470
+ const elements = new Map();
471
+ const readElement = (selector) => {
472
+ if (!elements.has(selector)) {
473
+ const checks = textChecks.get(selector) ?? [];
474
+ elements.set(
475
+ selector,
476
+ (checks.length > 0
477
+ ? inspectElement(selector, {
478
+ textChecks: checks.map((key) => JSON.parse(key)),
479
+ })
480
+ : inspectElement(selector)
481
+ ).then((element) => ({ element, textChecks: checks })),
482
+ );
483
+ }
484
+ return elements.get(selector);
485
+ };
486
+
487
+ if (!normalized.anyOf) {
488
+ return checkOneCondition(normalized, readPage, readElement, readExpression);
489
+ }
490
+
491
+ const alternatives = [];
492
+ for (const condition of normalized.anyOf) {
493
+ const check = await checkOneCondition(
494
+ condition,
495
+ readPage,
496
+ readElement,
497
+ readExpression,
498
+ );
499
+ alternatives.push(check);
500
+ if (check.matched) {
501
+ return {
502
+ ...check,
503
+ matchedIndex: alternatives.length - 1,
504
+ alternatives,
505
+ };
506
+ }
507
+ }
508
+ return {
509
+ matched: false,
510
+ page: null,
511
+ element: null,
512
+ text: null,
513
+ expression: null,
514
+ matchedIndex: null,
515
+ alternatives,
516
+ };
517
+ }
518
+
519
+ function describeCondition(condition) {
520
+ return {
521
+ selector: condition.selector,
522
+ state: condition.selector ? condition.state : null,
523
+ url: condition.url,
524
+ urlIncludes: condition.urlIncludes,
525
+ readyState: condition.readyState,
526
+ textEquals: condition.textEquals,
527
+ textIncludes: condition.textIncludes,
528
+ textExcludes: condition.textExcludes,
529
+ ...(condition.expression ? { expression: condition.expression } : {}),
530
+ };
531
+ }
532
+
123
533
  export async function waitForPageCondition({
124
534
  getPageState,
125
535
  inspectElement,
536
+ evaluate,
126
537
  options,
127
538
  }) {
128
539
  const normalized = normalizeWaitForOptions(options);
129
540
  const startedAt = Date.now();
130
541
  let attempts = 0;
131
- let lastPage = null;
132
- let lastElement = null;
542
+ let lastCheck = null;
133
543
 
134
544
  while (true) {
135
545
  attempts += 1;
136
546
 
137
- if (normalized.url || normalized.urlIncludes || normalized.readyState) {
138
- lastPage = await getPageState();
139
- }
140
-
141
- if (normalized.selector) {
142
- lastElement = await inspectElement(normalized.selector);
143
- if (lastElement?.error) {
144
- throw new Error(lastElement.error);
547
+ let check;
548
+ try {
549
+ check = await checkPageCondition({
550
+ getPageState,
551
+ inspectElement,
552
+ evaluate,
553
+ normalized,
554
+ deadline: startedAt + normalized.timeoutMs,
555
+ });
556
+ } catch (error) {
557
+ // An expression cut off by the deadline after earlier polls completed
558
+ // is an ordinary timeout; report what those polls observed.
559
+ if (error.code === EXPRESSION_TIMEOUT && lastCheck) {
560
+ throw new Error(buildTimeoutMessage(normalized, lastCheck), {
561
+ cause: error,
562
+ });
145
563
  }
564
+ throw error;
146
565
  }
566
+ lastCheck = check;
147
567
 
148
- const matchedSelector = normalized.selector
149
- ? selectorMatches(lastElement, normalized.state)
150
- : true;
151
- const matchedUrl = normalized.url ? lastPage?.url === normalized.url : true;
152
- const matchedUrlIncludes = normalized.urlIncludes
153
- ? lastPage?.url?.includes(normalized.urlIncludes) === true
154
- : true;
155
- const matchedReadyState = normalized.readyState
156
- ? readyStateMatches(lastPage?.readyState, normalized.readyState)
157
- : true;
158
-
159
- if (
160
- matchedSelector &&
161
- matchedUrl &&
162
- matchedUrlIncludes &&
163
- matchedReadyState
164
- ) {
568
+ if (check.matched) {
569
+ const matchedCondition = normalized.anyOf
570
+ ? normalized.anyOf[check.matchedIndex]
571
+ : normalized;
572
+ const lastPage = check.page;
573
+ const lastElement = check.element;
165
574
  const browserFamily =
166
575
  lastPage?.browserFamily ?? lastElement?.browserFamily ?? null;
167
576
 
168
577
  return {
169
578
  browserFamily,
170
579
  matched: true,
580
+ ...(normalized.anyOf ? { matchedIndex: check.matchedIndex } : {}),
171
581
  waitedMs: Date.now() - startedAt,
172
582
  attempts,
173
583
  timeoutMs: normalized.timeoutMs,
174
584
  pollIntervalMs: normalized.pollIntervalMs,
175
- condition: {
176
- selector: normalized.selector,
177
- state: normalized.selector ? normalized.state : null,
178
- url: normalized.url,
179
- urlIncludes: normalized.urlIncludes,
180
- readyState: normalized.readyState,
181
- },
585
+ condition: normalized.anyOf
586
+ ? { anyOf: normalized.anyOf.map(describeCondition) }
587
+ : describeCondition(normalized),
182
588
  page: lastPage,
183
- element: normalized.selector
589
+ element: matchedCondition.selector
184
590
  ? {
185
- selector: normalized.selector,
591
+ selector: matchedCondition.selector,
186
592
  found: Boolean(lastElement?.found),
187
593
  locator:
188
594
  lastElement?.locator ?? lastElement?.node?.locator ?? null,
@@ -193,7 +599,7 @@ export async function waitForPageCondition({
193
599
  }
194
600
 
195
601
  if (Date.now() - startedAt >= normalized.timeoutMs) {
196
- throw new Error(buildTimeoutMessage(normalized, lastPage, lastElement));
602
+ throw new Error(buildTimeoutMessage(normalized, check));
197
603
  }
198
604
 
199
605
  await sleep(normalized.pollIntervalMs);