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,655 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "monitor"
5
+
6
+ module Testsurfer
7
+ # One page (a web view) in a context.
8
+ class Page
9
+ # How long `goto` waits for the stream reader to hand over the document's response.
10
+ NAV_RESPONSE_GRACE = 1.0
11
+ # The longest single `vs_locate` wait; longer ones are several, so each
12
+ # stays inside the wire's request timeout.
13
+ LOCATE_CHUNK_MS = 30_000
14
+
15
+ attr_reader :context, :wire, :session_id, :events, :input_mode, :base_url, :hook_state
16
+ attr_accessor :opener
17
+
18
+ def initialize(context, page_id: nil, url: "about:blank")
19
+ browser = context.browser
20
+ o = browser.options
21
+ @context = context
22
+ @wire = browser.wire
23
+ @session_id = context.session_id
24
+ @timeouts = o.timeouts.dup
25
+ @input_mode = o.input_mode
26
+ @base_url = context.base_url
27
+ @test_id_attribute = o.test_id_attribute || "data-testid"
28
+ @viewport = context.viewport_override || o.viewport
29
+ @dpr = o.device_scale_factor
30
+ @page_id = page_id
31
+ @open_lock = Monitor.new
32
+ @state_lock = Mutex.new
33
+ @token = +""
34
+ @last_href = url
35
+ @closed = false
36
+ @pointer = { at: [0.0, 0.0], pressed_at: nil }
37
+ @events = EventState.new
38
+ @opener = nil
39
+ @init_scripts = []
40
+ @hook_state = { sockets: {}, routed: {}, routes: [], workers: {} }
41
+ @hooks_lock = Monitor.new
42
+ @recorder = nil
43
+ end
44
+
45
+ # A page the daemon opened on its own (a popup), already at `url`.
46
+ def self.adopt(context, page_id, url)
47
+ page = new(context, page_id: page_id, url: url)
48
+ context.hub.register(page_id, page)
49
+ page
50
+ end
51
+
52
+ def inspect
53
+ "#<Testsurfer::Page #{url}>"
54
+ end
55
+
56
+ # --- internals shared with the other files --------------------------
57
+
58
+ def timeouts
59
+ @state_lock.synchronize { @timeouts.dup }
60
+ end
61
+
62
+ def test_id_attribute
63
+ @state_lock.synchronize { @test_id_attribute }
64
+ end
65
+
66
+ def note_location(href)
67
+ @state_lock.synchronize { @last_href = href.to_s }
68
+ end
69
+
70
+ def token
71
+ @state_lock.synchronize { @token.dup }
72
+ end
73
+
74
+ def set_token(t)
75
+ @state_lock.synchronize { @token = t.to_s }
76
+ end
77
+
78
+ def pointer
79
+ @state_lock.synchronize { @pointer.dup }
80
+ end
81
+
82
+ def update_pointer
83
+ @state_lock.synchronize { yield @pointer }
84
+ end
85
+
86
+ def hooks_sync(&blk)
87
+ @hooks_lock.synchronize(&blk)
88
+ end
89
+
90
+ def socket(id)
91
+ hooks_sync { @hook_state[:sockets][id] }
92
+ end
93
+
94
+ def routed(id)
95
+ hooks_sync { @hook_state[:routed][id] }
96
+ end
97
+
98
+ def worker(id)
99
+ hooks_sync { @hook_state[:workers][id] }
100
+ end
101
+
102
+ # The page's running workers.
103
+ def workers
104
+ hooks_sync { @hook_state[:workers].values }
105
+ end
106
+
107
+ def ws_call(f, args)
108
+ evaluate("(a) => { if (window.__ts && window.__ts.#{f}) window.__ts.#{f}(...a); return null; }", arg: args)
109
+ nil
110
+ end
111
+
112
+ # The page id once the web view is open, else nil.
113
+ def page_id
114
+ @open_lock.synchronize { @page_id }
115
+ end
116
+
117
+ # The page id, opening a blank web view if the page has none yet.
118
+ def ensure_open
119
+ @open_lock.synchronize do
120
+ return @page_id if @page_id
121
+ raise UsageError, "Target page, context or browser has been closed" if closed?
122
+
123
+ @page_id = open_view("about:blank")
124
+ end
125
+ end
126
+
127
+ # The context's init scripts, then this page's.
128
+ def all_init_scripts
129
+ @context.init_scripts + @state_lock.synchronize { @init_scripts.dup }
130
+ end
131
+
132
+ # Open a web view at `url`, sized to the page's viewport. Init
133
+ # scripts must be in place before the first document, so a page
134
+ # with any opens blank, installs them, then loads.
135
+ def open_view(url)
136
+ scripts = all_init_scripts
137
+ first = scripts.empty? ? url : "about:blank"
138
+ resp = @wire.call(Wire::Request.new("vs_open").arg(first).flag_value("session", @session_id))
139
+ id = resp.body.first
140
+ raise ProtocolError, "vs_open returned no page id for #{url}" if id.nil?
141
+
142
+ set_token(resp.token)
143
+ @context.hub.register(id, self)
144
+ apply_viewport(id)
145
+ begin_video(id, @context.record_video) if @context.record_video
146
+ scripts.each do |s|
147
+ @wire.call(Wire::Request.new("vs_init_script").arg(id).arg(s).flag_value("session", @session_id))
148
+ end
149
+ if first != url
150
+ nav = @wire.call(Wire::Request.new("vs_goto").arg(id).arg(url).flag_value("session", @session_id))
151
+ set_token(nav.token)
152
+ end
153
+ note_location(url)
154
+ id
155
+ end
156
+
157
+ def apply_viewport(id)
158
+ size = @state_lock.synchronize { @viewport }
159
+ return unless size
160
+
161
+ req = Wire::Request.new("vs_viewport").arg(id).arg("#{size[0]}x#{size[1]}")
162
+ .flag_value("session", @session_id).flag_value("dpr", Testsurfer.fmt_num(@dpr.to_f))
163
+ @wire.call(req)
164
+ end
165
+
166
+ # Run `body` (an expression that may use the engine as `E`) in the
167
+ # page, or the subframe with URL `frame`; its value, decoded.
168
+ def engine_call(body, frame = nil)
169
+ id = ensure_open
170
+ req = Wire::Request.new("vs_engine").arg(id).arg(body).flag_value("session", @session_id)
171
+ req.flag_value("frame", frame) if frame
172
+ resp = @wire.call(req)
173
+ line = resp.result_line
174
+ raise ProtocolError, "vs_engine sent no result" if line.nil?
175
+
176
+ r = Page.parse_json(line)
177
+ raise Page.gone if r.nil? || (r.is_a?(Hash) && r["gone"] == true)
178
+
179
+ note_location(r["u"]) if frame.nil? && r["u"].is_a?(String)
180
+ raise Page.page_error(r["e"]) if r.key?("e")
181
+
182
+ Serialize.decode(r["v"])
183
+ end
184
+
185
+ # One locator request: { steps:, op:, args:, many:, first: }. With
186
+ # `wait`, the daemon retries until the element is ready. Returns the
187
+ # reply hash ("k", "v", "n", "why", "strict", "sample", ...).
188
+ def locate(req, wait: false, timeout: 0, func: nil, handlers: [], click: nil)
189
+ id = ensure_open
190
+ deadline = timeout.to_i.zero? ? nil : Testsurfer.now + timeout / 1000.0
191
+ loop do
192
+ chunk = if deadline
193
+ ((deadline - Testsurfer.now) * 1000).round.clamp(1, LOCATE_CHUNK_MS)
194
+ else
195
+ LOCATE_CHUNK_MS
196
+ end
197
+ body = { "steps" => req[:steps], "op" => req[:op], "args" => req[:args], "wait" => wait }
198
+ body["many"] = true if req[:many]
199
+ body["first"] = true if req[:first]
200
+ body["fn"] = func if func
201
+ body["handlers"] = handlers unless handlers.empty?
202
+ body["click"] = click if click
203
+ call = Wire::Request.new("vs_locate").arg(id).arg(JSON.generate(body))
204
+ .flag_value("session", @session_id).flag_value("timeout", wait ? chunk : 0)
205
+ resp = @wire.call(call)
206
+ line = resp.result_line
207
+ raise ProtocolError, "vs_locate sent no result" if line.nil?
208
+
209
+ r = Page.parse_json(line)
210
+ raise ProtocolError, "vs_locate sent #{line}" unless r.is_a?(Hash)
211
+ raise Page.gone if r["gone"]
212
+
213
+ note_location(r["u"]) if r["u"].is_a?(String)
214
+ raise Page.page_error(r["e"]) if r["e"]
215
+
216
+ r["v"] = Serialize.decode(r["v"])
217
+ r["sample"] = Serialize.decode(r["sample"])
218
+ unless r["clicks"].nil?
219
+ r["token"] = resp.token
220
+ r["change"] = resp.after_result
221
+ end
222
+ # A chunk of a longer wait ran out: wait on.
223
+ next if r["timeout"] && (deadline.nil? || Testsurfer.now < deadline)
224
+
225
+ return r
226
+ end
227
+ end
228
+
229
+ # A locator request the daemon waits on until the element is ready,
230
+ # more than one matches, or `timeout` (ms) runs out.
231
+ def locate_waiting(req, timeout, func: nil, click: nil)
232
+ r = locate(req, wait: true, timeout: timeout, func: func, click: click)
233
+ set_token(r["token"]) if !r["clicks"].nil? && !r["token"].to_s.empty?
234
+ r
235
+ end
236
+
237
+ def self.parse_json(line)
238
+ JSON.parse(line)
239
+ rescue JSON::ParserError => e
240
+ raise ProtocolError, "vibesurfer sent a reply testsurfer cannot read: #{e.message}"
241
+ end
242
+
243
+ def self.gone
244
+ ContextDestroyedError.new("Execution context was destroyed, most likely because of a navigation")
245
+ end
246
+
247
+ # A page error as Playwright prints one: `TypeError: Load failed`.
248
+ def self.page_error(e)
249
+ e = {} unless e.is_a?(Hash)
250
+ n = e["name"]
251
+ msg = n && n != "Error" && !n.empty? ? "#{n}: #{e['message']}" : e["message"].to_s
252
+ JavaScriptError.new(msg)
253
+ end
254
+
255
+ # The page closed itself (`window.close()`).
256
+ def mark_closed
257
+ @state_lock.synchronize { @closed = true }
258
+ end
259
+
260
+ # Whether `e` came from a popup closing itself under the call: the
261
+ # daemon no longer knows the page, and its close event arrives within a second.
262
+ def closed_by_itself?(e)
263
+ return false unless Testsurfer.daemon_code(e) == "NOT_FOUND" && e.message.include?("page=") && opener
264
+
265
+ deadline = Testsurfer.now + 1
266
+ sleep 0.02 while !closed? && Testsurfer.now < deadline
267
+ closed?
268
+ end
269
+
270
+ # --- public API ----------------------------------------------------
271
+
272
+ # Install `source` as a document-start script, if the page has a web view.
273
+ def install_init_script(source)
274
+ id = page_id
275
+ @wire.call(Wire::Request.new("vs_init_script").arg(id).arg(source).flag_value("session", @session_id)) if id
276
+ nil
277
+ end
278
+
279
+ # A script the page runs at the start of each later document, before its own scripts.
280
+ def add_init_script(script = nil, path: nil)
281
+ source = path ? File.read(path) : script.to_s
282
+ @state_lock.synchronize { @init_scripts << source }
283
+ install_init_script(source)
284
+ end
285
+
286
+ # Whether two objects are the same page.
287
+ def same?(other)
288
+ equal?(other)
289
+ end
290
+
291
+ # `url` against the base URL, when there is one and it is relative.
292
+ def resolve_url(url)
293
+ Testsurfer.resolve_against(@base_url, url)
294
+ end
295
+
296
+ # Navigate to `url` (relative to the base URL when one is set) and
297
+ # wait for it to load. Returns the main document's Response, after
298
+ # redirects, in a context with events; nil otherwise.
299
+ def goto(url, timeout: nil, wait_until: nil) # rubocop:disable Lint/UnusedMethodArgument
300
+ url = resolve_url(url.to_s)
301
+ events_on = @context.events?
302
+ hub = @context.hub
303
+ # Only the fragment changes: a same-document navigation, which has
304
+ # no load for the daemon to wait on (and no response, as in Playwright).
305
+ if page_id && url.include?("#")
306
+ here = evaluate("location.href")
307
+ if here.is_a?(String) && here.split("#", 2)[0] == url.split("#", 2)[0]
308
+ evaluate("(u) => { location.href = u; return null; }", arg: url)
309
+ note_location(url)
310
+ return nil
311
+ end
312
+ end
313
+ id = @open_lock.synchronize do
314
+ raise UsageError, "page.goto: Target page, context or browser has been closed" if closed?
315
+
316
+ # With events, the page joins the hub before its document's request, so open blank first.
317
+ if @page_id.nil? && events_on
318
+ @page_id = open_view("about:blank")
319
+ # Routes and extra headers set before the page existed hold requests now.
320
+ hub.sync_routing(@wire, @session_id)
321
+ end
322
+ if @page_id
323
+ hub.forget_last_nav(@page_id)
324
+ req = Wire::Request.new("vs_goto").arg(@page_id).arg(url).flag_value("session", @session_id)
325
+ resp = navigation_call(url) { @wire.call(req) }
326
+ set_token(resp.token)
327
+ note_location(url)
328
+ @page_id
329
+ else
330
+ @page_id = navigation_call(url) { open_view(url) }
331
+ end
332
+ end
333
+ # The engine reports the URL as loaded, which a redirect changes.
334
+ begin
335
+ href = engine_call("location.href")
336
+ note_location(href) if href.is_a?(String)
337
+ rescue Error
338
+ nil
339
+ end
340
+ return nil if !events_on || url.start_with?("about:", "data:")
341
+
342
+ # The response line is on the stream before the load ends; the
343
+ # reader may not have handed it over yet.
344
+ deadline = Testsurfer.now + NAV_RESPONSE_GRACE
345
+ loop do
346
+ r = hub.get_last_nav(id)
347
+ return r if r
348
+ return nil if Testsurfer.now >= deadline
349
+
350
+ sleep 0.005
351
+ end
352
+ end
353
+
354
+ # Headers every later request of the page carries.
355
+ def set_extra_http_headers(headers)
356
+ @events.extra_headers = headers.to_h { |k, v| [k.to_s.downcase, v.to_s] }
357
+ @context.hub.sync_routing(@wire, @session_id)
358
+ end
359
+
360
+ # The page's URL as of the last call into it (actions, reads and
361
+ # navigations all refresh it), as Playwright's `page.url`.
362
+ def url
363
+ href = @state_lock.synchronize { @last_href.dup }
364
+ # WebKit percent-encodes data: URLs; show them as written.
365
+ return Testsurfer.percent_decode(href) if href.start_with?("data:")
366
+
367
+ href
368
+ end
369
+
370
+ def title
371
+ evaluate("document.title")
372
+ end
373
+
374
+ # The document's HTML, doctype included.
375
+ def content
376
+ evaluate("(() => { const d = document.doctype; return (d ? '<!DOCTYPE ' + d.name + '>' : '') + document.documentElement.outerHTML; })()")
377
+ end
378
+
379
+ # Replace the document with `html`; its scripts run. On an http(s)
380
+ # page the document is rewritten in place, keeping its origin;
381
+ # otherwise the page loads the HTML as a data: URL.
382
+ def set_content(html, timeout: nil) # rubocop:disable Lint/UnusedMethodArgument
383
+ here = page_id ? url : ""
384
+ if here.start_with?("http:", "https:")
385
+ evaluate("(document.open(), document.write(#{Serialize.js_string(html)}), document.close(), 'ok')")
386
+ wait_for_function("document.readyState === 'complete'", timeout: timeouts.navigation)
387
+ return nil
388
+ end
389
+ goto("data:text/html;charset=utf-8,#{Testsurfer.percent_encode(html)}")
390
+ nil
391
+ end
392
+
393
+ # Run `expression` in the page: an expression, or a function source
394
+ # called with `arg`. Promises are awaited.
395
+ def evaluate(expression, arg: nil)
396
+ body = "(function(){var v=(#{expression});return typeof v==='function'?v(E.des(#{JSON.generate(Serialize.encode(arg))})):v;})()"
397
+ engine_call(body)
398
+ end
399
+
400
+ # Poll `expression` until it is truthy; returns its value.
401
+ def wait_for_function(expression, arg: nil, timeout: nil, polling: 16)
402
+ timeout ||= timeouts.action
403
+ deadline = Testsurfer.now + timeout / 1000.0
404
+ loop do
405
+ v = evaluate(expression, arg: arg)
406
+ return v if Testsurfer.truthy?(v)
407
+ raise TimeoutError, "page.waitForFunction: Timeout #{timeout}ms exceeded." if Testsurfer.now >= deadline
408
+
409
+ sleep(polling.is_a?(Numeric) ? polling / 1000.0 : 0.016)
410
+ end
411
+ end
412
+
413
+ # Wait for `ms` milliseconds. Prefer a web-first assertion: it waits only as long as it must.
414
+ def wait_for_timeout(ms)
415
+ sleep(ms / 1000.0)
416
+ nil
417
+ end
418
+
419
+ # Resize the page: `set_viewport_size(width: 400, height: 300)`.
420
+ def set_viewport_size(size = nil, width: nil, height: nil)
421
+ if size
422
+ width = size[:width] || size["width"]
423
+ height = size[:height] || size["height"]
424
+ end
425
+ @state_lock.synchronize { @viewport = [Integer(width), Integer(height)] }
426
+ id = page_id
427
+ apply_viewport(id) if id
428
+ nil
429
+ end
430
+
431
+ # The page size in CSS pixels: { width:, height: }, or nil.
432
+ def viewport_size
433
+ v = @state_lock.synchronize { @viewport }
434
+ v && { width: v[0], height: v[1] }
435
+ end
436
+
437
+ # Change the default action timeout (ms) for this page.
438
+ def set_default_timeout(ms)
439
+ @state_lock.synchronize { @timeouts.action = ms }
440
+ end
441
+
442
+ def set_default_navigation_timeout(ms)
443
+ @state_lock.synchronize { @timeouts.navigation = ms }
444
+ end
445
+
446
+ # The default assertion timeout (ms) for this page.
447
+ def set_default_expect_timeout(ms)
448
+ @state_lock.synchronize { @timeouts.expect = ms }
449
+ end
450
+
451
+ # A PNG of the viewport (or the whole page with `full_page`, or the
452
+ # `clip` rectangle { x:, y:, width:, height: } in CSS px), at the
453
+ # page's device scale factor. With `path`, also written there.
454
+ def screenshot(path: nil, full_page: false, clip: nil)
455
+ id = ensure_open
456
+ req = Wire::Request.new("vs_capture").arg(id).flag_value("session", @session_id)
457
+ # At the page's own devicePixelRatio, which the screen may fix.
458
+ .flag_value("scale", "device")
459
+ req.flag("full-page") if full_page
460
+ if clip
461
+ c = clip.to_h.transform_keys(&:to_s)
462
+ req.flag_value("clip", %w[x y width height].map { |k| Testsurfer.fmt_num(c[k].to_f) }.join(","))
463
+ end
464
+ bytes = Page.read_capture(@wire.call(req).body)
465
+ if path
466
+ FileUtils.mkdir_p(File.dirname(path))
467
+ File.binwrite(path, bytes)
468
+ end
469
+ bytes
470
+ end
471
+
472
+ # The PNG a `vs_capture` wrote: its body's first line is the file.
473
+ def self.read_capture(body)
474
+ file = body.first.to_s.strip
475
+ raise ProtocolError, "vs_capture returned no path" if file.empty?
476
+
477
+ File.binread(file)
478
+ rescue SystemCallError => e
479
+ raise ConnectionError, "vibesurfer daemon: #{e.message}"
480
+ end
481
+
482
+ # Close the page's web view.
483
+ def close
484
+ @state_lock.synchronize { @closed = true }
485
+ id = @open_lock.synchronize { i = @page_id; @page_id = nil; i }
486
+ if id
487
+ finish_video(id)
488
+ begin
489
+ @wire.call(Wire::Request.new("vs_close").arg(id).flag_value("session", @session_id))
490
+ rescue Error
491
+ nil
492
+ end
493
+ end
494
+ nil
495
+ end
496
+
497
+ def closed?
498
+ @state_lock.synchronize { @closed }
499
+ end
500
+ alias is_closed closed?
501
+
502
+ # --- locators -------------------------------------------------------
503
+
504
+ def root(query)
505
+ Locator.new(self, Chain.of(query))
506
+ end
507
+
508
+ # Elements matching a Playwright selector (CSS, `text=`, `role=`,
509
+ # `>>` chains, ...), optionally filtered (has_text:, has_not_text:, has:, has_not:).
510
+ def locator(selector, **filter)
511
+ l = Locator.new(self, Selector.steps(selector))
512
+ filter.empty? ? l : l.filter(**filter)
513
+ end
514
+
515
+ # Elements by ARIA role and options, as `getByRole`:
516
+ # `get_by_role("button", name: "Go", exact: true)`.
517
+ def get_by_role(role, **options)
518
+ root(Query.new(:role, role: role.to_s, options: ByRole.new(**options)))
519
+ end
520
+
521
+ # Elements containing `text` (case-insensitive substring; with
522
+ # `exact: true` the whole text, case-sensitively; a pattern as given).
523
+ def get_by_text(text, exact: false)
524
+ root(Query.new(:text, text: TextMatch.check!(text), exact: exact, light: false, legacy: false))
525
+ end
526
+
527
+ # Form controls by their label (or aria-label, aria-labelledby).
528
+ def get_by_label(text, exact: false)
529
+ root(Query.new(:label, text: TextMatch.check!(text), exact: exact))
530
+ end
531
+
532
+ def get_by_placeholder(text, exact: false)
533
+ root(Query.new(:attr, method: "getByPlaceholder", attr: "placeholder", value: TextMatch.check!(text), exact: exact))
534
+ end
535
+
536
+ def get_by_alt_text(text, exact: false)
537
+ root(Query.new(:attr, method: "getByAltText", attr: "alt", value: TextMatch.check!(text), exact: exact))
538
+ end
539
+
540
+ def get_by_title(text, exact: false)
541
+ root(Query.new(:attr, method: "getByTitle", attr: "title", value: TextMatch.check!(text), exact: exact))
542
+ end
543
+
544
+ # Elements by test id (`data-testid`, or the launch option's attribute).
545
+ def get_by_test_id(id)
546
+ root(Query.new(:attr, method: "getByTestId", attr: test_id_attribute, value: TextMatch.check!(id), exact: true))
547
+ end
548
+
549
+ # Call `function(element, arg)` on the first element matching
550
+ # `selector`, without waiting and without strict mode (Playwright's
551
+ # `page.$eval`); an error when nothing matches.
552
+ def eval_on_selector(selector, function, arg: nil)
553
+ req = locator(selector).request("eval", { "arg" => Serialize.encode(arg) })
554
+ req[:first] = true
555
+ r = locate(req, func: function)
556
+ raise UsageError, "page.$eval: Failed to find element matching selector \"#{selector}\"" if r["k"] == "none"
557
+
558
+ r["v"]
559
+ end
560
+
561
+ # Call `function(elements, arg)` with every element matching `selector` (Playwright's `page.$$eval`).
562
+ def eval_on_selector_all(selector, function, arg: nil)
563
+ locator(selector).evaluate_all(function, arg: arg)
564
+ end
565
+
566
+ # PDF generation needs Chromium, as in Playwright on WebKit.
567
+ def pdf(**)
568
+ raise UsageError, "page.pdf: PDF generation is only supported for Headless Chromium"
569
+ end
570
+
571
+ private
572
+
573
+ # A navigation failure as Playwright reports one.
574
+ def navigation_call(url)
575
+ yield
576
+ rescue DaemonError => e
577
+ raise TimeoutError, "page.goto: Timeout exceeded navigating to \"#{url}\"" if e.code == "TIMEOUT"
578
+
579
+ raise e.exception("page.goto: #{e.message} navigating to \"#{url}\"")
580
+ rescue Error => e
581
+ raise e.exception("page.goto: #{e.message} navigating to \"#{url}\"")
582
+ end
583
+ end
584
+
585
+ module_function
586
+
587
+ def truthy?(v)
588
+ case v
589
+ when nil, false then false
590
+ when Numeric then !v.zero? && !(v.is_a?(Float) && v.nan?)
591
+ when String then !v.empty?
592
+ else true
593
+ end
594
+ end
595
+
596
+ # A number as Rust's `{}` prints an f64: no `.0` on whole numbers.
597
+ def fmt_num(v)
598
+ f = v.to_f
599
+ f == f.round && f.abs < 1e15 ? f.round.to_s : f.to_s
600
+ end
601
+
602
+ # `v` rounded to two decimals, printed as `fmt_num` does.
603
+ def fmt_coord(v)
604
+ fmt_num((v.to_f * 100).round / 100.0)
605
+ end
606
+
607
+ # `url` against `base`, when there is one and `url` is relative.
608
+ def resolve_against(base, url)
609
+ return url if base.nil? || url.include?("://") || url.start_with?("data:", "about:")
610
+
611
+ join_url(base, url)
612
+ end
613
+
614
+ # `path` against `base`, as a browser resolves a link.
615
+ def join_url(base, path)
616
+ start = base.index("://")
617
+ return path if start.nil?
618
+
619
+ start += 3
620
+ slash = base.index("/", start)
621
+ scheme_host, base_path = slash ? [base[0...slash], base[slash..]] : [base, "/"]
622
+ return "#{scheme_host}#{path}" if path.start_with?("/")
623
+
624
+ if path.start_with?("?", "#")
625
+ cut = base_path.index(path[0]) || base_path.length
626
+ return "#{scheme_host}#{base_path[0...cut]}#{path}"
627
+ end
628
+ dir = base_path[0..(base_path.rindex("/") || 0)]
629
+ "#{scheme_host}#{dir}#{path}"
630
+ end
631
+
632
+ def percent_encode(s)
633
+ s.to_s.b.each_byte.map do |b|
634
+ c = b.chr
635
+ c.match?(/[A-Za-z0-9\-_.!~*'()]/) ? c : format("%%%02X", b)
636
+ end.join
637
+ end
638
+
639
+ def percent_decode(s)
640
+ bytes = s.b
641
+ out = +"".b
642
+ i = 0
643
+ while i < bytes.length
644
+ if bytes[i] == "%" && i + 2 < bytes.length && bytes[i + 1, 2].match?(/\A\h\h\z/)
645
+ out << bytes[i + 1, 2].to_i(16).chr
646
+ i += 3
647
+ next
648
+ end
649
+ out << bytes[i]
650
+ i += 1
651
+ end
652
+ r = out.force_encoding(Encoding::UTF_8)
653
+ r.valid_encoding? ? r : s
654
+ end
655
+ end