ferrum 0.20.2 → 0.21.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.
Files changed (64) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +2 -4
  3. data/lib/ferrum/accessibility.rb +40 -6
  4. data/lib/ferrum/browser/command.rb +2 -11
  5. data/lib/ferrum/browser/options/chrome.rb +58 -1
  6. data/lib/ferrum/browser/options.rb +63 -9
  7. data/lib/ferrum/browser/process.rb +12 -4
  8. data/lib/ferrum/browser/xvfb.rb +22 -2
  9. data/lib/ferrum/browser.rb +74 -35
  10. data/lib/ferrum/client/web_socket.rb +13 -6
  11. data/lib/ferrum/client.rb +119 -81
  12. data/lib/ferrum/concurrency/awaitable_map.rb +171 -0
  13. data/lib/ferrum/concurrency/cell.rb +128 -0
  14. data/lib/ferrum/concurrency/dispatcher.rb +146 -0
  15. data/lib/ferrum/console.rb +3 -2
  16. data/lib/ferrum/context.rb +162 -27
  17. data/lib/ferrum/contexts.rb +45 -22
  18. data/lib/ferrum/cookies/collection.rb +93 -0
  19. data/lib/ferrum/cookies/cookie.rb +0 -11
  20. data/lib/ferrum/cookies.rb +79 -86
  21. data/lib/ferrum/deadline.rb +140 -0
  22. data/lib/ferrum/dialog.rb +22 -0
  23. data/lib/ferrum/downloads.rb +83 -10
  24. data/lib/ferrum/errors.rb +96 -6
  25. data/lib/ferrum/frame/dom.rb +147 -38
  26. data/lib/ferrum/frame/runtime.rb +40 -32
  27. data/lib/ferrum/frame/script.rb +7 -38
  28. data/lib/ferrum/frame.rb +57 -20
  29. data/lib/ferrum/headers.rb +32 -27
  30. data/lib/ferrum/interceptable/chain.rb +99 -0
  31. data/lib/ferrum/interceptable.rb +44 -27
  32. data/lib/ferrum/isolated_world.rb +9 -10
  33. data/lib/ferrum/keyboard.rb +27 -6
  34. data/lib/ferrum/mouse.rb +139 -52
  35. data/lib/ferrum/network/auth_request.rb +42 -7
  36. data/lib/ferrum/network/error.rb +34 -4
  37. data/lib/ferrum/network/exchange.rb +35 -7
  38. data/lib/ferrum/network/intercepted_request.rb +42 -9
  39. data/lib/ferrum/network/request.rb +33 -9
  40. data/lib/ferrum/network/request_params.rb +11 -2
  41. data/lib/ferrum/network/response.rb +23 -2
  42. data/lib/ferrum/network.rb +267 -64
  43. data/lib/ferrum/node.rb +430 -62
  44. data/lib/ferrum/page/animation.rb +4 -0
  45. data/lib/ferrum/page/cookies.rb +133 -0
  46. data/lib/ferrum/page/frames.rb +7 -7
  47. data/lib/ferrum/page/navigation.rb +430 -0
  48. data/lib/ferrum/page/screencast.rb +4 -0
  49. data/lib/ferrum/page/screenshot.rb +13 -1
  50. data/lib/ferrum/page/stream.rb +13 -5
  51. data/lib/ferrum/page/tracing.rb +12 -7
  52. data/lib/ferrum/page.rb +168 -190
  53. data/lib/ferrum/remote_object.rb +4 -0
  54. data/lib/ferrum/target.rb +49 -11
  55. data/lib/ferrum/utils/deprecate.rb +73 -2
  56. data/lib/ferrum/utils/poll.rb +57 -0
  57. data/lib/ferrum/version.rb +1 -1
  58. data/lib/ferrum/worker.rb +34 -19
  59. data/lib/ferrum.rb +5 -1
  60. metadata +11 -6
  61. data/lib/ferrum/browser/options/base.rb +0 -112
  62. data/lib/ferrum/client/subscriber.rb +0 -145
  63. data/lib/ferrum/frame/runtime/legacy.rb +0 -336
  64. data/lib/ferrum/utils/event.rb +0 -33
