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,357 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Testsurfer
4
+ # Playwright's string selector syntax, compiled to locator steps:
5
+ # `>>` chains, the `css=`, `text=`, `xpath=`, `id=`, `data-testid=`,
6
+ # `role=`, `nth=` and `visible=` engines, and `*` capture parts. CSS
7
+ # goes to the engine whole: it handles Playwright's pseudo-classes.
8
+ module Selector
9
+ ROLE_ATTRS = %w[checked disabled expanded include-hidden level name pressed selected].freeze
10
+ ROLE_SUPPORT = {
11
+ "checked" => %w[checkbox menuitemcheckbox option radio switch menuitemradio treeitem],
12
+ "pressed" => %w[button],
13
+ "selected" => %w[row gridcell tab option columnheader rowheader treeitem],
14
+ "level" => %w[heading listitem row treeitem]
15
+ }.freeze
16
+
17
+ class ParseError < StandardError; end
18
+
19
+ module_function
20
+
21
+ # A selector string as chain steps. A selector that does not parse
22
+ # becomes a step that fails when the locator is used, as in Playwright.
23
+ def steps(selector)
24
+ parse_steps(selector)
25
+ rescue ParseError => e
26
+ Chain.of(Query.new(:invalid, selector: selector, message: e.message))
27
+ end
28
+
29
+ def parse_steps(selector)
30
+ parts = split_top(selector, ">>").map { |p| one_part(p) }
31
+ at = parts.index { |(_, c)| c }
32
+ if at && at + 1 < parts.length
33
+ # A capture: keep the marked part's matches that contain the rest.
34
+ head = steps_of(parts[0..at])
35
+ rest = steps_of(parts[(at + 1)..])
36
+ tail = head.steps.last
37
+ tail.filters << Filter.new(has: rest)
38
+ tail.capture = true
39
+ head
40
+ else
41
+ steps_of(parts)
42
+ end
43
+ end
44
+
45
+ def steps_of(parts)
46
+ steps = []
47
+ parts.each do |(kind, value), _|
48
+ case kind
49
+ when :nth
50
+ raise ParseError, '"nth=" cannot start a selector' if steps.empty?
51
+
52
+ steps.last.index = value
53
+ when :visible
54
+ raise ParseError, '"visible=" cannot start a selector' if steps.empty?
55
+
56
+ steps.last.filters << Filter.new(visible: value)
57
+ else
58
+ steps << Step.new(value)
59
+ end
60
+ end
61
+ raise ParseError, "empty selector" if steps.empty?
62
+
63
+ Chain.new(steps)
64
+ end
65
+
66
+ # Split on a top-level separator, ignoring it inside quotes, brackets and parentheses.
67
+ def split_top(s, sep)
68
+ chars = s.chars
69
+ sepc = sep.chars
70
+ out = []
71
+ depth = 0
72
+ quote = nil
73
+ start = 0
74
+ i = 0
75
+ while i < chars.length
76
+ c = chars[i]
77
+ if quote
78
+ if c == "\\"
79
+ i += 1
80
+ elsif c == quote
81
+ quote = nil
82
+ end
83
+ i += 1
84
+ next
85
+ end
86
+ # A quote opens a string only where one can start: a part's
87
+ # start, or after `=`, `(` or `,`. Elsewhere it is a literal.
88
+ before = chars[start...i].join.rstrip
89
+ opens = before.empty? || before.end_with?("=", "(", ",")
90
+ if ['"', "'", "`"].include?(c) && opens
91
+ quote = c
92
+ elsif c == "(" || c == "["
93
+ depth += 1
94
+ elsif c == ")" || c == "]"
95
+ depth -= 1
96
+ elsif depth.zero? && chars[i, sepc.length] == sepc
97
+ out << chars[start...i].join
98
+ start = i + sepc.length
99
+ i += sepc.length
100
+ next
101
+ end
102
+ i += 1
103
+ end
104
+ out << chars[start..].join
105
+ out
106
+ end
107
+
108
+ # A quoted body: [value, quoted, trailing flag "i"/"s" or nil].
109
+ def unquote(v)
110
+ t = v.strip
111
+ q = t[0]
112
+ return [t, false, nil] unless ['"', "'", "`"].include?(q)
113
+
114
+ body = t[1..].chars
115
+ if body.length >= 2 && %w[i s].include?(body[-1]) && body[-2] == q
116
+ stop = body.length - 2
117
+ flag = body[-1]
118
+ elsif !body.empty? && body[-1] == q
119
+ stop = body.length - 1
120
+ flag = nil
121
+ else
122
+ return [t, false, nil]
123
+ end
124
+ value = +""
125
+ it = body[0...stop].each
126
+ loop do
127
+ c = it.next
128
+ if c == "\\"
129
+ begin
130
+ value << it.next
131
+ rescue StopIteration
132
+ break
133
+ end
134
+ else
135
+ value << c
136
+ end
137
+ end
138
+ [value, true, flag]
139
+ end
140
+
141
+ # `/source/flags` as a pattern.
142
+ def parse_regex(v)
143
+ t = v.strip
144
+ return nil unless t.start_with?("/")
145
+
146
+ rest = t[1..]
147
+ e = rest.rindex("/")
148
+ return nil if e.nil?
149
+
150
+ flags = rest[(e + 1)..]
151
+ return nil unless flags.match?(/\A[a-z]*\z/)
152
+
153
+ JSRegex.new(rest[0...e], flags)
154
+ end
155
+
156
+ def text_part(body)
157
+ if (re = parse_regex(body))
158
+ return Query.new(:text, text: re, exact: false, light: false, legacy: false)
159
+ end
160
+ # Only a quote right at the start makes a quoted body.
161
+ unless body.start_with?('"', "'", "`")
162
+ return Query.new(:text, text: body.strip, exact: false, light: false, legacy: false)
163
+ end
164
+
165
+ value, quoted, flag = unquote(body)
166
+ # "quoted" matches the element's own text, case-sensitively; a trailing i relaxes that.
167
+ Query.new(:text, text: value, exact: quoted && flag != "i", light: false, legacy: true)
168
+ end
169
+
170
+ # One `[key op value flag]` of a role selector: [key, op, raw, flag, rest] or nil.
171
+ def role_attr(s)
172
+ return nil unless s.start_with?("[")
173
+
174
+ inner = s[1..]
175
+ key_end = inner.length
176
+ inner.each_char.with_index do |c, i|
177
+ if c == "]" || c == "=" || "*~^$|".include?(c)
178
+ key_end = i
179
+ break
180
+ end
181
+ end
182
+ key = inner[0...key_end].gsub(/\s/, "")
183
+ rest = inner[key_end..].lstrip
184
+ return [key, nil, nil, nil, rest[1..]] if rest.start_with?("]")
185
+
186
+ op = ["*=", "~=", "^=", "$=", "|=", "="].find { |o| rest.start_with?(o) }
187
+ return nil if op.nil?
188
+
189
+ rest = rest[op.length..].lstrip
190
+ first = rest[0]
191
+ return nil if first.nil?
192
+
193
+ if ['"', "'", "/"].include?(first)
194
+ esc = false
195
+ stop = nil
196
+ rest.each_char.with_index do |c, i|
197
+ next if i.zero?
198
+
199
+ if esc
200
+ esc = false
201
+ elsif c == "\\"
202
+ esc = true
203
+ elsif c == first
204
+ stop = i
205
+ break
206
+ end
207
+ end
208
+ return nil if stop.nil?
209
+
210
+ stop += 1
211
+ stop += rest[stop..][/\A[a-z]*/].length if first == "/"
212
+ raw = rest[0...stop]
213
+ after = rest[stop..]
214
+ else
215
+ len = rest.index(/[\]\s]/) || rest.length
216
+ raw = rest[0...len]
217
+ after = rest[len..]
218
+ end
219
+ after = after.lstrip
220
+ flag = nil
221
+ if after.start_with?("i", "s")
222
+ flag = after[0]
223
+ after = after[1..].lstrip
224
+ end
225
+ return nil unless after.start_with?("]")
226
+
227
+ [key, op, raw, flag, after[1..]]
228
+ end
229
+
230
+ # `role=button[name="OK"i][pressed]`, with Playwright's attribute grammar and errors.
231
+ def role_part(body)
232
+ src = body.strip
233
+ role_len = src.index(/[^a-zA-Z]/) || src.length
234
+ role = src[0...role_len].downcase
235
+ raise ParseError, "Error: Role must not be empty" if role.empty?
236
+
237
+ options = ByRole.new
238
+ rest = src[role_len..].strip
239
+ until rest.empty?
240
+ a = role_attr(rest)
241
+ raise ParseError, "Error: Unexpected token while parsing role selector \"role=#{src}\"" if a.nil?
242
+
243
+ key, op, raw, flag, after = a
244
+ rest = after.strip
245
+ unless ROLE_ATTRS.include?(key)
246
+ raise ParseError, "Error: Unknown attribute \"#{key}\", must be one of #{ROLE_ATTRS.map { |x| "\"#{x}\"" }.join(', ')}."
247
+ end
248
+ if (roles = ROLE_SUPPORT[key]) && !roles.include?(role)
249
+ raise ParseError, "Error: \"#{key}\" attribute is only supported for roles: #{roles.map { |x| "\"#{x}\"" }.join(', ')}"
250
+ end
251
+
252
+ quoted = !raw.nil? && raw.start_with?('"', "'")
253
+ value = raw.nil? ? nil : (quoted ? unquote(raw)[0] : raw)
254
+ # As testsurfer for Node: `=` everywhere, and `*=` on `name`.
255
+ if op && op != "=" && !(key == "name" && op == "*=")
256
+ raise ParseError, "Error: cannot use #{op} in attribute with non-string matching value"
257
+ end
258
+
259
+ case key
260
+ when "name"
261
+ raise ParseError, 'Error: "name" attribute must have a value' if value.nil?
262
+
263
+ re = quoted ? nil : parse_regex(raw)
264
+ if re
265
+ options.name = re
266
+ elsif op == "*="
267
+ options.name = value
268
+ else
269
+ options.name = value
270
+ if flag == "s"
271
+ options.exact = true
272
+ else
273
+ options.name_full = true
274
+ end
275
+ end
276
+ when "level"
277
+ n = !quoted && value&.match?(/\A\d+\z/) ? value.to_i : nil
278
+ raise ParseError, 'Error: "level" attribute must be compared to a number' if n.nil?
279
+
280
+ options.level = n
281
+ else
282
+ tri = %w[checked pressed].include?(key)
283
+ v = if value.nil? then true
284
+ elsif value == "true" && !quoted then true
285
+ elsif value == "false" && !quoted then false
286
+ elsif value == "mixed" && tri then "mixed"
287
+ elsif tri then raise ParseError, "Error: \"#{key}\" must be one of true, false, \"mixed\""
288
+ else raise ParseError, "Error: \"#{key}\" must be one of true, false"
289
+ end
290
+ b = v == true
291
+ case key
292
+ when "checked" then options.checked = v
293
+ when "pressed" then options.pressed = v
294
+ when "disabled" then options.disabled = b
295
+ when "expanded" then options.expanded = b
296
+ when "selected" then options.selected = b
297
+ else options.include_hidden = b
298
+ end
299
+ end
300
+ end
301
+ Query.new(:role, role: role, options: options)
302
+ end
303
+
304
+ # One part of a chain as [[kind, value], capture].
305
+ def one_part(raw)
306
+ part = raw.strip
307
+ # `*css=div >> span`: the result is the marked part, among those the rest matches inside.
308
+ return [base_part(part[1..]), true] if part.start_with?("*") && engine_name(part[1..])
309
+
310
+ [base_part(part), false]
311
+ end
312
+
313
+ # `name=` at the start of a part: [engine name, body after `=`] or nil.
314
+ def engine_name(part)
315
+ return nil unless part.match?(/\A[a-zA-Z_]/)
316
+
317
+ len = part.index(/[^a-zA-Z0-9_\-:]/) || part.length
318
+ name = part[0...len]
319
+ after = part[len..].lstrip
320
+ return nil unless after.start_with?("=")
321
+
322
+ body = after[1..]
323
+ ns = name.split(":", 2)
324
+ valid = ns.length == 1 || ns[1] == "light"
325
+ valid ? [name, body] : nil
326
+ end
327
+
328
+ def base_part(part)
329
+ if (en = engine_name(part))
330
+ name, body = en
331
+ case name
332
+ when "css" then return [:query, Query.new(:css, selector: body.strip, light: false)]
333
+ when "css:light" then return [:query, Query.new(:css, selector: body.strip, light: true)]
334
+ when "text" then return [:query, text_part(body)]
335
+ when "text:light"
336
+ q = text_part(body)
337
+ return [:query, Query.new(:text, text: q[:text], exact: q[:exact], light: true, legacy: q[:legacy])]
338
+ when "xpath" then return [:query, Query.new(:xpath, xpath: body.strip)]
339
+ when "id", "data-testid", "data-test-id", "data-test"
340
+ return [:query, Query.new(:attr, method: "locator", attr: name, value: unquote(body)[0], exact: true)]
341
+ when "role" then return [:query, role_part(body)]
342
+ when "nth"
343
+ raise ParseError, "Error: bad nth= index #{body.inspect}" unless body.strip.match?(/\A-?\d+\z/)
344
+
345
+ return [:nth, body.strip.to_i]
346
+ when "visible" then return [:visible, body.strip != "false"]
347
+ else raise ParseError, "Unknown engine \"#{name}\" while parsing selector #{part}"
348
+ end
349
+ end
350
+ return [:query, Query.new(:xpath, xpath: part)] if part.start_with?("//", "..", "(//")
351
+ # A quoted string alone is a text selector.
352
+ return [:query, text_part(part)] if part.start_with?('"', "'", "`") && unquote(part)[1]
353
+
354
+ [:query, Query.new(:css, selector: part, light: false)]
355
+ end
356
+ end
357
+ end
@@ -0,0 +1,122 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "time"
5
+
6
+ module Testsurfer
7
+ # Values between Ruby and the page, in the page engine's tagged form
8
+ # (vibesurfer `engine/src/serialize.js`): JSON, with `{ "$t" => tag, "v" => ... }`
9
+ # for what JSON cannot say (undefined, NaN, dates, maps, handles).
10
+ module Serialize
11
+ HANDLE_KEY = "$handle"
12
+ RAW_KEY = "$js"
13
+
14
+ module_function
15
+
16
+ # Encode an argument for the page. Times become dates, regexps
17
+ # become RegExps, NaN and the infinities stay what they are, and a
18
+ # JSHandle passes the page value it holds.
19
+ def encode(v)
20
+ case v
21
+ when Array then v.map { |x| encode(x) }
22
+ when Hash
23
+ if v.size == 1
24
+ key, val = v.first
25
+ return { "$t" => "h", "v" => val } if key.to_s == HANDLE_KEY && val.is_a?(Integer)
26
+ return val if key.to_s == RAW_KEY
27
+ end
28
+ { "$t" => "o", "v" => v.each_with_object({}) { |(k, x), o| o[k.to_s] = encode(x) } }
29
+ when JSHandle then { "$t" => "h", "v" => v.id }
30
+ when Time then { "$t" => "d", "v" => v.utc.iso8601(3) }
31
+ when Regexp then { "$t" => "r", "v" => [v.source, TextMatch.js_flags(v)] }
32
+ when Float
33
+ if v.nan? then { "$t" => "n", "v" => "NaN" }
34
+ elsif v.infinite? then { "$t" => "n", "v" => v.positive? ? "Infinity" : "-Infinity" }
35
+ else v
36
+ end
37
+ when Symbol then v.to_s
38
+ when String, Integer, true, false, nil then v
39
+ else
40
+ return v.to_h.then { |h| encode(h) } if v.respond_to?(:to_h)
41
+
42
+ v.to_s
43
+ end
44
+ end
45
+
46
+ # Decode a value from the page. What JSON cannot hold comes back as
47
+ # its nearest JSON form: undefined, NaN and the infinities as nil,
48
+ # dates as ISO strings, regexps as `/source/flags`, maps as hashes
49
+ # (or `[key, value]` pairs when a key is not a string), sets as
50
+ # arrays, DOM nodes and windows as empty hashes (as Playwright does).
51
+ def decode(v)
52
+ case v
53
+ when Array then v.map { |x| decode(x) }
54
+ when Hash
55
+ tag = v["$t"]
56
+ inner = v["v"]
57
+ case tag
58
+ when nil then v.transform_values { |x| decode(x) }
59
+ when "u" then nil
60
+ when "n" then inner == "-0" ? -0.0 : nil
61
+ when "b", "d", "url" then inner
62
+ when "r" then "/#{inner[0]}/#{inner[1]}"
63
+ when "e" then { "name" => inner && inner["name"], "message" => inner && inner["message"] }
64
+ when "node", "win", "cyc" then {}
65
+ when "map"
66
+ pairs = (inner || []).map { |p| [decode(p[0]), decode(p[1])] }
67
+ pairs.all? { |k, _| k.is_a?(String) } ? pairs.to_h : pairs
68
+ when "set" then (inner || []).map { |x| decode(x) }
69
+ when "o" then (inner || {}).transform_values { |x| decode(x) }
70
+ else v
71
+ end
72
+ else v
73
+ end
74
+ end
75
+
76
+ # A string literal for a JavaScript expression.
77
+ def js_string(s)
78
+ JSON.generate(s.to_s)
79
+ end
80
+ end
81
+
82
+ # JavaScript values JSON has no form for, as `evaluate` arguments:
83
+ # `page.evaluate("({ d }) => d.getUTCFullYear()", arg: { d: Testsurfer::JS.date_ms(0) })`.
84
+ # A Ruby Time, Regexp, NaN or Infinity converts by itself.
85
+ module JS
86
+ module_function
87
+
88
+ def raw(tagged)
89
+ { Serialize::RAW_KEY => tagged }
90
+ end
91
+
92
+ # `undefined`.
93
+ def undefined
94
+ raw({ "$t" => "u" })
95
+ end
96
+
97
+ # A Date at `ms` milliseconds since the epoch.
98
+ def date_ms(ms)
99
+ raw({ "$t" => "d", "v" => Time.at(Rational(ms, 1000)).utc.iso8601(3) })
100
+ end
101
+
102
+ # A Date from an ISO 8601 string.
103
+ def date(iso)
104
+ raw({ "$t" => "d", "v" => iso })
105
+ end
106
+
107
+ # A BigInt from its decimal digits.
108
+ def bigint(digits)
109
+ raw({ "$t" => "b", "v" => digits.to_s })
110
+ end
111
+
112
+ # A RegExp with JavaScript source and flags.
113
+ def regex(source, flags = "")
114
+ raw({ "$t" => "r", "v" => [source, flags] })
115
+ end
116
+
117
+ # NaN, Infinity or -Infinity.
118
+ def number(v)
119
+ Serialize.encode(v.to_f).then { |e| e.is_a?(Hash) ? raw(e) : e }
120
+ end
121
+ end
122
+ end