cdpm-mcp 0.1.8 → 0.1.12

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.
@@ -4,6 +4,7 @@ import path from 'node:path';
4
4
  import { CdpTimeoutError } from '../cdp/client.js';
5
5
  import { downloadStartedSince } from '../cdp/downloads.js';
6
6
  import { wildcard } from '../cdp/network.js';
7
+ import { listPrintPreviews } from '../cdp/targets.js';
7
8
  import { pageSession } from '../cdp/sessions.js';
8
9
  import { CdpmError } from '../errors.js';
9
10
  import { isPaused } from '../pause.js';
@@ -28,42 +29,54 @@ export class DialogInterrupt extends CdpmError {
28
29
  }
29
30
  /** 입력한 뒤 실제 값이 넣으려던 글자와 다를 때 결과에 붙는 표시 (이때는 제출하지 않는다) */
30
31
  export const VALUE_MISMATCH = '[warning] Value differs from what was typed';
31
- // ---------- 에이전트 조작 동안에만: OS 창·인쇄 창 막기 ----------
32
+ // ---------- 에이전트 조작 동안에만: OS 창 막기 ----------
32
33
  // 사람이 직접 누른 것은 평소처럼 떠야 하므로, CDPM이 조작하는 그 순간에만 켜고 끝나면 바로 푼다.
33
34
  // - 파일 선택 창: 클릭뿐 아니라 키(파일 칸에서 Enter·Space)나 폼 제출 등 어떤 경로로 열려도 OS 창 대신 가로챈다.
