nukadoko 0.1.0 → 0.3.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 (159) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +417 -0
  3. data/README.ja.md +62 -7
  4. data/README.md +19 -5
  5. data/exe/nuka +8 -0
  6. data/lib/nukadoko/aria_snapshot.rb +1008 -0
  7. data/lib/nukadoko/aria_tree.rb +150 -0
  8. data/lib/nukadoko/base.rb +294 -0
  9. data/lib/nukadoko/check.rb +669 -22
  10. data/lib/nukadoko/claim_check.rb +177 -0
  11. data/lib/nukadoko/claim_check_run.rb +293 -0
  12. data/lib/nukadoko/claim_line.rb +381 -0
  13. data/lib/nukadoko/claim_rules.rb +519 -0
  14. data/lib/nukadoko/claim_sides.rb +469 -0
  15. data/lib/nukadoko/claims.rb +576 -37
  16. data/lib/nukadoko/cli.rb +814 -22
  17. data/lib/nukadoko/codes.json +947 -0
  18. data/lib/nukadoko/codes.rb +19 -0
  19. data/lib/nukadoko/command.rb +214 -12
  20. data/lib/nukadoko/criteria.rb +172 -0
  21. data/lib/nukadoko/definition.rb +33 -41
  22. data/lib/nukadoko/env_check.rb +88 -0
  23. data/lib/nukadoko/features.rb +80 -10
  24. data/lib/nukadoko/fixtures.rb +329 -11
  25. data/lib/nukadoko/http_recording.rb +68 -0
  26. data/lib/nukadoko/init.rb +129 -0
  27. data/lib/nukadoko/js_json.rb +274 -0
  28. data/lib/nukadoko/js_pattern.rb +531 -0
  29. data/lib/nukadoko/judge.rb +221 -0
  30. data/lib/nukadoko/judgment_file.rb +78 -0
  31. data/lib/nukadoko/judgments.rb +256 -0
  32. data/lib/nukadoko/literal.rb +129 -0
  33. data/lib/nukadoko/measured.rb +105 -0
  34. data/lib/nukadoko/order.rb +84 -0
  35. data/lib/nukadoko/parts.rb +43 -22
  36. data/lib/nukadoko/pattern.rb +73 -3
  37. data/lib/nukadoko/poll.rb +21 -8
  38. data/lib/nukadoko/program.rb +105 -17
  39. data/lib/nukadoko/project_files.rb +17 -0
  40. data/lib/nukadoko/project_fixtures.rb +17 -2
  41. data/lib/nukadoko/project_program.rb +119 -0
  42. data/lib/nukadoko/report_allure.rb +751 -0
  43. data/lib/nukadoko/report_messages.rb +167 -0
  44. data/lib/nukadoko/report_run.rb +169 -0
  45. data/lib/nukadoko/run.rb +898 -91
  46. data/lib/nukadoko/run_record.rb +535 -0
  47. data/lib/nukadoko/scaffold.rb +1015 -0
  48. data/lib/nukadoko/schema.rb +120 -21
  49. data/lib/nukadoko/secrets.rb +375 -0
  50. data/lib/nukadoko/selection.rb +163 -0
  51. data/lib/nukadoko/signature.rb +4 -1
  52. data/lib/nukadoko/skill.rb +36 -0
  53. data/lib/nukadoko/spaces.rb +28 -0
  54. data/lib/nukadoko/step.rb +68 -21
  55. data/lib/nukadoko/summary.rb +662 -0
  56. data/lib/nukadoko/table.rb +34 -2
  57. data/lib/nukadoko/text_fit.rb +179 -0
  58. data/lib/nukadoko/trace.rb +244 -0
  59. data/lib/nukadoko/trace_actions.rb +116 -0
  60. data/lib/nukadoko/tree_passes.rb +122 -0
  61. data/lib/nukadoko/verdict.rb +128 -0
  62. data/lib/nukadoko/version.rb +2 -1
  63. data/lib/nukadoko/vocabulary.rb +6 -0
  64. data/lib/nukadoko/walk.rb +305 -0
  65. data/lib/nukadoko/walk_files.rb +473 -0
  66. data/lib/nukadoko/walk_step.rb +149 -0
  67. data/lib/nukadoko.rb +60 -2
  68. data/llms.txt +297 -0
  69. data/sig/generated/nukadoko/aria_snapshot.rbs +331 -0
  70. data/sig/generated/nukadoko/aria_tree.rbs +142 -0
  71. data/sig/generated/nukadoko/base.rbs +142 -0
  72. data/sig/generated/nukadoko/check.rbs +255 -0
  73. data/sig/generated/nukadoko/claim_check.rbs +118 -0
  74. data/sig/generated/nukadoko/claim_check_run.rbs +88 -0
  75. data/sig/generated/nukadoko/claim_line.rbs +158 -0
  76. data/sig/generated/nukadoko/claim_rules.rbs +172 -0
  77. data/sig/generated/nukadoko/claim_sides.rbs +207 -0
  78. data/sig/generated/nukadoko/claims.rbs +208 -0
  79. data/sig/generated/nukadoko/cli.rbs +182 -0
  80. data/sig/generated/nukadoko/codes.rbs +16 -0
  81. data/sig/generated/nukadoko/command.rbs +109 -0
  82. data/sig/generated/nukadoko/criteria.rbs +83 -0
  83. data/sig/generated/nukadoko/definition.rbs +30 -0
  84. data/sig/generated/nukadoko/env_check.rbs +34 -0
  85. data/sig/generated/nukadoko/features.rbs +101 -0
  86. data/sig/generated/nukadoko/fixtures.rbs +175 -0
  87. data/sig/generated/nukadoko/http_recording.rbs +29 -0
  88. data/sig/generated/nukadoko/init.rbs +64 -0
  89. data/sig/generated/nukadoko/js_json.rbs +109 -0
  90. data/sig/generated/nukadoko/js_pattern.rbs +194 -0
  91. data/sig/generated/nukadoko/judge.rbs +64 -0
  92. data/sig/generated/nukadoko/judgment_file.rbs +39 -0
  93. data/sig/generated/nukadoko/judgments.rbs +120 -0
  94. data/sig/generated/nukadoko/literal.rbs +71 -0
  95. data/sig/generated/nukadoko/measured.rbs +42 -0
  96. data/sig/generated/nukadoko/order.rbs +54 -0
  97. data/sig/generated/nukadoko/parts.rbs +35 -0
  98. data/sig/generated/nukadoko/pattern.rbs +62 -0
  99. data/sig/generated/nukadoko/poll.rbs +41 -0
  100. data/sig/generated/nukadoko/program.rbs +101 -0
  101. data/sig/generated/nukadoko/project_files.rbs +19 -0
  102. data/sig/generated/nukadoko/project_fixtures.rbs +57 -0
  103. data/sig/generated/nukadoko/project_program.rbs +55 -0
  104. data/sig/generated/nukadoko/report_allure.rbs +268 -0
  105. data/sig/generated/nukadoko/report_messages.rbs +68 -0
  106. data/sig/generated/nukadoko/report_run.rbs +102 -0
  107. data/sig/generated/nukadoko/run.rbs +264 -0
  108. data/sig/generated/nukadoko/run_record.rbs +175 -0
  109. data/sig/generated/nukadoko/scaffold.rbs +328 -0
  110. data/sig/generated/nukadoko/schema.rbs +155 -0
  111. data/sig/generated/nukadoko/secrets.rbs +172 -0
  112. data/sig/generated/nukadoko/selection.rbs +73 -0
  113. data/sig/generated/nukadoko/signature.rbs +17 -0
  114. data/sig/generated/nukadoko/skill.rbs +20 -0
  115. data/sig/generated/nukadoko/spaces.rbs +31 -0
  116. data/sig/generated/nukadoko/step.rbs +115 -0
  117. data/sig/generated/nukadoko/summary.rbs +204 -0
  118. data/sig/generated/nukadoko/table.rbs +43 -0
  119. data/sig/generated/nukadoko/text_fit.rbs +70 -0
  120. data/sig/generated/nukadoko/trace.rbs +127 -0
  121. data/sig/generated/nukadoko/trace_actions.rbs +40 -0
  122. data/sig/generated/nukadoko/tree_passes.rbs +48 -0
  123. data/sig/generated/nukadoko/verdict.rbs +56 -0
  124. data/sig/generated/nukadoko/version.rbs +5 -0
  125. data/sig/generated/nukadoko/vocabulary.rbs +25 -0
  126. data/sig/generated/nukadoko/walk.rbs +139 -0
  127. data/sig/generated/nukadoko/walk_files.rbs +189 -0
  128. data/sig/generated/nukadoko/walk_step.rbs +50 -0
  129. data/sig/generated/nukadoko.rbs +26 -0
  130. data/sig/nukadoko.rbs +5 -48
  131. data/skills/nukadoko/SKILL.md +120 -0
  132. data/skills/nukadoko/references/checking-steps.md +200 -0
  133. data/skills/nukadoko/references/diagnosing.md +200 -0
  134. data/skills/nukadoko/references/done.md +99 -0
  135. data/skills/nukadoko/references/evidence.md +124 -0
  136. data/skills/nukadoko/references/examples/cli.md +230 -0
  137. data/skills/nukadoko/references/examples/http-api.md +342 -0
  138. data/skills/nukadoko/references/examples/workflow.md +173 -0
  139. data/skills/nukadoko/references/exploring.md +184 -0
  140. data/skills/nukadoko/references/fixtures.md +198 -0
  141. data/skills/nukadoko/references/from-prose.md +51 -0
  142. data/skills/nukadoko/references/judgments.md +95 -0
  143. data/skills/nukadoko/references/maintenance.md +97 -0
  144. data/skills/nukadoko/references/merge-risk.md +74 -0
  145. data/skills/nukadoko/references/parts.md +152 -0
  146. data/skills/nukadoko/references/perturbed-worlds.md +109 -0
  147. data/skills/nukadoko/references/program.md +200 -0
  148. data/skills/nukadoko/references/reviewing.md +200 -0
  149. data/skills/nukadoko/references/running.md +200 -0
  150. data/skills/nukadoko/references/scenario-rules.md +188 -0
  151. data/skills/nukadoko/references/states.md +66 -0
  152. data/skills/nukadoko/references/step-files.md +200 -0
  153. data/skills/nukadoko/references/verdicts.md +200 -0
  154. data/skills/nukadoko/references/writing-steps.md +200 -0
  155. data/skills/nukadoko/references/writing-the-feature.md +165 -0
  156. data/skills/nukadoko/scripts/claude-code-verdict-hook.mjs +99 -0
  157. data/skills/nukadoko/scripts/merge-risk.jq +56 -0
  158. data/skills/nukadoko-verification/SKILL.md +263 -0
  159. metadata +133 -1
