nukadoko 0.3.0 → 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.
@@ -5,14 +5,39 @@
5
5
  # a value must pass at run time, the RBS a Steep user checks the step body
6
6
  # against, and the Data class the body receives. A type is a symbol for a
7
7
  # scalar, `[:array, type]` for a list, or a nested Schema for an object.
8
+ # `[:checked, type, checks]` is an array item with bounds of its own.
9
+ #
10
+ # Each field method takes the options zod spells as methods: `null: true`
11
+ # (`.nullable()`), `optional: true` (`.optional()`: the key may be absent,
12
+ # and the body reads nil), `default:` (`.default(x)`: an absent key reads
13
+ # as the value), and bounds: `min:` and `max:` (a number's value, a
14
+ # string's length, an array's item count), `positive: true` (> 0) and
15
+ # `negative: true` (< 0).
8
16
  module Nukadoko
9
17
  class Schema
18
+ # The value of `default` when the field declares none.
19
+ NONE = Object.new.freeze
20
+
10
21
  Field = Data.define(
11
22
  :name, #: Symbol
12
23
  :type, #: untyped
13
24
  :description, #: String?
25
+ :optional, #: bool
26
+ :default, #: untyped
27
+ :checks, #: Hash[Symbol, untyped]
14
28
  )
15
29
 
30
+ class Field
31
+ # An absent key passes: the field is optional or has a default.
32
+ #: () -> bool
33
+ def absent_ok? = optional || default?
34
+
35
+ #: () -> bool
36
+ def default? = !NONE.equal?(default)
37
+ end
38
+
39
+ CHECKS = %i[min max positive negative].freeze
40
+
16
41
  #: () ?{ () [self: Schema] -> void } -> Schema
17
42
  def self.build(&block)
18
43
  schema = new
@@ -27,34 +52,56 @@ module Nukadoko
27
52
  @fields = fields
28
53
  end
29
54
 
30
- # `null: true` lets the value be nil as well, as zod's `.nullable()` does.
31
- #: (Symbol, ?String?, ?null: bool) -> void
32
- def string(name, description = nil, null: false) = add(name, :string, description, null)
33
- #: (Symbol, ?String?, ?null: bool) -> void
34
- def boolean(name, description = nil, null: false) = add(name, :boolean, description, null)
35
- #: (Symbol, ?String?, ?null: bool) -> void
36
- def integer(name, description = nil, null: false) = add(name, :integer, description, null)
37
- #: (Symbol, ?String?, ?null: bool) -> void
38
- def number(name, description = nil, null: false) = add(name, :number, description, null)
39
- #: (Symbol, ?String?) -> void
40
- def unknown(name, description = nil) = add(name, :unknown, description)
41
- #: (Symbol, Array[String | Symbol], ?String?, ?null: bool) -> void
42
- def enum(name, values, description = nil, null: false) = add(name, [:enum, values.map(&:to_s)], description, null)
43
- #: (Symbol, ?String?, ?null: bool) -> void
44
- def strings(name, description = nil, null: false) = add(name, [:array, :string], description, null)
45
- #: (Symbol, ?String?, ?null: bool) -> void
46
- def table(name, description = nil, null: false) = add(name, [:array, [:array, :string]], description, null)
47
- #: (Symbol, ?String?, ?null: bool) { () [self: Schema] -> void } -> void
48
- def object(name, description = nil, null: false, &block) = add(name, Schema.build(&block), description, null)
55
+ #: (Symbol, ?String?, **untyped) -> void
56
+ def string(name, description = nil, **options) = add(name, :string, description, **options)
57
+ #: (Symbol, ?String?, **untyped) -> void
58
+ def boolean(name, description = nil, **options) = add(name, :boolean, description, **options)
59
+ #: (Symbol, ?String?, **untyped) -> void
60
+ def integer(name, description = nil, **options) = add(name, :integer, description, **options)
61
+ #: (Symbol, ?String?, **untyped) -> void
62
+ def number(name, description = nil, **options) = add(name, :number, description, **options)
63
+ #: (Symbol, ?String?, **untyped) -> void
64
+ def unknown(name, description = nil, **options) = add(name, :unknown, description, **options)
65
+ #: (Symbol, Array[String | Symbol], ?String?, **untyped) -> void
66
+ def enum(name, values, description = nil, **options) = add(name, [:enum, values.map(&:to_s)], description, **options)
67
+ #: (Symbol, ?String?, **untyped) -> void
68
+ def strings(name, description = nil, **options) = array(name, description, of: :string, **options)
69
+ #: (Symbol, ?String?, **untyped) -> void
70
+ def numbers(name, description = nil, **options) = array(name, description, of: :number, **options)
71
+ #: (Symbol, ?String?, **untyped) -> void
72
+ def integers(name, description = nil, **options) = array(name, description, of: :integer, **options)
73
+ #: (Symbol, ?String?, **untyped) -> void
74
+ def table(name, description = nil, **options) = add(name, [:array, [:array, :string]], description, **options)
75
+ #: (Symbol, ?String?, **untyped) { () [self: Schema] -> void } -> void
76
+ def object(name, description = nil, **options, &block) = add(name, Schema.build(&block), description, **options)
77
+
78
+ # A list: of objects the block declares (`array :todos do string :id end`),
79
+ # or of `of:` (:string, :number, :integer, :boolean, or a Schema).
80
+ # `each:` holds bounds every item meets (`each: { positive: true }`);
81
+ # `min:` and `max:` bound the item count.
82
+ #: (Symbol, ?String?, ?of: untyped, ?each: Hash[Symbol, untyped], **untyped) ?{ () [self: Schema] -> void } -> void
83
+ def array(name, description = nil, of: nil, each: {}, **options, &block)
84
+ item = block ? Schema.build(&block) : of
85
+ raise ArgumentError, "array :#{name} needs of: or a block that declares its items" if item.nil?
86
+
87
+ unknown = each.keys - CHECKS
88
+ raise ArgumentError, "array :#{name} each: takes #{CHECKS.join(", ")}, not #{unknown.join(", ")}" if unknown.any?
89
+
90
+ add(name, [:array, each.empty? ? item : [:checked, item, each]], description, **options)
91
+ end
49
92
 