34
- // - 인쇄: window.print()는 인쇄 미리보기를 띄우고 탭을 멈추게 한다(CDP로 닫을 수 없음). 그 순간에만 페이지의 print를 잠깐 막는다.
35
- const PRINT_GUARD_KEY = '__cdpmPrintGuard';
36
- const PRINT_GUARD_ON = `(() => { const k = '${PRINT_GUARD_KEY}'; if (window[k]) return; const orig = window.print; const g = { orig, hit: 0 };
37
- Object.defineProperty(window, k, { value: g, configurable: true });
38
- window.print = function () { g.hit++; }; })()`;
39
- const PRINT_GUARD_OFF = `(() => { const k = '${PRINT_GUARD_KEY}'; const g = window[k]; if (!g) return 0; window.print = g.orig; delete window[k]; return g.hit; })()`;
40
- /** 에이전트 조작 하나를 감싼다. 조작 중에 파일 선택 창이 열리려 했거나 인쇄를 막았으면 그 안내를 돌려준다. */
35
+ // - 인쇄: 페이지의 window.print를 바꿔치기하지 않는다 (페이지 스크립트가 바뀐 걸 알아챌 수 있음). 인쇄 미리보기가 뜨면 알리기만 한다.
36
+ /** 조작 도중 페이지가 인쇄 미리보기를 띄움. 조작 자체는 이루어졌고, 그 탭은 사람이 미리보기를 닫을 때까지 멈춘다. */
37
+ export class PrintInterrupt extends CdpmError {
38
+ }
39
+ export const PRINT_NOTE = 'It freezes that tab until a person closes it (Print or Cancel); CDPM does not close it. Tell the user it is open (slot and tab) and wait for them; actions on that tab will not respond until then. For a PDF, use browser_pdf after it is closed.';
40
+ // 조작이 이만큼 지나도 안 끝나면 인쇄 미리보기가 떴는지 살핀다 (빨리 끝나는 조작은 확인하지 않음)
41
+ const PRINT_CHECK_AFTER_MS = 300;
42
+ const PRINT_CHECK_EVERY_MS = 300;
43
+ /** 조작이 끝나기 전에 새 인쇄 미리보기가 뜨면 기다리지 않고 PrintInterrupt로 돌아온다 (미리보기가 떠 있으면 클릭 응답이 오지 않음). */
44
+ async function watchPrint(s, run) {
45
+ // 조작과 함께 시작해 둔다: 미리보기는 클릭이 도착한 뒤에야 생기므로 그 전에 끝난다
46
+ const before = listPrintPreviews(s.slot).then((l) => new Set(l.map((p) => p.id)), () => new Set());
47
+ let settled = false;
48
+ const end = run.then(() => { settled = true; }, () => { settled = true; });
49
+ await Promise.race([end, sleep(PRINT_CHECK_AFTER_MS)]);
50
+ const known = await before;
51
+ while (!settled) {
52
+ const fresh = (await listPrintPreviews(s.slot).catch(() => [])).find((p) => !known.has(p.id));
53
+ if (fresh) {
54
+ run.catch(() => undefined); // 미리보기가 닫히면 마저 끝나거나 시간 초과로 끝난다
55
+ throw new PrintInterrupt(`The page opened Chrome's print dialog. ${PRINT_NOTE}`);
56
+ }
57
+ await Promise.race([end, sleep(PRINT_CHECK_EVERY_MS)]);
58
+ }
59
+ return run;
60
+ }
61
+ /** 에이전트 조작 하나를 감싼다. 조작 중에 파일 선택 창이 열리려 했으면 그 안내를 돌려준다. */
41
62
  export async function guardAction(s, fn) {
42
63
  const started = Date.now();
43
64
  let chooser;
44
65
  const off = s.conn.on('Page.fileChooserOpened', (p) => { chooser = p; });
45
66
  // 알림창이 떠 있으면 탭이 응답하지 않으므로 건너뛴다 (그때는 조작도 거의 못 함)
46
67
  const on = !s.dialog;
47
- if (on) {
68
+ if (on)
48
69
  await s.send('Page.setInterceptFileChooserDialog', { enabled: true }, 1500).catch(() => undefined);
49
- // 페이지 쪽(main world)의 print만 잠깐 바꾼다. Runtime.enable은 쓰지 않는다.
50
- await s.send('Runtime.evaluate', { expression: PRINT_GUARD_ON, returnByValue: true }, 1500).catch(() => undefined);
51
- }
70
+ const undo = () => s.send('Page.setInterceptFileChooserDialog', { enabled: false }, 1500).catch(() => undefined);
52
71
  let value;
53
- let printed = 0;
54
- const undo = async () => {
55
- await s.send('Page.setInterceptFileChooserDialog', { enabled: false }, 1500).catch(() => undefined);
56
- const r = await s.send('Runtime.evaluate', { expression: PRINT_GUARD_OFF, returnByValue: true }, 1500).catch(() => undefined);
57
- return Number(r?.result?.value) || 0;
58
- };
59
72
  try {
60
- value = await fn();
73
+ value = await watchPrint(s, fn());
61
74
  }
62
75
  finally {
63
76
  off();
64
77
  if (on && !s.dialog)
65
- printed = await undo();
66
- // 조작 도중 알림창이 떠서 지금은 풀 수 없으면, 알림창이 닫히는 순간 푼다 (켜 둔 채 남으면 사람이 누른 파일 칸·인쇄까지 막힘)
78
+ await undo();
79
+ // 조작 도중 알림창이 떠서 지금은 풀 수 없으면, 알림창이 닫히는 순간 푼다 (켜 둔 채 남으면 사람이 누른 파일 칸까지 막힘)
67
80
  else if (on)
68
81
  void s.conn.waitFor('Page.javascriptDialogClosed', () => true, 6 * 3600_000).then((p) => (p ? undo() : undefined));
69
82
  }
@@ -71,10 +84,9 @@ export async function guardAction(s, fn) {
71
84
  // 클릭이 이미 안내했으면(같은 창) 다시 붙이지 않는다
72
85
  if (chooser && !(s.fileChooser && s.fileChooser.at >= started)) {
73
86
  s.fileChooser = { fs: s, backendNodeId: chooser.backendNodeId, multiple: chooser.mode === 'selectMultiple', at: Date.now() };
74
- note += `\nA file chooser tried to open; it was not shown to the user. Use browser_upload(files=[path${s.fileChooser.multiple ? ', ...' : ''}]).`;
87
+ note += `
88
+ A file chooser tried to open; it was not shown to the user. Use browser_upload(files=[path${s.fileChooser.multiple ? ', ...' : ''}]).`;
75
89
  }
76
- if (printed)
77
- note += '\nBlocked the page from opening a print dialog (would freeze the tab). Use browser_pdf to save as PDF.';
78
90
  return { value, note };
79
91
  }
80
92
  /** 사용자가 슬롯을 멈춤: 하던 조작을 다음 입력을 보내기 직전에 그만둔다. */
@@ -82,6 +94,20 @@ export class PausedInterrupt extends CdpmError {
82
94
  }
83
95
  // 화면을 바꾸는 명령 (멈춘 슬롯에서는 하나도 보내지 않는다). 읽기 명령은 그대로 보낸다.
84
96
  const CHANGES_PAGE = /^(Input\.(dispatch|insertText)|Page\.(navigate|reload|navigateToHistoryEntry)$|DOM\.(setFileInputFiles|scrollIntoViewIfNeeded)$)/;
97
+ /** 여러 대기 중 처음으로 값(null이 아닌)을 낸 것. 모두 null이면 null. */
98
+ function firstNonNull(waits) {
99
+ return new Promise((resolve) => {
100
+ let left = waits.length;
101
+ for (const w of waits) {
102
+ void w.then((v) => {
103
+ if (v !== null)
104
+ resolve(v);
105
+ else if (--left === 0)
106
+ resolve(null);
107
+ });
108
+ }
109
+ });
110
+ }
85
111
  function stopIfPaused(s) {
86
112
  if (isPaused(s.slot))
87
113
  throw new PausedInterrupt('The user paused this slot, so the action stopped midway (only input already sent was applied).');
@@ -186,22 +212,22 @@ const DATE_FORMAT = {
186
212
  week: 'YYYY-Www (e.g. 2026-W41)',
187
213
  color: '#RRGGBB (e.g. #ff0000)',
188
214
  };
189
- const DESCRIBE = `function () {
190
- const el = this.nodeType === 1 ? this : this.parentElement;
191
- const tag = el ? el.tagName.toLowerCase() : '';
192
- const host = el && el.getRootNode && el.getRootNode().host;
193
- const dateOf = (n) => n && n.tagName === 'INPUT' && ${JSON.stringify(DATE_LIKE)}.includes(n.type) ? n.type : '';
194
- const selfDate = dateOf(el), hostDate = dateOf(host);
195
- const control = tag === 'label' ? el.control : null;
196
- const isFile = (n) => !!n && n.tagName === 'INPUT' && n.type === 'file';
197
- return {
198
- tag, inputType: tag === 'input' ? el.type : '',
199
- dateType: selfDate || hostDate, inDateHost: !selfDate && !!hostDate,
200
- fileInput: isFile(el) || isFile(control),
201
- select: tag === 'select' || tag === 'option',
202
- editable: (tag === 'input' || tag === 'textarea') ? 'value' : (el && el.isContentEditable ? 'content' : 'none'),
203
- connected: !!el && el.isConnected,
204
- };
215
+ const DESCRIBE = `function () {
216
+ const el = this.nodeType === 1 ? this : this.parentElement;
217
+ const tag = el ? el.tagName.toLowerCase() : '';
218
+ const host = el && el.getRootNode && el.getRootNode().host;
219
+ const dateOf = (n) => n && n.tagName === 'INPUT' && ${JSON.stringify(DATE_LIKE)}.includes(n.type) ? n.type : '';
220
+ const selfDate = dateOf(el), hostDate = dateOf(host);
221
+ const control = tag === 'label' ? el.control : null;
222
+ const isFile = (n) => !!n && n.tagName === 'INPUT' && n.type === 'file';
223
+ return {
224
+ tag, inputType: tag === 'input' ? el.type : '',
225
+ dateType: selfDate || hostDate, inDateHost: !selfDate && !!hostDate,
226
+ fileInput: isFile(el) || isFile(control),
227
+ select: tag === 'select' || tag === 'option',
228
+ editable: (tag === 'input' || tag === 'textarea') ? 'value' : (el && el.isContentEditable ? 'content' : 'none'),
229
+ connected: !!el && el.isConnected,
230
+ };
205
231
  }`;
206
232
  async function describe(s, objectId, ref) {
207
233
  const info = await callOn(s, objectId, DESCRIBE);
@@ -266,32 +292,32 @@ async function coveringElement(s, t, targetObj, x, y) {
266
292
  throw e;
267
293
  return null; // 다른 프레임의 요소(보통 iframe 자체) → 그냥 클릭
268
294
  }
269
- return callOn(s, targetObj, `function (hit, x, y) {
270
- if (hit.nodeName === 'IFRAME' || hit.nodeName === 'FRAME') return null;
271
- const inside = (n) => { while (n) { if (n === this) return true; n = n.parentNode || n.host; } return false; };
272
- if (inside(hit)) return null;
273
- // pointer-events:none인 투명 덮개 등은 클릭을 받지 않는다: 실제로 클릭을 받을 요소를 다시 확인
274
- let real = document.elementFromPoint(x, y);
275
- while (real && real.shadowRoot) { const inner = real.shadowRoot.elementFromPoint(x, y); if (!inner || inner === real) break; real = inner; }
276
- if (real && inside(real)) return null;
277
- const el = hit.nodeType === 1 ? hit : hit.parentElement;
278
- if (!el) return { blocked: 'unknown element' };
279
- const label = (el.getAttribute('aria-label') || el.innerText || el.getAttribute('alt') || '').trim().slice(0, 40);
280
- const id = el.id ? '#' + el.id : '';
281
- const cls = typeof el.className === 'string' && el.className.trim() ? '.' + el.className.trim().split(/\\s+/).slice(0, 2).join('.') : '';
282
- const desc = '<' + el.tagName.toLowerCase() + id + cls + '>' + (label ? ' "' + label + '"' : '');
283
- // 카드를 덮는 투명 링크인지: 대상에서 6단계 안의 가까운 공통 조상을 갖고, 대상의 상자를 다 덮는 링크·버튼
284
- const link = el.closest('a[href], button, [role=link], [role=button]');
285
- if (link) {
286
- let common = this, depth = 0;
287
- while (common && !common.contains(link) && depth < 6) { common = common.parentElement; depth++; }
288
- const a = link.getBoundingClientRect(), b = this.getBoundingClientRect();
289
- const covers = a.left <= b.left + 1 && a.top <= b.top + 1 && a.right >= b.right - 1 && a.bottom >= b.bottom - 1;
290
- if (common && common.contains(link) && common !== document.body && common !== document.documentElement && covers) {
291
- return { overlay: desc, href: link.href || '' };
292
- }
293
- }
294
- return { blocked: desc };
295
+ return callOn(s, targetObj, `function (hit, x, y) {
296
+ if (hit.nodeName === 'IFRAME' || hit.nodeName === 'FRAME') return null;
297
+ const inside = (n) => { while (n) { if (n === this) return true; n = n.parentNode || n.host; } return false; };
298
+ if (inside(hit)) return null;
299
+ // pointer-events:none인 투명 덮개 등은 클릭을 받지 않는다: 실제로 클릭을 받을 요소를 다시 확인
300
+ let real = document.elementFromPoint(x, y);
301
+ while (real && real.shadowRoot) { const inner = real.shadowRoot.elementFromPoint(x, y); if (!inner || inner === real) break; real = inner; }
302
+ if (real && inside(real)) return null;
303
+ const el = hit.nodeType === 1 ? hit : hit.parentElement;
304
+ if (!el) return { blocked: 'unknown element' };
305
+ const label = (el.getAttribute('aria-label') || el.innerText || el.getAttribute('alt') || '').trim().slice(0, 40);
306
+ const id = el.id ? '#' + el.id : '';
307
+ const cls = typeof el.className === 'string' && el.className.trim() ? '.' + el.className.trim().split(/\\s+/).slice(0, 2).join('.') : '';
308
+ const desc = '<' + el.tagName.toLowerCase() + id + cls + '>' + (label ? ' "' + label + '"' : '');
309
+ // 카드를 덮는 투명 링크인지: 대상에서 6단계 안의 가까운 공통 조상을 갖고, 대상의 상자를 다 덮는 링크·버튼
310
+ const link = el.closest('a[href], button, [role=link], [role=button]');
311
+ if (link) {
312
+ let common = this, depth = 0;
313
+ while (common && !common.contains(link) && depth < 6) { common = common.parentElement; depth++; }
314
+ const a = link.getBoundingClientRect(), b = this.getBoundingClientRect();
315
+ const covers = a.left <= b.left + 1 && a.top <= b.top + 1 && a.right >= b.right - 1 && a.bottom >= b.bottom - 1;
316
+ if (common && common.contains(link) && common !== document.body && common !== document.documentElement && covers) {
317
+ return { overlay: desc, href: link.href || '' };
318
+ }
319
+ }
320
+ return { blocked: desc };
295
321
  }`, [{ objectId: hitObj }, { value: x }, { value: y }]);
296
322
  }
297
323
  async function mouseClick(s, x, y, clickCount, visible) {
@@ -322,6 +348,9 @@ async function settleAfter(s, action) {
322
348
  }
323
349
  }),
324
350
  s.conn.on('Page.frameRequestedNavigation', (p) => {
351
+ // 새 탭·새 창으로 열리는 링크(target=_blank 등)는 이 탭에서 이동하지 않는다 (새 탭은 탭 목록 알림으로 따로 알린다)
352
+ if (p.disposition === 'newTab' || p.disposition === 'newWindow')
353
+ return;
325
354
  if (!s.mainFrameId || p.frameId === s.mainFrameId) {
326
355
  started = true;
327
356
  wake();
@@ -461,20 +490,20 @@ export async function click(s, agent, ref, double = false) {
461
490
  }
462
491
  if (chooser) {
463
492
  s.fileChooser = { fs, backendNodeId: chooser.backendNodeId, multiple: chooser.mode === 'selectMultiple', at: Date.now() };
464
- note += `
493
+ note += `
465
494
  A file chooser tried to open; it was held back from the user's screen. Use browser_upload(files=[path${s.fileChooser.multiple ? ', ...' : ''}]).`;
466
495
  }
467
496
  let extra = '';
468
497
  if (!note && !s.dialog) {
469
498
  // 제출 버튼인데 페이지가 이동하지 않았으면, 폼 검증에 걸렸는지 확인해 알려준다
470
- const invalid = await callOn(fs, obj, `function () {
471
- const btn = this.closest && this.closest('button, input[type=submit], input[type=image]');
472
- const form = btn && btn.form;
473
- if (!form || (btn.type && btn.type !== 'submit' && btn.type !== 'image')) return '';
474
- const bad = [...form.elements].find((e) => e.willValidate && !e.checkValidity());
475
- if (!bad) return '';
476
- const label = (bad.labels && bad.labels[0] && bad.labels[0].innerText.trim()) || bad.name || bad.id || bad.type;
477
- return label + ': ' + bad.validationMessage;
499
+ const invalid = await callOn(fs, obj, `function () {
500
+ const btn = this.closest && this.closest('button, input[type=submit], input[type=image]');
501
+ const form = btn && btn.form;
502
+ if (!form || (btn.type && btn.type !== 'submit' && btn.type !== 'image')) return '';
503
+ const bad = [...form.elements].find((e) => e.willValidate && !e.checkValidity());
504
+ if (!bad) return '';
505
+ const label = (bad.labels && bad.labels[0] && bad.labels[0].innerText.trim()) || bad.name || bad.id || bad.type;
506
+ return label + ': ' + bad.validationMessage;
478
507
  }`).catch(() => '');
479
508
  if (invalid)
480
509
  extra = `\n[warning] Form not submitted (failed page validation) — ${invalid}`;
@@ -527,14 +556,14 @@ async function setDateLike(s, obj, info, text, ref) {
527
556
  if (!target)
528
557
  throw new CdpmError(`[${ref}]: date/time/color input not found.`);
529
558
  // 형식이 틀리면 브라우저가 값을 비워 버리므로, 먼저 넣어 보고 틀리면 원래 값으로 되돌린다. 이벤트는 맞을 때만 낸다.
530
- const r = await callOn(s, target, `function (v) {
531
- const set = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value').set;
532
- const prev = this.value;
533
- set.call(this, v);
534
- if (this.value.toLowerCase() !== String(v).toLowerCase()) { set.call(this, prev); return { ok: false, prev }; }
535
- this.dispatchEvent(new Event('input', { bubbles: true }));
536
- this.dispatchEvent(new Event('change', { bubbles: true }));
537
- return { ok: true, prev };
559
+ const r = await callOn(s, target, `function (v) {
560
+ const set = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value').set;
561
+ const prev = this.value;
562
+ set.call(this, v);
563
+ if (this.value.toLowerCase() !== String(v).toLowerCase()) { set.call(this, prev); return { ok: false, prev }; }
564
+ this.dispatchEvent(new Event('input', { bubbles: true }));
565
+ this.dispatchEvent(new Event('change', { bubbles: true }));
566
+ return { ok: true, prev };
538
567
  }`, [{ value: text }]);
539
568
  if (!r.ok) {
540
569
  throw new CdpmError(`[${ref}] is a ${info.dateType} input. Wrong format, not set (kept ${JSON.stringify(r.prev)}). Format: ${DATE_FORMAT[info.dateType] ?? info.dateType}`);
@@ -583,10 +612,10 @@ export async function type(s, agent, ref, text, clear, submit, fast = false) {
583
612
  await mouseClick(s, x + dx, y + dy, 1, (await s.visibility()) === 'visible');
584
613
  }
585
614
  if (clear) {
586
- await callOn(fs, obj, `function () {
587
- if (typeof this.select === 'function' && ('value' in this)) { this.select(); return; }
588
- const r = document.createRange(); r.selectNodeContents(this);
589
- const sel = getSelection(); sel.removeAllRanges(); sel.addRange(r);
615
+ await callOn(fs, obj, `function () {
616
+ if (typeof this.select === 'function' && ('value' in this)) { this.select(); return; }
617
+ const r = document.createRange(); r.selectNodeContents(this);
618
+ const sel = getSelection(); sel.removeAllRanges(); sel.addRange(r);
590
619
  }`);
591
620
  await pressCombo(s, parseCombo('Backspace'));
592
621
  }
@@ -631,16 +660,16 @@ export async function select(s, agent, ref, option) {
631
660
  const { fs } = await locate(s, t);
632
661
  try {
633
662
  const obj = await objectOf(fs, t);
634
- const find = await callOn(fs, obj, `function (want) {
635
- const sel = this.tagName === 'SELECT' ? this : this.closest && this.closest('select');
636
- if (!sel) return { ok: false, error: 'notselect' };
637
- const opts = [...sel.options];
638
- const norm = (x) => x.replace(/\\s+/g, ' ').trim();
639
- const o = opts.find((o) => o.value === want) || opts.find((o) => norm(o.text) === norm(want)) ||
640
- opts.find((o) => norm(o.text).includes(norm(want)));
641
- if (!o) return { ok: false, options: opts.slice(0, 40).map((o) => norm(o.text) + (o.value !== norm(o.text) ? ' (value: ' + o.value + ')' : '')) };
642
- if (o.disabled) return { ok: false, error: 'disabled', label: norm(o.text) };
643
- return { ok: true, index: o.index, label: norm(o.text), value: o.value, multiple: sel.multiple };
663
+ const find = await callOn(fs, obj, `function (want) {
664
+ const sel = this.tagName === 'SELECT' ? this : this.closest && this.closest('select');
665
+ if (!sel) return { ok: false, error: 'notselect' };
666
+ const opts = [...sel.options];
667
+ const norm = (x) => x.replace(/\\s+/g, ' ').trim();
668
+ const o = opts.find((o) => o.value === want) || opts.find((o) => norm(o.text) === norm(want)) ||
669
+ opts.find((o) => norm(o.text).includes(norm(want)));
670
+ if (!o) return { ok: false, options: opts.slice(0, 40).map((o) => norm(o.text) + (o.value !== norm(o.text) ? ' (value: ' + o.value + ')' : '')) };
671
+ if (o.disabled) return { ok: false, error: 'disabled', label: norm(o.text) };
672
+ return { ok: true, index: o.index, label: norm(o.text), value: o.value, multiple: sel.multiple };
644
673
  }`, [{ value: option }]);
645
674
  if (!find.ok) {
646
675
  if (find.error === 'notselect')
@@ -673,12 +702,12 @@ export async function select(s, agent, ref, option) {
673
702
  if (idx === find.index)
674
703
  return `Selected [${ref}] "${find.label}" (value: ${find.value})`;
675
704
  // 키로 고르지 못한 경우(맥에서 앞글자가 같은 항목이 먼저 있을 때 등): 값을 직접 넣고 input/change 이벤트를 낸다 (이 이벤트는 isTrusted=false).
676
- const forced = await callOn(fs, obj, `function (i) {
677
- const sel = this.tagName === 'SELECT' ? this : this.closest('select');
678
- sel.selectedIndex = i;
679
- sel.dispatchEvent(new Event('input', { bubbles: true }));
680
- sel.dispatchEvent(new Event('change', { bubbles: true }));
681
- return sel.selectedIndex;
705
+ const forced = await callOn(fs, obj, `function (i) {
706
+ const sel = this.tagName === 'SELECT' ? this : this.closest('select');
707
+ sel.selectedIndex = i;
708
+ sel.dispatchEvent(new Event('input', { bubbles: true }));
709
+ sel.dispatchEvent(new Event('change', { bubbles: true }));
710
+ return sel.selectedIndex;
682
711
  }`, [{ value: find.index }]);
683
712
  if (forced !== find.index)
684
713
  throw new CdpmError(`Could not select "${find.label}". The page may be blocking it.`);
@@ -689,17 +718,17 @@ export async function select(s, agent, ref, option) {
689
718
  }
690
719
  }
691
720
  /** 화면 가운데의 스크롤 대상(가장 가까운 스크롤 가능한 조상, 없으면 문서)을 찾아 정보를 돌려주거나 스크롤한다. */
692
- const SCROLL_FN = (dy) => `(() => {
693
- const isScrollable = (el) => {
694
- if (!el || el === document.body || el === document.documentElement) return false;
695
- const s = getComputedStyle(el);
696
- return /(auto|scroll|overlay)/.test(s.overflowY) && el.scrollHeight > el.clientHeight + 1;
697
- };
698
- let el = document.elementFromPoint(innerWidth / 2, innerHeight / 2);
699
- while (el && !isScrollable(el)) el = el.parentElement;
700
- const t = el || document.scrollingElement || document.documentElement;
701
- ${dy === null ? '' : `t.scrollBy({ top: ${dy}, behavior: 'instant' });`}
702
- return { top: Math.round(t.scrollTop), max: Math.max(0, Math.round(t.scrollHeight - t.clientHeight)), inner: !!el };
721
+ const SCROLL_FN = (dy) => `(() => {
722
+ const isScrollable = (el) => {
723
+ if (!el || el === document.body || el === document.documentElement) return false;
724
+ const s = getComputedStyle(el);
725
+ return /(auto|scroll|overlay)/.test(s.overflowY) && el.scrollHeight > el.clientHeight + 1;
726
+ };
727
+ let el = document.elementFromPoint(innerWidth / 2, innerHeight / 2);
728
+ while (el && !isScrollable(el)) el = el.parentElement;
729
+ const t = el || document.scrollingElement || document.documentElement;
730
+ ${dy === null ? '' : `t.scrollBy({ top: ${dy}, behavior: 'instant' });`}
731
+ return { top: Math.round(t.scrollTop), max: Math.max(0, Math.round(t.scrollHeight - t.clientHeight)), inner: !!el };
703
732
  })()`;
704
733
  export async function scroll(s, agent, ref, dy) {
705
734
  await s.ensureNoDialog();
@@ -777,11 +806,18 @@ async function history(s, delta) {
777
806
  await sleep(100);
778
807
  return `Went ${word}: ${decodeUrl(entry.url)} (same-document)`;
779
808
  }
809
+ // SPA가 pushState로 만든 기록(/a → /b)은 주소가 달라도 같은 문서 안의 이동이라 frameNavigated가 오지 않는다 → 둘 중 먼저 오는 것
810
+ const main = await s.mainFrame().catch(() => undefined);
780
811
  const committed = s.conn.waitFor('Page.frameNavigated', (p) => !p.frame.parentId, 30_000);
812
+ const within = s.conn.waitFor('Page.navigatedWithinDocument', (p) => !main || p.frameId === main, 30_000);
781
813
  await send(s, 'Page.navigateToHistoryEntry', { entryId: entry.id });
782
- const nav = await committed;
814
+ const nav = await firstNonNull([committed.then((p) => p && 'document'), within.then((p) => p && 'same')]);
815
+ if (nav === 'same') {
816
+ await sleep(100);
817
+ return `Went ${word}: ${decodeUrl(entry.url)} (same-document)`;
818
+ }
783
819
  const state = nav ? await waitLoad(s, false) : 'timeout';
784
- return `Went ${word}: ${decodeUrl(entry.url)}${state === 'complete' ? '' : `
820
+ return `Went ${word}: ${decodeUrl(entry.url)}${state === 'complete' ? '' : `
785
821
  (${LOAD_NOTE[state]})`}`;
786
822
  }
787
823
  /** 지금 페이지를 다시 불러온다 (진짜 새로고침, 주소로 다시 이동하는 것과 달리 Chrome의 새로고침 그대로). */
@@ -791,7 +827,7 @@ export async function reload(s, ignoreCache = false) {
791
827
  await send(s, 'Page.reload', { ignoreCache });
792
828
  const nav = await committed;
793
829
  const state = nav ? await waitLoad(s, false) : 'timeout';
794
- return `Reloaded${ignoreCache ? ' (cache bypassed)' : ''}${state === 'complete' ? '' : `
830
+ return `Reloaded${ignoreCache ? ' (cache bypassed)' : ''}${state === 'complete' ? '' : `
795
831
  (${LOAD_NOTE[state]})`}${downloadNote(s)}`;
796
832
  }
797
833
  /** 요소 위에 진짜 마우스를 올린다 (마우스를 올려야 열리는 메뉴 등). */
@@ -834,16 +870,16 @@ export async function drag(s, agent, fromRef, toRef, dx, dy, toText) {
834
870
  }
835
871
  if (toText) {
836
872
  // 놓을 곳은 역할이 없는 칸(div)인 경우가 많아 ref가 없다 → 그 글자가 들어 있는 가장 작은 보이는 요소의 가운데
837
- const r = await s.evaluate(`(() => {
838
- const t = ${JSON.stringify(toText)};
839
- let best = null, area = Infinity;
840
- for (const el of document.querySelectorAll('body *')) {
841
- if (!(el.innerText || '').includes(t)) continue;
842
- const b = el.getBoundingClientRect();
843
- if (b.width < 2 || b.height < 2 || b.bottom < 0 || b.top > innerHeight) continue;
844
- if (b.width * b.height < area) { area = b.width * b.height; best = b; }
845
- }
846
- return best && { x: best.left + best.width / 2, y: best.top + best.height / 2 };
873
+ const r = await s.evaluate(`(() => {
874
+ const t = ${JSON.stringify(toText)};
875
+ let best = null, area = Infinity;
876
+ for (const el of document.querySelectorAll('body *')) {
877
+ if (!(el.innerText || '').includes(t)) continue;
878
+ const b = el.getBoundingClientRect();
879
+ if (b.width < 2 || b.height < 2 || b.bottom < 0 || b.top > innerHeight) continue;
880
+ if (b.width * b.height < area) { area = b.width * b.height; best = b; }
881
+ }
882
+ return best && { x: best.left + best.width / 2, y: best.top + best.height / 2 };
847
883
  })()`, { timeoutMs: 5000 });
848
884
  if (!r.value)
849
885
  throw new CdpmError(`No drop target containing "${toText}" found on screen (if off-screen, browser_scroll so both are visible, then retry).`);
@@ -886,17 +922,80 @@ export async function pdf(s, outPath, title) {
886
922
  fs.writeFileSync(file, Buffer.from(data, 'base64'));
887
923
  return `Saved PDF: ${file} (${(fs.statSync(file).size / 1024).toFixed(1)}KB)`;
888
924
  }
925
+ /** 탭 안의 iframe들 (중첩·다른 사이트 iframe 포함). 스냅샷과 같은 방식으로 찾는다. */
926
+ async function frameReaders(s, depth = 0) {
927
+ if (depth > 3)
928
+ return [];
929
+ const doc = await s.send('DOM.getDocument', { depth: -1, pierce: true }, 3000).catch(() => undefined);
930
+ if (!doc)
931
+ return [];
932
+ const out = [];
933
+ const remote = [];
934
+ const walk = (n) => {
935
+ if (!n)
936
+ return;
937
+ if ((n.nodeName === 'IFRAME' || n.nodeName === 'FRAME') && n.frameId) {
938
+ // 같은 프로세스 iframe은 문서가 같이 오고, 다른 사이트 iframe은 문서 없이 frameId만 온다
939
+ if (n.contentDocument)
940
+ out.push({ session: s, frameId: n.frameId });
941
+ else
942
+ remote.push(n.frameId);
943
+ }
944
+ n.children?.forEach(walk);
945
+ n.shadowRoots?.forEach(walk);
946
+ walk(n.contentDocument);
947
+ };
948
+ walk(doc.root);
949
+ for (const id of remote) {
950
+ const child = await pageSession(s.slot, id).catch(() => undefined);
951
+ if (!child)
952
+ continue;
953
+ out.push({ session: child });
954
+ out.push(...(await frameReaders(child, depth + 1)));
955
+ }
956
+ return out;
957
+ }
958
+ /**
959
+ * 글자가 탭 화면에 있는지: 메인 문서와, 크기가 있는(보이는) iframe 안까지 (로그인·결제 폼은 iframe 안에 있는 경우가 많다).
960
+ * iframe 목록은 1초에 한 번만 새로 찾는다. 메인 문서를 못 읽으면 undefined.
961
+ */
962
+ function textChecker(s, text) {
963
+ const t = JSON.stringify(text);
964
+ const main = `(() => { const t = ${t}; const b = document.body; return { hit: (!!b && b.innerText.includes(t)) || document.title.includes(t), frames: !!document.querySelector('iframe, frame') }; })()`;
965
+ // 크기가 0인 iframe(display:none 등)은 화면에 없는 것으로 본다
966
+ const inFrame = `(() => { const t = ${t}; const b = document.body; return innerWidth > 0 && innerHeight > 0 && !!b && b.innerText.includes(t); })()`;
967
+ let frames = [];
968
+ let foundAt = 0;
969
+ return async () => {
970
+ const r = await s.evaluate(main, { timeoutMs: 3000 });
971
+ if (!r.value)
972
+ return undefined;
973
+ if (r.value.hit)
974
+ return true;
975
+ if (!r.value.frames)
976
+ return false;
977
+ if (Date.now() - foundAt > 1000) {
978
+ frames = await frameReaders(s);
979
+ foundAt = Date.now();
980
+ }
981
+ for (const f of frames) {
982
+ const v = await f.session.evaluate(inFrame, { timeoutMs: 2000, frameId: f.frameId }).catch(() => undefined);
983
+ if (v?.value)
984
+ return true;
985
+ }
986
+ return false;
987
+ };
988
+ }
889
989
  export async function waitForText(s, text, timeoutSec, stop) {
890
990
  const until = Date.now() + timeoutSec * 1000;
891
- const expression = `(() => { const t = ${JSON.stringify(text)}; const b = document.body; return (!!b && b.innerText.includes(t)) || document.title.includes(t); })()`;
991
+ const present = textChecker(s, text);
892
992
  while (Date.now() < until) {
893
993
  await s.ensureNoDialog();
894
994
  const why = stop?.();
895
995
  if (why)
896
996
  return why;
897
997
  try {
898
- const r = await s.evaluate(expression, { timeoutMs: 3000 });
899
- if (r.value)
998
+ if (await present())
900
999
  return `Text appeared: ${JSON.stringify(text)}`;
901
1000
  }
902
1001
  catch (e) {
@@ -914,14 +1013,13 @@ export async function waitForText(s, text, timeoutSec, stop) {
914
1013
  /** 글자가 페이지에서 사라질 때까지 (예: 로그인 폼의 "비밀번호"가 사라짐 = 로그인 완료). 화면은 건드리지 않고 읽기만 한다. */
915
1014
  export async function waitForGone(s, text, timeoutSec, stop) {
916
1015
  const until = Date.now() + timeoutSec * 1000;
917
- const expression = `(() => { const t = ${JSON.stringify(text)}; const b = document.body; return !((!!b && b.innerText.includes(t)) || document.title.includes(t)); })()`;
1016
+ const present = textChecker(s, text);
918
1017
  while (Date.now() < until) {
919
1018
  await s.ensureNoDialog();
920
1019
  const why = stop?.();
921
1020
  if (why)
922
1021
  return why;
923
- const r = await s.evaluate(expression, { timeoutMs: 3000 }).catch(() => undefined);
924
- if (r?.value)
1022
+ if ((await present().catch(() => undefined)) === false)
925
1023
  return `Text gone: ${JSON.stringify(text)}`;
926
1024
  await sleep(100);
927
1025
  }
@@ -932,10 +1030,10 @@ export async function waitForEnabled(s, agent, ref, timeoutSec, stop) {
932
1030
  const t = targetOf(s, agent, ref);
933
1031
  // 다른 사이트 iframe 안의 요소면 그 iframe의 연결로 본다 (스크롤하지 않음)
934
1032
  const fs = t.targetId ? await pageSession(s.slot, t.targetId) : s;
935
- const check = `function () {
936
- if (!this.isConnected) return 'gone';
937
- const off = this.disabled === true || this.getAttribute('aria-disabled') === 'true' || !!this.closest('fieldset[disabled]');
938
- return off ? 'off' : 'on';
1033
+ const check = `function () {
1034
+ if (!this.isConnected) return 'gone';
1035
+ const off = this.disabled === true || this.getAttribute('aria-disabled') === 'true' || !!this.closest('fieldset[disabled]');
1036
+ return off ? 'off' : 'on';
939
1037
  }`;
940
1038
  const until = Date.now() + timeoutSec * 1000;
941
1039
  let obj;
@@ -989,7 +1087,9 @@ export class WaitStopped extends Error {
989
1087
  }
990
1088
  export async function waitForUrl(s, contains, timeoutSec, stop) {
991
1089
  const href = async () => (await s.evaluate('location.href', { timeoutMs: 3000 }).catch(() => undefined))?.value;
992
- const start = await href();
1090
+ // 페이지가 바빠 시작 주소를 못 읽으면 브라우저 쪽 방문 기록으로 정한다 (기준이 없으면 처음 읽힌 주소를 "바뀜"으로 잘못 봄)
1091
+ const start = (await href()) ?? (await s.send('Page.getNavigationHistory', {}, 3000)
1092
+ .then((h) => h.entries[h.currentIndex]?.url).catch(() => undefined));
993
1093
  const until = Date.now() + timeoutSec * 1000;
994
1094
  while (Date.now() < until) {
995
1095
  await s.ensureNoDialog();
@@ -1049,7 +1149,12 @@ export async function upload(s, agent, ref, files) {
1049
1149
  }
1050
1150
  export async function evaluate(s, expression) {
1051
1151
  await s.ensureNoDialog();
1052
- const r = await s.evaluate(expression, { awaitPromise: true, timeoutMs: 30_000 });
1152
+ const r = await s.evaluate(expression, { awaitPromise: true, timeoutMs: 30_000, once: true }).catch((e) => {
1153
+ if (/Execution context was destroyed|navigated or closed/i.test(e.message)) {
1154
+ throw new CdpmError('The page navigated while the script was running; it was not re-run (it may have partly run). Check the page with browser_text or browser_snapshot.');
1155
+ }
1156
+ throw e;
1157
+ });
1053
1158
  if (r.exception)
1054
1159
  throw new CdpmError(`JS error: ${r.exception}`);
1055
1160
  if (r.type === 'undefined')
@@ -1078,10 +1183,10 @@ export async function extractText(s, agent, ref, page) {
1078
1183
  }
1079
1184
  }
1080
1185
  else {
1081
- const r = await s.evaluate(`(() => {
1082
- const main = document.querySelector('main, article, [role=main]');
1083
- const el = main && main.innerText.trim().length > 200 ? main : document.body;
1084
- return el ? el.innerText.trim() : '';
1186
+ const r = await s.evaluate(`(() => {
1187
+ const main = document.querySelector('main, article, [role=main]');
1188
+ const el = main && main.innerText.trim().length > 200 ? main : document.body;
1189
+ return el ? el.innerText.trim() : '';
1085
1190
  })()`, { timeoutMs: 10_000 });
1086
1191
  text = r.value ?? '';
1087
1192
  }
package/dist/page/keys.js CHANGED
@@ -46,7 +46,7 @@ function lookup(name) {
46
46
  /** "Control+Shift+A" 같은 조합을 해석한다. */
47
47
  export function parseCombo(combo) {
48
48
  const parts = combo.split('+').map((p) => p.trim()).filter(Boolean);
49
- if (combo.endsWith('++'))
49
+ if (combo.endsWith('++') || combo.trim() === '+')
50
50
  parts.push('+');
51
51
  if (!parts.length)
52
52
  return undefined;
@@ -199,6 +199,13 @@ export function subtree(text, ref) {
199
199
  out.push(lines[j]);
200
200
  return out.map((l) => l.slice(base)).join('\n');
201
201
  }
202
+ /** CDP 속성 목록([이름, 값, 이름, 값…])에서 이름으로 값 찾기. 이름 자리(짝수)만 본다 (class="href" 같은 값에 걸리지 않게). */
203
+ export function attrValue(attrs, name) {
204
+ for (let i = 0; i + 1 < attrs.length; i += 2)
205
+ if (attrs[i] === name)
206
+ return attrs[i + 1];
207
+ return undefined;
208
+ }
202
209
  /** 한 대상(탭 또는 다른 사이트 iframe)의 링크 주소와 iframe 요소 → 프레임 ID. */
203
210
  async function domInfo(session) {
204
211
  const doc = await session.send('DOM.getDocument', { depth: -1, pierce: true }).catch(() => undefined);
@@ -210,14 +217,13 @@ async function domInfo(session) {
210
217
  return;
211
218
  const attrs = n.attributes ?? [];
212
219
  if (n.nodeName === 'A') {
213
- const i = attrs.indexOf('href');
214
- if (i >= 0 && i % 2 === 0)
215
- hrefs.set(n.backendNodeId, attrs[i + 1]);
220
+ const href = attrValue(attrs, 'href');
221
+ if (href !== undefined)
222
+ hrefs.set(n.backendNodeId, href);
216
223
  }
217
224
  if ((n.nodeName === 'IFRAME' || n.nodeName === 'FRAME') && n.frameId)
218
225
  iframeFrame.set(n.backendNodeId, n.frameId);
219
- const d = attrs.indexOf('draggable');
220
- if (d >= 0 && d % 2 === 0 && attrs[d + 1] === 'true')
226
+ if (attrValue(attrs, 'draggable') === 'true')
221
227
  draggable.add(n.backendNodeId);
222
228
  n.children?.forEach(walk);
223
229
  n.shadowRoots?.forEach(walk);