@@ -1,4 +1,5 @@
1
1
  # frozen_string_literal: true
2
+ # rbs_inline: enabled
2
3
 
3
4
  # A Then step declares what it compares; the engine judges. A claim names the
4
5
  # actual value (a key the step observed or was given, and an optional `at`
@@ -6,79 +7,231 @@
6
7
  # key, `{ literal: v }`, or `{ from: key }` for an args key an earlier step
7
8
  # filled. The judge returns every comparison it made, so a broken claim shows
8
9
  # what was read.
10
+ require "ipaddr"
11
+ require_relative "text_fit"
12
+
9
13
  module Nukadoko
10
14
  module Engine
11
15
  module Claims
12
16
  COMPARES = %w[equal not-equal contains-text starts-with-text ends-with-text has-item has-same-items has-fields
13
17
  lacks-field fits-text fits-aria-snapshot is-a matches greater-than at-least less-than at-most judged-as].freeze
14
18
 
15
- def self.unknown_compares(node)
16
- case node
17
- in Array then node.flat_map { unknown_compares(_1) }
18
- in Hash
19
- own = node.key?(:compare) && !COMPARES.include?(node[:compare]) ? [node[:compare]] : []
20
- own + node.values.flat_map { unknown_compares(_1) }
21
- else []
19
+ # The ARIA snapshots nukadoko took of what observe returned, by the
20
+ # value observe returned, so a claim judges the tree taken right
21
+ # after that reading and never reads a live page.
22
+ ARIA_TAKEN = ObjectSpace::WeakKeyMap.new #: ObjectSpace::WeakKeyMap[Hash[String, untyped], Hash[String, Hash[Symbol, String]]]
23
+ ARIA_TAKES = "fits-aria-snapshot takes the ARIA snapshot of a locator or page that observe returns: return the locator or page itself, and nukadoko takes its snapshot"
24
+
25
+ # Takes the ARIA snapshot of the locator or page at each path a
26
+ # fits-aria-snapshot claim reads, once per reading. One path's failure
27
+ # is that path's read, so taking them never raises.
28
+ #: (Array[Hash[Symbol, untyped]], untyped) -> untyped
29
+ def self.take_aria_snapshots(claims, observed)
30
+ paths = claims.filter_map { _1[:actual].to_s if !_1[:each] && _1[:compare] == "fits-aria-snapshot" }
31
+ judged = claims.filter_map { judged_path(_1) if !_1[:each] && _1[:compare] == "judged-as" }
32
+ return observed if (paths + judged).empty? || !observed.is_a?(Hash)
33
+
34
+ taken = paths.uniq.to_h { [_1, aria_snapshot_at(observed, _1.split("."))] }
35
+ # A judged value is read as the tree the browser printed when it is
36
+ # a locator or a page, and as its plain value when it is not, so a
37
+ # judged path that holds neither keeps no entry.
38
+ judged.uniq.each do |path|
39
+ read = aria_snapshot_at(observed, path.split("."))
40
+ taken["judged:#{path}"] = read unless read[:broken]
41
+ end
42
+ ARIA_TAKEN[observed] = taken
43
+ observed
44
+ end
45
+
46
+ # The path a judged-as claim reads: its actual and, with no view, its at.
47
+ #: (Hash[Symbol, untyped]) -> String
48
+ def self.judged_path(claim)
49
+ [claim[:actual], (claim[:at] unless claim[:view])].compact.join(".")
50
+ end
51
+
52
+ #: (untyped, Array[String]) -> Hash[Symbol, String]
53
+ def self.aria_snapshot_at(root, segments)
54
+ found = segments.reduce(root) do |current, segment|
55
+ case current
56
+ when Hash then current.key?(segment) ? current[segment] : current.fetch(segment.to_sym, :missing)
57
+ when Array then segment.match?(/\A(0|[1-9][0-9]*)\z/) && segment.to_i < current.size ? current[segment.to_i] : :missing
58
+ else :missing
59
+ end
60
+ end
61
+ return { broken: "is undefined" } if found == :missing
62
+ return { broken: "is #{aria_value_kind(found)}, and #{ARIA_TAKES}" } unless aria_snapshot_taker?(found)
63
+
64
+ taker = found #: untyped
65
+ text = begin
66
+ taker.aria_snapshot
67
+ rescue StandardError => e
68
+ return { unjudged: "gave no ARIA snapshot: #{e.message.lines.first.to_s.chomp.delete_suffix(".")}, so the claim was not judged" }
69
+ end
70
+ text.is_a?(String) ? { text: text } : { unjudged: "gave #{aria_value_kind(text)} from ariaSnapshot() rather than a text, so the claim was not judged" }
71
+ end
72
+
73
+ # Only Playwright's own locator and page: a value step code wrote with
74
+ # a method of that name would be a tree written in code.
75
+ #: (untyped) -> bool
76
+ def self.aria_snapshot_taker?(value)
77
+ value.class.ancestors.any? { %w[Playwright::Locator Playwright::Page].include?(_1.name) }
78
+ end
79
+
80
+ # The phrase for a value that is not a locator or a page, as the
81
+ # TypeScript engine names it.
82
+ #: (untyped) -> String
83
+ def self.aria_value_kind(value)
84
+ case value
85
+ when nil then "null"
86
+ when String then "a string"
87
+ when Numeric then "a number"
88
+ when true, false then "a boolean"
89
+ when Hash then "an Object"
90
+ when Array then "an Array"
91
+ else
92
+ name = value.class.name.to_s.split("::").last.to_s
93
+ name.empty? ? "an object of no class" : article_of(name)
22
94
  end