50
93
  # Reuses a field another step declared, so two contracts that must agree
51
94
  # on one shape are written once: `field :created, AnItemExists.returns[:body]`.
52
95
  #: (Symbol, Field, ?String?) -> void
53
- def field(name, other, description = nil) = add(name, other.type, description || other.description)
96
+ def field(name, other, description = nil) = fields << other.with(name: name.to_sym, description: description || other.description)
54
97
 
55
98
  #: (Symbol | String) -> Field?
56
99
  def [](name) = fields.find { _1.name == name.to_sym }
57
100
 
101
+ # The keys a value must hold: neither optional nor defaulted.
102
+ #: () -> Array[String]
103
+ def required_names = fields.reject { _1.absent_ok? }.map { _1.name.to_s }
104
+
58
105
  #: (Array[String]) -> Schema
59
106
  def without(names) = Schema.new(fields.reject { names.include?(_1.name.to_s) })
60
107
 
@@ -65,7 +112,7 @@ module Nukadoko
65
112
 
66
113
  #: (Hash[String, untyped]) -> untyped
67
114
  def load(hash)
68
- data_class.new(**fields.to_h { [_1.name, hash.fetch(_1.name.to_s)] })
115
+ data_class.new(**fields.to_h { |field| [field.name, hash.fetch(field.name.to_s) { field.default? ? field.default : (field.optional ? nil : hash.fetch(field.name.to_s)) }] })
69
116
  end
70
117
 
71
118
  # Every way `value` departs from the schema, as `path: problem` lines in
@@ -80,8 +127,10 @@ module Nukadoko
80
127
  hash = value.transform_keys(&:to_s)
81
128
  found = fields.flat_map do |field|
82
129
  key = join(path, field.name)
83
- if hash.key?(field.name.to_s) then Schema.type_problems(field.type, hash[field.name.to_s], key)
84
- elsif field.type == :unknown then []
130
+ if hash.key?(field.name.to_s)
131
+ found = Schema.type_problems(field.type, hash[field.name.to_s], key)
132
+ found.empty? ? Schema.check_problems(field.checks, hash[field.name.to_s], key) : found
133
+ elsif field.type == :unknown || field.absent_ok? then []
85
134
  else Schema.type_problems(field.type, MISSING, key)