@@ -33,24 +33,48 @@ module Ferrum
33
33
  end
34
34
 
35
35
  #
36
- # The request resource type.
36
+ # The request's resource type, e.g. `"Document"`, `"Script"` or `"XHR"`.
37
37
  #
38
38
  # @return [String]
39
39
  #
40
- def type
40
+ def resource_type
41
41
  @params["type"]
42
42
  end
43
43
 
44
44
  #
45
- # Determines if the request is of the given type.
45
+ # Determines if the request is of the given resource type, ignoring case.
46
+ #
47
+ # @param [String, Symbol] value
48
+ # The type to compare against, e.g. `:document`.
49
+ #
50
+ # @return [Boolean]
51
+ #
52
+ def resource_type?(value)
53
+ resource_type.downcase == value.to_s.downcase
54
+ end
55
+
56
+ #
57
+ # @deprecated Will be removed in Ferrum 0.22. Use {#resource_type}.
58
+ #
59
+ # @return [String]
60
+ #
61
+ def type
62
+ Utils::Deprecate.warn("Request#type will be removed in Ferrum 0.22. Use resource_type instead.",
63
+ user_code: true)
64
+ resource_type
65
+ end
66
+
67
+ #
68
+ # @deprecated Will be removed in Ferrum 0.22. Use {#resource_type?}.
46
69
  #
47
70
  # @param [String, Symbol] value
48
- # The type value to compare against.
49
71
  #
50
72
  # @return [Boolean]
51
73
  #
52
74
  def type?(value)
53
- type.downcase == value.to_s.downcase
75
+ Utils::Deprecate.warn("Request#type? will be removed in Ferrum 0.22. Use resource_type? instead.",
76
+ user_code: true)
77
+ resource_type?(value)
54
78
  end
55
79
 
56
80
  #
@@ -59,7 +83,7 @@ module Ferrum
59
83
  # @return [Boolean]
60
84
  #
61
85
  def xhr?
62
- type?("xhr")
86
+ resource_type?("xhr")
63
87
  end
64
88
 
65
89
  #
@@ -81,12 +105,12 @@ module Ferrum
81
105
  end
82
106
 
83
107
  #
84
- # The request timestamp.
108
+ # The wall time the request was sent at, with sub-second precision.
85
109
  #
86
110
  # @return [Time]
87
111
  #
88
112
  def time
89
- @time ||= Time.strptime(@params["wallTime"].to_s, "%s")
113
+ @time ||= Time.at(@params["wallTime"])
90
114
  end
91
115
 
92
116
  #
@@ -95,7 +119,7 @@ module Ferrum
95
119
  # @return [Boolean]
96
120
  #
97
121
  def ping?
98
- type?("ping")
122
+ resource_type?("ping")
99
123
  end
100
124
 
101
125
  #
@@ -48,10 +48,19 @@ module Ferrum
48
48
  # @return [String, nil]
49
49
  # The HTTP `POST` form data.
50
50
  #
51
- def post_data
51
+ def body
52
52
  @request["postData"]
53
53
  end
54
- alias body post_data
54
+
55
+ #
56
+ # @deprecated Will be removed in Ferrum 0.22. Use {#body}.
57
+ #
58
+ # @return [String, nil]
59
+ #
60
+ def post_data
61
+ Utils::Deprecate.warn("post_data will be removed in Ferrum 0.22. Use body instead.", user_code: true)
62
+ body
63
+ end
55
64
  end
56
65
  end
57
66
  end
@@ -10,6 +10,8 @@ module Ferrum
10
10
  # The response body size.
11
11
  #
12
12
  # @return [Integer, nil]
13
+ #
14
+ # @note The writer is a private API, Ferrum sets it.
13
15
  attr_reader :body_size
14
16
 
15
17
  # The parsed JSON attributes for the [Network.Response](https://chromedevtools.github.io/devtools-protocol/1-3/Network/#type-Response)
