nukadoko 0.4.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.
data/lib/nukadoko/run.rb CHANGED
@@ -718,20 +718,22 @@ module Nukadoko
718
718
  @browser&.step = { step_record_id: record[:step_record_id], step: record[:step], line: at_line }
719
719
  @browser&.begin_step
720
720
  Trace.within(boundary) do
721
- fixtures, finish = build_fixtures(step, dir, log, world, record)
721
+ fixtures, finish = build_fixtures(step, dir, log, world, record, results)
722
722
  HttpRecording.collect(log) do
723
723
  Processes.collect(processes) { RedactedOutput.around(secrets) { body(step, fixtures, args, [then_line, at_line], record, results, origins, texts) } }
724
724
  end
725
725
  end
726
- record[:page_view] = @browser.judged(dir, record[:step_record_id], aria_in_claims: step.claims.to_a.any? { !_1[:each] && _1[:compare] == "fits-aria-snapshot" }) if step.claims && fixtures[:page] && record[:observation] != "unobserved"
726
+ record[:page_view] = @browser.judged(dir, record[:step_record_id], aria_in_claims: step.claims.to_a.any? { !_1[:each] && _1[:compare] == "fits-aria-snapshot" }) if step.claims && (fixtures[:page] || fixtures[:context]) && record[:observation] != "unobserved"
727
727
  record[:status] ||= "passed"
728
728
  rescue StandardError => e
729
729
  record.merge!(status: "failed", outcome: :broke, error: e.message)
730
730
  record[:error_kind] ||= "step_error"
731
+ record[:error_at] = ErrorFrames.of(e, @project).map { redact(_1) } if record[:error_kind] == "step_error"
731
732
  ensure
732
733
  @browser&.step = nil
733
734
  finish&.call
734
- log.concat(fixtures[:request].log) if fixtures[:request]
735
+ log.concat(@request_log.log) if @request_log
736
+ @request_log = nil
735
737
  # A world at a URL has a log nukadoko does not read.
736
738
  record[:program_log] = @program_log&.slice(dir, boundary) if boundary
737
739
  record[:finished_at] = Time.now.utc.iso8601(3)
@@ -753,6 +755,17 @@ module Nukadoko
753
755
  record[:scratch] = made if made.any?
754
756
  end
755
757
  record[:calls] = fixtures[:call].calls if fixtures[:call]&.calls&.any?
758
+ # The step's own marks, waits, and files, as plain values for the record.
759
+ sections = record.delete(:section_log)&.entries
760
+ record[:sections] = sections if sections&.any?
761
+ polls = record.delete(:poll_log)&.entries
762
+ record[:polls] = polls if polls&.any?
763
+ if (evidence = record.delete(:evidence_log))
764
+ attachments, total = evidence.snapshot
765
+ record[:attachments] = attachments if attachments.any?
766
+ record[:attachments_total] = total if total
767
+ end
768
+ record.delete(:required_env) if record[:required_env] && record[:required_env].empty?
756
769
  # A page's own traffic is in http.jsonl and the trace, not counted as the step's.
757
770
  record[:http_count] = log.count { _1[:via] != "page" }
758
771
  File.write(File.join(dir, "http.jsonl"), "#{log.map { JSON.generate(secrets.redact(_1)) }.join("\n")}\n") if log.any?
@@ -809,7 +822,7 @@ module Nukadoko
809
822
  received: observes ? step.inputs.fields.map { _1.name.to_s } : [], transformed: transformed_fills(step, origins))
810
823
  end
811
824
  # A reading with a page open is timed, so the record can say what the page had received by then.
812
- read = (plain = read; -> { @browser.reading(&plain) }) if own[:page]
825
+ read = (plain = read; -> { @browser.reading(&plain) }) if own[:page] || own[:context]
813
826
  observed = begin
814
827
  step.poll ? Poll.new(step.poll, step.claims, args, sides).call(record, &read) : read.()
815
828
  rescue StandardError => e
@@ -915,6 +928,8 @@ module Nukadoko
915
928
  used = []
916
929
  step.from.each do |key, sources|
917
930
  cls, value, at_line, record_id = results.reverse_each.find { |c, _| sources.any? { _1.first == c } }
931
+ # An optional key stays absent when no producer ran, as zod leaves it.
932
+ next if !cls && step.args[key]&.absent_ok?
918
933
  unless cls
919
934
  record[:error_kind] = "binding_invalid"