86
135
  end
87
136
  end
@@ -96,7 +145,15 @@ module Nukadoko
96
145
  #: (Hash[untyped, untyped]) -> Hash[String, untyped]
97
146
  def strip(value)
98
147
  hash = value.transform_keys(&:to_s)
99
- fields.to_h { [_1.name.to_s, Schema.strip_type(_1.type, hash[_1.name.to_s])] }
148
+ kept = {} #: Hash[String, untyped]
149
+ fields.each do |field|
150
+ key = field.name.to_s
151
+ if hash.key?(key) then kept[key] = Schema.strip_type(field.type, hash[key])
152
+ elsif field.default? then kept[key] = field.default
153
+ elsif !field.optional then kept[key] = nil
154
+ end
155
+ end
156
+ kept
100
157
  end
101
158
 
102
159
  #: (untyped, untyped) -> untyped
@@ -104,6 +161,7 @@ module Nukadoko
104
161
  case type
105
162
  in [:nullable, inner] then value.nil? ? nil : strip_type(inner, value)
106
163
  in [:array, item] then value.map { strip_type(item, _1) }
164
+ in [:checked, inner, _] then strip_type(inner, value)
107
165
  in Schema then type.strip(value)
108
166
  else value
109
167
  end
@@ -136,6 +194,7 @@ module Nukadoko
136
194
  case type
137
195
  in [:nullable, inner] then value.nil? ? [] : drops_type(inner, value, at)
138
196
  in [:array, item] then value.is_a?(Array) ? value.each_with_index.flat_map { drops_type(item, _1, [*at, _2.to_s]) } : []
197
+ in [:checked, inner, _] then drops_type(inner, value, at)
139
198
  in Schema then type.drops(value, at)
140
199
  else []
141
200
  end
@@ -146,6 +205,7 @@ module Nukadoko
146
205
  case type
147
206
  in [:nullable, inner] then value.nil? ? [] : dropped_type(inner, value, path)
148
207
  in [:array, item] then value.each_with_index.flat_map { dropped_type(item, _1, "#{path}[#{_2}]") }
208
+ in [:checked, inner, _] then dropped_type(inner, value, path)
149
209
  in Schema then type.dropped(value, path)
150
210
  else []
151
211
  end
@@ -189,11 +249,39 @@ module Nukadoko
189
249
  return ["#{path}: #{invalid("array", value)}"] unless value.is_a?(Array)
190
250
 
191
251
  return value.each_with_index.flat_map { |v, i| type_problems(item, v, "#{path}.#{i}") }
252
+ in [:checked, inner, checks]
253
+ found = type_problems(inner, value, path)
254
+ return found.empty? ? check_problems(checks, value, path) : found
192
255
  in Schema then return value.is_a?(Hash) ? type.problems(value, path) : ["#{path}: #{invalid("object", value)}"]
193
256
  end
194
257
  problem ? ["#{path}: #{problem}"] : []
195
258
  end
196
259
 
260
+ # A bound zod reports in its own words, once the type passed: a number's
261
+ # value, a string's length in UTF-16 units, an array's item count.
262
+ #: (Hash[Symbol, untyped], untyped, String) -> Array[String]
263
+ def self.check_problems(checks, value, path)
264
+ return [] if checks.empty? || value.nil?
265
+
266
+ size, what, unit = case value
267
+ when String then [value.encode("UTF-16LE").bytesize / 2, "string", " characters"]
268
+ when Array then [value.size, "array", " items"]
269
+ when Numeric then [value, "number", ""]
270
+ else return []
271
+ end
272
+ relation = what == "number" ? "be" : "have"
273
+ bounds = [] #: Array[String]
274
+ bounds << "Too small: expected #{what} to #{relation} >0#{unit}" if checks[:positive] && size <= 0
275
+ bounds << "Too small: expected #{what} to #{relation} >=#{js(checks[:min])}#{unit}" if checks.key?(:min) && size < checks[:min]
276
+ bounds << "Too big: expected #{what} to #{relation} <0#{unit}" if checks[:negative] && size >= 0
277
+ bounds << "Too big: expected #{what} to #{relation} <=#{js(checks[:max])}#{unit}" if checks.key?(:max) && size > checks[:max]
278
+ bounds.map { "#{path}: #{_1}" }
279
+ end
280
+
281
+ # A number as JavaScript prints it: 2.0 is 2.
282
+ #: (Numeric) -> String
283
+ def self.js(number) = number.is_a?(Float) && number == number.floor && number.finite? ? number.to_i.to_s : number.to_s
284
+
197
285
  # zod's int: a finite whole number within Number.MAX_SAFE_INTEGER.
