cdp-toolkit 3.2.0 → 3.4.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.
@@ -731,6 +731,53 @@ var init_session_lease = __esm(() => {
731
731
  };
732
732
  });
733
733
 
734
+ // src/frontApp.ts
735
+ import { execFile } from "node:child_process";
736
+ function run(cmd, args) {
737
+ return new Promise((resolve) => {
738
+ execFile(cmd, args, { timeout: 2000 }, (err, stdout) => resolve(err ? "" : String(stdout)));
739
+ });
740
+ }
741
+ function restoreFrontAppEnabled(platform = process.platform) {
742
+ return platform === "darwin" && (process.env.CDP_RESTORE_FRONT_APP ?? "").trim() !== "0";
743
+ }
744
+ async function keepFrontApp(fn, opts = {}) {
745
+ const enabled = opts.enabled ?? restoreFrontAppEnabled();
746
+ if (!enabled)
747
+ return fn();
748
+ const ops = opts.ops ?? macFrontAppOps;
749
+ const before = await ops.front().catch(() => null);
750
+ const result = await fn();
751
+ if (before === null)
752
+ return result;
753
+ const fix = async () => {
754
+ const now = await ops.front().catch(() => null);
755
+ if (now !== null && now !== before)
756
+ await ops.setFront(before).catch(() => {
757
+ return;
758
+ });
759
+ };
760
+ await fix();
761
+ await new Promise((r) => setTimeout(r, opts.recheckMs ?? 250));
762
+ await fix();
763
+ return result;
764
+ }
765
+ var macFrontAppOps;
766
+ var init_frontApp = __esm(() => {
767
+ macFrontAppOps = {
768
+ async front() {
769
+ const asn = (await run("lsappinfo", ["front"])).trim();
770
+ if (!asn)
771
+ return null;
772
+ const m = /"?pid"?\s*=\s*(\d+)/.exec(await run("lsappinfo", ["info", "-only", "pid", asn]));
773
+ return m ? Number(m[1]) : null;
774
+ },
775
+ async setFront(pid) {
776
+ await run("osascript", ["-e", `tell application "System Events" to set frontmost of (first process whose unix id is ${pid}) to true`]);
777
+ }
778
+ };
779
+ });
780
+
734
781
  // src/driver.ts
735
782
  import { mkdir as mkdir3, readFile as readFile3, unlink as unlink3, writeFile as writeFile3 } from "node:fs/promises";
736
783
  import { join as join3 } from "node:path";
@@ -903,7 +950,7 @@ async function originIndex(backend, liveIds) {
903
950
  return index;
904
951
  }
905
952
  async function newTrackedPage(driver, backend, opts = {}) {
906
- const page = await driver.newPage(opts.url);
953
+ const page = await driver.newPage(opts.url, { focus: opts.focus === true });
907
954
  await recordOrigin(backend, page.id, { label: opts.label });
908
955
  return page;
909
956
  }