@@ -21,6 +23,8 @@ module Ferrum
21
23
  # The response is fully loaded by the browser.
22
24
  #
23
25
  # @return [Boolean]
26
+ #
27
+ # @api private
24
28
  attr_writer :loaded
25
29
 
26
30
  #
@@ -93,14 +97,25 @@ module Ferrum
93
97
  end
94
98
 
95
99
  #
96
- # The resource type of the response.
100
+ # The response's resource type, e.g. `"Document"`, `"Script"` or `"XHR"`.
97
101
  #
98
102
  # @return [String]
99
103
  #
100
- def type
104
+ def resource_type
101
105
  @params["type"]
102
106
  end
103
107
 
108
+ #
109
+ # @deprecated Will be removed in Ferrum 0.22. Use {#resource_type}.
110
+ #
111
+ # @return [String]
112
+ #
113
+ def type
114
+ Utils::Deprecate.warn("Response#type will be removed in Ferrum 0.22. Use resource_type instead.",
115
+ user_code: true)
116
+ resource_type
117
+ end
118
+
104
119
  #
105
120
  # The `Content-Type` header value of the response.
106
121
  #
@@ -115,6 +130,8 @@ module Ferrum
115
130
  # See https://crbug.com/764946
116
131
  # `Network.loadingFinished` encodedDataLength contains both body and
117
132
  # headers sizes received by wire.
133
+ #
134
+ # @api private
118
135
  def body_size=(size)
119
136
  @body_size = size - headers_size
120
137
  end
@@ -126,6 +143,8 @@ module Ferrum
126
143
  #
127
144
  # @raise [Ferrum::BrowserError]
128
145
  #
146
+ # @raise [TimeoutError]
147
+ #
129
148
  def body!
130
149
  @body ||= begin
131
150
  body, encoded = @page.command("Network.getResponseBody", requestId: id)
@@ -139,6 +158,8 @@ module Ferrum
139
158
  #
140
159
  # @return [String, nil]
141
160
  #
161
+ # @raise [TimeoutError]
162
+ #
142
163
  def body
143
164
  body!
144
165
  rescue Ferrum::BrowserError
@@ -13,10 +13,17 @@ module Ferrum
13
13
  # {Network::Exchange}s built from the underlying CDP `Network.*` events.
14
14
  # Also provides request interception/authorization (`intercept`,
15
15
  # `authorize`, `blacklist=`/`whitelist=`) and network condition emulation
16
- # (`emulate_network_conditions`, `offline_mode`).
16
+ # (`throttle`, `offline=`), and user agent, language
17
+ # platform and client hints emulation (`emulate`).
17
18
  #
18
19
  class Network
20
+ WAIT_INTERVAL = 0.05
21
+ WAIT_FOR_IDLE_DEPRECATED = "wait_for_idle will be removed in Ferrum 0.22. Use wait_idle instead, duration: is " \
22
+ "interval: there."
19
23
  CLEAR_TYPE = %i[traffic cache].freeze
24
+ EMULATE_KEYS = %i[user_agent accept_language platform metadata].freeze
25
+ METADATA_REQUIRED = %i[platform platform_version architecture model mobile].freeze
26
+ METADATA_OPTIONAL = %i[brands full_version_list full_version bitness wow64 form_factors].freeze
20
27
  AUTHORIZE_TYPE = %i[server proxy].freeze
21
28
  REQUEST_STAGES = %i[Request Response].freeze