23
95
  end
24
96
 
25
- def self.judge(claims, observed, args)
26
- claims.map { judge_one(_1, observed, args) }
97
+ #: (String) -> String
98
+ def self.article_of(word) = word.match?(/\A[aeiou]/i) ? "an #{word}" : "a #{word}"
99
+
100
+ # The side a fits-aria-snapshot claim reads: the text of the snapshot
101
+ # taken of the value at its actual path.
102
+ #: (Hash[Symbol, untyped], untyped) -> Hash[Symbol, String]
103
+ def self.aria_side(claim, observed)
104
+ path = claim[:actual].to_s
105
+ taken = (observed.is_a?(Hash) ? ARIA_TAKEN[observed] : nil)&.[](path) || { unjudged: "has no ARIA snapshot nukadoko took, so the claim was not judged" } #: Hash[Symbol, String]
106
+ taken[:text] ? taken : taken.transform_values { "observe:#{path} #{_1}" }
107
+ end
108
+
109
+ # `inputs` says where each side sits, so a top-level comparison is read
110
+ # as the TypeScript engine reads it (ClaimSides); without it, a claim
111
+ # reads `observed` as the value of each key.
112
+ #: (Array[Hash[Symbol, untyped]], untyped, untyped, ?ClaimSides::Inputs?) -> Array[Hash[Symbol, untyped]]
113
+ def self.judge(claims, observed, args, inputs = nil)
114
+ claims.map do |claim|
115
+ sided = !claim[:each] && claim[:compare] != "fits-aria-snapshot" && !(claim[:compare] == "judged-as" && aria_judged(claim, observed))
116
+ next each_judged(claim, inputs) if inputs && claim[:each]
117
+
118
+ inputs && sided ? ClaimSides.judge(claim, inputs) : judge_one(claim, observed, args)
119
+ end
120
+ end
121
+
122
+ # An each judged as its record judges it, so a poll waits on the
123
+ # outcome the record will hold.
124
+ #: (Hash[Symbol, untyped], ClaimSides::Inputs) -> Hash[Symbol, untyped]
125
+ def self.each_judged(claim, inputs)
126
+ record = RunRecord.each_claim(claim, inputs, {}, {})
127
+ { holds: record[:outcome] == "held", **(record[:reason] ? { reason: record[:reason] } : {}),
128
+ **(record[:outcome] == "unjudged" ? { unjudged: true } : {}) }
129
+ end
130
+
131
+ # `top` is what observe returned, which an expected { observe } reads
132
+ # from inside an each as well. A claim on an item with no actual reads
133
+ # the item itself.
134
+ #: (Hash[Symbol, untyped], untyped, untyped, ?untyped) -> Hash[Symbol, untyped]
135
+ def self.judge_one(claim, observed, args, top = observed)
136
+ actual = dig(view(claim[:view], claim[:actual].nil? ? observed : read(observed, claim[:actual])), claim[:at])
137
+ return judge_each(claim[:each], actual, args, top) if claim[:each]
138
+ return judge_aria(claim, observed, args, top) if claim[:compare] == "fits-aria-snapshot"
139
+ return judge_judged(claim, observed, args, top) if claim[:compare] == "judged-as" && aria_judged(claim, observed)
140
+
141
+ if claim[:count]
142
+ unless actual.is_a?(Array)
143
+ # A count of no array has no value, and the record says so by leaving the actual out.
144
+ return { compare: claim[:compare], expected: expected_value(claim, args, top), holds: false, reason: "count reads an array, and the value is #{article(json_type(actual))}" }
145
+ end
146
+
147
+ actual = actual.size
148
+ end
149
+ expected = expected_value(claim, args, top)
150
+ result = compare(claim[:compare], actual, expected)
151
+ { actual: actual, compare: claim[:compare], expected: expected, holds: result[:holds] == true, **(result[:for_judgment] ? { for_judgment: true } : {}),
152
+ **(result[:reason] ? { reason: result[:reason] } : {}), **(result[:stopped] ? { reason: result[:stopped], unjudged: true } : {}) }
153
+ end
154
+
155
+ #: (Hash[Symbol, untyped], untyped, untyped, untyped) -> Hash[Symbol, untyped]
156
+ def self.judge_aria(claim, observed, args, top)
157
+ side = aria_side(claim, observed)
158
+ expected = expected_value(claim, args, top)
159
+ return { compare: claim[:compare], expected: expected, holds: false, reason: side[:broken] } if side[:broken]
160
+ return { compare: claim[:compare], expected: expected, holds: false, reason: side[:unjudged], unjudged: true } if side[:unjudged]
161
+
162
+ result = compare(claim[:compare], side[:text], expected)
163
+ { actual: side[:text], compare: claim[:compare], expected: expected, holds: result[:holds] == true,
164
+ **(result[:reason] ? { reason: result[:reason] } : {}), **(result[:stopped] ? { reason: result[:stopped], unjudged: true } : {}) }
165
+ end
166
+
167
+ # The tree nukadoko took of a judged value that is a locator or a page.
168
+ #: (Hash[Symbol, untyped], untyped) -> Hash[Symbol, String]?
169
+ def self.aria_judged(claim, observed)
170
+ observed.is_a?(Hash) ? ARIA_TAKEN[observed]&.[]("judged:#{judged_path(claim)}") : nil
27
171
  end