198
286
  #: (untyped) -> String?
199
287
  def self.integer_problem(value)
@@ -209,32 +297,66 @@ module Nukadoko
209
297
  # side (`returns`), where zod drops the keys it does not declare.
210
298
  #: (?root: bool, ?output: bool) -> Hash[Symbol, untyped]
211
299
  def json_schema(root: true, output: false)
212
- schema = { type: "object", properties: fields.to_h { [_1.name, Schema.json_type(_1.type, output).merge(_1.description ? { description: _1.description } : {})] } } #: Hash[Symbol, untyped]
213
- schema[:required] = fields.map(&:name) if fields.any?
300
+ properties = fields.to_h do |field|
301
+ type = Schema.json_type(field.type, output, field.checks)
302
+ type = { default: field.default, **type } if field.default?
303
+ [field.name, type.merge(field.description ? { description: field.description } : {})]
304
+ end
305
+ schema = { type: "object", properties: properties } #: Hash[Symbol, untyped]
306
+ # zod's output side always holds a defaulted key; the input may leave it out.
307
+ required = fields.reject { _1.optional || (_1.default? && !output) }.map(&:name)
308
+ schema[:required] = required if required.any?
214
309
  return { "$schema": "https://json-schema.org/draft/2020-12/schema", **schema, additionalProperties: false } if root
215
310
 
216
311
  output ? schema.merge(additionalProperties: false) : schema
217
312
  end
218
313
 
219
- #: (untyped, ?bool) -> Hash[Symbol, untyped]
220
- def self.json_type(type, output = false)
314
+ # As z.toJSONSchema writes it, bounds included and in its key order.
315
+ #: (untyped, ?bool, ?Hash[Symbol, untyped]) -> Hash[Symbol, untyped]
316
+ def self.json_type(type, output = false, checks = {})
221
317
  case type
222
- in :string then { type: "string" }
318
+ in :string then { type: "string", **length_bounds(checks, :minLength, :maxLength) }
223
319
  in :boolean then { type: "boolean" }
224
- in :integer then { type: "integer" }
225
- in :number then { type: "number" }
320
+ in :integer
321
+ { type: "integer", **number_bounds(checks, -SAFE, SAFE) }
322
+ in :number then { type: "number", **number_bounds(checks, nil, nil) }
226
323
  in :unknown then {}
227
- in [:nullable, inner] then { anyOf: [json_type(inner, output), { type: "null" }] }
324
+ in [:nullable, inner] then { anyOf: [json_type(inner, output, checks), { type: "null" }] }
228
325
  in [:enum, values] then { type: "string", enum: values }
229
- in [:array, item] then { type: "array", items: json_type(item, output) }
326
+ in [:array, item] then { **length_bounds(checks, :minItems, :maxItems), type: "array", items: json_type(item, output) }
327
+ in [:checked, inner, own] then json_type(inner, output, own)
230
328
  in Schema then type.json_schema(root: false, output: output)
231
329
  end
232
330
  end
233
331
 
332
+ #: (Hash[Symbol, untyped], Integer?, Integer?) -> Hash[Symbol, untyped]
333
+ def self.number_bounds(checks, floor, ceiling)
334
+ low = if checks[:positive] then { exclusiveMinimum: 0 }
335
+ elsif checks.key?(:min) then { minimum: checks[:min] }
336
+ elsif floor then { minimum: floor }
337
+ else {}
338
+ end
339
+ high = if checks[:negative] then { exclusiveMaximum: 0 }
340
+ elsif checks.key?(:max) then { maximum: checks[:max] }
341
+ elsif ceiling then { maximum: ceiling }
342
+ else {}
343
+ end
344
+ { **low, **high }
345
+ end
346
+
347
+ #: (Hash[Symbol, untyped], Symbol, Symbol) -> Hash[Symbol, untyped]
348
+ def self.length_bounds(checks, low, high)
349
+ { **(checks.key?(:min) ? { low => checks[:min] } : {}), **(checks.key?(:max) ? { high => checks[:max] } : {}) }
350
+ end
351
+
234
352
  #: () -> Array[String]
