dsh-browser-cdp 1.7.12 → 1.9.6

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.
@@ -6354,6 +6354,70 @@ function capabilitiesFromEnvValue(value) {
6354
6354
  return capabilitiesFor("unknown");
6355
6355
  }
6356
6356
 
6357
+ //#endregion
6358
+ //#region src/worker/window-size.ts
6359
+ /** Chrome refuses slivers; below this a resize is not worth sending. */
6360
+ const MIN_VIEWPORT_WIDTH = 320;
6361
+ const MIN_VIEWPORT_HEIGHT = 200;
6362
+ /** A sanity ceiling; the OS clamps to the display anyway. */
6363
+ const MAX_VIEWPORT_WIDTH = 3840;
6364
+ const MAX_VIEWPORT_HEIGHT = 2160;
6365
+ /** Keep a requested viewport inside a sane range (a sliver is unusable). */
6366
+ function clampViewportSize(width, height) {
6367
+ return {
6368
+ width: Math.min(MAX_VIEWPORT_WIDTH, Math.max(MIN_VIEWPORT_WIDTH, Math.round(width))),
6369
+ height: Math.min(MAX_VIEWPORT_HEIGHT, Math.max(MIN_VIEWPORT_HEIGHT, Math.round(height)))
6370
+ };
6371
+ }
6372
+ /**
6373
+ * Apply a drag delta to the current viewport width. The panel edge maps to a
6374
+ * window-width CHANGE, not an absolute width: the panel is much narrower than
6375
+ * the window, so absolute mapping would shrink the window to the sidebar on the
6376
+ * first frame.
6377
+ */
6378
+ function widthWithDelta(currentWidth, delta) {
6379
+ const next = Math.round(currentWidth + delta);
6380
+ return Math.min(MAX_VIEWPORT_WIDTH, Math.max(MIN_VIEWPORT_WIDTH, next));
6381
+ }
6382
+ /**
6383
+ * Compute CDP `Browser.setWindowBounds` bounds for a desired page viewport.
6384
+ * `left`/`top` are preserved when known so the window does not jump while the
6385
+ * user drags a panel edge. `windowState: 'normal'` is always included: a
6386
+ * maximized window ignores width/height until it is restored.
6387
+ */
6388
+ function computeWindowBounds(viewport, chromeFrame = {
6389
+ width: 0,
6390
+ height: 0
6391
+ }, current = {}) {
6392
+ const width = Math.max(MIN_VIEWPORT_WIDTH, Math.round(viewport.width + Math.max(0, chromeFrame.width)));
6393
+ const height = Math.max(MIN_VIEWPORT_HEIGHT, Math.round(viewport.height + Math.max(0, chromeFrame.height)));
6394
+ return {
6395
+ ...typeof current.left === "number" && Number.isFinite(current.left) ? { left: Math.round(current.left) } : {},
6396
+ ...typeof current.top === "number" && Number.isFinite(current.top) ? { top: Math.round(current.top) } : {},
6397
+ width,
6398
+ height,
6399
+ windowState: "normal"
6400
+ };
6401
+ }
6402
+ /** Aspect-ratio presets offered by the panel (label → height/width ratio). */
6403
+ const ASPECT_RATIOS = {
6404
+ "16:9": 9 / 16,
6405
+ "4:3": 3 / 4,
6406
+ "21:9": 9 / 21,
6407
+ "1:1": 1,
6408
+ "9:16": 16 / 9
6409
+ };
6410
+ /**
6411
+ * Resolve an aspect preset to a viewport height for the given width. Unknown
6412
+ * labels fall back to the current height (a no-op), so a stale client value
6413
+ * never distorts the window.
6414
+ */
6415
+ function aspectHeight(width, aspect, fallbackHeight) {
6416
+ const ratio = ASPECT_RATIOS[aspect];
6417
+ if (ratio === void 0) return fallbackHeight;
6418
+ return Math.round(width * ratio);
6419
+ }
6420
+
6357
6421
  //#endregion
6358
6422
  //#region src/worker/cdp-cast-worker.ts
6359
6423
  const SENTINEL = "@@DSH_RESULT@@";
@@ -6400,6 +6464,8 @@ const sseClients = /* @__PURE__ */ new Set();
6400
6464
  const videoClients = /* @__PURE__ */ new Set();
6401
6465
  const probeCache = /* @__PURE__ */ new Map();
6402
6466
  const frameCache = /* @__PURE__ */ new Map();
6467
+ const winCache = /* @__PURE__ */ new Map();
6468
+ const chromeFrameCache = /* @__PURE__ */ new Map();
6403
6469
  let active = null;