28
172
 
29
- def self.judge_one(claim, observed, args)
30
- actual = dig(view(claim[:view], read(observed, claim[:actual])), claim[:at])
31
- return judge_each(claim[:each], actual, args) if claim[:each]
173
+ #: (Hash[Symbol, untyped], untyped, untyped, untyped) -> Hash[Symbol, untyped]
174
+ def self.judge_judged(claim, observed, args, top)
175
+ taken = aria_judged(claim, observed) || {}
176
+ expected = expected_value(claim, args, top)
177
+ return { compare: claim[:compare], expected: expected, holds: false, reason: "observe:#{judged_path(claim)} #{taken[:unjudged]}", unjudged: true, aria: true } if taken[:unjudged]
32
178
 
33
- expected = expected_value(claim, args)
34
- { actual: actual, compare: claim[:compare], expected: expected, holds: holds?(claim[:compare], actual, expected) }
179
+ { actual: taken[:text], compare: claim[:compare], expected: expected, holds: true, for_judgment: true, aria: true }
35
180
  end
36
181
 
37
- def self.judge_each(each, items, args)
38
- chosen = Array(items).select { |item| each[:where].all? { judge_one(_1, item, args)[:holds] } }
39
- results = chosen.flat_map { |item| each[:claims].map { judge_one(_1, item, args) } }
182
+ #: (Hash[Symbol, untyped], untyped, untyped, untyped) -> Hash[Symbol, untyped]
183
+ def self.judge_each(each, items, args, top)
184
+ chosen = Array(items).select { |item| (each[:where] || []).all? { judge_one(_1, item, args, top)[:holds] } }
185
+ results = chosen.flat_map { |item| each[:claims].map { judge_one(_1, item, args, top) } }
40
186
  { each: results, chosen: chosen.size, holds: !chosen.empty? && results.all? { _1[:holds] } }
41
187
  end
42
188
 
43
- def self.expected_value(claim, args)
189
+ #: (Hash[Symbol, untyped], untyped, ?untyped) -> untyped
190
+ def self.expected_value(claim, args, top = nil)
44
191
  value =
45
192
  case claim[:expected]
46
193
  in String => key then read(args, key)
47
194
  in { literal: literal } then literal
48
195
  in { from: String => key } then read(args, key)
196
+ in { observe: String => path } then dig(read(top, path.split(".").first), path.split(".").drop(1).join(".").then { _1.empty? ? nil : _1 })
49
197
  end
