testsurfer 0.5.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.
@@ -0,0 +1,299 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Testsurfer
4
+ # How to open a context: Playwright's `browser.newContext` options, in snake_case.
5
+ class ContextOptions
6
+ KEYS = %i[isolated intercept ignore_https_errors user_agent locale timezone_id has_touch is_mobile
7
+ java_script_enabled bypass_csp geolocation permissions offline extra_http_headers http_credentials
8
+ color_scheme reduced_motion forced_colors contrast media storage_state record_video_dir
9
+ record_video_size record_har_path record_har_url_filter record_har_content base_url viewport].freeze
10
+
11
+ attr_reader(*KEYS)
12
+
13
+ # isolated: its own in-memory cookie and storage jar, discarded on
14
+ # close (default true). intercept: every request goes through
15
+ # vibesurfer's proxy, which routes, network and page events need
16
+ # (default true; isolated contexts only).
17
+ def initialize(**opts)
18
+ @isolated = true
19
+ @intercept = true
20
+ @java_script_enabled = true
21
+ @permissions = []
22
+ @extra_http_headers = {}
23
+ opts.each do |k, v|
24
+ raise UsageError, "new_context: unknown option #{k}" unless KEYS.include?(k)
25
+
26
+ instance_variable_set("@#{k}", v)
27
+ end
28
+ @permissions = Array(@permissions).map(&:to_s)
29
+ end
30
+
31
+ def media_fields
32
+ {
33
+ "media" => media, "colorScheme" => color_scheme, "reducedMotion" => reduced_motion,
34
+ "forcedColors" => forced_colors, "contrast" => contrast
35
+ }.compact.transform_values(&:to_s)
36
+ end
37
+
38
+ # The `vs_emulate` options a new context starts with.
39
+ def emulation
40
+ m = {}
41
+ m["userAgent"] = user_agent if user_agent
42
+ m["locale"] = locale if locale
43
+ m["timezoneId"] = timezone_id if timezone_id
44
+ m["hasTouch"] = true if has_touch || is_mobile
45
+ m["isMobile"] = true if is_mobile
46
+ m["javaScriptEnabled"] = false unless java_script_enabled
47
+ m["bypassCSP"] = true if bypass_csp
48
+ m["geolocation"] = Emulation.geolocation(geolocation) if geolocation
49
+ m["permissions"] = permissions unless permissions.empty?
50
+ m["offline"] = true if offline
51
+ m["extraHTTPHeaders"] = Emulation.headers(extra_http_headers) unless extra_http_headers.nil? || extra_http_headers.empty?
52
+ m["httpCredentials"] = Emulation.credentials(http_credentials) if http_credentials
53
+ m.merge(media_fields)
54
+ end
55
+ end
56
+
57
+ # A set of pages sharing cookies and storage.
58
+ class BrowserContext
59
+ include EventTarget
60
+
61
+ attr_reader :browser, :session_id, :hub, :record_video, :base_url, :viewport_override
62
+
63
+ def self.open(browser, options)
64
+ req = Wire::Request.new("vs_session_open")
65
+ intercept = options.intercept && options.isolated
66
+ req.flag("isolated") if options.isolated
67
+ if intercept
68
+ # Popups open as their own pages, and page events reach the same stream as the network's.
69
+ req.flag("intercept").flag("popups").flag("events")
70
+ req.flag("ignore-https-errors") if options.ignore_https_errors
71
+ end
72
+ resp = browser.wire.call(req)
73
+ session_id = resp.body.first
74
+ raise ConnectionError, "vs_session_open returned no session id" if session_id.nil?
75
+
76
+ rv = options.record_video_dir && { dir: options.record_video_dir.to_s, width: options.record_video_size && (options.record_video_size[:width] || options.record_video_size["width"]) }
77
+ ctx = new(browser, session_id, own: true, events: intercept, record_video: rv, options: options)
78
+ ctx.granted.replace(options.permissions)
79
+ Dispatch.start(ctx) if intercept
80
+ ctx.emulate(options.emulation)
81
+ ctx.apply_storage_state(StorageState.coerce(options.storage_state)) if options.storage_state
82
+ if options.record_har_path
83
+ ctx.start_har(options.record_har_path, options.record_har_url_filter, options.record_har_content)
84
+ ctx.instance_variable_set(:@recording_har, true)
85
+ end
86
+ ctx
87
+ end
88
+
89
+ # The browser's own session as a context.
90
+ def self.shared(browser)
91
+ new(browser, browser.session_id, own: false, events: false, record_video: nil, options: ContextOptions.new)
92
+ end
93
+
94
+ def initialize(browser, session_id, own:, events:, record_video:, options:)
95
+ @browser = browser
96
+ @session_id = session_id
97
+ @own = own
98
+ @events_on = events
99
+ @pages = []
100
+ @hub = Hub.new
101
+ @closed = false
102
+ @init_scripts = []
103
+ @granted = []
104
+ @record_video = record_video
105
+ @recording_har = false
106
+ @base_url = options.base_url || browser.options.base_url
107
+ @viewport_override = options.viewport && [Integer(options.viewport[:width] || options.viewport["width"]),
108
+ Integer(options.viewport[:height] || options.viewport["height"])]
109
+ @lock = Monitor.new
110
+ end
111
+
112
+ def wire
113
+ browser.wire
114
+ end
115
+
116
+ def events
117
+ hub.state
118
+ end
119
+
120
+ def events?
121
+ @events_on
122
+ end
123
+
124
+ def closed?
125
+ @lock.synchronize { @closed }
126
+ end
127
+
128
+ def granted
129
+ @granted
130
+ end
131
+
132
+ def init_scripts
133
+ @lock.synchronize { @init_scripts.dup }
134
+ end
135
+
136
+ def wait_api_name
137
+ "browserContext"
138
+ end
139
+
140
+ def need_events!(what)
141
+ return if events?
142
+
143
+ raise UsageError, "#{what} needs an intercepting context (the default context options)"
144
+ end
145
+
146
+ def sync_routing
147
+ hub.sync_routing(wire, session_id)
148
+ nil
149
+ end
150
+
151
+ def event_timeout
152
+ browser.options.timeouts.action
153
+ end
154
+
155
+ # Keep a page the context did not open itself (a popup).
156
+ def remember(page)
157
+ @lock.synchronize { @pages << page }
158
+ end
159
+
160
+ # A new page; `goto` loads a URL.
161
+ def new_page
162
+ page = Page.new(self)
163
+ @lock.synchronize { @pages << page }
164
+ page
165
+ end
166
+
167
+ # The pages open in this context, popups included.
168
+ def pages
169
+ @lock.synchronize do
170
+ @pages.reject!(&:closed?)
171
+ @pages.dup
172
+ end
173
+ end
174
+
175
+ # A script every page of the context runs at the start of each document, before the page's own.
176
+ def add_init_script(script = nil, path: nil)
177
+ source = path ? File.read(path) : script.to_s
178
+ @lock.synchronize { @init_scripts << source }
179
+ pages.each { |p| p.install_init_script(source) }
180
+ nil
181
+ end
182
+
183
+ # Make `name(...args)` in every page call the block here, as Playwright's `exposeFunction`.
184
+ def expose_function(name, callable = nil, &blk)
185
+ need_events!("context.exposeFunction")
186
+ f = callable || blk
187
+ events.sync do
188
+ raise UsageError, "Function \"#{name}\" has been already registered" if events.bindings.key?(name.to_s)
189
+
190
+ events.bindings[name.to_s] = f
191
+ end
192
+ script = Events.binding_script(name.to_s)
193
+ add_init_script(script)
194
+ pages.each do |p|
195
+ p.evaluate("(#{script}, 0)")
196
+ rescue Error
197
+ nil
198
+ end
199
+ nil
200
+ end
201
+
202
+ # The next page opened in the context.
203
+ def expect_page(predicate: nil, timeout: nil, &blk)
204
+ expect_event("page", predicate: predicate, timeout: timeout, &blk)
205
+ end
206
+ alias wait_for_page expect_page
207
+
208
+ # Close every page, and the context's session with its cookies and storage.
209
+ def close(**)
210
+ @lock.synchronize { @closed = true }
211
+ ps = @lock.synchronize { @pages.slice!(0..) }
212
+ ps.each(&:close)
213
+ stop_har if @recording_har
214
+ if @own
215
+ begin
216
+ wire.call(Wire::Request.new("vs_session_close").arg(session_id))
217
+ rescue Error
218
+ nil
219
+ end
220
+ browser.forget(self)
221
+ end
222
+ nil
223
+ end
224
+
225
+ # --- HAR ------------------------------------------------------------
226
+
227
+ def start_har(path, url_filter, content)
228
+ req = Wire::Request.new("vs_net_har").arg("record").arg(path.to_s)
229
+ req.flag_value("url-filter", url_filter) if url_filter
230
+ req.flag_value("content", content) if content
231
+ har(req)
232
+ end
233
+
234
+ # Write the HAR the context is recording (closing it does too).
235
+ def stop_har
236
+ har(Wire::Request.new("vs_net_har").arg("stop"))
237
+ end
238
+
239
+ # Answer the context's requests from a HAR file, before any route.
240
+ # not_found: "abort" (default) or "fallback".
241
+ def route_from_har(path, url: nil, not_found: "abort", update: nil) # rubocop:disable Lint/UnusedMethodArgument
242
+ req = Wire::Request.new("vs_net_har").arg("replay").arg(path.to_s)
243
+ req.flag_value("url", url) if url
244
+ req.flag_value("not-found", "fallback") if not_found.to_s == "fallback"
245
+ har(req)
246
+ end
247
+
248
+ # --- tracing and clock ----------------------------------------------
249
+
250
+ # Trace the context's actions, screenshots and network.
251
+ def tracing
252
+ Tracing.new(self)
253
+ end
254
+
255
+ # Fake time for every page of the context.
256
+ def clock
257
+ Clock.new(context: self)
258
+ end
259
+
260
+ # API requests that share this context's cookies.
261
+ def request
262
+ APIRequestContext.new(browser, jar: [:context, self], base_url: base_url)
263
+ end
264
+
265
+ # A page whose jar the cookie calls go through.
266
+ def jar_page
267
+ pages.each do |p|
268
+ id = p.page_id
269
+ return id if id
270
+ end
271
+ new_page.ensure_open
272
+ end
273
+
274
+ private
275
+
276
+ def har(req)
277
+ wire.call(req.flag_value("session", session_id))
278
+ nil
279
+ end
280
+ end
281
+
282
+ class Page
283
+ # Answer requests from a HAR file, before any route. The daemon
284
+ # replays per session, so the page's context answers from it too.
285
+ def route_from_har(path, **opts)
286
+ context.route_from_har(path, **opts)
287
+ end
288
+
289
+ # API requests that share the page's context cookies.
290
+ def request
291
+ context.request
292
+ end
293
+
294
+ # Fake time for this page.
295
+ def clock
296
+ Clock.new(page: self)
297
+ end
298
+ end
299
+ end
@@ -0,0 +1,136 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "base64"
4
+ require "json"
5
+
6
+ module Testsurfer
7
+ # Cookies of a context, read and written in the engine's jar
8
+ # (`vs_cookies`), HttpOnly ones included. A cookie is a hash as
9
+ # Playwright reports one: "name", "value", "domain", "path", "expires"
10
+ # (Unix seconds, -1 for a session cookie), "httpOnly", "secure", "sameSite".
11
+ module Cookies
12
+ module_function
13
+
14
+ def same_site(s)
15
+ case s.to_s.downcase
16
+ when "strict" then "Strict"
17
+ when "lax" then "Lax"
18
+ else "None"
19
+ end
20
+ end
21
+
22
+ # The daemon's jar JSON as Playwright cookies.
23
+ def from_wire(list)
24
+ (list || []).map do |c|
25
+ {
26
+ "name" => c["name"].to_s, "value" => c["value"].to_s, "domain" => c["domain"].to_s,
27
+ "path" => c["path"].to_s.empty? ? "/" : c["path"].to_s,
28
+ "expires" => c["expires_unix"].is_a?(Integer) ? c["expires_unix"] : -1,
29
+ "httpOnly" => c["http_only"] == true, "secure" => c["secure"] == true, "sameSite" => same_site(c["same_site"])
30
+ }
31
+ end
32
+ end
33
+
34
+ # A Playwright cookie as the daemon's jar takes it.
35
+ def wire_of(c)
36
+ h = { "name" => c["name"], "value" => c["value"], "domain" => c["domain"], "path" => c["path"],
37
+ "secure" => c["secure"] == true, "http_only" => c["httpOnly"] == true }
38
+ h["expires_unix"] = c["expires"] if c["expires"].is_a?(Numeric) && c["expires"].positive?
39
+ h["same_site"] = c["sameSite"] if c["sameSite"]
40
+ h
41
+ end
42
+
43
+ # The scheme, lowercase host and path of a URL.
44
+ def url_parts(url)
45
+ scheme, rest = url.to_s.split("://", 2)
46
+ return nil if rest.nil?
47
+
48
+ stop = rest.index(%r{[/?#]}) || rest.length
49
+ authority = rest[0...stop]
50
+ host = authority.include?("@") ? authority.rpartition("@").last : authority
51
+ host = host.start_with?("[") ? host[0..(host.index("]") || -1)] : host.split(":").first.to_s
52
+ path_end = (i = rest[stop..].index(/[?#]/)) ? stop + i : rest.length
53
+ path = stop == path_end ? "/" : rest[stop...path_end]
54
+ [scheme.downcase, host.downcase, path]
55
+ end
56
+
57
+ # A cookie to add (with `url`, or `domain` and `path`) in wire form.
58
+ def to_wire(c)
59
+ c = c.to_h.transform_keys(&:to_s)
60
+ parts = c["url"] && url_parts(c["url"])
61
+ domain = c["domain"] || parts&.at(1)
62
+ raise UsageError, "browserContext.addCookies: a cookie needs url or domain" if domain.nil?
63
+
64
+ path = c["path"] || (parts ? parts[2][0..(parts[2].rindex("/") || 0)] : "/")
65
+ path = "/" if path.empty?
66
+ expires = c["expires"]
67
+ secure = c.key?("secure") ? c["secure"] == true : (parts && parts[0] == "https") || false
68
+ h = { "name" => c["name"].to_s, "value" => c["value"].to_s, "domain" => domain, "path" => path,
69
+ "secure" => secure, "http_only" => (c["httpOnly"] || c["http_only"]) == true }
70
+ h["expires_unix"] = expires.to_i if expires.is_a?(Numeric) && expires.positive?
71
+ ss = c["sameSite"] || c["same_site"]
72
+ h["same_site"] = ss.to_s if ss
73
+ h
74
+ end
75
+
76
+ # Whether `c` goes with a request to `url` (RFC 6265 domain, path and secure rules).
77
+ def goes_with?(c, url)
78
+ parts = url_parts(url)
79
+ return false if parts.nil?
80
+
81
+ scheme, host, path = parts
82
+ d = c["domain"].downcase
83
+ domain_ok = d.start_with?(".") ? (host == d[1..] || host.end_with?(d)) : host == d
84
+ cp = c["path"]
85
+ path_ok = path == cp || (path.start_with?(cp) && (cp.end_with?("/") || path[cp.length..].start_with?("/")))
86
+ loopback = %w[localhost 127.0.0.1 [::1]].include?(host)
87
+ expired = c["expires"].positive? && c["expires"] < Time.now.to_i
88
+ domain_ok && path_ok && !(c["secure"] && scheme != "https" && !loopback) && !expired
89
+ end
90
+ end
91
+
92
+ class BrowserContext
93
+ # Add cookies to the context's jar: hashes with name:, value:, and url:
94
+ # or domain: and path:; optional expires:, httpOnly:, secure:, sameSite:.
95
+ def add_cookies(cookies)
96
+ jar("set", cookies.map { |c| Cookies.to_wire(c) })
97
+ nil
98
+ end
99
+
100
+ # The context's cookies, HttpOnly included; with `urls`, only those
101
+ # that go with a request to one of them.
102
+ def cookies(urls = [])
103
+ all = jar("list")
104
+ urls = Array(urls)
105
+ urls.empty? ? all : all.select { |c| urls.any? { |u| Cookies.goes_with?(c, u) } }
106
+ end
107
+
108
+ # Remove the cookies matching name:, domain:, path: (all, when none is given).
109
+ def clear_cookies(name: nil, domain: nil, path: nil)
110
+ keep = if name.nil? && domain.nil? && path.nil?
111
+ []
112
+ else
113
+ test = ->(want, v) { want.nil? || (want.is_a?(Regexp) ? want.match?(v) : want == v) }
114
+ jar("list").reject { |c| test.(name, c["name"]) && test.(domain, c["domain"]) && test.(path, c["path"]) }
115
+ end
116
+ jar("clear")
117
+ jar("set", keep.map { |c| Cookies.wire_of(c) }) unless keep.empty?
118
+ nil
119
+ end
120
+
121
+ private
122
+
123
+ def jar(op, list = nil)
124
+ page = jar_page
125
+ req = Wire::Request.new("vs_cookies").arg(page).arg(op).flag_value("session", session_id)
126
+ req.arg(Base64.strict_encode64(JSON.generate(list))) if list
127
+ resp = wire.call(req)
128
+ parsed = begin
129
+ JSON.parse(resp.body.first || "[]")
130
+ rescue JSON::ParserError
131
+ []
132
+ end
133
+ Cookies.from_wire(parsed.is_a?(Array) ? parsed : [])
134
+ end
135
+ end
136
+ end
@@ -0,0 +1,176 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "digest"
4
+ require "fileutils"
5
+ require "open3"
6
+ require "rbconfig"
7
+ require "tmpdir"
8
+
9
+ module Testsurfer
10
+ # Finding, fetching and starting the vibesurfer daemon.
11
+ #
12
+ # testsurfer drives a local vibesurfer daemon. It uses, in order: the
13
+ # binary `TESTSURFER_VS` names, `vs` on the PATH, or the release this
14
+ # gem pins, cached under `~/.vibesurfer/bin/<version>` (where the other
15
+ # ports cache it too) and downloaded there on first use, with its
16
+ # checksum verified. `vs status` starts the daemon when none runs.
17
+ module Daemon
18
+ REPO = "frane/vibesurfer"
19
+
20
+ # The first `vs status` may start a cold daemon and its web engine.
21
+ START_TIMEOUT = 180
22
+
23
+ module_function
24
+
25
+ # The command to run vs: the program and any leading arguments.
26
+ def vs_command
27
+ if (v = ENV["TESTSURFER_VS"]) && !v.strip.empty?
28
+ return v.split
29
+ end
30
+ if (on_path = which("vs"))
31
+ return [on_path]
32
+ end
33
+
34
+ cached = File.join(cache_dir, bin_name)
35
+ download(cached) unless File.exist?(cached)
36
+ [cached]
37
+ end
38
+
39
+ # `vs <args>`, its stdout stripped.
40
+ def output(cmd, *args)
41
+ out = err = nil
42
+ status = nil
43
+ Open3.popen3(*cmd, *args) do |stdin, stdout, stderr, wait|
44
+ stdin.close
45
+ o = Thread.new { stdout.read }
46
+ e = Thread.new { stderr.read }
47
+ unless wait.join(START_TIMEOUT)
48
+ Process.kill("KILL", wait.pid) rescue nil # rubocop:disable Style/RescueModifier
49
+ raise ConnectionError, "`#{(cmd + args).join(' ')}` did not finish within #{START_TIMEOUT}s"
50
+ end
51
+ out = o.value.to_s
52
+ err = e.value.to_s
53
+ status = wait.value
54
+ end
55
+ unless status.success?
56
+ raise ConnectionError, "`#{(cmd + args).join(' ')}` failed (#{status}): #{out.strip}#{err.strip}"
57
+ end
58
+
59
+ out.strip
60
+ rescue SystemCallError => e
61
+ raise ConnectionError, "running #{cmd.first}: #{e.message}"
62
+ end
63
+
64
+ def bin_name
65
+ Gem.win_platform? ? "vs.exe" : "vs"
66
+ end
67
+
68
+ def home
69
+ var = Gem.win_platform? ? "USERPROFILE" : "HOME"
70
+ h = ENV[var]
71
+ raise ConnectionError, "$#{var} is not set" if h.nil? || h.empty?
72
+
73
+ h
74
+ end
75
+
76
+ def cache_dir
77
+ File.join(home, ".vibesurfer", "bin", PINNED_VIBESURFER)
78
+ end
79
+
80
+ # `name` on the PATH, as the shell would find it.
81
+ def which(name)
82
+ exe = Gem.win_platform? ? "#{name}.exe" : name
83
+ ENV.fetch("PATH", "").split(File::PATH_SEPARATOR).each do |dir|
84
+ p = File.join(dir, exe)
85
+ return p if File.file?(p)
86
+ end
87
+ nil
88
+ end
89
+
90
+ # The release asset for this platform: [target triple, archive extension].
91
+ def target
92
+ os = RbConfig::CONFIG["host_os"]
93
+ cpu = RbConfig::CONFIG["host_cpu"]
94
+ arm = cpu.match?(/arm64|aarch64/)
95
+ x86 = cpu.match?(/x86_64|x64|amd64/)
96
+ return ["aarch64-apple-darwin", "tar.gz"] if os.match?(/darwin/) && arm
97
+ return ["x86_64-apple-darwin", "tar.gz"] if os.match?(/darwin/) && x86
98
+ return ["x86_64-unknown-linux-gnu", "tar.gz"] if os.match?(/linux/) && x86
99
+ return ["x86_64-pc-windows-msvc", "zip"] if os.match?(/mswin|mingw|cygwin/) && x86
100
+
101
+ raise ConnectionError,
102
+ "no prebuilt vibesurfer binary for #{os}/#{cpu}; install it with `cargo install vibesurfer` and put `vs` on the PATH"
103
+ end
104
+
105
+ # The release archive's name for a triple and extension.
106
+ def asset_name(triple, ext)
107
+ "vs-v#{PINNED_VIBESURFER}-#{triple}.#{ext}"
108
+ end
109
+
110
+ # Fetch the pinned release into `dest`, checking it against the
111
+ # release's checksums.txt. Uses the system's curl and tar, which
112
+ # macOS, Linux and Windows 10+ all ship.
113
+ def download(dest)
114
+ triple, ext = target
115
+ tag = "v#{PINNED_VIBESURFER}"
116
+ asset = asset_name(triple, ext)
117
+ base = "https://github.com/#{REPO}/releases/download/#{tag}"
118
+ warn "testsurfer: fetching vibesurfer #{PINNED_VIBESURFER} (#{asset}, first run)"
119
+ Dir.mktmpdir("testsurfer-vs-") do |tmp|
120
+ archive = File.join(tmp, asset)
121
+ sums = File.join(tmp, "checksums.txt")
122
+ curl("#{base}/#{asset}", archive)
123
+ curl("#{base}/checksums.txt", sums)
124
+ want = checksum_for(File.read(sums), asset)
125
+ raise ConnectionError, "#{asset} is not listed in the release's checksums.txt" if want.nil?
126
+
127
+ got = Digest::SHA256.file(archive).hexdigest
128
+ raise ConnectionError, "checksum mismatch for #{asset}: got #{got}, want #{want}" if got != want
129
+
130
+ tar = if Gem.win_platform?
131
+ File.join(ENV.fetch("SystemRoot", "C:\\Windows"), "System32", "tar.exe")
132
+ else
133
+ "tar"
134
+ end
135
+ ok = system(tar, "-xf", archive, "-C", tmp)
136
+ raise ConnectionError, "unpacking #{asset} failed" unless ok
137
+
138
+ FileUtils.mkdir_p(File.dirname(dest))
139
+ FileUtils.cp(File.join(tmp, bin_name), dest)
140
+ File.chmod(0o755, dest) unless Gem.win_platform?
141
+ end
142
+ end
143
+
144
+ def curl(url, to)
145
+ ok = system("curl", "-fsSL", "--retry", "3", "-o", to, url)
146
+ if ok.nil?
147
+ raise ConnectionError,
148
+ "running curl to fetch vibesurfer failed; install vibesurfer yourself (`cargo install vibesurfer`) and put `vs` on the PATH"
149
+ end
150
+ raise ConnectionError, "fetching #{url} failed" unless ok
151
+ end
152
+
153
+ # The checksum checksums.txt lists for `asset` (`<sha256> <asset>` lines).
154
+ def checksum_for(sums, asset)
155
+ sums.each_line do |l|
156
+ sum, name = l.split
157
+ return sum.downcase if name == asset && sum&.length == 64
158
+ end
159
+ nil
160
+ end
161
+
162
+ # The daemon's address, starting the daemon if none answers there.
163
+ def address
164
+ addr = Wire.default_address
165
+ return addr if addr && Wire::Pool.reachable?(addr)
166
+
167
+ vs = vs_command
168
+ # `vs status` starts a daemon when none runs; `vs socket` names its address.
169
+ output(vs, "status")
170
+ addr = Wire.default_address
171
+ return addr if addr
172
+
173
+ output(vs, "socket").lines.last.to_s.strip
174
+ end
175
+ end
176
+ end
@@ -0,0 +1,87 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "base64"
4
+ require "json"
5
+
6
+ module Testsurfer
7
+ # Context and media emulation: Playwright's context options, done by
8
+ # the daemon (`vs_emulate`). The page side runs at each document's
9
+ # start; headers, credentials, offline and script policy are done by
10
+ # the session's proxy.
11
+ module Emulation
12
+ module_function
13
+
14
+ def geolocation(g)
15
+ h = g.to_h.transform_keys(&:to_s)
16
+ { "latitude" => h["latitude"].to_f, "longitude" => h["longitude"].to_f, "accuracy" => (h["accuracy"] || 0).to_f }
17
+ end
18
+
19
+ def headers(h)
20
+ h.to_h { |k, v| [k.to_s.downcase, v.to_s] }
21
+ end
22
+
23
+ def credentials(c)
24
+ h = c.to_h.transform_keys(&:to_s)
25
+ { "username" => h["username"].to_s, "password" => h["password"].to_s, "origin" => h["origin"] }
26
+ end
27
+ end
28
+
29
+ class BrowserContext
30
+ def emulate(cfg)
31
+ return nil if cfg.empty?
32
+
33
+ req = Wire::Request.new("vs_emulate").arg(Base64.strict_encode64(JSON.generate(cfg))).flag_value("session", session_id)
34
+ wire.call(req)
35
+ nil
36
+ end
37
+
38
+ # Fail every request, and report `navigator.onLine` false, while `offline`.
39
+ def set_offline(offline)
40
+ emulate({ "offline" => offline ? true : false })
41
+ end
42
+
43
+ # The position `navigator.geolocation` reports ({ latitude:, longitude:, accuracy: }); nil makes it unavailable.
44
+ def set_geolocation(geolocation)
45
+ emulate({ "geolocation" => geolocation && Emulation.geolocation(geolocation) })
46
+ end
47
+
48
+ # Grant permissions (`geolocation`, `notifications`, ...), as `navigator.permissions` reports them.
49
+ def grant_permissions(permissions, origin: nil) # rubocop:disable Lint/UnusedMethodArgument
50
+ all = granted.dup
51
+ Array(permissions).each { |p| all << p.to_s unless all.include?(p.to_s) }
52
+ granted.replace(all)
53
+ emulate({ "permissions" => all })
54
+ end
55
+
56
+ def clear_permissions
57
+ granted.clear
58
+ emulate({ "permissions" => [] })
59
+ end
60
+
61
+ # Headers every request of the context carries.
62
+ def set_extra_http_headers(headers)
63
+ emulate({ "extraHTTPHeaders" => Emulation.headers(headers) })
64
+ end
65
+
66
+ # Credentials for HTTP authentication ({ username:, password:, origin: }); nil stops sending them.
67
+ def set_http_credentials(credentials)
68
+ emulate({ "httpCredentials" => credentials && Emulation.credentials(credentials) })
69
+ end
70
+ end
71
+
72
+ class Page
73
+ # Emulate media features for this page (`page.emulateMedia`): media:,
74
+ # color_scheme:, reduced_motion:, forced_colors:, contrast:.
75
+ def emulate_media(media: nil, color_scheme: nil, reduced_motion: nil, forced_colors: nil, contrast: nil)
76
+ cfg = { "media" => media, "colorScheme" => color_scheme, "reducedMotion" => reduced_motion,
77
+ "forcedColors" => forced_colors, "contrast" => contrast }.compact.transform_values(&:to_s)
78
+ return nil if cfg.empty?
79
+
80
+ id = ensure_open
81
+ req = Wire::Request.new("vs_emulate").arg(Base64.strict_encode64(JSON.generate(cfg)))
82
+ .flag_value("session", session_id).flag_value("page", id)
83
+ wire.call(req)
84
+ nil
85
+ end
86
+ end
87
+ end