920
935
  raise ArgumentError, %(no earlier step in this scenario gave "#{key}")
@@ -927,7 +942,7 @@ module Nukadoko
927
942
  used << { step: cls.step_name, record: "steps/#{record_id}", result: value } unless used.any? { _1[:record] == "steps/#{record_id}" }
928
943
  end
929
944
  record[:used] = used
930
- open = step.args.fields.map { _1.name.to_s } - args.keys
945
+ open = step.args.required_names - args.keys
931
946
  attachment = line.table || line.doc_string
932
947
  if attachment && open.any?
933
948
  args[open.first] = attachment
@@ -943,7 +958,7 @@ module Nukadoko
943
958
  # for the one key it fills.
944
959
  #: (singleton(Step), Hash[String, untyped], PickleStep) -> Hash[String, String]
945
960
  def attachment_texts(step, captures, line)
946
- open = step.args.fields.map { _1.name.to_s } - captures.keys - step.from.keys
961
+ open = step.args.required_names - captures.keys - step.from.keys
947
962
  return {} if open.empty?
948
963
  return { open.first => line.doc_string } if line.doc_string
949
964
  return { open.first => line.table.map { |row| "| #{row.join(" | ")} |" }.join("\n") } if line.table
@@ -956,17 +971,20 @@ module Nukadoko
956
971
 
957
972
  # A project fixture is built the first time a step of its scope names
958
973
  # it, directly or through another fixture, and kept until the scope ends.
959
- #: (Symbol, World, Array[Symbol]) -> untyped
960
- def project_fixture(name, world, chain)
974
+ #: (Symbol, World, Array[Symbol], ?(^(Symbol) -> untyped)?) -> untyped
975
+ def project_fixture(name, world, chain, builtin = nil)
961
976
  fixture = Nukadoko.project_fixtures[name] or raise ArgumentError, "the Ruby engine has no fixture #{name} yet"
962
977
  raise ArgumentError, "fixtures depend on each other in a cycle: #{[*chain, name].join(" -> ")}" if chain.include?(name)
963
978
 
964
979
  cache = fixture.scope == :process ? @process_fixtures : @scenario_fixtures
980
+ # A fixture that names itself wraps the builtin of that name, as a
981
+ # page override in the TypeScript config does, so it is no cycle.
965
982
  deps = fixture.dependencies.to_h do |dep|