50
- claim[:expected_view] == "json" ? JSON.parse(value) : value
198
+ claim[:expected_view] == "json" ? JsJson.parse(value) : value
51
199
  end
52
200
 
53
201
  VIEWS = %w[text lines comma-list json].freeze
54
202
 
55
203
  # A view reads a string as something else before `at` walks into it.
204
+ #: (String?, untyped) -> untyped
56
205
  def self.view(name, value)
57
206
  return value unless name
58
207
  raise ArgumentError, "view #{name} reads a string, and the value is #{value.inspect}" unless value.is_a?(String)
59
208
 
60
209
  case name
61
- when "text" then value.rstrip
62
- when "lines" then value.rstrip.empty? ? [] : value.rstrip.split(/\r?\n/)
63
- when "comma-list" then value.strip.empty? ? [] : value.strip.split(",").map(&:strip)
64
- when "json" then JSON.parse(value)
210
+ when "text" then Spaces.trim_end(value)
211
+ when "lines" then (text = Spaces.trim_end(value)).empty? ? [] : text.split(/\r?\n/, -1)
212
+ when "comma-list" then (text = Spaces.trim(value)).empty? ? [] : text.split(",", -1).map { Spaces.trim(_1) }
213
+ when "json" then JsJson.parse(value)
65
214
  else raise ArgumentError, "unknown view #{name}"
66
215
  end
67
216
  end
68
217
 
218
+ #: (untyped, String | Symbol) -> untyped
69
219
  def self.read(hash, key)
70
220
  hash = hash.transform_keys(&:to_s) if hash.is_a?(Hash)
71
221
  hash.fetch(key.to_s)
72
222
  end
73
223
 
224
+ #: (untyped, untyped) -> untyped
74
225
  def self.dig(value, path)
75
226
  return value unless path
76
227
 
77
228
  path.to_s.split(".").reduce(value) { |v, part| v.is_a?(Array) ? v[Integer(part)] : read(v, part) }
78
229
  end
79
230
 
231
+ #: (untyped, untyped) -> bool
80
232
  def self.same?(a, b) = normal(a) == normal(b)
81
233
 
234
+ #: (untyped) -> untyped
82
235
  def self.normal(value)
83
236
  case value
84
237
  when Hash then value.to_h { |k, v| [k.to_s, normal(v)] }
@@ -88,23 +241,409 @@ module Nukadoko
88
241
  end
89
242
  end
90
243
 