22
29
  RESOURCE_TYPES = %i[Document Stylesheet Image Media Font Script TextTrack
@@ -45,60 +52,97 @@ module Ferrum
45
52
  @exchange = nil
46
53
  @blacklist = nil
47
54
  @whitelist = nil
55
+ @overrides = {}
48
56
  @mutex = Mutex.new
49
57
  end
50
58
 
51
59
  #
52
- # Waits for network idle.
60
+ # Polls {#idle?} until the network is idle.
53
61
  #
54
62
  # @param [Integer] connections
55
- # how many connections are allowed for network to be idling,
63
+ # How many connections may still be pending.
56
64
  #
57
- # @param [Float] duration
58
- # Sleep for given amount of time and check again.
65
+ # @param [Numeric, Deadline, nil] timeout
66
+ # How long to keep trying, the page's `timeout` by default.
59
67
  #
60
- # @param [Float] timeout
61
- # During what time we try to check idle.
68
+ # @param [Numeric] interval
69
+ # Seconds to sleep between the attempts.
62
70
  #
63
- # @return [Boolean]
71
+ # @return [true, nil]
72
+ # `nil` when the network doesn't go idle in time.
64
73
  #
65
74
  # @example
66
75
  # browser.go_to("https://example.com/")
67
76
  # browser.at_xpath("//a[text() = 'No UI changes button']").click
68
- # browser.network.wait_for_idle # => false
77
+ # browser.network.wait_idle # => true
69
78
  #
70
- def wait_for_idle(connections: 0, duration: 0.05, timeout: @page.timeout)
71
- start = Utils::ElapsedTime.monotonic_time
72
-
73
- until idle?(connections)
74
- return false if Utils::ElapsedTime.timeout?(start, timeout)
79
+ def wait_idle(connections: 0, timeout: nil, interval: WAIT_INTERVAL)
80
+ Utils::Poll.call(timeout || @page.timeout, interval) { idle?(connections: connections) || nil }
81
+ end
75
82
 
76
- sleep(duration)
77
- end
83
+ #
84
+ # Same as {#wait_idle}, but raises if the network doesn't go idle in time.
85
+ #
86
+ # @param [Hash] options
87
+ # The options of {#wait_idle}.
88
+ #
89
+ # @return [true]
90
+ #
91
+ # @raise [TimeoutError]
92
+ # If the network doesn't go idle in time.
93
+ #
94
+ def wait_idle!(**options)
95
+ wait_idle(**options) || raise(TimeoutError)
96
+ end
78
97
 
79
- true
98
+ #
99
+ # Waits for network idle.
100
+ #
101
+ # @deprecated Will be removed in Ferrum 0.22. Use {#wait_idle}, `duration:` is `interval:` there.
102
+ #
103
+ # @param [Integer] connections
104
+ #
105
+ # @param [Float] duration
106
+ #
107
+ # @param [Numeric, Deadline] timeout
108
+ #
109
+ # @return [Boolean]
110
+ #
111
+ def wait_for_idle(connections: 0, duration: WAIT_INTERVAL, timeout: @page.timeout)
112
+ Utils::Deprecate.warn(WAIT_FOR_IDLE_DEPRECATED, user_code: true)
113
+ wait_idle(connections: connections, timeout: timeout, interval: duration) || false
80
114
  end
81
115
 
82
116
  #
83
117
  # Waits for network idle or raises {Ferrum::TimeoutError} error.
84
- # Accepts same arguments as `wait_for_idle`.
118
+ #
119
+ # @deprecated Will be removed in Ferrum 0.22. Use {#wait_idle!}.
120
+ #
121
+ # @param [Hash] options
122
+ # The options of {#wait_for_idle}.
123
+ #
124
+ # @return [void]
85
125
  #
86
126
  # @raise [Ferrum::TimeoutError]
87
- def wait_for_idle!(...)
88
- result = wait_for_idle(...)
89
- raise TimeoutError unless result
127
+ #
128
+ def wait_for_idle!(**options)
129
+ raise TimeoutError unless wait_for_idle(**options)
90
130
  end
91
131
 
92
132
  #
93
133
  # Whether the network is idle, i.e. no more than `connections`
94
134
  # connections are still pending.
95
135
  #
136
+ # @param [Integer, nil] deprecated_connections
137
+ # Deprecated, pass `connections:` instead.
138
+ #
96
139
  # @param [Integer] connections
97
- # How many connections are allowed for network to be idling.
140
+ # How many connections may still be pending.
98
141
  #
99
142
  # @return [Boolean]
100
143
  #
101
- def idle?(connections = 0)
144
+ def idle?(deprecated_connections = nil, connections: 0)
145
+ connections = Utils::Deprecate.positional(:connections, deprecated_connections, connections)
102
146
  pending_connections <= connections
103
147
  end
104
148
 
@@ -178,7 +222,9 @@ module Ferrum
178
222
  # @param [:traffic, :cache] type
179
223
  # The type of traffic to clear.
180
224
  #
181
- # @return [true]
225
+ # @return [nil]
226
+ #
227
+ # @raise [TimeoutError]
182
228
  #
183
229
  # @example
184
230
  # traffic = browser.network.traffic # => []
@@ -196,7 +242,7 @@ module Ferrum
196
242
  @page.command("Network.clearBrowserCache")
197
243
  end
198
244
 
199
- true
245
+ nil
200
246
  end
201
247
 
202
248
  #
@@ -208,6 +254,8 @@ module Ferrum
208
254
  # One or more patterns matched against the request's URL, see
209
255
  # {InterceptedRequest#match?}.
210
256
  #
257
+ # @raise [TimeoutError]
258
+ #
211
259
  # @example
212
260
  # browser.network.blacklist = /jquery/
213
261
  # browser.go_to("https://example.com/")
@@ -227,6 +275,8 @@ module Ferrum
227
275
  # One or more patterns matched against the request's URL, see
228
276
  # {InterceptedRequest#match?}.
229
277
  #
278
+ # @raise [TimeoutError]
279
+ #
230
280
  # @example
231
281
  # browser.network.whitelist = /example/
232
282
  # browser.go_to("https://example.com/")
@@ -247,6 +297,10 @@ module Ferrum
247
297
  # @param [Symbol, nil] resource_type
248
298
  # One of the [resource types](https://chromedevtools.github.io/devtools-protocol/tot/Network#type-ResourceType)
249
299
  #
300
+ # @return [nil]
301
+ #
302
+ # @raise [TimeoutError]
303
+ #
250
304
  # @example
251
305
  # browser = Ferrum::Browser.new
252
306
  # browser.network.intercept
@@ -275,6 +329,7 @@ module Ferrum
275
329
  pattern[:resourceType] = resource_type if resource_type
276
330
  pattern[:requestStage] = request_stage if request_stage
277
331
  @page.command("Fetch.enable", patterns: [pattern], handleAuthRequests: handle_auth_requests)
332
+ nil
278
333
  end
279
334
 
280
335
  #
@@ -296,11 +351,13 @@ module Ferrum
296
351
  # @yieldparam [Request] request
297
352
  # An HTTP request.
298
353
  #
354
+ # @raise [TimeoutError]
355
+ #
299
356
  # @example
300
357
  # browser.network.authorize(user: "login", password: "pass") { |req| req.continue }
301
358
  # browser.go_to("http://example.com/authenticated")
302
359
  # puts browser.network.status # => 200
303
- # puts browser.body # => Welcome, authenticated client
360
+ # puts browser.html # => Welcome, authenticated client
304
361
  #
305
362
  def authorize(user:, password:, type: :server, &block)
306
363
  raise ArgumentError, AUTHORIZE_TYPE_WRONG unless AUTHORIZE_TYPE.include?(type)
@@ -313,19 +370,15 @@ module Ferrum
313
370
 
314
371
  @page.on(:request, &block)
315
372
 
316
- @page.on(:auth) do |request, index, total|
317
- if request.auth_challenge?(type)
318
- response = authorized_response(@authorized_ids[type],
319
- request.request_id,
320
- user, password)
321
-
322
- @authorized_ids[type] << request.request_id
323
- request.continue(authChallengeResponse: response)
324
- elsif index + 1 < total
325
- next # There are other callbacks that can handle this
326
- else
327
- request.abort
328
- end
373
+ @page.on(:auth) do |request|
374
+ next unless request.auth_challenge?(type)
375
+
376
+ response = authorized_response(@authorized_ids[type],
377
+ request.id,
378
+ user, password)
379
+
380
+ @authorized_ids[type] << request.id
381
+ request.continue(authChallengeResponse: response)
329
382
  end
330
383
  end
331
384
 
@@ -395,7 +448,7 @@ module Ferrum
395
448
  end
396
449
 
397
450
  # `Network.requestWillBeSent` and `Fetch.requestPaused` are handled on
398
- # separate threads (see `Client::Subscriber`), so the "find the existing
451
+ # separate threads (see `Concurrency::Dispatcher`), so the "find the existing
399
452
  # exchange for this id or build a new one" check has to be atomic,
400
453
  # otherwise both threads can race past the `select` before either has
401
454
  # appended, and end up building two exchanges for the same request.
@@ -406,19 +459,17 @@ module Ferrum
406
459
  end
407
460
 
408
461
  #
409
- # Activates emulation of network conditions.
410
- #
411
- # @param [Boolean] offline
412
- # Emulate internet disconnection,
462
+ # Slows the page's network down. Each call replaces the previous conditions and turns {#offline=} off, Chrome
463
+ # keeps a single set of them.
413
464
  #
414
465
  # @param [Integer] latency
415
466
  # Minimum latency from request sent to response headers received (ms).
416
467
  #
417
- # @param [Integer] download_throughput
418
- # Maximal aggregated download throughput (bytes/sec).
468
+ # @param [Integer] download
469
+ # Maximal aggregated download throughput (bytes/sec), `-1` for no limit.
419
470
  #
420
- # @param [Integer] upload_throughput
421
- # Maximal aggregated upload throughput (bytes/sec).
471
+ # @param [Integer] upload
472
+ # Maximal aggregated upload throughput (bytes/sec), `-1` for no limit.
422
473
  #
423
474
  # @param [String, nil] connection_type
424
475
  # Connection type if known:
@@ -432,49 +483,193 @@ module Ferrum
432
483
  # * `"wimax"`
433
484
  # * `"other"`
434
485
  #
486
+ # @return [void]
487
+ #
488
+ # @raise [TimeoutError]
489
+ #
490
+ # @example
491
+ # browser.network.throttle(latency: 300, download: 50_000, connection_type: "cellular2g")
492
+ # browser.go_to("https://github.com/")
493
+ #
494
+ def throttle(latency: 0, download: -1, upload: -1, connection_type: nil)
495
+ network_conditions(offline: false, latency: latency, download: download, upload: upload,
496
+ connection_type: connection_type)
497
+ nil
498
+ end
499
+
500
+ #
501
+ # Takes the page offline or back online. It replaces the conditions set by {#throttle}, so going back online
502
+ # leaves the network unthrottled, call {#throttle} again to restore them.
503
+ #
504
+ # @param [Boolean] offline
505
+ #
506
+ # @raise [TimeoutError]
507
+ #
435
508
  # @example
436
- # browser.network.emulate_network_conditions(connection_type: "cellular2g")
509
+ # browser.network.offline = true
437
510
  # browser.go_to("https://github.com/")
511
+ # # => Request to https://github.com/ failed (net::ERR_INTERNET_DISCONNECTED) (Ferrum::StatusError)
512
+ # browser.network.offline = false
513
+ #
514
+ def offline=(offline)
515
+ network_conditions(offline: offline)
516
+ end
517
+
518
+ #
519
+ # @deprecated Will be removed in Ferrum 0.22. Use {#throttle}, or {#offline=} for `offline: true`.
520
+ #
521
+ # @return [true]
522
+ #
523
+ # @raise [TimeoutError]
438
524
  #
439
525
  def emulate_network_conditions(offline: false, latency: 0,
440
526
  download_throughput: -1, upload_throughput: -1,
441
527
  connection_type: nil)
442
- params = {
443
- offline: offline, latency: latency,
444
- downloadThroughput: download_throughput,
445
- uploadThroughput: upload_throughput
446
- }
447
-
448
- params[:connectionType] = connection_type if connection_type && ALLOWED_CONNECTION_TYPE.include?(connection_type)
528
+ Utils::Deprecate.warn("emulate_network_conditions will be removed in Ferrum 0.22. Use throttle, or " \
529
+ "offline = true, instead.", user_code: true)
530
+ network_conditions(offline: offline, latency: latency, download: download_throughput,
531
+ upload: upload_throughput, connection_type: connection_type)
532
+ true
533
+ end
449
534
 
450
- @page.command("Network.emulateNetworkConditions", **params)
535
+ #
536
+ # @deprecated Will be removed in Ferrum 0.22. Use `offline = true`.
537
+ #
538
+ # @return [true]
539
+ #
540
+ # @raise [TimeoutError]
541
+ #
542
+ def offline_mode
543
+ Utils::Deprecate.warn("offline_mode will be removed in Ferrum 0.22. Use offline = true instead.",
544
+ user_code: true)
545
+ network_conditions(offline: true, download: 0, upload: 0)
451
546
  true
452
547
  end
453
548
 
454
549
  #
455
- # Activates offline mode for a page.
550
+ # Overrides the user agent, the accept language, the platform and the
551
+ # client hints the page reports, both in the request headers and to
552
+ # JavaScript via `navigator`. Chrome replaces the whole override on every
553
+ # call, so the values you don't pass keep their previous ones. Pass `nil`
554
+ # to bring one back to the browser's default.
555
+ #
556
+ # While an override is active Chrome stops sending client hints
557
+ # (`Sec-CH-UA-*` headers and `navigator.userAgentData`) unless you pass
558
+ # `:metadata`. Once every option is back to `nil` the override is removed
559
+ # and Chrome sends them again.
560
+ #
561
+ # Setting the `User-Agent` or `Accept-Language` through {Headers} goes
562
+ # through here too, and the last one set wins.
563
+ #
564
+ # @param [Hash{Symbol => String, Hash, nil}] overrides
565
+ #
566
+ # @option overrides [String, nil] :user_agent
567
+ # The `User-Agent` header and `navigator.userAgent`.
568
+ #
569
+ # @option overrides [String, nil] :accept_language
570
+ # The `Accept-Language` header and `navigator.language`.
571
+ #
572
+ # @option overrides [String, nil] :platform
573
+ # `navigator.platform`, e.g. `"Win32"`.
574
+ #
575
+ # @option overrides [Hash{Symbol => Object}, nil] :metadata
576
+ # The client hints, needs all of `:platform`, `:platform_version`,
577
+ # `:architecture`, `:model` and `:mobile`. `:brands` and
578
+ # `:full_version_list` take an array of `{ brand:, version: }`, and
579
+ # `:full_version`, `:bitness`, `:wow64` and `:form_factors` are optional
580
+ # too.
581
+ #
582
+ # @return [nil]
583
+ #
584
+ # @raise [ArgumentError] on any other option, or a `:metadata` that is
585
+ # missing a key or has an unknown one.
586
+ #
587
+ # @raise [TimeoutError]
456
588
  #
457
589
  # @example
458
- # browser.network.offline_mode
590
+ # browser.network.emulate(platform: "Win32", accept_language: "de-DE")
459
591
  # browser.go_to("https://github.com/")
460
- # # => Request to https://github.com/ failed (net::ERR_INTERNET_DISCONNECTED) (Ferrum::StatusError)
461
592
  #
462
- def offline_mode
463
- emulate_network_conditions(offline: true, latency: 0, download_throughput: 0, upload_throughput: 0)
593
+ # @example Client hints that match the user agent:
594
+ # browser.network.emulate(
595
+ # user_agent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/130.0.0.0 Safari/537.36",
596
+ # platform: "Win32",
597
+ # metadata: { platform: "Windows", platform_version: "15.0.0", architecture: "x86", model: "", mobile: false }
598
+ # )
599
+ #
600
+ def emulate(**overrides)
601
+ unknown = overrides.keys - EMULATE_KEYS
602
+ raise ArgumentError, "unknown keywords: #{unknown.map(&:inspect).join(', ')}" unless unknown.empty?
603
+
604
+ validate_metadata(overrides[:metadata]) if overrides[:metadata]
605
+
606
+ @overrides.merge!(overrides).compact!
607
+ params = { userAgent: @overrides.empty? ? "" : @overrides[:user_agent] || @page.default_user_agent }
608
+ params[:acceptLanguage] = @overrides[:accept_language] if @overrides[:accept_language]
609
+ params[:platform] = @overrides[:platform] if @overrides[:platform]
610
+ params[:userAgentMetadata] = camelize(@overrides[:metadata]) if @overrides[:metadata]
611
+
612
+ @page.command("Network.setUserAgentOverride", **params)
613
+ nil
464
614
  end
465
615
 
466
616
  #
467
- # Toggles ignoring cache for each request. If true, cache will not be used.
617
+ # Turns the browser cache on or off for the page's requests.
618
+ #
619
+ # @param [Boolean] enabled
620
+ #
621
+ # @raise [TimeoutError]
468
622
  #
469
623
  # @example
470
- # browser.network.cache(disable: true)
624
+ # browser.network.cache = false
625
+ #
626
+ def cache=(enabled)
627
+ @page.command("Network.setCacheDisabled", cacheDisabled: !enabled)
628
+ end
629
+
630
+ #
631
+ # @deprecated Will be removed in Ferrum 0.22. Use `cache = false`.
632
+ #
633
+ # @param [Boolean] disable
634
+ #
635
+ # @return [Hash]
636
+ #
637
+ # @raise [TimeoutError]
471
638
  #
472
639
  def cache(disable:)
640
+ Utils::Deprecate.warn("cache(disable:) will be removed in Ferrum 0.22. Use cache = false instead.",
641
+ user_code: true)
473
642
  @page.command("Network.setCacheDisabled", cacheDisabled: disable)
474
643
  end
475
644
 
476
645
  private
477
646
 
647
+ def network_conditions(offline:, latency: 0, download: -1, upload: -1, connection_type: nil)
648
+ params = { offline: offline, latency: latency, downloadThroughput: download, uploadThroughput: upload }
649
+ params[:connectionType] = connection_type if connection_type && ALLOWED_CONNECTION_TYPE.include?(connection_type)
650
+ @page.command("Network.emulateNetworkConditions", **params)
651
+ end
652
+
653
+ def validate_metadata(metadata)
654
+ missing = METADATA_REQUIRED - metadata.keys
655
+ raise ArgumentError, "metadata is missing: #{missing.map(&:inspect).join(', ')}" unless missing.empty?
656
+
657
+ unknown = metadata.keys - METADATA_REQUIRED - METADATA_OPTIONAL
658
+ raise ArgumentError, "metadata has unknown keys: #{unknown.map(&:inspect).join(', ')}" unless unknown.empty?
659
+ end
660
+
661
+ def camelize(value)
662
+ case value
663
+ when Hash then value.to_h { |key, v| [camel_case(key), camelize(v)] }
664
+ when Array then value.map { |v| camelize(v) }
665
+ else value
666
+ end
667
+ end
668
+
669
+ def camel_case(key)
670
+ key.to_s.gsub(/_(\w)/) { Regexp.last_match(1).upcase }.to_sym
671
+ end
672
+
478
673
  def subscribe_request_will_be_sent
479
674
  @page.on("Network.requestWillBeSent") do |params|
480
675
  request = Network::Request.new(params)
@@ -549,10 +744,18 @@ module Ferrum
549
744
  exchange.error.type = params["type"]
550
745
  exchange.error.error_text = params["errorText"]
551
746
  exchange.error.monotonic_time = params["timestamp"]
747
+ exchange.error.time ||= failed_at(exchange.request, params["timestamp"])
552
748
  exchange.error.canceled = params["canceled"]
553
749
  end
554
750
  end
555
751
 
752
+ def failed_at(request, timestamp)
753
+ started = request.to_h
754
+ return Time.now unless started["wallTime"] && started["timestamp"] && timestamp
755
+
756
+ Time.at(started["wallTime"] + (timestamp - started["timestamp"]))
757
+ end
758
+
556
759
  def subscribe_log_entry_added
557
760
  @page.on("Log.entryAdded") do |params|
558
761
  entry = params["entry"] || {}