235
- def rbs_fields = fields.map { "attr_reader #{_1.name}: #{Schema.rbs_type(_1.type)}" }
353
+ def rbs_fields = fields.map { "attr_reader #{_1.name}: #{Schema.rbs_field(_1)}" }
236
354
  #: () -> String
237
- def rbs_record = "{ #{fields.map { "#{_1.name}: #{Schema.rbs_type(_1.type)}" }.join(", ")} }"
355
+ def rbs_record = "{ #{fields.map { "#{_1.name}: #{Schema.rbs_field(_1)}" }.join(", ")} }"
356
+
357
+ # An optional key reads as nil when it is absent.
358
+ #: (Field) -> String
359
+ def self.rbs_field(field) = field.optional && !field.default? ? "(#{rbs_type(field.type)})?" : rbs_type(field.type)
238
360
 
239
361
  #: (untyped) -> String
240
362
  def self.rbs_type(type)
@@ -247,14 +369,20 @@ module Nukadoko
247
369
  in [:nullable, inner] then "(#{rbs_type(inner)})?"
248
370
  in [:enum, values] then values.map(&:inspect).join(" | ")
249
371
  in [:array, item] then "Array[#{rbs_type(item)}]"
372
+ in [:checked, inner, _] then rbs_type(inner)
250
373
  in Schema then type.fields.empty? ? "Hash[Symbol, untyped]" : type.rbs_record
251
374
  end
252
375
  end
253
376
 
254
377
  private
255
378
 
256
- #: (Symbol, untyped, String?, ?bool) -> void
257
- def add(name, type, description, null = false) = fields << Field.new(name.to_sym, null ? [:nullable, type] : type, description)
379
+ #: (Symbol, untyped, String?, ?null: bool, ?optional: bool, ?default: untyped, **untyped) -> void
380
+ def add(name, type, description, null: false, optional: false, default: NONE, **checks)
381
+ unknown = checks.keys - CHECKS
382
+ raise ArgumentError, ":#{name} takes null:, optional:, default:, #{CHECKS.map { "#{_1}:" }.join(", ")}, not #{unknown.map { "#{_1}:" }.join(", ")}" if unknown.any?
383
+
384
+ fields << Field.new(name: name.to_sym, type: null ? [:nullable, type] : type, description: description, optional: optional, default: default, checks: checks)
385
+ end
258
386
  #: (String?, Symbol | String) -> String
259
387
  def join(path, name) = path ? "#{path}.#{name}" : name.to_s
260
388
  end