91
- def self.holds?(compare, actual, expected)
244
+ # A pattern that backtracks gets this long before the claim is left unjudged.
245
+ PATTERN_TIMEOUT = 1.0
246
+
247
+ # What `is-a` names, as the TypeScript engine lists the kinds.
248
+ VALUE_KINDS = %w[string text number integer boolean list array object null uuid date timestamp url].freeze
249
+ DATE = /\A(\d{4})-(\d{2})-(\d{2})\z/
250
+ # Seconds are required and a leap second refused, as a program's clock
251
+ # never prints 60; the separator and the offset take the spellings
252
+ # RFC 3339 and ISO 8601 allow.
253
+ TIMESTAMP = /\A(\d{4})-(\d{2})-(\d{2})[Tt ](\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:[Zz]|[+-](\d{2})(?::?(\d{2}))?)\z/
254
+ UUID = /\A\h{8}-\h{4}-\h{4}-\h{4}-\h{12}\z/
255
+
256
+ #: (Integer, Integer, Integer) -> bool
257
+ def self.calendar_day?(year, month, day)
258
+ return false if month < 1 || month > 12 || day < 1
259
+
260
+ leap = (year % 4).zero? && !(year % 100).zero? || (year % 400).zero?
261
+ day <= [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month - 1]
262
+ end
263
+
264
+ #: (untyped) -> bool
265
+ def self.date?(value)
266
+ match = value.is_a?(String) ? DATE.match(value) : nil
267
+ return false unless match
268
+
269
+ year, month, day = match.captures.map(&:to_i)
270
+ calendar_day?(year.to_i, month.to_i, day.to_i)
271
+ end
272
+
273
+ #: (untyped) -> bool
274
+ def self.timestamp?(value)
275
+ match = value.is_a?(String) ? TIMESTAMP.match(value) : nil
276
+ return false unless match
277
+
278
+ year, month, day, hour, minute, second = match.captures.map(&:to_i)
279
+ return false unless calendar_day?(year.to_i, month.to_i, day.to_i)
280
+
281
+ hour = hour.to_i
282
+ minute = minute.to_i
283
+ second = second.to_i
284
+ offset = match[7].nil? || (match[7].to_i <= 23 && match[8].to_i <= 59)
285
+ hour <= 23 && minute <= 59 && second <= 59 && offset
286
+ end
287
+
288
+ # A text a URL parser accepts can still be no URL a program wrote, so
289
+ # the scheme needs "//" and no character a reader cannot see may appear.
290
+ # The rest is what the WHATWG URL parser, which the TypeScript engine
291
+ # uses, refuses for http and https: a missing host, a port that is not
292
+ # a number up to 65535, a host with a character no domain may hold, and
293
+ # an IPv4 or IPv6 address that does not parse. A path, a query, and a
294
+ # fragment can hold anything, as a browser takes them.
295
+ #: (untyped) -> bool
296
+ def self.url?(value)
297
+ return false unless value.is_a?(String) && value.match?(%r{\Ahttps?://}i) && !value.match?(/[\s\p{Cc}\p{Cf}]/)
298
+
299
+ rest = value.sub(%r{\Ahttps?:[/\\]*}i, "")
300
+ authority = rest[%r{\A[^/\\?#]*}].to_s
301
+ at = authority.rindex("@")
302
+ host_port = at ? authority[(at + 1)..].to_s : authority
303
+ host, port = split_host_port(host_port)
304
+ return false if host.nil? || host.empty?
305
+ return false unless port.nil? || (port.match?(/\A\d*\z/) && port.to_i <= 65_535)
306
+
307
+ host.start_with?("[") ? ipv6?(host[1...-1].to_s) : domain?(host)
308
+ end
309
+
310
+ # The host and the port of `host:port`, a colon inside brackets kept.
311
+ #: (String) -> [String?, String?]
312
+ def self.split_host_port(text)
313
+ if text.start_with?("[")
314
+ close = text.index("]")
315
+ return [nil, nil] unless close
316
+
317
+ after = text[(close + 1)..].to_s
318
+ return [nil, nil] unless after.empty? || after.start_with?(":")
319
+
320
+ return [text[0..close], after.empty? ? nil : after[1..]]
321
+ end
322
+ colon = text.index(":")
323
+ colon ? [text[0...colon], text[(colon + 1)..]] : [text, nil]
324
+ end
325
+
326
+ #: (String) -> bool
327
+ def self.ipv6?(text)
328
+ return false if text.empty? || text.include?("%")
329
+
330
+ IPAddr.new(text).ipv6?
331
+ rescue IPAddr::Error
332
+ false
333
+ end
334
+
335
+ FORBIDDEN_DOMAIN = /[\u0000- #%\/:<>?@\[\\\]^|\u007f]/
336
+
337
+ # A host percent-decoded and mapped as UTS #46 maps it (NFKC, then
338
+ # lower case), which holds no character a domain may not, and whose
339
+ # last label, when it reads as a number, is an IPv4 address.
340
+ #: (String) -> bool
341
+ def self.domain?(host)
342
+ decoded = host.b.gsub(/%(\h\h)/n) { Regexp.last_match(1).to_s.hex.chr }.force_encoding("UTF-8")
343
+ return false unless decoded.valid_encoding?
344
+
345
+ mapped = decoded.unicode_normalize(:nfkc).downcase.tr("。.。", "...")
346
+ return false if mapped.empty? || mapped.match?(FORBIDDEN_DOMAIN) || mapped.include?("�")
347
+
348
+ labels = mapped.split(".", -1)
349
+ # Node checks an xn-- label only in a host that is not all ASCII.
350
+ return false if !decoded.ascii_only? && labels.any? { _1.start_with?("xn--") && !punycode_label?(_1) }
351
+ last = labels.last == "" && labels.size > 1 ? labels[-2] : labels.last
352
+ return true unless last.to_s.match?(/\A(?:\d+|0[xX]\h*)\z/)
353
+
354
+ ipv4?(labels)
355
+ end
356
+
357
+ # Whether a label written as `xn--` decodes, under RFC 3492, to a
358
+ # label UTS #46 keeps: one with a character outside ASCII, no control,
359
+ # joiner, or unassigned character, and already in its mapped form.
360
+ #: (String) -> bool
361
+ def self.punycode_label?(label)
362
+ decoded = punycode_decode(label[4..].to_s)
363
+ !decoded.nil? && !decoded.ascii_only? && !decoded.match?(/[\p{Cc}\p{Cf}\p{Cn}\p{Co}\p{Cs}]/) && decoded == decoded.unicode_normalize(:nfkc).downcase
364
+ end
365
+
366
+ # RFC 3492's decoder, or nil for a text that does not decode.
367
+ #: (String) -> String?
368
+ def self.punycode_decode(text)
369
+ return nil if text.empty?
370
+
371
+ base, damp, tmin, tmax, skew = 36, 700, 1, 26, 38
372
+ cut = text.rindex("-")
373
+ output = cut ? text[0...cut].to_s.codepoints : []
374
+ return nil unless output.all? { _1 < 0x80 }
375
+
376
+ n = 128
377
+ i = 0
378
+ bias = 72
379
+ index = cut ? cut + 1 : 0
380
+ while index < text.length
381
+ old = i
382
+ w = 1
383
+ k = base
384
+ loop do
385
+ return nil if index >= text.length
386
+
387
+ char = text[index].to_s.downcase
388
+ index += 1
389
+ digit = if char.match?(/[a-z]/) then char.ord - 97
390
+ elsif char.match?(/[0-9]/) then char.ord - 22
391
+ else return nil
392
+ end
393
+ i += digit * w
394
+ t = if k <= bias then tmin elsif k >= bias + tmax then tmax else k - bias end
395
+ break if digit < t
396
+
397
+ w *= base - t
398
+ k += base
399
+ end
400
+ length = output.size + 1
401
+ delta = old.zero? ? (i - old) / damp : (i - old) / 2
402
+ delta += delta / length
403
+ k = 0
404
+ while delta > ((base - tmin) * tmax) / 2
405
+ delta /= base - tmin
406
+ k += base
407
+ end
408
+ bias = k + (((base - tmin + 1) * delta) / (delta + skew))
409
+ n += i / length
410
+ i %= length
411
+ return nil if n > 0x10FFFF || n.between?(0xD800, 0xDFFF)
412
+
413
+ output.insert(i, n)
414
+ i += 1
415
+ end
416
+ output.pack("U*")
417
+ end
418
+
419
+ # The WHATWG IPv4 parser: up to four parts, each decimal, octal with a
420
+ # leading 0, or hex with 0x, every part but the last below 256 and the
421
+ # last below what the parts before it leave.
422
+ #: (Array[String]) -> bool
423
+ def self.ipv4?(labels)
424
+ parts = labels.last == "" ? labels[0...-1].to_a : labels
425
+ return false if parts.empty? || parts.size > 4
426
+
427
+ numbers = parts.map do |part|
428
+ number = case part
429
+ when /\A0[xX]\h*\z/ then part[2..].to_s.empty? ? 0 : part[2..].to_s.hex
430
+ when /\A0[0-7]+\z/ then part.to_i(8)
431
+ when /\A0\d+\z/ then nil
432
+ when /\A\d+\z/ then part.to_i
433
+ end
434
+ return false unless number
435
+
436
+ number
437
+ end
438
+ return false if numbers[0...-1].to_a.any? { _1 > 255 }
439
+
440
+ numbers.last.to_i < 256**(5 - numbers.size)
441
+ end
442
+
443
+ KIND_TESTS = {
444
+ "string" => ->(v) { v.is_a?(String) }, "text" => ->(v) { v.is_a?(String) },
445
+ "number" => ->(v) { v.is_a?(Numeric) }, "integer" => ->(v) { v.is_a?(Integer) || (v.is_a?(Float) && v.finite? && v == v.floor) },
446
+ "boolean" => ->(v) { [true, false].include?(v) }, "list" => ->(v) { v.is_a?(Array) }, "array" => ->(v) { v.is_a?(Array) },
447
+ "object" => ->(v) { v.is_a?(Hash) }, "null" => ->(v) { v.nil? }, "uuid" => ->(v) { v.is_a?(String) && v.match?(UUID) },
448
+ "date" => method(:date?), "timestamp" => method(:timestamp?), "url" => method(:url?)
449
+ }.freeze
450
+
451
+ # The test of the kind `name` names, read trimmed and in any case.
452
+ #: (String) -> untyped
453
+ def self.value_kind(name) = KIND_TESTS[Spaces.trim(name).downcase]
454
+
455
+ #: (untyped) -> String
456
+ def self.json_type(value)
457
+ case value
458
+ when nil then "null"
459
+ when true, false then "boolean"
460
+ when Numeric then "number"
461
+ when String then "string"
462
+ when Array then "array"
463
+ else "object"
464
+ end
465
+ end
466
+
467
+ #: (String) -> String
468
+ def self.article(type) = %w[array object].include?(type) ? "an #{type}" : "a #{type}"
469
+
470
+ # JavaScript's trim, which takes Unicode spaces and a byte order mark.
471
+ #: (String) -> bool
472
+ def self.blank?(text) = Spaces.blank?(text)
473
+
474
+ # Structural equality over JSON values: key order does not count, and
475
+ # 1 equals 1.0, as JSON writes one number.
476
+ #: (untyped, untyped) -> bool
477
+ def self.deep_equal?(a, b)
478
+ type = json_type(a)
479
+ return false unless type == json_type(b)
480
+
481
+ case type
482
+ when "array" then a.size == b.size && a.each_index.all? { deep_equal?(a[_1], b[_1]) }
483
+ when "object"
484
+ left = normal(a)
485
+ right = normal(b)
486
+ left.size == right.size && left.all? { |key, value| right.key?(key) && deep_equal?(value, right[key]) }
487
+ else a == b
488
+ end
489
+ end
490
+
491
+ # The same items, each as many times, in any order.
492
+ #: (Array[untyped], Array[untyped]) -> bool
493
+ def self.same_items?(a, b)
494
+ return false unless a.size == b.size
495
+
496
+ unmatched = b.dup
497
+ a.all? do |item|
498
+ index = unmatched.index { deep_equal?(item, _1) }
499
+ index && unmatched.delete_at(index)
500
+ !index.nil?
501
+ end
502
+ end
503
+
504
+ # The first place `expected` does not fit `actual` under has-fields, or
505
+ # nil: an object fits one that holds each of its fields with a value
506
+ # that fits, an array one of its length whose items fit, and anything
507
+ # else an equal value.
508
+ #: (untyped, untyped, ?Array[String | Integer]) -> Hash[Symbol, untyped]?
509
+ def self.field_misfit(actual, expected, path = [])
510
+ case json_type(expected)
511
+ when "object"
512
+ return { kind: "differs", path: path, actual: actual, expected: expected } unless json_type(actual) == "object"
513
+
514
+ have = normal(actual)
515
+ normal(expected).each do |key, value|
516
+ return { kind: "missing", path: [*path, key], expected: value } unless have.key?(key)
517
+
518
+ found = field_misfit(have[key], value, [*path, key])
519
+ return found if found
520
+ end
521
+ nil
522
+ when "array"
523
+ return { kind: "differs", path: path, actual: actual, expected: expected } unless actual.is_a?(Array)
524
+ return { kind: "length", path: path, actual: actual.size, expected: expected.size } unless actual.size == expected.size
525
+
526
+ expected.each_index do |index|
527
+ found = field_misfit(actual[index], expected[index], [*path, index.to_s])
528
+ return found if found
529
+ end
530
+ nil
531
+ else deep_equal?(actual, expected) ? nil : { kind: "differs", path: path, actual: actual, expected: expected }
532
+ end
533
+ end
534
+
535
+ # The path of the first object with no field, at any depth, or nil.
536
+ #: (untyped, ?Array[String | Integer]) -> Array[String | Integer]?
537
+ def self.fieldless_object(value, path = [])
538
+ type = json_type(value)
539
+ return nil unless %w[object array].include?(type)
540
+
541
+ entries = type == "array" ? value.each_with_index.map { |item, index| [index.to_s, item] } : normal(value).to_a
542
+ return path if type == "object" && entries.empty?
543
+
544
+ entries.each do |key, item|
545
+ found = fieldless_object(item, [*path, key])
546
+ return found if found
547
+ end
548
+ nil
549
+ end
550
+
551
+ # { holds: } or { reason: } when the two sides cannot be compared, or
552
+ # { stopped: } when nothing judged them. A comparison across two JSON
553
+ # types never holds for the reason the claim states, so it breaks with
554
+ # both types named, and so does an expected value every actual holds.
555
+ #: (String, untyped, untyped) -> Hash[Symbol, untyped]
556
+ def self.compare(compare, actual, expected)
557
+ a_type = json_type(actual)
558
+ e_type = json_type(expected)
92
559
  case compare
93
- when "equal" then same?(actual, expected)
94
- when "not-equal" then !same?(actual, expected)
95
- when "contains-text" then actual.to_s.include?(expected.to_s)
96
- when "starts-with-text" then actual.to_s.start_with?(expected.to_s)
97
- when "ends-with-text" then actual.to_s.end_with?(expected.to_s)
98
- when "has-item" then Array(actual).any? { same?(_1, expected) }
99
- when "has-same-items" then Array(actual).map { normal(_1) }.tally == Array(expected).map { normal(_1) }.tally
100
- when "greater-than" then actual.is_a?(Numeric) && actual > expected
101
- when "at-least" then actual.is_a?(Numeric) && actual >= expected
102
- when "less-than" then actual.is_a?(Numeric) && actual < expected
103
- when "at-most" then actual.is_a?(Numeric) && actual <= expected
104
- when "matches" then Regexp.new(expected.to_s).match?(actual.to_s)
105
- else raise NotImplementedError, "the Ruby engine cannot judge #{compare} yet"
560
+ when "equal", "not-equal"
561
+ return { reason: "#{compare} compares #{article(a_type)} with #{article(e_type)}" } unless a_type == e_type
562
+
563
+ same = deep_equal?(actual, expected)
564
+ { holds: compare == "equal" ? same : !same }
565
+ when "contains-text", "starts-with-text", "ends-with-text", "matches"
566
+ return { reason: "#{compare} reads two strings, and compares #{article(a_type)} with #{article(e_type)}" } unless a_type == "string" && e_type == "string"
567
+
568
+ if compare != "matches"
569
+ return { reason: "#{compare} has an expected text of only whitespace or nothing, which almost every string holds" } if blank?(expected)
570
+
571
+ return { holds: { "contains-text" => :include?, "starts-with-text" => :start_with?, "ends-with-text" => :end_with? }.then { actual.send(_1[compare], expected) } }
572
+ end
573
+ return { reason: "matches has an empty expected value, which every string holds" } if expected.empty?
574
+
575
+ # Read as JavaScript's RegExp reads it, as the TypeScript engine does.
576
+ pattern = begin
577
+ JsPattern.compile(expected, timeout: PATTERN_TIMEOUT)
578
+ rescue JsPattern::Invalid => e
579
+ return { reason: "matches could not build a regular expression: #{e.message}" }
580
+ end
581
+
582
+ begin
583
+ return { reason: "matches has a pattern that matches the empty string, so every string holds it" } if pattern.match?("")
584
+
585
+ { holds: pattern.match?(JsPattern.units(actual)) }
586
+ rescue Regexp::TimeoutError
587
+ { stopped: "matches ran for more than #{PATTERN_TIMEOUT} seconds, so nukadoko stopped judging it" }
588
+ end
589
+ when "fits-text"
590
+ return { reason: "fits-text reads two strings, and compares #{article(a_type)} with #{article(e_type)}" } unless a_type == "string" && e_type == "string"
591
+ return { reason: "fits-text has an expected text of only whitespace, ... lines, [..], and [..:name], which almost every text holds" } if TextFit.only_stand_ins?(expected)
592
+
593
+ { holds: TextFit.fit(actual, expected)[:fits] }
594
+ when "fits-aria-snapshot"
595
+ return { reason: "fits-aria-snapshot reads two ARIA snapshots as texts, and compares #{article(a_type)} with #{article(e_type)}" } unless a_type == "string" && e_type == "string"
596
+
597
+ judged = AriaSnapshot.judge(actual, expected)
598
+ return { reason: judged[:broken] } if judged[:broken]
599
+ return { stopped: judged[:unjudged] } if judged[:unjudged]
600
+
601
+ { holds: judged[:fits] }
602
+ when "is-a"
603
+ return { reason: "is-a reads the name of a kind as a string, and the expected value is #{article(e_type)}" } unless e_type == "string"
604
+
605
+ kind = value_kind(expected) or return { reason: "is-a names one of the kinds #{VALUE_KINDS.join(", ")}, and the expected value is #{JSON.generate(expected)}" }
606
+ { holds: kind.(actual) }
607
+ when "lacks-field"
608
+ return { reason: "lacks-field reads an object, and the actual value is #{article(a_type)}" } unless a_type == "object"
609
+ return { reason: "lacks-field reads the name of a field as a string, and the expected value is #{article(e_type)}" } unless e_type == "string"
610
+ return { reason: "lacks-field has a blank field name, which almost every object lacks" } if blank?(expected)
611
+
612
+ { holds: !normal(actual).key?(expected) }
613
+ when "has-item"
614
+ return { reason: "has-item reads an array, and the actual value is #{article(a_type)}" } unless a_type == "array"
615
+ return { reason: "has-item looks for #{article(e_type)}, and no item is one" } if !actual.empty? && actual.none? { json_type(_1) == e_type }
616
+
617
+ { holds: actual.any? { deep_equal?(_1, expected) } }
618
+ when "has-same-items"
619
+ return { reason: "has-same-items compares two arrays, and compares #{article(a_type)} with #{article(e_type)}" } unless a_type == "array" && e_type == "array"
620
+
621
+ { holds: same_items?(actual, expected) }
622
+ when "has-fields"
623
+ return { reason: "has-fields compares two objects, and compares #{article(a_type)} with #{article(e_type)}" } unless a_type == "object" && e_type == "object"
624
+
625
+ empty = fieldless_object(expected)
626
+ return { reason: "has-fields has an expected object with no field#{" at #{empty.join(".")}" if empty&.any?}, which every object holds" } if empty
627
+
628
+ { holds: field_misfit(actual, expected).nil? }
629
+ when "greater-than", "at-least", "less-than", "at-most"
630
+ return { reason: "#{compare} compares two numbers, and compares #{article(a_type)} with #{article(e_type)}" } unless a_type == "number" && e_type == "number"
631
+
632
+ { holds: actual.send({ "greater-than" => :>, "at-least" => :>=, "less-than" => :<, "at-most" => :<= }[compare], expected) }
633
+ when "judged-as"
634
+ # The run reads a judged value and compares nothing: whether it
635
+ # meets the quality is a judgment the table reads later
636
+ # (lib/nukadoko/judgments.rb), so it holds the step up nowhere.
637
+ { holds: true, for_judgment: true }
638
+ else
639
+ # A step whose claim names another compare never loads, so this
640
+ # is a fault of nukadoko's, and the claim breaks saying so.
641
+ { reason: "#{compare} is no compare nukadoko knows" }
106
642
  end
107
643
  end
644
+
645
+ #: (String, untyped, untyped) -> bool
646
+ def self.holds?(compare, actual, expected) = compare(compare, actual, expected)[:holds] == true
108
647
  end
109
648
  end
110
649
  end