6404
6470
  /**
6405
6471
  * M1.4 / T5.1c — the pick channel rides the worker's RESIDENT connection.
@@ -7010,13 +7076,168 @@ async function main() {
7010
7076
  await active.cdp.call("Target.closeTarget", { targetId });
7011
7077
  return sendJson(res, 200, { ok: true });
7012
7078
  }
7079
+ if (req.method === "POST" && url.pathname === "/api/switch-tab") {
7080
+ const body = await readJson(req);
7081
+ const targetId = typeof body?.targetId === "string" ? body.targetId : "";
7082
+ if (!active || targetId === "") return sendJson(res, 400, {
7083
+ ok: false,
7084
+ error: "targetId required"
7085
+ });
7086
+ try {
7087
+ await active.cdp.call("Target.activateTarget", { targetId });
7088
+ return sendJson(res, 200, {
7089
+ ok: true,
7090
+ targetId
7091
+ });
7092
+ } catch (error) {
7093
+ return sendJson(res, 502, {
7094
+ ok: false,
7095
+ error: error.message || String(error)
7096
+ });
7097
+ }
7098
+ }
7013
7099
  if (req.method === "POST" && url.pathname === "/api/flush") {
7014
7100
  if (!active) return sendJson(res, 409, {
7015
7101
  ok: false,
7016
7102
  error: "no live browser"
7017
7103
  });
7018
- await active.cdp.call("Storage.flushCookies").catch(() => {});
7019
- return sendJson(res, 200, { ok: true });
7104
+ let total = 0;
7105
+ try {
7106
+ const jar = await active.cdp.call("Storage.getCookies");
7107
+ total = Array.isArray(jar?.cookies) ? jar.cookies.length : 0;
7108
+ } catch {
7109
+ total = 0;
7110
+ }
7111
+ const flushed = await active.cdp.call("Storage.flushCookies").then(() => total).catch(() => 0);
7112
+ return sendJson(res, 200, {
7113
+ ok: true,
7114
+ total,
7115
+ flushed
7116
+ });
7117
+ }
7118
+ if (req.method === "POST" && url.pathname === "/api/window-size") {
7119
+ if (!active) return sendJson(res, 409, {
7120
+ ok: false,
7121
+ error: "no live browser"
7122
+ });
7123
+ const body = await readJson(req);
7124
+ const targetId = await activeTargetId();
7125
+ if (!targetId) return sendJson(res, 409, {
7126
+ ok: false,
7127
+ error: "no active page target"
7128
+ });
7129
+ try {
7130
+ let win = winCache.get(targetId);
7131
+ if (!win || Date.now() - win.at > 1e4) {
7132
+ const r = await active.cdp.call("Browser.getWindowForTarget", { targetId });
7133
+ win = {
7134
+ windowId: r.windowId,
7135
+ bounds: r.bounds || {},
7136
+ at: Date.now()
7137
+ };
7138
+ winCache.set(targetId, win);
7139
+ }
7140
+ if (body.maximize === true) {
7141
+ await active.cdp.call("Browser.setWindowBounds", {
7142
+ windowId: win.windowId,
7143
+ bounds: { windowState: "maximized" }
7144
+ });
7145
+ return sendJson(res, 200, {
7146
+ ok: true,
7147
+ maximized: true,
7148
+ windowId: win.windowId
7149
+ });
7150
+ }
7151
+ let cf = chromeFrameCache.get(targetId);
7152
+ if (!cf || Date.now() - cf.at > 2e3) {
7153
+ const v = (await active.sessions.call(targetId, "Runtime.evaluate", {
7154
+ expression: "({ow:outerWidth,oh:outerHeight,iw:innerWidth,ih:innerHeight})",
7155
+ returnByValue: true
7156
+ }, 3e3))?.result?.value || {};
7157
+ cf = {
7158
+ width: Math.max(0, (v.ow || 0) - (v.iw || 0)),
7159
+ height: Math.max(0, (v.oh || 0) - (v.ih || 0)),
7160
+ viewport: {
7161
+ width: v.iw || 0,
7162
+ height: v.ih || 0
7163
+ },
7164
+ at: Date.now()
7165
+ };
7166
+ chromeFrameCache.set(targetId, cf);
7167
+ }
7168
+ const cur = cf.viewport;
7169
+ let width = typeof body.width === "number" && Number.isFinite(body.width) ? body.width : typeof body.delta === "number" && Number.isFinite(body.delta) ? widthWithDelta(cur.width, body.delta) : cur.width;
7170
+ let height = typeof body.height === "number" && Number.isFinite(body.height) ? body.height : typeof body.dy === "number" && Number.isFinite(body.dy) ? cur.height + body.dy : cur.height;
7171
+ if (typeof body.aspect === "string" && body.aspect !== "") height = aspectHeight(width, body.aspect, height);
7172
+ const clamped = clampViewportSize(width, height);
7173
+ const bounds = computeWindowBounds(clamped, {
7174
+ width: cf.width,
7175
+ height: cf.height
7176
+ }, {
7177
+ left: win.bounds.left,
7178
+ top: win.bounds.top
7179
+ });
7180
+ await active.cdp.call("Browser.setWindowBounds", {
7181
+ windowId: win.windowId,
7182
+ bounds
7183
+ });
7184
+ cf.viewport = {
7185
+ width: clamped.width,
7186
+ height: clamped.height
7187
+ };
7188
+ cf.at = Date.now();
7189
+ return sendJson(res, 200, {
7190
+ ok: true,
7191
+ windowId: win.windowId,
7192
+ viewport: {
7193
+ width: clamped.width,
7194
+ height: clamped.height
7195
+ }
7196
+ });
7197
+ } catch (error) {
7198
+ return sendJson(res, 502, {
7199
+ ok: false,
7200
+ error: error.message || String(error)
7201
+ });
7202
+ }
7203
+ }
7204
+ if (req.method === "POST" && url.pathname === "/api/navigate") {
7205
+ if (!active) return sendJson(res, 409, {
7206
+ ok: false,
7207
+ error: "no live browser"
7208
+ });
7209
+ const body = await readJson(req);
7210
+ const targetId = await activeTargetId();
7211
+ if (!targetId) return sendJson(res, 409, {
7212
+ ok: false,
7213
+ error: "no active page target"
7214
+ });
7215
+ try {
7216
+ if (body.reload === true) {
7217
+ await active.sessions.call(targetId, "Page.reload", { ignoreCache: body.ignoreCache === true }, 15e3);
7218
+ return sendJson(res, 200, {
7219
+ ok: true,
7220
+ reloaded: true,
7221
+ targetId
7222
+ });
7223
+ }
7224
+ const navUrl = typeof body.url === "string" ? body.url.trim() : "";
7225
+ if (navUrl === "") return sendJson(res, 400, {
7226
+ ok: false,
7227
+ error: "url required"
7228
+ });
7229
+ await active.sessions.call(targetId, "Page.navigate", { url: navUrl }, 15e3);
7230
+ return sendJson(res, 200, {
7231
+ ok: true,
7232
+ url: navUrl,
7233
+ targetId
7234
+ });
7235
+ } catch (error) {
7236
+ return sendJson(res, 502, {
7237
+ ok: false,
7238
+ error: error.message || String(error)
7239
+ });
7240
+ }
7020
7241
  }
7021
7242
  if (req.method === "GET" && url.pathname === "/api/stream") {
7022
7243
  res.writeHead(200, {
@@ -316,6 +316,38 @@ async function recordElement(backendNodeId) {
316
316
  }
317
317
  }
318
318
 
319
+ /**
320
+ * Does the target node contain (or equal) the node hit at the click point?
321
+ *
322
+ * `DOM.getNodeForLocation` returns the TOPMOST node, which for `<a><img></a>` is
323
+ * the IMG, not the anchor we targeted. Strict id equality then misreports a good
324
+ * click as `click-missed` (issue #9 #4). Accepting the target itself OR any of its
325
+ * descendants via `Node.contains` fixes that without weakening the overlay guard:
326
+ * a genuine overlay is neither the target nor its child, so it still fails.
327
+ * Best-effort: any resolution hiccup returns false and the caller keeps the strict result.
328
+ */
329
+ async function nodeContains(targetBackendId, hitBackendId) {
330
+ if (!Number.isFinite(hitBackendId) || hitBackendId <= 0) return false
331
+ if (hitBackendId === targetBackendId) return true
332
+ try {
333
+ const pushed = await call('DOM.pushNodesByBackendIdsToFrontend', { backendNodeIds: [targetBackendId, hitBackendId] })
334
+ const [targetNodeId, hitNodeId] = pushed?.nodeIds ?? []
335
+ if (!targetNodeId || !hitNodeId) return false
336
+ const tObj = (await call('DOM.resolveNode', { nodeId: targetNodeId }))?.object?.objectId
337
+ const hObj = (await call('DOM.resolveNode', { nodeId: hitNodeId }))?.object?.objectId
338
+ if (!tObj || !hObj) return false
339
+ const fn = await call('Runtime.callFunctionOn', {
340
+ objectId: tObj,
341
+ functionDeclaration: 'function(h){ return this === h || this.contains(h) }',
342
+ arguments: [{ objectId: hObj }],
343
+ returnByValue: true,
344
+ })
345
+ return fn?.result?.value === true
346
+ } catch {
347
+ return false
348
+ }
349
+ }
350
+
319
351
  async function actOnCandidate(params) {
320
352
  const backendNodeId = Number(params.backendNodeId)
321
353
  const action = String(params.action || 'click')
@@ -382,7 +414,7 @@ async function actOnCandidate(params) {
382
414
  const hit = await call('DOM.getNodeForLocation', {
383
415
  x: Math.round(measured.centre.x), y: Math.round(measured.centre.y), includeUserAgentShadowDOM: false,
384
416
  })
385
- if (Number(hit?.backendNodeId) !== backendNodeId) {
417
+ if (Number(hit?.backendNodeId) !== backendNodeId && !(await nodeContains(backendNodeId, Number(hit?.backendNodeId)))) {
386
418
  const at = Math.round(measured.centre.x) + ',' + Math.round(measured.centre.y)
387
419
  return {
388
420
  ok: false,
@@ -392,6 +424,12 @@ async function actOnCandidate(params) {
392
424
  }
393
425
  }
394
426
 
427
+ // Remember where we were so a navigation can be told apart from a re-layout
428
+ // (issue #9 #5): a link that navigates makes the point resolve to a different
429
+ // node afterwards, which the old post-check reported as a failed click even
430
+ // though the navigation succeeded and the caller then clicked twice.
431
+ const beforeHref = (await call('Runtime.evaluate', { expression: 'location.href', returnByValue: true }))?.result?.value
432
+
395
433
  for (const type of ['mouseMoved', 'mousePressed', 'mouseReleased']) {
396
434
  await call('Input.dispatchMouseEvent', {
397
435
  type,
@@ -407,7 +445,15 @@ async function actOnCandidate(params) {
407
445
  const after = await call('DOM.getNodeForLocation', {
408
446
  x: Math.round(measured.centre.x), y: Math.round(measured.centre.y), includeUserAgentShadowDOM: false,
409
447
  })
410
- if (Number(after?.backendNodeId) !== backendNodeId) {
448
+ if (Number(after?.backendNodeId) !== backendNodeId && !(await nodeContains(backendNodeId, Number(after?.backendNodeId)))) {
449
+ // The node changed. If the URL changed too, the click navigated — that is a
450
+ // success, not a miss. Only report click-missed when neither the node family
451
+ // nor the URL accounts for the change.
452
+ const afterHref = (await call('Runtime.evaluate', { expression: 'location.href', returnByValue: true }))?.result?.value
453
+ if (typeof afterHref === 'string' && typeof beforeHref === 'string' && afterHref !== beforeHref) {
454
+ const navRecorded = await recordElement(backendNodeId)
455
+ return { ok: true, code: 'ok', action: 'click', navigated: true, backendNodeId, point: measured.centre, measured: measured.rect, drift: measured.drift, ...(navRecorded === null ? {} : { recorded: navRecorded }) }
456
+ }
411
457
  return { ok: false, code: 'click-missed', message: 'the click dispatched but the point now resolves to a different node' }
412
458
  }
413
459
  const recorded = await recordElement(backendNodeId)
@@ -664,8 +710,15 @@ rl.on('line', (line) => {
664
710
  })
665
711
  })
666
712
  rl.on('close', () => {
667
- if (state.ws) { try { state.ws.close() } catch { /* already gone */ } }
668
- process.exit(0)
713
+ // Do NOT exit while a request is still in flight. stdin EOF arrives before the
714
+ // async `chain` finishes, and a hard process.exit() here truncates the not-yet-
715
+ // flushed stdout replies (issue #9 #2: "the worker returned no reply for capture").
716
+ // Drain the chain, close the socket, then let the event loop end naturally so
717
+ // stdout flushes; a truly stuck chain is bounded by the host's graceMs kill.
718
+ chain.finally(() => {
719
+ if (state.ws) { try { state.ws.close() } catch { /* already gone */ } }
720
+ process.exitCode = 0
721
+ })
669
722
  })
670
723
 
671
724
  log(`ready (pid ${process.pid}, node ${process.version})`)
package/dsh-plugin.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "$schema": "https://dsh.community/schemas/dsh-plugin-0.15.json",
3
3
  "id": "dsh-browser-cdp",
4
4
  "name": "dsh-browser-cdp",
5
- "version": "1.7.12",
5
+ "version": "1.9.6",
6
6
  "manifestVersion": "0.15",
7
7
  "facets": {
8
8
  "host": {
@@ -203,4 +203,4 @@
203
203
  "dsh-tui"
204
204
  ]
205
205
  }
206
- }
206
+ }