@@ -2999,6 +3046,8 @@ function mapBidiError(e) {
2999
3046
  return driverError("disconnected", e.message);
3000
3047
  if (code === "unsupported operation")
3001
3048
  return driverError("unsupported", e.message);
3049
+ if (code === "unknown command")
3050
+ return driverError("unsupported", `${e.message} (this Firefox predates that WebDriver BiDi command; see BIDI_CAPABILITY_MIN_FIREFOX for the version each capability needs)`);
3002
3051
  if (!code && /timed out/i.test(e.message))
3003
3052
  return driverError("timeout", e.message);
3004
3053
  if (!code && /(disposed|not open|connection closed)/i.test(e.message))
@@ -3152,6 +3201,69 @@ async function resolveElementLocator(conn, contextId, loc) {
3152
3201
  throw driverError("no-such-element", `text '${loc.text}' matched no element`);
3153
3202
  return sharedRefOf(nodes[0], `text '${loc.text}'`);
3154
3203
  }
3204
+ function modifierKeyValues(mods) {
3205
+ const out = [];
3206
+ for (const m of mods ?? []) {
3207
+ const v = MODIFIER_VALUES[m.toLowerCase()];
3208
+ if (v === undefined)
3209
+ throw driverError("page-error", `unknown modifier '${m}' (use Alt, Control, Meta, or Shift)`);
3210
+ if (!out.includes(v))
3211
+ out.push(v);
3212
+ }
3213
+ return out;
3214
+ }
3215
+ function modifierChord(pointerId, actions, keys) {
3216
+ const pointer = actions;
3217
+ if (keys.length === 0)
3218
+ return [{ type: "pointer", id: pointerId, actions: pointer }];
3219
+ const k = keys.length;
3220
+ const pause = () => ({ type: "pause" });
3221
+ const keyActions = [
3222
+ ...keys.map((v) => ({ type: "keyDown", value: v })),
3223
+ ...pointer.map(pause),
3224
+ ...[...keys].reverse().map((v) => ({ type: "keyUp", value: v }))
3225
+ ];
3226
+ const pointerActions = [
3227
+ ...Array.from({ length: k }, pause),
3228
+ ...pointer,
3229
+ ...Array.from({ length: k }, pause)
3230
+ ];
3231
+ return [
3232
+ { type: "key", id: "cdp-keyboard", actions: keyActions },
3233
+ { type: "pointer", id: pointerId, actions: pointerActions }
3234
+ ];
3235
+ }
3236
+ function firefoxMajor(conn) {
3237
+ const v = conn.capabilities?.browserVersion;
3238
+ if (typeof v !== "string")
3239
+ return;
3240
+ const major = Number.parseInt(v, 10);
3241
+ return Number.isFinite(major) ? major : undefined;
3242
+ }
3243
+ function requireFirefox(conn, token) {
3244
+ const min = BIDI_CAPABILITY_MIN_FIREFOX[token];
3245
+ if (min === undefined)
3246
+ return;
3247
+ const major = firefoxMajor(conn);
3248
+ if (major !== undefined && major < min) {
3249
+ const v = conn.capabilities.browserVersion;
3250
+ throw driverError("unsupported", `${token} needs Firefox ${min} or newer; this Firefox is ${v}.`);
3251
+ }
3252
+ }
3253
+ async function armPostHocBodies(conn) {
3254
+ if (process.env.CDP_FIREFOX_BODY_COLLECTOR === "off")
3255
+ return;
3256
+ try {
3257
+ requireFirefox(conn, "network.responseBodyPostHoc");
3258
+ } catch {
3259
+ return;
3260
+ }
3261
+ try {
3262
+ await conn.send("network.addDataCollector", { dataTypes: ["response"], maxEncodedDataSize: POST_HOC_BODY_MAX_BYTES });
3263
+ } catch (e) {
3264
+ console.error(`[cdp-toolkit] firefox response-body collector not armed: ${e instanceof Error ? e.message : String(e)}`);
3265
+ }
3266
+ }
3155
3267
  function bumpEpoch(endpoint, conn) {
3156
3268
  sessionEpochs.set(endpoint, (sessionEpochs.get(endpoint) ?? 0) + 1);
3157
3269
  connEndpoints.set(conn, endpoint);
@@ -3349,6 +3461,7 @@ async function getConnection(endpoint, timeoutMs, attached = false) {
3349
3461
  }
3350
3462
  connections.set(endpoint, conn);
3351
3463
  bumpEpoch(endpoint, conn);
3464
+ await armPostHocBodies(conn);
3352
3465
  if (muxMode(attached) !== "off") {
3353
3466
  try {
3354
3467
  const mux = await startBidiMux(conn);
@@ -3439,6 +3552,9 @@ async function pickContext(conn, contexts, selector) {
3439
3552
  return exact;
3440
3553
  throw driverError("no-such-target", `no context matching '${selector}'`);
3441
3554
  }
3555
+ function bidiCreateTabParams(opts) {
3556
+ return { type: "tab", background: opts?.focus !== true };
3557
+ }
3442
3558
 
3443
3559
  class BidiBrowserDriver {
3444
3560
  endpoint;
@@ -3465,12 +3581,13 @@ class BidiBrowserDriver {
3465
3581
  conn.release();
3466
3582
  }
3467
3583
  }
3468
- async newPage(url) {
3584
+ async newPage(url, opts) {
3469
3585
  const conn = await getConnection(this.endpoint, this.timeoutMs, this.attached);
3470
3586
  try {
3471
- const { context } = await conn.send("browsingContext.create", { type: "tab" }).catch((e) => {
3587
+ const create = () => conn.send("browsingContext.create", bidiCreateTabParams(opts)).catch((e) => {
3472
3588
  throw mapBidiError(e);
3473
3589
  });
3590
+ const { context } = opts?.focus === true ? await create() : await keepFrontApp(create);
3474
3591
  if (url)
3475
3592
  await conn.send("browsingContext.navigate", { context, url, wait: "complete" }).catch((e) => {
3476
3593
  throw mapBidiError(e);
@@ -3483,9 +3600,9 @@ class BidiBrowserDriver {
3483
3600
  async closePage(id) {
3484
3601
  const conn = await getConnection(this.endpoint, this.timeoutMs, this.attached);
3485
3602
  try {
3486
- await conn.send("browsingContext.close", { context: id }).catch((e) => {
3603
+ await keepFrontApp(() => conn.send("browsingContext.close", { context: id }).catch((e) => {
3487
3604
  throw mapBidiError(e);
3488
- });
3605
+ }));
3489
3606
  return { success: true };
3490
3607
  } finally {
3491
3608
  conn.release();
@@ -3564,7 +3681,35 @@ class BidiBrowserDriver {
3564
3681
  conn.release();
3565
3682
  }
3566
3683
  }
3684
+ async withBrowserConnection(fn) {
3685
+ const conn = await getConnection(this.endpoint, this.timeoutMs, this.attached);
3686
+ try {
3687
+ return await fn(conn);
3688
+ } finally {
3689
+ conn.release();
3690
+ }
3691
+ }
3692
+ setDisposeHook(key, hook) {
3693
+ let hooks = disposeHooks.get(this.endpoint);
3694
+ if (!hooks) {
3695
+ hooks = new Map;
3696
+ disposeHooks.set(this.endpoint, hooks);
3697
+ }
3698
+ if (hook)
3699
+ hooks.set(key, hook);
3700
+ else
3701
+ hooks.delete(key);
3702
+ }
3567
3703
  async dispose() {
3704
+ const hooks = disposeHooks.get(this.endpoint);
3705
+ disposeHooks.delete(this.endpoint);
3706
+ const live = connections.get(this.endpoint);
3707
+ if (hooks && live) {
3708
+ for (const hook of hooks.values())
3709
+ await hook(live).catch(() => {
3710
+ return;
3711
+ });
3712
+ }
3568
3713
  for (const key of [...bidiBeaconScripts.keys()]) {
3569
3714
  if (key.startsWith(`${this.endpoint}:`))
3570
3715
  bidiBeaconScripts.delete(key);
@@ -3639,8 +3784,9 @@ async function hostFirefoxMux(endpoint, opts = {}) {
3639
3784
  function createFirefoxDriverForEndpoint(wsUrl, opts) {
3640
3785
  return new BidiBrowserDriver(wsUrl, opts?.timeoutMs, true);
3641
3786
  }
3642
- var LINE_RE, INTERACTIVE_ROLES, STAMP_ONE_SOURCE, KEY_VALUES, MODIFIER_VALUES, BUTTON_CODES, ARM_SCROLL_SETTLE_WATCH_SOURCE, AWAIT_SCROLL_SETTLE_SOURCE = "function(){return window.__cdpScrollSettle;}", BIDI_CAPABILITIES, connections, slotHandles, muxes, joined, connecting, sessionEpochs, connEndpoints, STALE_ID_HINT, sleep2 = (ms) => new Promise((r) => setTimeout(r, ms)), slotLabelOverride, bidiBeaconScripts, BidiPageDriver;
3787
+ var LINE_RE, INTERACTIVE_ROLES, STAMP_ONE_SOURCE, KEY_VALUES, MODIFIER_VALUES, BUTTON_CODES, RAW_MOUSE_SOURCE_ID = "cdp-raw-mouse", ARM_SCROLL_SETTLE_WATCH_SOURCE, AWAIT_SCROLL_SETTLE_SOURCE = "function(){return window.__cdpScrollSettle;}", BIDI_CAPABILITY_MIN_FIREFOX, POST_HOC_BODY_MAX_BYTES, BIDI_CAPABILITIES, connections, slotHandles, muxes, joined, connecting, sessionEpochs, connEndpoints, disposeHooks, STALE_ID_HINT, sleep2 = (ms) => new Promise((r) => setTimeout(r, ms)), slotLabelOverride, bidiBeaconScripts, BidiPageDriver;
3643
3788
  var init_driver2 = __esm(() => {
3789
+ init_frontApp();
3644
3790
  init_driver();
3645
3791
  init_leases();
3646
3792
  init_origins();
@@ -3694,13 +3840,25 @@ var init_driver2 = __esm(() => {
3694
3840
  MODIFIER_VALUES = { shift: "", control: "", ctrl: "", alt: "", meta: "", cmd: "", command: "" };
3695
3841
  BUTTON_CODES = { left: 0, middle: 1, right: 2 };
3696
3842
  ARM_SCROLL_SETTLE_WATCH_SOURCE = "function(){window.__cdpScrollSettle=new Promise((resolve)=>{let t;const done=()=>{window.removeEventListener('scroll',on,true);resolve(true);};" + "const on=()=>{clearTimeout(t);t=setTimeout(done,60);};window.addEventListener('scroll',on,true);t=setTimeout(done,60);setTimeout(done,500);});}";
3843
+ BIDI_CAPABILITY_MIN_FIREFOX = {
3844
+ "browser.downloads": 160,
3845
+ "browser.permissions": 160,
3846
+ "emulate.mediaFeatures": 160,
3847
+ "emulate.networkConditions": 160,
3848
+ "input.raw": 160,
3849
+ "input.modifierClick": 160,
3850
+ "network.responseBodyPostHoc": 160,
3851
+ "screenshot.scale": 160
3852
+ };
3853
+ POST_HOC_BODY_MAX_BYTES = 2 * 1024 * 1024;
3697
3854
  BIDI_CAPABILITIES = new Set([
3698
3855
  "emulate.deviceMetrics",
3699
3856
  "screenshot.fullPage",
3700
3857
  "screenshot.element",
3701
3858
  "screenshot.renderSize",
3702
3859
  "network.intercept",
3703
- "locate.xpath"
3860
+ "locate.xpath",
3861
+ ...Object.keys(BIDI_CAPABILITY_MIN_FIREFOX)
3704
3862
  ]);
3705
3863
  connections = new Map;
3706
3864
  slotHandles = new Map;
@@ -3709,6 +3867,7 @@ var init_driver2 = __esm(() => {
3709
3867
  connecting = new Map;
3710
3868
  sessionEpochs = new Map;
3711
3869
  connEndpoints = new WeakMap;
3870
+ disposeHooks = new Map;
3712
3871
  STALE_ID_HINT = " — the Firefox BiDi session was re-established after its previous holder went away, and Firefox " + "assigns new context ids per session — re-resolve the tab with list_pages (url:/title: selectors) " + "and claim it again";
3713
3872
  bidiBeaconScripts = new Map;
3714
3873
  BidiPageDriver = class BidiPageDriver {
@@ -3875,18 +4034,30 @@ var init_driver2 = __esm(() => {
3875
4034
  return { x, y };
3876
4035
  }
3877
4036
  async click(loc, opts) {
3878
- if (opts?.modifiers && opts.modifiers.length > 0) {
3879
- throw driverError("unsupported", "click: 'modifiers' is not supported by the Firefox/BiDi driver; omit 'modifiers' or use --browser chrome for a modifier click.");
3880
- }
4037
+ const hasModifiers = !!opts?.modifiers && opts.modifiers.length > 0;
4038
+ if (hasModifiers)
4039
+ requireFirefox(this.conn, "input.modifierClick");
4040
+ const keys = modifierKeyValues(opts?.modifiers);
3881
4041
  const ref = await resolveElementLocator(this.conn, this.contextId, loc);
3882
4042
  const { x, y } = await this.centerOf(ref);
3883
4043
  const button = BUTTON_CODES[opts?.button ?? "left"];
3884
4044
  const actions = [{ type: "pointerMove", x, y, duration: 0 }];
3885
4045
  for (let i = 0;i < (opts?.clickCount ?? 1); i++)
3886
4046
  actions.push({ type: "pointerDown", button }, { type: "pointerUp", button });
3887
- await this.performActions([{ type: "pointer", id: "cdp-mouse", actions }]);
4047
+ await this.performActions(modifierChord("cdp-mouse", actions, keys));
3888
4048
  return { x, y };
3889
4049
  }
4050
+ async dispatchMouse(event) {
4051
+ requireFirefox(this.conn, "input.raw");
4052
+ const keys = modifierKeyValues(event.modifiers);
4053
+ const button = BUTTON_CODES[event.button ?? "left"];
4054
+ const actions = [{ type: "pointerMove", x: event.x, y: event.y, duration: 0 }];
4055
+ if (event.action === "down")
4056
+ actions.push({ type: "pointerDown", button });
4057
+ else if (event.action === "up")
4058
+ actions.push({ type: "pointerUp", button });
4059
+ await this.performActions(modifierChord(RAW_MOUSE_SOURCE_ID, actions, keys));
4060
+ }
3890
4061
  async scroll(anchor, opts) {
3891
4062
  const { x, y } = await this.resolveScrollPoint(anchor);
3892
4063
  const deltaX = Math.round(opts.deltaX ?? 0);
@@ -3957,8 +4128,11 @@ var init_driver2 = __esm(() => {
3957
4128
  await this.callFunctionValue(BidiPageDriver.INSERT_TEXT_SOURCE, [value, false], ref);
3958
4129
  return;
3959
4130
  }
3960
- const clear = "function(){this.focus&&this.focus();if('value' in this){this.value='';this.dispatchEvent(new Event('input',{bubbles:true}));}}";
3961
- await this.callFunctionValue(clear, [], ref);
4131
+ const clear = "function(){if(this.disabled||this.readOnly)return this.disabled?'disabled':'readonly';this.focus&&this.focus();if('value' in this){this.value='';this.dispatchEvent(new Event('input',{bubbles:true}));}return 'ok';}";
4132
+ const state = await this.callFunctionValue(clear, [], ref);
4133
+ if (state === "disabled" || state === "readonly") {
4134
+ throw driverError("page-error", `cannot fill a ${state} field: it was left unchanged`);
4135
+ }
3962
4136
  await this.sendKeys(value);
3963
4137
  }
3964
4138
  async typeText(loc, text) {
@@ -3995,11 +4169,23 @@ var init_driver2 = __esm(() => {
3995
4169
  }
3996
4170
  async screenshot(opts, _consumeBands) {
3997
4171
  const renderSize = opts?.renderWidth !== undefined && opts?.renderHeight !== undefined ? { width: opts.renderWidth, height: opts.renderHeight } : undefined;
3998
- if (!renderSize)
4172
+ const scale = opts?.scale !== undefined && opts.scale !== 1 ? opts.scale : undefined;
4173
+ if (!renderSize && scale === undefined)
3999
4174
  return this.capture(opts);
4175
+ if (scale !== undefined)
4176
+ requireFirefox(this.conn, "screenshot.scale");
4000
4177
  const previous = await readViewportRecord(this.browser.scheme, this.contextId);
4178
+ let dprOverride;
4179
+ if (scale !== undefined) {
4180
+ const base = previous?.deviceScaleFactor ?? Number(await this.evaluate("window.devicePixelRatio").catch(() => 1));
4181
+ dprOverride = (Number.isFinite(base) && base > 0 ? base : 1) * scale;
4182
+ }
4001
4183
  try {
4002
- await this.conn.send("browsingContext.setViewport", { context: this.contextId, viewport: { width: renderSize.width, height: renderSize.height } });
4184
+ await this.conn.send("browsingContext.setViewport", {
4185
+ context: this.contextId,
4186
+ ...renderSize ? { viewport: { width: renderSize.width, height: renderSize.height } } : {},
4187
+ ...dprOverride !== undefined ? { devicePixelRatio: dprOverride } : {}
4188
+ });
4003
4189
  } catch (e) {
4004
4190
  throw mapBidiError(e);
4005
4191
  }
@@ -4016,29 +4202,35 @@ var init_driver2 = __esm(() => {
4016
4202
  await this.conn.send("browsingContext.setViewport", {
4017
4203
  context: this.contextId,
4018
4204
  viewport: { width: previous.width, height: previous.height },
4019
- ...previous.deviceScaleFactor != null ? { devicePixelRatio: previous.deviceScaleFactor } : {}
4205
+ ...previous.deviceScaleFactor != null ? { devicePixelRatio: previous.deviceScaleFactor } : scale !== undefined ? { devicePixelRatio: null } : {}
4020
4206
  });
4021
4207
  } else {
4022
- await this.conn.send("browsingContext.setViewport", { context: this.contextId, viewport: null });
4208
+ await this.conn.send("browsingContext.setViewport", {
4209
+ context: this.contextId,
4210
+ ...renderSize ? { viewport: null } : {},
4211
+ ...scale !== undefined ? { devicePixelRatio: null } : {}
4212
+ });
4023
4213
  }
4024
4214
  } catch (e) {
4025
4215
  restoreError = e instanceof Error ? e.message : String(e);
4026
4216
  }
4027
4217
  if (!shot) {
4028
4218
  if (restoreError !== undefined && captureError instanceof Error) {
4029
- captureError.message = `${captureError.message} ${renderRestoreFailureNote(renderSize, restoreError)}`;
4219
+ captureError.message = renderSize ? `${captureError.message} ${renderRestoreFailureNote(renderSize, restoreError)}` : `${captureError.message} (and restoring the device pixel ratio failed too, the tab may still be emulated at ratio ${dprOverride}: ${restoreError})`;
4030
4220
  }
4031
4221
  throw captureError;
4032
4222
  }
4223
+ if (!renderSize) {
4224
+ if (restoreError !== undefined)
4225
+ throw driverError("page-error", `screenshot captured, but restoring the device pixel ratio failed (the tab may still be emulated at ratio ${dprOverride}): ${restoreError}`);
4226
+ return shot;
4227
+ }
4033
4228
  const result = { ...shot, renderSize, renderRestored: restoreError === undefined };
4034
4229
  if (restoreError !== undefined)
4035
4230
  result.renderRestoreError = restoreError;
4036
4231
  return result;
4037
4232
  }
4038
4233
  async capture(opts) {
4039
- if (opts?.scale !== undefined && opts.scale !== 1) {
4040
- throw driverError("unsupported", `screenshot scale ${opts.scale} is not supported by this backend (WebDriver BiDi's ` + "browsingContext.captureScreenshot has no scale parameter). Call emulate with " + `deviceScaleFactor:${opts.scale} first and capture at scale 1, or use --browser chrome.`);
4041
- }
4042
4234
  if (opts?.tile === true) {
4043
4235
  throw driverError("unsupported", "screenshot tile:true is not supported by this backend: band tiling is declared only where the band " + "arithmetic has been measured against a real browser, and Firefox was not driven for it " + `(browsingContext.captureScreenshot's clip:{type:"box"} is the primitive it would ride, untested). ` + "Capture a smaller region or a single element, or use --browser chrome for a tiled capture.");
4044
4236
  }
@@ -4066,10 +4258,29 @@ var init_driver2 = __esm(() => {
4066
4258
  await this.conn.send("browsingContext.setViewport", { context: this.contextId, viewport: null, devicePixelRatio: null }).catch(() => {
4067
4259
  return;
4068
4260
  });
4261
+ await this.conn.send("emulation.setMediaFeaturesOverride", { features: null, contexts: [this.contextId] }).catch(() => {
4262
+ return;
4263
+ });
4264
+ await this.conn.send("emulation.setNetworkConditions", { networkConditions: null, contexts: [this.contextId] }).catch(() => {
4265
+ return;
4266
+ });
4069
4267
  await clearViewportRecord(this.browser.scheme, this.contextId);
4070
4268
  return { applied: [] };
4071
4269
  }
4072
4270
  const applied = [];
4271
+ if (opts.media != null && opts.media !== "") {
4272
+ throw driverError("unsupported", `emulate media "${opts.media}": WebDriver BiDi's emulation.setMediaFeaturesOverride takes media features (prefers-color-scheme, ...) but has no print/screen media-type override. Use mediaFeatures, or --browser chrome for media type emulation.`);
4273
+ }
4274
+ const net = opts.networkConditions;
4275
+ if (net != null) {
4276
+ const throttled = (net.latency ?? 0) > 0 || (net.downloadThroughput ?? -1) >= 0 || (net.uploadThroughput ?? -1) >= 0;
4277
+ if (throttled) {
4278
+ throw driverError("unsupported", 'emulate networkConditions: Firefox only emulates offline (emulation.setNetworkConditions has the single type "offline"); latency and download/upload throughput throttling are not available. Pass only {offline:true|false}, or use --browser chrome.');
4279
+ }
4280
+ requireFirefox(this.conn, "emulate.networkConditions");
4281
+ }
4282
+ if (opts.mediaFeatures != null)
4283
+ requireFirefox(this.conn, "emulate.mediaFeatures");
4073
4284
  try {
4074
4285
  if (opts.width != null && opts.height != null) {
4075
4286
  await this.conn.send("browsingContext.setViewport", { context: this.contextId, viewport: { width: opts.width, height: opts.height }, ...opts.deviceScaleFactor != null ? { devicePixelRatio: opts.deviceScaleFactor } : {} });
@@ -4084,6 +4295,21 @@ var init_driver2 = __esm(() => {
4084
4295
  await this.conn.send("emulation.setUserAgentOverride", { userAgent: opts.userAgent, contexts: [this.contextId] });
4085
4296
  applied.push("userAgent");
4086
4297
  }
4298
+ if (opts.mediaFeatures != null) {
4299
+ const features = Object.fromEntries(opts.mediaFeatures.map((f) => [f.name, f.value]));
4300
+ await this.conn.send("emulation.setMediaFeaturesOverride", {
4301
+ features: opts.mediaFeatures.length > 0 ? features : null,
4302
+ contexts: [this.contextId]
4303
+ });
4304
+ applied.push("mediaFeatures");
4305
+ }
4306
+ if (net != null) {
4307
+ await this.conn.send("emulation.setNetworkConditions", {
4308
+ networkConditions: net.offline ? { type: "offline" } : null,
4309
+ contexts: [this.contextId]
4310
+ });
4311
+ applied.push("networkConditions");
4312
+ }
4087
4313
  } catch (e) {
4088
4314
  throw mapBidiError(e);
4089
4315
  }
@@ -4218,12 +4444,25 @@ var init_driver2 = __esm(() => {
4218
4444
  };
4219
4445
  }
4220
4446
  async getResponseBody(requestId) {
4221
- if (!this.bodyCollector)
4222
- throw driverError("unsupported", "getResponseBody: call startBodyCapture() first (network.responseBodyPostHoc is not supported)");
4447
+ let collector;
4223
4448
  try {
4224
- const { bytes } = await this.conn.send("network.getData", { dataType: "response", collector: this.bodyCollector, request: requestId });
4449
+ requireFirefox(this.conn, "network.responseBodyPostHoc");
4450
+ } catch (e) {
4451
+ if (!this.bodyCollector) {
4452
+ throw driverError("unsupported", `${e.message} Call startBodyCapture() before the request to read its body on this Firefox.`);
4453
+ }
4454
+ collector = this.bodyCollector;
4455
+ }
4456
+ try {
4457
+ const { bytes } = await this.conn.send("network.getData", { dataType: "response", request: requestId, ...collector ? { collector } : {} });
4225
4458
  return bytes.type === "base64" ? { body: bytes.value, base64Encoded: true } : { body: bytes.value, base64Encoded: false };
4226
4459
  } catch (e) {
4460
+ if (e instanceof BidiError && e.code === "unavailable network data") {
4461
+ throw driverError("page-error", `getResponseBody: the body of request ${requestId} was collected but has been evicted (Firefox keeps only a bounded recent window of response bodies, on the order of 100-200 MB). Re-issue the request, then read it sooner.`);
4462
+ }
4463
+ if (e instanceof BidiError && e.code === "no such network data") {
4464
+ throw driverError("page-error", `getResponseBody: no body is held for request ${requestId}. Firefox cannot say which of these applies: the id is wrong, the request started before this Firefox session did, the response was larger than ${POST_HOC_BODY_MAX_BYTES} bytes (not retained), or it has no body.`);
4465
+ }
4227
4466
  throw mapBidiError(e);
4228
4467
  }
4229
4468
  }