@@ -0,0 +1,225 @@
1
+ # frozen_string_literal: true
2
+ # rbs_inline: enabled
3
+
4
+ require "time"
5
+ require "timeout"
6
+
7
+ # The fixtures a step body uses to say where it went, to wait for a state
8
+ # that is not there yet, and to keep evidence only it can produce. The
9
+ # TypeScript engine gives the same three on ctx. Each one fills a list the
10
+ # engine writes into the step record, also when the step raises, because a
11
+ # failed step is the one whose record a reader opens.
12
+ module Nukadoko
13
+ # poll gave up: the budget ended before the block returned a value.
14
+ class PollTimeoutError < StandardError
15
+ attr_reader :timeout_ms #: Numeric
16
+ attr_reader :description #: String?
17
+
18
+ #: (Numeric, String?) -> void
19
+ def initialize(timeout_ms, description)
20
+ @timeout_ms = timeout_ms
21
+ @description = description
22
+ super("poll timed out after #{timeout_ms}ms#{" while waiting for #{description}" if description}")
23
+ end
24
+ end
25
+
26
+ # A timeout or interval that cannot be a budget. Raised before the first
27
+ # attempt, so it is not in the record: there is no attempt to count.
28
+ class InvalidPollOptionsError < ArgumentError; end
29
+
30
+ # An evidence name that would land outside the step's directory.
31
+ class InvalidEvidenceNameError < ArgumentError; end
32
+
33
+ # An evidence name the engine itself writes into the step's directory.
34
+ class ReservedEvidenceNameError < ArgumentError; end
35
+
36
+ # A pageAs name that cannot be part of a file name.
37
+ class InvalidContextNameError < ArgumentError; end
38
+
39
+ # A pageAs call that asks an open context for options it was not made with.
40
+ class ContextOptionsConflictError < ArgumentError; end
41
+
42
+ module Engine
43
+ #: () -> String
44
+ def self.now_iso = Time.now.utc.iso8601(3)
45
+
46
+ # `section.("label")` marks that the body reached a stage. It is a bare
47
+ # marker, not a block wrapper, so nesting and an early return need no
48
+ # meaning: the record answers where the body stopped.
49
+ class Sections
50
+ attr_reader :entries #: Array[Hash[Symbol, String]]
51
+
52
+ #: () -> void
53
+ def initialize
54
+ @entries = []
55
+ end
56
+
57
+ #: (String | Symbol) -> nil
58
+ def call(label)
59
+ @entries << { label: label.to_s, at: Engine.now_iso }
60
+ nil
61
+ end
62
+ end
63
+
64
+ # `poll.(description:, timeout:, interval:) { value or nil }` calls the
65
+ # block until it gives a value other than nil. The budget holds the
66
+ # attempt in flight too, so a value that arrives after it is not
67
+ # returned. Every finished call is kept, so the record tells a wait that
68
+ # did nothing from one that took seconds.
69
+ class Polls
70
+ DEFAULT_TIMEOUT_MS = 30_000
71
+ DEFAULT_INTERVAL_MS = 500
72
+ # The longest timer Node accepts, kept so both engines refuse the same values.
73
+ MAX_MS = 2_147_483_647
74
+
75
+ # An Exception, not a StandardError, so a block that rescues its own
76
+ # errors cannot swallow the end of its budget.
77
+ class AttemptOver < Exception; end
78
+
79
+ attr_reader :entries #: Array[Hash[Symbol, untyped]]
80
+
81
+ #: () -> void
82
+ def initialize
83
+ @entries = []
84
+ end
85
+
86
+ #: [T] (?description: String?, ?timeout: Numeric?, ?interval: Numeric?) { () -> T? } -> T
87
+ def call(description: nil, timeout: nil, interval: nil, &block)
88
+ raise ArgumentError, "poll needs a block that returns nil until the state exists" unless block
89
+
90
+ timeout_ms = timeout || DEFAULT_TIMEOUT_MS
91
+ seconds = budget(timeout_ms, "timeout")
92
+ pause = budget(interval || DEFAULT_INTERVAL_MS, "interval")
93
+ started = monotonic
94
+ at = Engine.now_iso
95
+ attempts = 0
96
+ outcome = "resolved"
97
+ over = lambda do
98
+ outcome = "timed_out"
99
+ raise PollTimeoutError.new(timeout_ms, description)
100
+ end
101
+ begin
102
+ loop do
103
+ left = seconds - (monotonic - started)
104
+ over.() unless left.positive?
105
+ attempts += 1
106
+ value = begin
107
+ Timeout.timeout(left, AttemptOver) { block.call } #: untyped
108
+ rescue AttemptOver
109
+ over.()
110
+ rescue StandardError
111
+ outcome = "failed"
112
+ raise
113
+ end
114
+ return value unless value.nil?
115
+
116
+ left = seconds - (monotonic - started)
117
+ over.() if left < pause
118
+ sleep(pause)
119
+ end
120
+ ensure
121
+ @entries << { description: description, at: at, attempts: attempts,
122
+ waited_ms: ((monotonic - started) * 1000).round, outcome: outcome }.compact
123
+ end
124
+ end
125
+
126
+ private
127
+
128
+ # The budget in seconds, from milliseconds.
129
+ #: (untyped, String) -> Float
130
+ def budget(value, option)
131
+ # A String or a Complex is not a number of milliseconds, so it reads as NaN.
132
+ number = value.is_a?(Numeric) && value.real? ? (_ = value).to_f : Float::NAN #: Float
133
+ return number / 1000 if number.finite? && number.positive? && number <= MAX_MS
134
+
135
+ raise InvalidPollOptionsError, "poll #{option} must be a finite number of milliseconds greater than 0 and " \
136
+ "at most #{MAX_MS} (got #{value.inspect})"
137
+ end
138
+
139
+ #: () -> Float
140
+ def monotonic = Process.clock_gettime(Process::CLOCK_MONOTONIC)
141
+ end
142
+
143
+ # `evidence.attach(name, body)` writes a file into the step's own
144
+ # directory, and `evidence.path(name)` gives a path there without
145
+ # writing. A name used twice keeps both files. A name that differs only
146
+ # by case counts as the same, since a case-insensitive volume would put
147
+ # the two on one file.
148
+ class Evidence
149
+ # The files and directories the engine writes into the same directory.
150
+ HARNESS = %w[record.json final.png trace.zip requests.zip http.jsonl mcp.jsonl websocket.jsonl
151
+ program-log.txt program-log-late.txt events.jsonl events-late.jsonl events-read.jsonl judged].freeze
152
+ PROCESS_FILE = /\Aprocess-[1-9][0-9]*\.((stdout|stderr|stdin)\.txt|json)\z/
153
+ NAMED_FILE = /\A(?:trace\.[a-z0-9][a-z0-9-]{0,63}\.zip|final\.[a-z0-9][a-z0-9-]{0,63}\.png)\z/
154
+ MAX_ATTACHMENTS = 100
155
+
156
+ #: (String, ?reserved: Array[String]) -> void
157
+ def initialize(dir, reserved: [])
158
+ @dir = dir
159
+ @reserved = reserved
160
+ @used = (HARNESS + reserved).to_h { [_1.downcase, true] }
161
+ @attached = []
162
+ @paths = []
163
+ end
164
+
165
+ #: (String | Symbol, String) -> nil
166
+ def attach(name, body)
167
+ file = allocate(name.to_s)
168
+ FileUtils.mkdir_p(@dir)
169
+ File.binwrite(File.join(@dir, file), body)
170
+ @attached << { name: name.to_s, file: file, at: Engine.now_iso }
171
+ nil
172
+ end
173
+
174
+ #: (String | Symbol) -> String
175
+ def path(name)
176
+ file = allocate(name.to_s)
177
+ FileUtils.mkdir_p(@dir)
178
+ @paths << { name: name.to_s, file: file }
179
+ File.join(@dir, file)
180
+ end
181
+
182
+ # What the step left: its attachments, and each path it wrote to, by
183
+ # time, at most MAX_ATTACHMENTS of them, with the whole count when
184
+ # there were more.
185
+ #: () -> [Array[Hash[Symbol, String]], Integer?]
186
+ def snapshot
187
+ written = @paths.filter_map do |entry|
188
+ full = File.join(@dir, entry[:file])
189
+ { **entry, at: File.mtime(full).utc.iso8601(3) } if File.exist?(full)
190
+ end
191
+ # Ruby's sort is not stable, and two files can share a millisecond.
192
+ all = (@attached + written).each_with_index.sort_by { |entry, index| [entry[:at], index] }.map(&:first)
193
+ [all.first(MAX_ATTACHMENTS), all.size > MAX_ATTACHMENTS ? all.size : nil]
194
+ end
195
+
196
+ private
197
+
198
+ #: (String) -> String
199
+ def allocate(name)
200
+ if name.empty? || %w[. ..].include?(name) || name.match?(%r{[/\\]})
201
+ raise InvalidEvidenceNameError, %(evidence name #{name.inspect} is not allowed: it must not contain "/" or "\\", ) +
202
+ %(and must not be ".", "..", or empty. Every attachment and path is written inside this step's own evidence directory.)
203
+ end
204
+ key = name.downcase
205
+ if (HARNESS + @reserved).any? { _1.downcase == key } || key.match?(PROCESS_FILE) || key.match?(NAMED_FILE)
206
+ raise ReservedEvidenceNameError, "evidence name #{name.inspect} is reserved for a file the engine writes itself " \
207
+ "(record.json, final.png, trace.zip, http.jsonl, the program's log lines, the trace.<name>.zip and " \
208
+ "final.<name>.png files of a pageAs context, and the process-<n> files of a run_command). " \
209
+ "A name that differs only by case is reserved too. Choose a different name."
210
+ end
211
+ unless @used.key?(key)
212
+ @used[key] = true
213
+ return name
214
+ end
215
+ dot = name.rindex(".")
216
+ stem, ext = dot&.positive? ? [name[0...dot].to_s, name[dot..].to_s] : [name, ""]
217
+ counter = 2
218
+ counter += 1 while @used.key?("#{stem}-#{counter}#{ext}".downcase)
219
+ candidate = "#{stem}-#{counter}#{ext}"
220
+ @used[candidate.downcase] = true
221
+ candidate
222
+ end
223
+ end
224
+ end
225
+ end
@@ -16,10 +16,12 @@ require "zlib"
16
16
  module Nukadoko
17
17
  module Engine
18
18
  module TraceActions
19
- # Version 8 as the TypeScript engine measured it, and version 10 as
19
+ # Version 8 as the TypeScript engine measured it, version 9 as
20
+ # Playwright 1.63.0 writes it (the same fields and the same actions as
21
+ # version 8), and version 10 as
20
22
  # Playwright 1.65.1 writes it for the Ruby client: the same `before`
21
23
  # and `after` fields, with a number for `callId`.
22
- KNOWN_VERSIONS = [8, 10].freeze
24
+ KNOWN_VERSIONS = [8, 9, 10].freeze
23
25
  MAX_ACTIONS = 100
24
26
  INTERNAL_WAIT = "__waitInfo__"
25
27
  JUDGED_VIEW_GROUP = "nukadoko: view of the judged reading"
@@ -2,5 +2,5 @@
2
2
  # rbs_inline: enabled
3
3
 
4
4
  module Nukadoko
5
- VERSION = "0.3.0"
5
+ VERSION = "0.5.0"
6
6
  end
@@ -6,7 +6,7 @@
6
6
  # engine's vocabulary without opening a file.
7
7
  module Nukadoko
8
8
  module Vocabulary
9
- BROWSER = %i[page context pageAs].freeze
9
+ BROWSER = %i[page context pageAs page_as].freeze
10
10
 
11
11
  #: (singleton(Step), String) -> Hash[Symbol, untyped]
12
12
  def self.entry(step, project)
data/lib/nukadoko.rb CHANGED
@@ -4,6 +4,7 @@
4
4
  require "json"
5
5
  require_relative "nukadoko/version"
6
6
  require_relative "nukadoko/project_files"
7
+ require_relative "nukadoko/error_frames"
7
8
  require_relative "nukadoko/spaces"
8
9
  require_relative "nukadoko/js_pattern"
9
10
  require_relative "nukadoko/schema"
@@ -29,6 +30,7 @@ require_relative "nukadoko/claim_check_run"
29
30
  require_relative "nukadoko/check"
30
31
  require_relative "nukadoko/trace"
31
32
  require_relative "nukadoko/trace_actions"
33
+ require_relative "nukadoko/step_fixtures"
32
34
  require_relative "nukadoko/fixtures"
33
35
  require_relative "nukadoko/http_recording"
34
36
  require_relative "nukadoko/secrets"
@@ -42,6 +44,7 @@ require_relative "nukadoko/definition"
42
44
  require_relative "nukadoko/vocabulary"
43
45
  require_relative "nukadoko/program"
44
46
  require_relative "nukadoko/project_program"
47
+ require_relative "nukadoko/parameter_types"
45
48
  require_relative "nukadoko/table"
46
49
  require_relative "nukadoko/order"
47
50
  require_relative "nukadoko/run_record"
@@ -76,6 +79,7 @@ module Nukadoko
76
79
  config = File.join(root, Engine::CONFIG)
77
80
  @legacy_program = nil
78
81
  load config if File.exist?(config)
82
+ Engine::ParameterTypes.read(config_options[:parameterTypes])
79
83
  @program_options = Engine::ProjectProgram.read(root)
80
84
  end
81
85