966
- case dep
967
- when :baseURL then [dep, world.base_url]
968
- when :scratch then [dep, @scratch]
969
- else [dep, project_fixture(dep, world, [*chain, name])]
983
+ if BUILTINS.include?(dep) && (dep == name || !Nukadoko.project_fixtures.key?(dep))
984
+ raise ArgumentError, %(fixture "#{name}" names "#{dep}", which only a step's own fixtures can give) unless builtin
985
+
986
+ [dep, builtin.(dep)]
987
+ else [dep, project_fixture(dep, world, [*chain, name], builtin)]
970
988
  end
971
989
  end
972
990
  return cache[name].tap { note_fixture(name, fixture.scope, nil, nil) } if cache.key?(name)
@@ -1013,29 +1031,102 @@ module Nukadoko
1013
1031
  raise Refusal.new("env-file-unreadable", e.message)
1014
1032
  end
1015
1033
 
1016
- #: (singleton(Step), String, Array[Hash[Symbol, untyped]], World, Hash[Symbol, untyped]) -> [Hash[Symbol, untyped], (^() -> void)?]
1017
- def build_fixtures(step, dir, log, world, record)
1018
- finish = nil
1034
+ BUILTINS = %i[request baseURL env requireEnv scratch page context pageAs section poll evidence resultOf
1035
+ base_url require_env page_as result_of].freeze
1036
+
1037
+ # The snake_case spelling of each builtin a Ruby step may name instead,
1038
+ # so a body passes RuboCop's naming cops. Both reach the same fixture.
1039
+ ALIASES = { base_url: :baseURL, require_env: :requireEnv, page_as: :pageAs, result_of: :resultOf }.freeze
1040
+
1041
+ #: (singleton(Step), String, Array[Hash[Symbol, untyped]], World, Hash[Symbol, untyped], Array[untyped]) -> [Hash[Symbol, untyped], (^() -> void)?]
1042
+ def build_fixtures(step, dir, log, world, record, results)
1043
+ finishes = [] #: Array[^() -> void]
1019
1044
  @fixture_usage = []
1020
- fixtures = (step.bag - [:call]).to_h do |name|
1021
- case name
1022
- when :request then [name, Request.new(world.base_url)]
1023
- when :baseURL then [name, world.base_url]
1024
- when :env then [name, step_env(world)]
1025
- when :requireEnv then [name, ->(key) { step_env(world).fetch(key.to_s) { raise %(requireEnv("#{key}"): the world's env has no #{key}) } }]
1026
- when :scratch then [name, @scratch]
1027
- when :page
1028
- page, finish = @browser.page_for(dir, log)
1029
- [name, page]
1030
- else [name, project_fixture(name, world, [])]
1031
- end
1045
+ built = {} #: Hash[Symbol, untyped]
1046
+ builtin = lambda do |name|
1047
+ name = ALIASES.fetch(name, name)
1048
+ next built[name] if built.key?(name)
1049
+
1050
+ built[name] =
1051
+ case name
1052
+ when :request then Request.new(world.base_url)
1053
+ when :baseURL then world.base_url
1054
+ when :env then step_env(world)
1055
+ when :requireEnv then require_env(world, record)
1056
+ when :scratch then @scratch
1057
+ when :page
1058
+ page, finish = @browser.page_for(dir, log)
1059
+ finishes << finish
1060
+ page
1061
+ when :context then builtin.(:page).context
1062
+ when :pageAs
1063
+ finishes << lambda do
1064
+ traces = @browser.finish_named
1065
+ record[:named_traces] = traces if traces.any?
1066
+ end
1067
+ ->(as, options = nil) { @browser.page_as(as, options, dir, log) }
1068
+ when :section then (record[:section_log] = Sections.new)
1069
+ when :poll then (record[:poll_log] = Polls.new)
1070
+ when :evidence then (record[:evidence_log] = Evidence.new(dir))
1071
+ when :resultOf then result_of(step, results, record)
1072
+ end
1032
1073
  end
1074
+ # A project fixture of a builtin's name replaces it for the step.
1075
+ fixtures = {} #: Hash[Symbol, untyped]
1076
+ (step.bag - [:call]).each do |name|
1077
+ fixtures[name] = Nukadoko.project_fixtures.key?(name) || !BUILTINS.include?(name) ? project_fixture(name, world, [], builtin) : builtin.(name)
1078
+ end
1079
+ # Requests a wrapped request fixture sends are the builtin's, so the record keeps them.
1080
+ @request_log = built[:request]
1033
1081
  fixtures[:call] = Caller.new(step, fixtures) if step.fixtures.include?(:call)
1034
1082
  record[:fixtures] = @fixture_usage if @fixture_usage.any?
1035
1083
  @fixture_usage = nil
1084
+ finish = finishes.empty? ? nil : -> { finishes.reverse_each(&:call) }
1036
1085
  [fixtures, finish]
1037
1086
  end
1038
1087
 
1088
+ # requireEnv: the env fixture's value for a key, or a raise that names
1089
+ # only the key. An empty value counts as missing, since a step that
1090
+ # requires it is broken either way. Every name asked for is kept, in
1091
+ # the order asked, whether the read found a value or not.
1092
+ #: (World, Hash[Symbol, untyped]) -> ^(String | Symbol) -> String
1093
+ def require_env(world, record)
1094
+ asked = record[:required_env] = [] #: Array[String]
1095
+ lambda do |key|
1096
+ key = key.to_s
1097
+ asked << key unless asked.include?(key)
1098
+ value = step_env(world)[key]
1099
+ raise %(requireEnv("#{key}") found no value: set "#{key}" in one of the environment's env files, or in the world's env) if value.nil? || value.empty?
1100
+
1101
+ value
1102
+ end
1103
+ end
1104
+
1105
+ # resultOf: the result an earlier step of the scenario last gave when
1106
+ # it passed, or nil when it has not. A claim step takes an earlier
1107
+ # value through `from` alone, so its record names where the value
1108
+ # came from. A read that found a result names its step in `used`, as
1109
+ # a from key does.
1110
+ #: (singleton(Step), Array[untyped], Hash[Symbol, untyped]) -> ^(untyped) -> untyped
1111
+ def result_of(step, results, record)
1112
+ lambda do |source|
1113
+ unless source.is_a?(Class) && source < Step && @steps.include?(source)
1114
+ raise ArgumentError, "resultOf(#{source.inspect}): that is not a step this project registered, so no step record could hold its result"
1115
+ end
1116
+ if step.claims
1117
+ raise ArgumentError, %(Step "#{step.step_name}" declares claims, so it takes an earlier step's value through "from" alone, ) +
1118
+ %(which names where the value came from; resultOf(#{source.step_name}) is not available in a claim step.)
1119
+ end
1120
+
1121
+ _, value, _, record_id = results.reverse_each.find { |cls, *| cls == source }
1122
+ next nil unless value
1123
+
1124
+ used = (record[:used] ||= []) #: Array[Hash[Symbol, untyped]]
1125
+ used << { step: source.step_name, record: "steps/#{record_id}", result: value } unless used.any? { _1[:record] == "steps/#{record_id}" }
1126
+ (schema = source.returns) ? schema.load(value) : value
1127
+ end
1128
+ end
1129
+
1039
1130
  #: (String) -> String
1040
1131
  def new_id(kind) = "#{kind}-#{Time.now.utc.strftime("%Y%m%d-%H%M%S")}-#{SecureRandom.alphanumeric(4).downcase}"
1041
1132
 
@@ -25,7 +25,7 @@ module Nukadoko
25
25
  def step_file(record, environment:, world_name:, run_id:, scenario_record_id:, evidence_dir:)
26
26
  passed = record[:status] == "passed"
27
27
  outcome = if passed then { result: record[:result] || {}, returns_dropped: record[:returns_dropped] }.compact
28
- else { error: { message: record[:error], kind: record[:error_kind] } }
28
+ else { error: { message: record[:error], kind: record[:error_kind], **(record[:error_at]&.any? ? { at: record[:error_at] } : {}) } }
29
29
  end
30
30
  processes = record[:processes]
31
31
  used = (record[:used] || []).map do |entry|
@@ -35,12 +35,16 @@ module Nukadoko
35
35
  args: record[:args] || {}, **(record[:args_origin]&.any? ? { args_origin: record[:args_origin] } : {}),
36
36
  **outcome, status: record[:status], environment: environment, world_name: world_name,
37
37
  scenario_record_id: scenario_record_id, run_id: run_id, started_at: record[:started_at], finished_at: record[:finished_at],
38
- evidence: { dir: evidence_dir, screenshots: [], **(record[:scratch] ? { scratch: record[:scratch] } : {}),
39
- **(record[:http_file] ? { http: "http.jsonl" } : {}), **(record[:trace] ? { trace: record[:trace] } : {}) },
38
+ evidence: { dir: evidence_dir, screenshots: [], **(record[:attachments] ? { attachments: record[:attachments] } : {}),
39
+ **(record[:scratch] ? { scratch: record[:scratch] } : {}),
40
+ **(record[:http_file] ? { http: "http.jsonl" } : {}), **(record[:trace] ? { trace: record[:trace] } : {}),
41
+ **(record[:named_traces] ? { named_traces: record[:named_traces] } : {}) },
40
42
  observed: { processes: processes&.any? ? processes : nil, http: record[:http_count].to_i.positive? ? record[:http_count] : nil,
41
43
  files: record[:files], unmeasured: [], **(record.key?(:program_log) ? { program_log: record[:program_log] } : {}) },
42
- mutates: record[:mutates], **(used.any? ? { used: used } : {}), **(record[:calls] ? { calls: record[:calls] } : {}),
43
- **(record[:actions] ? { actions: record[:actions] } : {}), **(record[:actions_truncated] ? { truncated: { actions: record[:actions_truncated] } } : {}),
44
+ mutates: record[:mutates], **(used.any? ? { used: used } : {}), **(record[:sections] ? { sections: record[:sections] } : {}),
45
+ **(record[:calls] ? { calls: record[:calls] } : {}), **(record[:polls] ? { polls: record[:polls] } : {}),
46
+ **(record[:required_env] ? { required_env: record[:required_env] } : {}),
47
+ **(record[:actions] ? { actions: record[:actions] } : {}), **(record[:actions_truncated] || record[:attachments_total] ? { truncated: { actions: record[:actions_truncated], evidence: record[:attachments_total] }.compact } : {}),
44
48
  **(record[:fixtures] ? { fixtures: record[:fixtures] } : {}),
45
49
  **(record[:claim_records] ? { claims: record[:claim_records], observation: record[:observation] || "observed", **poll_fields(record), **page_fields(record) } : {}) }
46
50
  end
@@ -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