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,350 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+
5
+ module Testsurfer
6
+ # Locators inside the document of the iframe `owner` matches
7
+ # (Playwright's FrameLocator).
8
+ class FrameLocator
9
+ def initialize(frame)
10
+ @frame = frame
11
+ end
12
+
13
+ # The `<iframe>` locator itself.
14
+ def owner
15
+ @frame
16
+ end
17
+
18
+ def first
19
+ FrameLocator.new(@frame.first)
20
+ end
21
+
22
+ def last
23
+ FrameLocator.new(@frame.last)
24
+ end
25
+
26
+ def nth(index)
27
+ FrameLocator.new(@frame.nth(index))
28
+ end
29
+
30
+ def locator(selector, **filter)
31
+ inside.locator(selector, **filter)
32
+ end
33
+
34
+ # An iframe inside this one.
35
+ def frame_locator(selector)
36
+ FrameLocator.new(inside.locator(selector))
37
+ end
38
+
39
+ %i[get_by_role get_by_text get_by_label get_by_placeholder get_by_alt_text get_by_title get_by_test_id].each do |m|
40
+ define_method(m) { |*args, **kw| inside.public_send(m, *args, **kw) }
41
+ end
42
+
43
+ private
44
+
45
+ def inside
46
+ @frame.content_frame
47
+ end
48
+ end
49
+
50
+ # One frame of a page: the main frame or an iframe.
51
+ class Frame
52
+ attr_reader :page, :element, :parent_id, :name, :url
53
+
54
+ def initialize(page, element: nil, parent: nil, name: "", url: "", cross_origin: false)
55
+ @page = page
56
+ @element = element
57
+ @parent_id = parent
58
+ @name = name
59
+ @url = url
60
+ @cross_origin = cross_origin
61
+ end
62
+
63
+ def main?
64
+ @element.nil?
65
+ end
66
+ alias is_main main?
67
+
68
+ def inspect
69
+ "#<Testsurfer::Frame #{url}>"
70
+ end
71
+
72
+ # Locators in this frame.
73
+ def locator(selector, **filter)
74
+ return page.locator(selector, **filter) if main?
75
+
76
+ Locator.new(page, Chain.new([Step.new(Query.new(:handle, id: @element)), Step.new(Query.new(:frame))]))
77
+ .locator(selector, **filter)
78
+ end
79
+
80
+ # The `<iframe>` element of this frame, as a locator (nil for the main frame).
81
+ def frame_element
82
+ main? ? nil : Locator.new(page, Chain.new([Step.new(Query.new(:handle, id: @element))]))
83
+ end
84
+
85
+ # Run `expression` (or a function source called with `arg`) in this frame.
86
+ def evaluate(expression, arg: nil)
87
+ return page.evaluate(expression, arg: arg) if main?
88
+
89
+ enc = JSON.generate(Serialize.encode(arg))
90
+ if @cross_origin
91
+ page.engine_call("(function(){var v=(#{expression});return typeof v==='function'?v(E.des(#{enc})):v;})()", @url)
92
+ else
93
+ page.engine_call("(function(){var w=E.h(#{@element}).contentWindow;var v=w.eval(#{Serialize.js_string("(#{expression})")});" \
94
+ "return typeof v==='function'?v(E.des(#{enc})):v;})()")
95
+ end
96
+ end
97
+
98
+ # The frame this one sits in, from a frame listing.
99
+ def parent_frame(frames = page.frames)
100
+ return nil if main?
101
+ return frames.find(&:main?) if @parent_id.nil?
102
+
103
+ frames.find { |f| f.element == @parent_id }
104
+ end
105
+ end
106
+
107
+ class Page
108
+ # Locators inside the iframe `selector` matches.
109
+ def frame_locator(selector)
110
+ FrameLocator.new(locator(selector))
111
+ end
112
+
113
+ # The main frame and every iframe, depth first.
114
+ def frames
115
+ out = [main_frame]
116
+ rows = engine_call("E.frames()")
117
+ (rows || []).each do |row|
118
+ next unless row[0].is_a?(Integer)
119
+
120
+ out << Frame.new(self, element: row[0], parent: row[1].is_a?(Integer) ? row[1] : nil, name: row[2].to_s,
121
+ url: row[3].to_s, cross_origin: row[4] == 1)
122
+ end
123
+ out
124
+ end
125
+
126
+ # The frame with this name or URL (a string, glob or pattern).
127
+ def frame(name: nil, url: nil)
128
+ matcher = url && UrlMatcher.new(url) { |s| resolve_url(s) }
129
+ frames.find { |f| (name.nil? || f.name == name) && (matcher.nil? || matcher.match?(f.url)) }
130
+ end
131
+
132
+ # The main frame.
133
+ def main_frame
134
+ Frame.new(self, url: self.url)
135
+ end
136
+
137
+ # Wait until the page has loaded. `goto` already waits; this is for
138
+ # a page that navigated by itself.
139
+ def wait_for_load_state(state = nil, timeout: nil) # rubocop:disable Lint/UnusedMethodArgument
140
+ wait_for_function("document.readyState === 'complete'", timeout: timeout || timeouts.navigation)
141
+ nil
142
+ end
143
+ end
144
+
145
+ # A page value held by the test (Playwright's JSHandle). Pass it in an
146
+ # `evaluate` argument to hand the value back to the page.
147
+ class JSHandle
148
+ attr_reader :page, :id, :preview
149
+
150
+ def initialize(page, id, preview = "")
151
+ @page = page
152
+ @id = id
153
+ @preview = preview
154
+ end
155
+
156
+ # The handle the expression's value (awaited) gets.
157
+ def self.adopt(page, expr)
158
+ v = page.engine_call("E.adoptValue(#{expr})")
159
+ raise UsageError, "evaluateHandle: unexpected reply #{v.inspect}" unless v.is_a?(Hash) && v["id"].is_a?(Integer)
160
+
161
+ new(page, v["id"], v["p"].to_s)
162
+ end
163
+
164
+ def inspect
165
+ "JSHandle@#{preview}"
166
+ end
167
+ alias to_s inspect
168
+
169
+ # Call `function(value, arg)` in the page and return its result.
170
+ def evaluate(function, arg: nil)
171
+ page.engine_call(call(function, arg))
172
+ end
173
+
174
+ # Like `evaluate`, keeping the result in the page.
175
+ def evaluate_handle(function, arg: nil)
176
+ JSHandle.adopt(page, call(function, arg))
177
+ end
178
+
179
+ # The value, serialized back.
180
+ def json_value
181
+ page.engine_call("E.h(#{id})")
182
+ end
183
+
184
+ # A handle to one property of the value.
185
+ def get_property(name)
186
+ JSHandle.adopt(page, "(function(v){return v==null?undefined:v[#{Serialize.js_string(name)}];})(E.h(#{id}))")
187
+ end
188
+
189
+ # The value's own properties, as handles by name.
190
+ def get_properties
191
+ rows = page.engine_call("E.props(#{id})") || []
192
+ rows.to_h { |k, hid, _| [k, JSHandle.new(page, hid, k)] }
193
+ end
194
+
195
+ # The element this handle holds, as a locator.
196
+ def as_locator
197
+ Locator.new(page, Chain.new([Step.new(Query.new(:handle, id: id))]))
198
+ end
199
+
200
+ # This value as an `evaluate` argument (a JSHandle works directly too).
201
+ def as_arg
202
+ { Serialize::HANDLE_KEY => id }
203
+ end
204
+
205
+ # Let the page forget the value.
206
+ def dispose
207
+ page.engine_call("E.drop(#{id})")
208
+ nil
209
+ rescue Error
210
+ nil
211
+ end
212
+
213
+ private
214
+
215
+ def call(function, arg)
216
+ "(#{function})(E.h(#{id}),E.des(#{JSON.generate(Serialize.encode(arg))}))"
217
+ end
218
+ end
219
+
220
+ class Page
221
+ # Like `evaluate`, but keeps the result in the page and returns a handle to it.
222
+ def evaluate_handle(expression, arg: nil)
223
+ body = "(function(){var v=(#{expression});return typeof v==='function'?v(E.des(#{JSON.generate(Serialize.encode(arg))})):v;})()"
224
+ JSHandle.adopt(self, body)
225
+ end
226
+ end
227
+
228
+ # History moves and URL waits for a page.
229
+ module Navigation
230
+ # How long `go_back` / `go_forward` wait for the URL to change before
231
+ # taking the move for a no-op (nothing in history).
232
+ HISTORY_SETTLE = 2.0
233
+ URL_POLL = 0.05
234
+
235
+ module_function
236
+
237
+ # A Playwright URL glob as a regular expression source:
238
+ # `**` any characters, `*` any but `/`, `{a,b}` alternatives.
239
+ def glob_to_regex(glob)
240
+ out = +"^"
241
+ chars = glob.chars
242
+ in_group = false
243
+ i = 0
244
+ while i < chars.length
245
+ c = chars[i]
246
+ if c == "\\" && i + 1 < chars.length
247
+ # A backslash makes the next character literal.
248
+ i += 1
249
+ nxt = chars[i]
250
+ out << "\\" if "\\^$.|?+()[]{}*".include?(nxt)
251
+ out << nxt
252
+ elsif c == "*" && chars[i + 1] == "*"
253
+ out << ".*"
254
+ i += 1
255
+ # `**/` also matches nothing, so `**/api` matches `/api`.
256
+ if chars[i + 1] == "/"
257
+ out << "/?"
258
+ i += 1
259
+ end
260
+ elsif c == "*"
261
+ out << "[^/]*"
262
+ elsif c == "{"
263
+ in_group = true
264
+ out << "("
265
+ elsif c == "}" && in_group
266
+ in_group = false
267
+ out << ")"
268
+ elsif c == "," && in_group
269
+ out << "|"
270
+ elsif "\\^$.|?+()[]".include?(c)
271
+ out << "\\" << c
272
+ else
273
+ out << c
274
+ end
275
+ i += 1
276
+ end
277
+ out << "$"
278
+ end
279
+
280
+ # A URL matcher as a JavaScript test of `u`: an exact URL, a glob
281
+ # (resolved against the base URL when relative), or a pattern.
282
+ def url_test_js(page, matcher)
283
+ if TextMatch.regex?(matcher)
284
+ s, f = TextMatch.parts(matcher)
285
+ return "new RegExp(#{JSON.generate(s)}, #{JSON.generate(f)}).test(u)"
286
+ end
287
+
288
+ pattern = matcher.start_with?("*") || matcher.include?("://") ? matcher : page.resolve_url(matcher)
289
+ return "new RegExp(#{JSON.generate(glob_to_regex(pattern))}).test(u)" if pattern.match?(/[*{]/)
290
+
291
+ "u === #{JSON.generate(pattern)}"
292
+ end
293
+ end
294
+
295
+ class Page
296
+ # Wait until the URL matches (an exact URL, a `**` glob, or a pattern).
297
+ def wait_for_url(url, timeout: nil, wait_until: nil) # rubocop:disable Lint/UnusedMethodArgument
298
+ matcher = TextMatch.check!(url)
299
+ budget = timeout || timeouts.navigation
300
+ deadline = Testsurfer.now + budget / 1000.0
301
+ script = "(function(){var u=location.href;return [u, #{Navigation.url_test_js(self, matcher)}];})()"
302
+ now = ""
303
+ loop do
304
+ begin
305
+ u, hit = evaluate(script)
306
+ return nil if hit
307
+
308
+ now = u
309
+ rescue Error
310
+ nil
311
+ end
312
+ raise TimeoutError, "page.waitForURL: Timeout #{budget}ms exceeded; URL is #{now}" if Testsurfer.now >= deadline
313
+
314
+ sleep Navigation::URL_POLL
315
+ end
316
+ end
317
+
318
+ # History back; returns once the URL changed (or at once when there is no history).
319
+ def go_back(**)
320
+ history_move(-1)
321
+ end
322
+
323
+ def go_forward(**)
324
+ history_move(1)
325
+ end
326
+
327
+ # Load the current URL again.
328
+ def reload(**)
329
+ here = evaluate("location.href")
330
+ goto(here)
331
+ end
332
+
333
+ private
334
+
335
+ def history_move(delta)
336
+ before = evaluate("location.href")
337
+ evaluate("(history.go(#{delta}), 'ok')")
338
+ deadline = Testsurfer.now + Navigation::HISTORY_SETTLE
339
+ while Testsurfer.now < deadline
340
+ sleep Navigation::URL_POLL
341
+ begin
342
+ break if evaluate("location.href") != before
343
+ rescue Error
344
+ nil
345
+ end
346
+ end
347
+ nil
348
+ end
349
+ end
350
+ end
@@ -0,0 +1,367 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "base64"
4
+ require "json"
5
+
6
+ module Testsurfer
7
+ # A WebSocket message: text, or binary (`binary?`).
8
+ class WsPayload
9
+ attr_reader :data
10
+
11
+ def initialize(data, binary: false)
12
+ @data = data
13
+ @binary = binary
14
+ end
15
+
16
+ def self.from_wire(d)
17
+ return new("") unless d.is_a?(Hash)
18
+ return new(Base64.decode64(d["b"]), binary: true) if d["b"].is_a?(String)
19
+
20
+ new(d["s"].to_s)
21
+ end
22
+
23
+ def self.of(m)
24
+ m.is_a?(WsPayload) ? m : new(m.to_s)
25
+ end
26
+
27
+ def binary?
28
+ @binary
29
+ end
30
+
31
+ def wire
32
+ @binary ? { "b" => Base64.strict_encode64(@data) } : { "s" => @data }
33
+ end
34
+
35
+ # The text of a text message (a binary one as UTF-8).
36
+ def text
37
+ @binary ? @data.dup.force_encoding(Encoding::UTF_8).scrub : @data
38
+ end
39
+ alias to_s text
40
+
41
+ def ==(other)
42
+ other = WsPayload.new(other) if other.is_a?(String)
43
+ other.is_a?(WsPayload) && other.data == data && other.binary? == binary?
44
+ end
45
+ end
46
+
47
+ # A WebSocket the page opened (Playwright's `page.on("websocket")`).
48
+ # Its events are kept, so a wait never misses one that came first.
49
+ class WebSocket
50
+ attr_reader :url
51
+
52
+ def initialize(url)
53
+ @url = url
54
+ @history = [] # [kind, payload]
55
+ @closed = false
56
+ @lock = Mutex.new
57
+ @cond = ConditionVariable.new
58
+ end
59
+
60
+ def push(kind, payload = nil)
61
+ @lock.synchronize do
62
+ return if kind == :close && @closed
63
+
64
+ @closed = true if kind == :close
65
+ @history << [kind, payload]
66
+ @cond.broadcast
67
+ end
68
+ end
69
+
70
+ def closed?
71
+ @lock.synchronize { @closed }
72
+ end
73
+ alias is_closed closed?
74
+
75
+ # The first event (`[kind, payload]`, kind one of :framesent,
76
+ # :framereceived, :close, :socketerror) the block accepts.
77
+ def wait_for_event(timeout: 30_000, &test)
78
+ deadline = Testsurfer.now + timeout / 1000.0
79
+ @lock.synchronize do
80
+ loop do
81
+ hit = @history.find { |e| test.call(*e) }
82
+ return hit if hit
83
+
84
+ left = deadline - Testsurfer.now
85
+ raise TimeoutError, "webSocket.waitForEvent: Timeout #{timeout}ms exceeded" if left <= 0
86
+
87
+ @cond.wait(@lock, left)
88
+ end
89
+ end
90
+ end
91
+
92
+ # The first frame the page sent.
93
+ def wait_for_frame_sent(timeout: 30_000)
94
+ wait_for_event(timeout: timeout) { |k, _| k == :framesent }[1]
95
+ end
96
+
97
+ # The first frame the page received.
98
+ def wait_for_frame_received(timeout: 30_000)
99
+ wait_for_event(timeout: timeout) { |k, _| k == :framereceived }[1]
100
+ end
101
+
102
+ def inspect
103
+ "#<Testsurfer::WebSocket #{url}>"
104
+ end
105
+ end
106
+
107
+ # A socket the page opened that a `route_web_socket` handler answers.
108
+ # The page side talks to the page; `connect_to_server` gives the side
109
+ # that talks to the real server.
110
+ class WebSocketRoute
111
+ attr_reader :url
112
+
113
+ def initialize(page, id, url, server_side)
114
+ @page = page
115
+ @id = id
116
+ @url = url
117
+ @server_side = server_side
118
+ @on_message = nil
119
+ @on_close = nil
120
+ @server = nil
121
+ @lock = Mutex.new
122
+ end
123
+
124
+ # Send to the page (page side) or to the server (server side).
125
+ def send(message)
126
+ m = WsPayload.of(message)
127
+ @page.socket(@id)&.push(:framereceived, m) unless @server_side
128
+ @page.ws_call(@server_side ? "wsServerSend" : "wsDeliver", [@id, m.wire])
129
+ end
130
+
131
+ # Close the page's socket (page side) or the server's (server side).
132
+ def close(code: nil, reason: nil)
133
+ @page.ws_call(@server_side ? "wsServerClose" : "wsCloseFake", [@id, code || 1000, reason || ""])
134
+ end
135
+
136
+ # Handle each message (a WsPayload) instead of passing it on.
137
+ def on_message(&handler)
138
+ @lock.synchronize { @on_message = handler }
139
+ end
140
+
141
+ # Handle the close (code, reason) instead of passing it on.
142
+ def on_close(&handler)
143
+ @lock.synchronize { @on_close = handler }
144
+ end
145
+
146
+ # Connect to the real server; messages flow through unless a handler takes them.
147
+ def connect_to_server
148
+ raise UsageError, "connectToServer must be called on the page side" if @server_side
149
+
150
+ s = nil
151
+ created = @lock.synchronize do
152
+ next false if @server
153
+
154
+ @server = WebSocketRoute.new(@page, @id, @url, true)
155
+ true
156
+ end
157
+ s = @lock.synchronize { @server }
158
+ Testsurfer.spawn { @page.ws_call("wsConnect", [@id]) } if created
159
+ s
160
+ end
161
+
162
+ def server
163
+ @lock.synchronize { @server }
164
+ end
165
+
166
+ def message_handler
167
+ @lock.synchronize { @on_message }
168
+ end
169
+
170
+ def close_handler
171
+ @lock.synchronize { @on_close }
172
+ end
173
+
174
+ def on_page_message(m)
175
+ if (h = message_handler)
176
+ h.call(m)
177
+ elsif (s = server)
178
+ s.send(m)
179
+ end
180
+ end
181
+
182
+ def on_server_message(m)
183
+ h = server&.message_handler
184
+ h ? h.call(m) : send(m)
185
+ end
186
+
187
+ def page_closed(code, reason)
188
+ if (h = close_handler)
189
+ h.call(code, reason)
190
+ elsif (s = server)
191
+ s.close(code: code, reason: reason)
192
+ end
193
+ @page.ws_call("wsCloseFake", [@id, code || 1000, reason || ""])
194
+ end
195
+
196
+ def server_closed(code, reason)
197
+ h = server&.close_handler
198
+ h ? h.call(code, reason) : close(code: code, reason: reason)
199
+ end
200
+ end
201
+
202
+ # A dedicated worker the page started.
203
+ class Worker
204
+ attr_reader :url, :id, :page
205
+
206
+ def initialize(page, id, url)
207
+ @page = page
208
+ @id = id
209
+ @url = url
210
+ end
211
+
212
+ # Run `function` (or an expression) in the worker and return its result.
213
+ def evaluate(function, arg: nil)
214
+ src = Worker.function?(function) ? function : "() => (#{function})"
215
+ @page.evaluate("([id, fn, arg]) => window.__ts.workerEval(id, fn, arg)", arg: [@id, src, arg])
216
+ end
217
+
218
+ def ==(other)
219
+ other.is_a?(Worker) && other.id == id && other.page.equal?(page)
220
+ end
221
+
222
+ # Whether `src` is a function (`function ...`, `(a) => ...`, `a => ...`,
223
+ # any of them `async`), not an expression.
224
+ def self.function?(src)
225
+ s = src.lstrip
226
+ s = s.delete_prefix("async").lstrip if s.start_with?("async")
227
+ return true if s.start_with?("(", "function")
228
+
229
+ m = s.match(/\A[\p{Alnum}_$]+/)
230
+ !m.nil? && s[m[0].length..].lstrip.start_with?("=>")
231
+ end
232
+
233
+ def inspect
234
+ "#<Testsurfer::Worker #{url}>"
235
+ end
236
+ end
237
+
238
+ # A file input the page tried to open (Playwright's `filechooser`).
239
+ class FileChooser
240
+ attr_reader :page
241
+
242
+ def initialize(page, id, multiple)
243
+ @page = page
244
+ @id = id
245
+ @multiple = multiple
246
+ end
247
+
248
+ def multiple?
249
+ @multiple
250
+ end
251
+ alias is_multiple multiple?
252
+
253
+ # Put `files` in the input, as a user picking them would (see Locator#set_input_files).
254
+ def set_files(files)
255
+ list = InputFiles.read(files, "fileChooser.setFiles").map { |f| { "name" => f[:name], "type" => f[:given_mime] || "", "b64" => f[:b64] } }
256
+ @page.evaluate(<<~JS, arg: [@id, list])
257
+ ([id, files]) => {
258
+ const input = window.__ts.fcEls[id];
259
+ const dt = new DataTransfer();
260
+ for (const f of files) {
261
+ const bin = atob(f.b64), u = new Uint8Array(bin.length);
262
+ for (let i = 0; i < bin.length; i++) u[i] = bin.charCodeAt(i);
263
+ dt.items.add(new File([u], f.name, { type: f.type }));
264
+ }
265
+ input.files = dt.files;
266
+ input.dispatchEvent(new Event('input', { bubbles: true, composed: true }));
267
+ input.dispatchEvent(new Event('change', { bubbles: true }));
268
+ return null;
269
+ }
270
+ JS
271
+ nil
272
+ end
273
+ end
274
+
275
+ # A page's sockets, socket routes and workers, and the shim rows that feed them.
276
+ module Hooks
277
+ module_function
278
+
279
+ # A shim row for sockets, workers or file choosers. Returns false for other rows.
280
+ def hook_event(page, e)
281
+ t = e["t"].to_s
282
+ id = e["id"].is_a?(Integer) ? e["id"] : 0
283
+ return socket_event(page, t, id, e) if t.start_with?("ws")
284
+
285
+ state = page.events
286
+ case t
287
+ when "worker"
288
+ w = Worker.new(page, id, e["url"].to_s)
289
+ page.hooks_sync { page.hook_state[:workers][id] = w }
290
+ state.deliver(Event.new("worker", w))
291
+ when "workerClose"
292
+ page.hooks_sync { page.hook_state[:workers].delete(id) }
293
+ when "filechooser"
294
+ state.deliver(Event.new("filechooser", FileChooser.new(page, id, e["multiple"] == true)))
295
+ else
296
+ return false
297
+ end
298
+ true
299
+ end
300
+
301
+ def socket_event(page, t, id, e)
302
+ d = -> { WsPayload.from_wire(e["d"]) }
303
+ code = e["code"].is_a?(Integer) ? e["code"] : nil
304
+ reason = e["reason"].is_a?(String) ? e["reason"] : nil
305
+ case t
306
+ when "ws"
307
+ ws = WebSocket.new(e["url"].to_s)
308
+ page.hooks_sync { page.hook_state[:sockets][id] = ws }
309
+ page.events.deliver(Event.new("websocket", ws))
310
+ when "wsSent" then page.socket(id)&.push(:framesent, d.call)
311
+ when "wsRecv" then page.socket(id)&.push(:framereceived, d.call)
312
+ when "wsClose", "wsError"
313
+ if (ws = page.socket(id))
314
+ ws.push(:socketerror) if t == "wsError"
315
+ ws.push(:close)
316
+ end
317
+ when "wsRouted" then routed_socket(page, id, e["url"].to_s)
318
+ when "wsPageSend"
319
+ page.socket(id)&.push(:framesent, d.call)
320
+ if (r = page.routed(id))
321
+ m = d.call
322
+ Testsurfer.spawn { r.on_page_message(m) }
323
+ end
324
+ when "wsPageClose"
325
+ if (r = page.routed(id))
326
+ Testsurfer.spawn { r.page_closed(code, reason) }
327
+ end
328
+ page.socket(id)&.push(:close)
329
+ when "wsServerMsg"
330
+ if (r = page.routed(id))
331
+ m = d.call
332
+ Testsurfer.spawn { r.on_server_message(m) }
333
+ end
334
+ when "wsServerClose"
335
+ if (r = page.routed(id))
336
+ Testsurfer.spawn { r.server_closed(code, reason) }
337
+ end
338
+ when "wsServerOpen", "wsServerError" then nil
339
+ else return false
340
+ end
341
+ true
342
+ end
343
+
344
+ # A socket the page opened while routing is on: kept, delivered, then
345
+ # handed to the first route matching `url`, or connected to the server.
346
+ def routed_socket(page, id, url)
347
+ route = WebSocketRoute.new(page, id, url, false)
348
+ ws = WebSocket.new(url)
349
+ handler = page.hooks_sync do
350
+ h = page.hook_state
351
+ h[:sockets][id] = ws
352
+ h[:routed][id] = route
353
+ found = h[:routes].find { |m, _| m.match?(url) }
354
+ found && found[1]
355
+ end
356
+ page.events.deliver(Event.new("websocket", ws))
357
+ Testsurfer.spawn do
358
+ page.ws_call("wsOpen", [id])
359
+ if handler
360
+ handler.call(route)
361
+ else
362
+ route.connect_to_server
363
+ end
364
+ end
365
+ end
366
+ end
367
+ end