verquest 0.7.1 → 0.8.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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: a8cd5618a10d4cd2445bfaa83544c67b1b2875aaf4c2a81f4f379c58b542fa48
4
- data.tar.gz: d6f5d4e461d21ea2ddbe00d0a5e1ecae6846807359b39d4af0deb17b53c353a5
3
+ metadata.gz: 4445e1ed3a032827a00b4805bb1eb3bcb57eb11cf3a261e334d4bb5362df953d
4
+ data.tar.gz: 14a3b0eb7fc630f6d227f4efc439eabfde307ed0e8d3c133a68b96120e6b588e
5
5
  SHA512:
6
- metadata.gz: 47f7a89e151551c01db83182d160af65ce0087eac9c9b98968f166c0bd6583fbd04308b8cd12dbf0a7fa037802a2858e464763002b74d12ae7675ec47ab928fd
7
- data.tar.gz: c9fea3cbebb730cd85757067b9f5b1ca7aa31893c61e617e05d6e1757dea57cd226a686cc8c43949c7bb5ca49babb6ee2b6546875a82e1286859fe6466da5bda
6
+ metadata.gz: 6605a7c2d01d8a1d89388340592f5f9ac7e61220f705ce06eecdc50b39b0b01771c70afa0311f4ca4ebd21f72c0ca61732ca2ab27e9fc332d5761f357f909e4a
7
+ data.tar.gz: c8dacd48fec778f398971dcf1f797fb639edd771069070c64c2f5ee3a9eb3c1389483f5dbb6348eb4607c579624ba3fb74a94fe64c05f9a7bd7cbe79112d9fd8
data/CHANGELOG.md CHANGED
@@ -1,5 +1,25 @@
1
1
  ## [Unreleased]
2
2
 
3
+ ## [0.8.0] - 2026-11-06
4
+
5
+ ### Changed
6
+ - **Breaking:** `enum` writes a `type` next to its values and checks the values when the request is defined. Without `type:`, the type is inferred: Strings are `string`, Integers `integer`, other Numerics `number`, `true`/`false` `boolean`, Hashes `object`; Integers next to other Numerics are `number`, and other mixes a type array. These now raise `ArgumentError`:
7
+ - a value of another class, such as a Symbol (Symbols never matched JSON values) or an Array;
8
+ - `nil` in the values without `nullable: true`;
9
+ - a `type:` other than the five above, or one a value doesn't fit;
10
+ - values equal in JSON, such as `1` and `1.0` (also inside Hashes);
11
+ - NaN or Infinity;
12
+ - `values:` that isn't an Array;
13
+ - a Hash value with a key that isn't a String, or with something inside that isn't JSON (such as a Symbol).
14
+
15
+ `nullable: true` adds `"null"` to the type, inferred or given. `with_options(type:)` no longer applies to enums.
16
+ - With `json_schema_version = :openapi30`, documents (`to_schema` and `to_parameters`) use OpenAPI 3.0 forms: `nullable: true` instead of a `"null"` type, an `anyOf` of single types (each nullable) instead of a type array, a nullable constant as an `enum` with `null`, an `allOf` around a nullable `$ref` or discriminated `one_of`, and `x-dependentRequired` instead of `dependentRequired`. Validation schemas keep the JSON Schema forms validators honour.
17
+ - Under `:openapi30`, `valid_schema?` and `validate_schema` check the document (`to_schema`) instead of the validation schema, whose JSON Schema forms made the check fail for any nullable request.
18
+ - Schemas leave out `required` when nothing is required, instead of an empty array, which draft 4 and OpenAPI 3.0 forbid. Validation is unchanged. `present` and `absent` without a property name raise `ArgumentError`.
19
+
20
+ ### Fixed
21
+ - Query params convert `""` to `nil` in nullable string and mixed enums, and in nullable fields with `enum:`.
22
+
3
23
  ## [0.7.1] - 2026-11-06
4
24
 
5
25
  ### Added
data/README.md CHANGED
@@ -166,19 +166,18 @@ Output:
166
166
  "description" => "Permissions associated with the user"
167
167
  },
168
168
  "role" => {
169
+ "type" => "string",
169
170
  "enum" => ["member", "manager"],
170
171
  "default" => "member",
171
172
  "description" => "Role of the user"
172
173
  },
173
174
  "profile_details" => {
174
175
  "type" => "object",
175
- "required" => [],
176
176
  "properties" => {
177
177
  "bio" => {"type" => "string", "description" => "Short biography of the user"},
178
178
  "hobbies" => {"type" => "array", "items" => {"type" => "string"}, "description" => "Tags associated with the user"},
179
179
  "social_links" => {
180
180
  "type" => "object",
181
- "required" => [],
182
181
  "properties" => {
183
182
  "github" => {"type" => "string", "format" => "uri", "description" => "GitHub profile URL"},
184
183
  "mastodon" => {"type" => "string", "format" => "uri", "description" => "Mastodon profile URL"}
@@ -237,18 +236,17 @@ Output:
237
236
  "description" => "Permissions associated with the user"
238
237
  },
239
238
  "role" => {
239
+ "type" => "string",
240
240
  "enum" => ["member", "manager"],
241
241
  "default" => "member",
242
242
  "description" => "Role of the user"
243
243
  },
244
244
  "profile_details" => {"type" => "object",
245
- "required" => [],
246
245
  "properties" => {
247
246
  "bio" => {"type" => "string", "description" => "Short biography of the user"},
248
247
  "hobbies" => {"type" => "array", "items" => {"type" => "string"}, "description" => "Tags associated with the user"},
249
248
  "social_links" => {
250
249
  "type" => "object",
251
- "required" => [],
252
250
  "properties" => {
253
251
  "github" => {"type" => "string", "format" => "uri", "description" => "GitHub profile URL"},
254
252
  "mastodon" => {"type" => "string", "format" => "uri", "description" => "Mastodon profile URL"}
@@ -262,7 +260,7 @@ Output:
262
260
  }
263
261
  ```
264
262
 
265
- You can also validate it to ensure it meets the JSON Schema standards:
263
+ You can also validate it to ensure it meets the JSON Schema standards. Under `:openapi30` this checks the document from `to_schema` against the OpenAPI 3.0 meta-schema, since validation schemas keep JSON Schema forms OpenAPI 3.0 forbids:
266
264
 
267
265
  ```ruby
268
266
  UserCreateRequest.valid_schema?(version: "2025-06") # => true/false
@@ -280,7 +278,7 @@ The JSON schema can be used for both validation of incoming parameters and for g
280
278
  #### Component types
281
279
 
282
280
  - `field`: a scalar value (string, integer, boolean, etc.).
283
- - `enum`: a value from a fixed list.
281
+ - `enum`: a value from a fixed list. Its `type` is inferred from the values (`string`, `integer`, `number`, `boolean`, `object`, or a type array for mixed values) unless you pass `type:`, and every value must fit it. A value of another class (such as a Symbol), `nil` without `nullable: true`, or values equal in JSON (`1` and `1.0`) raise `ArgumentError`.
284
282
  - `object`: a JSON object with its own properties.
285
283
  - `array`: a JSON array of scalar items.
286
284
  - `collection`: a JSON array of objects, defined inline or with `item:` pointing at another request.
@@ -333,17 +331,29 @@ Will produce this validation schema:
333
331
 
334
332
  You can define nullable properties in your request schema by setting the `nullable` option to `true`. This feature is based on the latest JSON Schema specification, which is also used in OpenAPI 3.1.
335
333
 
336
- Nullable enums include Ruby `nil` in their allowed values, which exports as JSON `null`, not the string `"null"`. This also applies to fields with an `enum:` constraint (including custom field types). The supplied values array is not modified.
334
+ Nullable enums include Ruby `nil` in their allowed values, which exports as JSON `null`, not the string `"null"`, and add `"null"` to the type, inferred or given. An enum that lists `nil` itself needs `nullable: true`. This also applies to fields with an `enum:` constraint (including custom field types). The supplied values array is not modified.
337
335
 
338
336
  ```ruby
339
337
  enum :role, values: %w[member admin], nullable: true
340
- # => {"role" => {"enum" => ["member", "admin", nil]}}
338
+ # => {"role" => {"type" => ["string", "null"], "enum" => ["member", "admin", nil]}}
339
+ # under :openapi30: {"type" => "string", "nullable" => true, "enum" => ["member", "admin", nil]}
341
340
 
342
341
  const :kind, value: "user", nullable: true
343
342
  # => {"kind" => {"anyOf" => [{"const" => "user"}, {"type" => "null"}]}}
344
343
  ```
345
344
 
346
- Nullable constants and references use `anyOf` with a null alternative in both exported and validation schemas. Nullable `one_of` uses an outer `anyOf` around the original `oneOf` and the null alternative. This allows null even when a referenced schema or multiple variants already accept it, while preserving all restrictions on non-null values. A discriminator, when present, stays alongside the inner `oneOf`.
345
+ Nullable constants and references use `anyOf` with a null alternative in both exported and validation schemas (except `:openapi30` documents, see below). Nullable `one_of` uses an outer `anyOf` around the original `oneOf` and the null alternative. This allows null even when a referenced schema or multiple variants already accept it, while preserving all restrictions on non-null values. A discriminator, when present, stays alongside the inner `oneOf`.
346
+
347
+ OpenAPI 3.0 has no `null` type, so with `json_schema_version = :openapi30` documents (`to_schema` and `to_parameters`) write `nullable: true` instead:
348
+ - next to the type;
349
+ - merged into a nullable constant (with `null` in its `enum`) or a `one_of` without a discriminator;
350
+ - next to an `allOf` around a nullable reference (`{"allOf" => [{"$ref" => "..."}], "nullable" => true}`) or a nullable `one_of` with a discriminator, which keeps null outside the discriminated `oneOf`, as versponse does.
351
+
352
+ OpenAPI 3.0 also has no `dependentRequired` (from `required: [:other]`), so documents write it as the `x-dependentRequired` extension. Validation still enforces it.
353
+
354
+ Mixed types become an `anyOf` of single types, each nullable when the property is. Strict OpenAPI 3.0.3 tools honour `nullable` only next to `type`, so they may still treat a nullable reference or `one_of` as not nullable. Validation schemas keep the forms above, which validators honour.
355
+
356
+ Enum values must be JSON values: Strings, Numerics, booleans or Hashes, given as an Array. Hash values need String keys, and everything inside them must be JSON too (Strings, finite numbers, booleans, `nil`, Arrays and Hashes). A BigDecimal or Rational value is a `number`, but Ruby's JSON generator writes it as a string, so prefer Integers and Floats in documented enums.
347
357
 
348
358
  `required: true` still requires the key to be present; `nullable: true` only permits its value to be null. Defaults stay on the outer nullable schema so missing properties still receive them when default insertion is enabled. Explicit null values are not replaced by defaults.
349
359
 
@@ -378,15 +388,13 @@ Will produce this validation schema:
378
388
  {
379
389
  "type" => "object",
380
390
  "description" => "This is a simple request with nullable properties for testing purposes.",
381
- "required" => [],
382
391
  "properties" => {
383
392
  "array" => {"type" => %w[array null], "items" => {"type" => "string"}},
384
393
  "collection_with_item" => {"type" => %w[array null], "items" => {"type" => "object", "description" => "This is an another example for testing purposes.", "required" => %w[simple_field nested], "properties" => {"simple_field" => {"type" => "string", "description" => "The simple field"}, "nested" => {"type" => "object", "required" => %w[nested_field_1 nested_field_2], "properties" => {"nested_field_1" => {"type" => "string", "description" => "This is a nested field"}, "nested_field_2" => {"type" => "string", "description" => "This is another nested field"}}, "additionalProperties" => false}}, "additionalProperties" => false}},
385
- "collection_with_object" => {"type" => %w[array null], "items" => {"type" => "object", "required" => [], "properties" => {"field" => {"type" => "string"}}, "additionalProperties" => false}},
394
+ "collection_with_object" => {"type" => %w[array null], "items" => {"type" => "object", "properties" => {"field" => {"type" => "string"}}, "additionalProperties" => false}},
386
395
  "field" => {"type" => %w[string null]},
387
396
  "object" => {
388
397
  "type" => %w[object null],
389
- "required" => [],
390
398
  "properties" => {
391
399
  "field" => {"type" => "string"}
392
400
  },
@@ -813,7 +821,7 @@ DealsIndexQuery.process(request.query_parameters, version: "2025-06")
813
821
  ```
814
822
 
815
823
  Conversion follows the validation schema:
816
- - `integer` and `number` from digits (`"2"`, `"-1.5"`), `boolean` from `"true"` and `"false"`, `null` from an empty string when the schema allows it;
824
+ - `integer` and `number` from digits (`"2"`, `"-1.5"`), `boolean` from `"true"` and `"false"`, `null` from an empty string when the schema allows it (a string outside an enum's values tries the next type, so `""` is `nil` in a nullable string enum);
817
825
  - arrays split on commas with `explode: false` (`status=open,won`), or come from repeated keys with `explode: true` (`status[]=open&status[]=won`; Rails keeps only the last value of a plain repeated key). `config.query_array_explode` sets the default (`true`);
818
826
  - objects (`deepObject`, one level deep) convert each property.
819
827
 
@@ -200,7 +200,7 @@ module Verquest
200
200
 
201
201
  required = default_options.fetch(:required, false) if required.nil?
202
202
  nullable = default_options.fetch(:nullable, false) if nullable.nil?
203
- schema_options = default_options.except(:required, :nullable).merge(schema_options)
203
+ schema_options = default_options.except(:type, :required, :nullable).merge(schema_options)
204
204
 
205
205
  enum_property = Properties::Enum.new(name:, values:, map:, required:, nullable:, **schema_options)
206
206
  add_property(enum_property, parameter_examples)
@@ -127,6 +127,8 @@ module Verquest
127
127
 
128
128
  # Validates the generated JSON schema structure
129
129
  #
130
+ # Under `:openapi30` it checks the document from `to_schema`, otherwise the validation schema.
131
+ #
130
132
  # @param version [String, nil] Specific version to use, defaults to configuration setting
131
133
  # @return [Boolean] True if schema is valid
132
134
  def valid_schema?(version: nil)
@@ -137,7 +139,8 @@ module Verquest
137
139
  #
138
140
  # This method validates the schema against the configured JSON Schema metaschema
139
141
  # and returns detailed validation errors if any are found. It's useful for debugging
140
- # schema issues during development and testing.
142
+ # schema issues during development and testing. Under `:openapi30` it checks the document from `to_schema`, so
143
+ # the pointers refer to it.
141
144
  #
142
145
  # @param version [String, nil] Specific version to use, defaults to configuration setting
143
146
  # @return [Array<Hash>] An array of validation error details, empty if schema is valid
@@ -80,8 +80,7 @@ module Verquest
80
80
  #
81
81
  # @return [Hash] The `required` and `dependentRequired` fragment
82
82
  def required_schema
83
- {}.tap do |schema|
84
- schema["required"] = required_properties if required_properties.any?
83
+ required_keyword.tap do |schema|
85
84
  schema["dependentRequired"] = dependent_required_properties if dependent_required_properties.any?
86
85
  end
87
86
  end
@@ -14,7 +14,10 @@ module Verquest
14
14
  # Initialize a new rule
15
15
  #
16
16
  # @param names [Array<Symbol, String>] The properties the rule names
17
+ # @raise [ArgumentError] If no property is named
17
18
  def initialize(names)
19
+ raise ArgumentError, "Name at least one property" if names.empty?
20
+
18
21
  @property_names = names.map(&:to_s)
19
22
  end
20
23
  end
@@ -169,6 +169,15 @@ module Verquest
169
169
  !VERSIONS_WITHOUT_CONST.include?(json_schema_version)
170
170
  end
171
171
 
172
+ # Checks whether documents write nullable as a keyword
173
+ #
174
+ # OpenAPI 3.0 has no "null" type, so its documents use `nullable: true` (see {Verquest::Openapi30}).
175
+ #
176
+ # @return [Boolean] True for OpenAPI 3.0
177
+ def nullable_keyword?
178
+ json_schema_version == :openapi30
179
+ end
180
+
172
181
  # Gets the JSON Schema URI for the configured schema version
173
182
  #
174
183
  # @return [String] The base URI for the configured JSON Schema version
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Verquest
4
- GEM_VERSION = "0.7.1"
4
+ GEM_VERSION = "0.8.0"
5
5
  end
@@ -25,6 +25,15 @@ module Verquest
25
25
  @_required_properties ||= properties.values.select { _1.required == true }.map(&:name)
26
26
  end
27
27
 
28
+ # Returns the `required` keyword for a schema, left out when nothing is required
29
+ #
30
+ # Draft 4 and OpenAPI 3.0 forbid an empty `required` array, and later drafts treat it like no `required`.
31
+ #
32
+ # @return [Hash] `{"required" => names}`, or an empty Hash when no property is required
33
+ def required_keyword
34
+ required_properties.any? ? {"required" => required_properties} : {}
35
+ end
36
+
28
37
  # Returns properties that are conditionally required based on other properties
29
38
  #
30
39
  # This method identifies properties that are required only when certain other
@@ -0,0 +1,128 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Verquest
4
+ # Rewrites a JSON Schema into OpenAPI 3.0 forms
5
+ #
6
+ # OpenAPI 3.0 has no "null" type and no type arrays. Properties write the JSON Schema forms, which validators
7
+ # honour, so only documents are converted, when `json_schema_version` is `:openapi30`:
8
+ # - "null" in a type array becomes `nullable: true`
9
+ # - several types become an `anyOf` of single types, each nullable when the schema is
10
+ # - an `anyOf` with a single null alternative becomes `nullable: true`, with an `allOf` around a `$ref`
11
+ # (OpenAPI 3.0 ignores keywords next to `$ref`) or a discriminated `oneOf` (which would reject null),
12
+ # and `null` added to an `enum`
13
+ # - `dependentRequired` becomes the `x-dependentRequired` extension
14
+ #
15
+ # Only schema positions are visited, so a property named "type" is never read as the keyword.
16
+ #
17
+ # @example
18
+ # Verquest::Openapi30.document({"type" => ["string", "null"]})
19
+ # # => {"type" => "string", "nullable" => true}
20
+ module Openapi30
21
+ # The null alternative of a nullable anyOf
22
+ NULL_SCHEMA = {"type" => "null"}.freeze
23
+
24
+ # Keywords whose value is a map from names to schemas
25
+ SCHEMA_MAPS = %w[properties patternProperties dependentSchemas dependencies $defs definitions].freeze
26
+
27
+ # Keywords whose value is a list of schemas
28
+ SCHEMA_LISTS = %w[prefixItems anyOf oneOf allOf].freeze
29
+
30
+ # Keywords whose value is a schema (`items` can also be a list)
31
+ SCHEMAS = %w[
32
+ items additionalProperties not if then else
33
+ contains propertyNames unevaluatedProperties unevaluatedItems additionalItems
34
+ ].freeze
35
+
36
+ # Keywords OpenAPI 3.0 lacks, written as extensions
37
+ RENAMED = {"dependentRequired" => "x-dependentRequired"}.freeze
38
+
39
+ module_function
40
+
41
+ # @param schema [Object] A schema; other values, such as `additionalProperties: false`, are returned as they are
42
+ # @return [Object] A converted copy of the schema
43
+ def document(schema)
44
+ return schema unless schema.is_a?(::Hash)
45
+
46
+ # The null alternative goes first, so a merged alternative's type array meets nullable in type_union
47
+ type_union(nullable_any_of(schema).to_h { |keyword, value| [RENAMED.fetch(keyword, keyword), child(keyword, value)] })
48
+ end
49
+
50
+ # @param keyword [String] The schema keyword
51
+ # @param value [Object] Its value
52
+ # @return [Object] The value, with the schemas it holds converted
53
+ def child(keyword, value)
54
+ if SCHEMA_MAPS.include?(keyword) && value.is_a?(::Hash)
55
+ value.transform_values { |schema| document(schema) }
56
+ elsif (SCHEMA_LISTS.include?(keyword) || SCHEMAS.include?(keyword)) && value.is_a?(::Array)
57
+ value.map { |schema| document(schema) }
58
+ elsif SCHEMAS.include?(keyword)
59
+ document(value)
60
+ else
61
+ value
62
+ end
63
+ end
64
+
65
+ # OpenAPI 3.0 honours nullable only next to type, so each branch of a union carries it, also when a merged
66
+ # nullable alternative has the type array
67
+ #
68
+ # @param schema [Hash] A schema with converted children
69
+ # @return [Hash] The schema without a type array
70
+ def type_union(schema)
71
+ types = schema["type"]
72
+ return schema unless types.is_a?(::Array)
73
+
74
+ others = types - ["null"]
75
+ return schema if others.empty?
76
+
77
+ nullable = (types.include?("null") || schema["nullable"]) ? {"nullable" => true} : {}
78
+ return schema.merge("type" => others.first).merge(nullable) if others.one?
79
+
80
+ any_of(schema.except("type"), others.map { |type| {"type" => type}.merge(nullable) })
81
+ end
82
+
83
+ # @param schema [Hash] A schema without its type
84
+ # @param variants [Array<Hash>] The single-type schemas
85
+ # @return [Hash] The schema with the variants as an anyOf, next to an existing anyOf through allOf
86
+ def any_of(schema, variants)
87
+ return schema.merge("anyOf" => variants) unless schema.key?("anyOf")
88
+
89
+ schema.except("anyOf").merge("allOf" => [*schema["allOf"], {"anyOf" => variants}, {"anyOf" => schema["anyOf"]}])
90
+ end
91
+
92
+ # @param schema [Hash] A schema whose children are not converted yet
93
+ # @return [Hash] The schema without a null alternative in its anyOf
94
+ def nullable_any_of(schema)
95
+ variants = schema["anyOf"]
96
+ return schema unless variants.is_a?(::Array) && variants.include?(NULL_SCHEMA)
97
+
98
+ others = variants - [NULL_SCHEMA]
99
+ return schema if others.empty?
100
+
101
+ siblings = schema.except("anyOf").merge("nullable" => true)
102
+ others.one? ? nullable_alternative(others.first, siblings) : siblings.merge("anyOf" => others)
103
+ end
104
+
105
+ # OpenAPI 3.0 ignores keywords next to $ref, so a nullable $ref goes into an allOf. So does a discriminated
106
+ # oneOf, keeping null outside it as versponse does.
107
+ #
108
+ # @param alternative [Object] The only non-null alternative
109
+ # @param siblings [Hash] The other keywords of the schema, with nullable
110
+ # @return [Hash] The nullable schema
111
+ def nullable_alternative(alternative, siblings)
112
+ return siblings.merge("anyOf" => [alternative]) unless alternative.is_a?(::Hash)
113
+ return {"allOf" => [alternative]}.merge(siblings) if alternative.key?("$ref") || alternative.key?("discriminator")
114
+
115
+ nullable_enum(alternative).merge(siblings)
116
+ end
117
+
118
+ # OpenAPI 3.0 needs null listed in an enum next to nullable
119
+ #
120
+ # @param schema [Hash] The only non-null alternative
121
+ # @return [Hash] The alternative, with nil in its enum
122
+ def nullable_enum(schema)
123
+ schema.key?("enum") ? schema.merge("enum" => schema["enum"] | [nil]) : schema
124
+ end
125
+
126
+ private_class_method :child, :type_union, :any_of, :nullable_any_of, :nullable_alternative, :nullable_enum
127
+ end
128
+ end
@@ -122,7 +122,7 @@ module Verquest
122
122
  "type" => type,
123
123
  "items" => {
124
124
  "type" => "object",
125
- "required" => required_properties,
125
+ **required_keyword,
126
126
  "properties" => all_properties.transform_values { |property| property.to_schema[property.name] },
127
127
  "additionalProperties" => Verquest.configuration.default_additional_properties
128
128
  }.tap do |schema|
@@ -160,7 +160,7 @@ module Verquest
160
160
  "type" => type,
161
161
  "items" => {
162
162
  "type" => "object",
163
- "required" => required_properties,
163
+ **required_keyword,
164
164
  "properties" => all_properties.transform_values { |property| property.to_validation_schema(version: version)[property.name] },
165
165
  "additionalProperties" => Verquest.configuration.default_additional_properties
166
166
  }.tap do |schema|
@@ -4,9 +4,27 @@ module Verquest
4
4
  module Properties
5
5
  # The Enum class represents a enum property with a list of possible values in a JSON schema.
6
6
  #
7
+ # The type is inferred from the values unless `type:` is given, and every value must fit it.
8
+ #
7
9
  # @example
8
10
  # enum = Enum.new(name: "type", values: ["member", "admin"])
11
+ # enum.to_schema # => {"type" => {"type" => "string", "enum" => ["member", "admin"]}}
9
12
  class Enum < Base
13
+ # Ruby classes the values of each JSON type can have
14
+ VALUE_CLASSES = {
15
+ "string" => [::String],
16
+ "integer" => [::Integer],
17
+ "number" => [::Numeric],
18
+ "boolean" => [::TrueClass, ::FalseClass],
19
+ "object" => [::Hash]
20
+ }.freeze
21
+
22
+ # Classes of the JSON values that need no further check inside a Hash
23
+ JSON_SCALARS = [::String, ::TrueClass, ::FalseClass, ::NilClass].freeze
24
+
25
+ # Added to errors about Symbols
26
+ SYMBOL_HINT = " (Symbols never match JSON values, use Strings)"
27
+
10
28
  # Initialize a new Enum property
11
29
  #
12
30
  # @param name [String, Symbol] The name of the property
@@ -14,31 +32,35 @@ module Verquest
14
32
  # @param required [Boolean, Array<Symbol>] Whether this property is required, or array of dependency names
15
33
  # @param nullable [Boolean] Whether this property can be null
16
34
  # @param map [String, nil] The mapping path for this property
35
+ # @param type [String, Symbol, Array<String, Symbol>, nil] The JSON type of the values, inferred from them when nil
17
36
  # @param schema_options [Hash] Additional JSON schema options for this property
18
37
  # @raise [ArgumentError] If attempting to map an enum to root without a name
19
- # @raise [ArgumentError] If values is empty
20
- # @raise [ArgumentError] If values are not unique
38
+ # @raise [ArgumentError] If values is not an Array, or is empty
39
+ # @raise [ArgumentError] If values are not unique, comparing them as JSON (1 and 1.0 are the same)
21
40
  # @raise [ArgumentError] If only one value is provided (should use const instead)
22
- def initialize(name:, values:, required: false, nullable: false, map: nil, **schema_options)
41
+ # @raise [ArgumentError] If values include nil without nullable, or a number that isn't finite
42
+ # @raise [ArgumentError] If a value has no JSON type, the type is unknown, or a value isn't of the type
43
+ # @raise [ArgumentError] If a Hash value has a key that isn't a String, or contains a value that isn't JSON
44
+ def initialize(name:, values:, required: false, nullable: false, map: nil, type: nil, **schema_options)
23
45
  raise ArgumentError, "You can not map enums to the root without a name" if map == "/"
24
- raise ArgumentError, "Values must not be empty" if values.empty?
25
- raise ArgumentError, "Values must be unique" if values.uniq.length != values.length
26
- raise ArgumentError, "Use const for a single value" if values.length == 1
46
+
47
+ check_values!(values, nullable)
27
48
 
28
49
  @name = name.to_s
29
50
  @values = nullable ? values | [nil] : values
51
+ @types = type.nil? ? inferred_types : checked_types(type)
30
52
  @required = required
31
53
  @nullable = nullable
32
54
  @map = map
33
- @schema_options = schema_options&.transform_keys(&:to_s)
55
+ @schema_options = schema_options.transform_keys(&:to_s).except("type")
34
56
  end
35
57
 
36
- # Generate JSON schema definition for this enum
58
+ # Generate JSON schema definition for this enum. Nullable adds "null" to the type.
37
59
  #
38
60
  # @return [Hash] The schema definition for this enum
39
61
  def to_schema
40
62
  {
41
- name => {"enum" => values}.merge(schema_options)
63
+ name => {"type" => schema_type, "enum" => values}.merge(schema_options)
42
64
  }
43
65
  end
44
66
 
@@ -55,7 +77,118 @@ module Verquest
55
77
 
56
78
  private
57
79
 
58
- attr_reader :values, :schema_options
80
+ attr_reader :values, :types, :schema_options
81
+
82
+ # @param values [Array] The given values
83
+ # @param nullable [Boolean] Whether the enum can be null
84
+ # @raise [ArgumentError] If the values are not an Array, empty, not JSON, not unique, a single value, or include nil
85
+ # without nullable
86
+ def check_values!(values, nullable)
87
+ raise ArgumentError, "Values must be an Array" unless values.is_a?(::Array)
88
+ raise ArgumentError, "Values must not be empty" if values.empty?
89
+
90
+ values.each { |value| check_json!(value, value) }
91
+ raise ArgumentError, "Values must be unique" if values.uniq { |value| json_value(value) }.length != values.length
92
+ raise ArgumentError, "Use const for a single value" if values.length == 1
93
+ raise ArgumentError, "Values include nil, which needs nullable: true" if values.include?(nil) && !nullable
94
+ end
95
+
96
+ # Checks numbers and walks Hashes; top-level Arrays and other classes are left to the type check
97
+ #
98
+ # @param value [Object] An enum value, or a part of a Hash value
99
+ # @param enum_value [Object] The enum value, for errors
100
+ # @param nested [Boolean] Whether the value is inside a Hash
101
+ # @raise [ArgumentError] If a number isn't finite, or a Hash value has a key or part that isn't JSON
102
+ def check_json!(value, enum_value, nested: false)
103
+ case value
104
+ when ::Numeric then raise ArgumentError, "Enum values must be finite numbers" unless finite?(value)
105
+ when ::Hash then value.each { |key, item| check_key!(key, enum_value) || check_json!(item, enum_value, nested: true) }
106
+ when ::Array then value.each { |item| check_json!(item, enum_value, nested: true) } if nested
107
+ when *JSON_SCALARS then nil
108
+ else
109
+ raise ArgumentError, "Enum value #{enum_value.inspect} contains #{value.inspect}, which is not a JSON value#{symbol_hint(value)}" if nested
110
+ end
111
+ end
112
+
113
+ # @param key [Object] A key of a Hash value
114
+ # @param enum_value [Object] The enum value, for errors
115
+ # @return [nil]
116
+ # @raise [ArgumentError] If the key isn't a String
117
+ def check_key!(key, enum_value)
118
+ return if key.is_a?(::String)
119
+
120
+ raise ArgumentError, "Enum value #{enum_value.inspect} has key #{key.inspect}, which is not a String#{symbol_hint(key)}"
121
+ end
122
+
123
+ # @param value [Numeric] A number
124
+ # @return [Boolean] Whether JSON can represent the number
125
+ def finite?(value)
126
+ value.real? && value.finite?
127
+ end
128
+
129
+ # @param value [Object] The value an error is about
130
+ # @return [String, nil] The hint for a Symbol
131
+ def symbol_hint(value)
132
+ SYMBOL_HINT if value.is_a?(::Symbol)
133
+ end
134
+
135
+ # @return [String, Array<String>] The type, with "null" when nullable
136
+ def schema_type
137
+ all = nullable ? types | ["null"] : types
138
+ (all.size == 1) ? all.first : all
139
+ end
140
+
141
+ # @return [Array<String>] The types of the non-nil values; integers next to other numerics are numbers
142
+ def inferred_types
143
+ found = values.compact.map { |value| json_type(value) }.uniq
144
+ found.delete("integer") if found.include?("number")
145
+ found
146
+ end
147
+
148
+ # VALUE_CLASSES lists "integer" before "number", so an Integer is an integer
149
+ #
150
+ # @param value [Object] A non-nil enum value
151
+ # @return [String] The JSON type of the value
152
+ # @raise [ArgumentError] If the value has no JSON type
153
+ def json_type(value)
154
+ type = VALUE_CLASSES.keys.find { |name| of_type?(value, name) }
155
+ return type if type
156
+
157
+ raise ArgumentError, "Enum value #{value.inspect} is not a String, Numeric, boolean or Hash#{symbol_hint(value)}"
158
+ end
159
+
160
+ # @param type [String, Symbol, Array<String, Symbol>] The given type
161
+ # @return [Array<String>] The given types as strings
162
+ # @raise [ArgumentError] If a type is unknown or a value isn't of the types
163
+ def checked_types(type)
164
+ given = Array(type).map(&:to_s).uniq
165
+ if given.empty? || !given.all? { |name| VALUE_CLASSES.key?(name) }
166
+ raise ArgumentError, "Unknown enum type #{type.inspect}, use one of #{VALUE_CLASSES.keys.join(", ")}"
167
+ end
168
+
169
+ invalid = values.compact.reject { |value| given.any? { |name| of_type?(value, name) } }
170
+ raise ArgumentError, "Enum value #{invalid.first.inspect} is not of type #{given.join(" or ")}" unless invalid.empty?
171
+
172
+ given
173
+ end
174
+
175
+ # @param value [Object] A non-nil enum value
176
+ # @param name [String] A JSON type in VALUE_CLASSES
177
+ # @return [Boolean] Whether the value is of the type
178
+ def of_type?(value, name)
179
+ VALUE_CLASSES.fetch(name).any? { |klass| value.is_a?(klass) }
180
+ end
181
+
182
+ # @param value [Object] An enum value, or a part of a Hash value
183
+ # @return [Object] The value as JSON compares it: whole numbers as Integers, also inside Hashes and Arrays
184
+ def json_value(value)
185
+ case value
186
+ when ::Hash then value.transform_values { |item| json_value(item) }
187
+ when ::Array then value.map { |item| json_value(item) }
188
+ when ::Numeric then (finite?(value) && value == value.to_i) ? value.to_i : value
189
+ else value
190
+ end
191
+ end
59
192
  end
60
193
  end
61
194
  end
@@ -59,7 +59,7 @@ module Verquest
59
59
  {
60
60
  name => {
61
61
  "type" => type,
62
- "required" => required_properties,
62
+ **required_keyword,
63
63
  "properties" => all_properties.transform_values { |property| property.to_schema[property.name] }
64
64
  }.merge(schema_options).tap do |schema|
65
65
  schema["dependentRequired"] = dependent_required_properties if dependent_required_properties.any?
@@ -76,7 +76,7 @@ module Verquest
76
76
  {
77
77
  name => {
78
78
  "type" => type,
79
- "required" => required_properties,
79
+ **required_keyword,
80
80
  "properties" => all_properties.transform_values { |property| property.to_validation_schema(version: version)[property.name] }
81
81
  }.merge(schema_options).tap do |schema|
82
82
  schema["dependentRequired"] = dependent_required_properties if dependent_required_properties.any?
@@ -106,7 +106,7 @@ module Verquest
106
106
  when "number" then coerce_number(value)
107
107
  when "boolean" then coerce_boolean(value)
108
108
  when "null" then (value.nil? || value == "") ? nil : NO_MATCH
109
- when "string" then value.is_a?(::String) ? value : NO_MATCH
109
+ when "string" then coerce_string(value, value_schema)
110
110
  when "array" then coerce_array(value, value_schema, path)
111
111
  when "object" then value.is_a?(::Hash) ? coerce_properties(value, value_schema, path) : NO_MATCH
112
112
  else NO_MATCH
@@ -136,6 +136,16 @@ module Verquest
136
136
  BOOLEANS.fetch(value, NO_MATCH)
137
137
  end
138
138
 
139
+ # A string outside the schema's enum tries the next type, so "" can still map to nil
140
+ #
141
+ # @return [String, Object] The string or NO_MATCH
142
+ def coerce_string(value, value_schema)
143
+ return NO_MATCH unless value.is_a?(::String)
144
+ return NO_MATCH if value_schema.key?("enum") && !value_schema["enum"].include?(value)
145
+
146
+ value
147
+ end
148
+
139
149
  # Splits a string by the array's explode value and converts each item;
140
150
  # an item no rule converts is kept as it is
141
151
  def coerce_array(value, array_schema, path)
@@ -9,7 +9,7 @@ module Verquest
9
9
  # (`param[:in]`, `param[:style]`, `param[:schema][:type]`).
10
10
  #
11
11
  # @example
12
- # schema = {"type" => "object", "required" => [], "properties" => {"page" => {"type" => "integer"}}}
12
+ # schema = {"type" => "object", "properties" => {"page" => {"type" => "integer"}}}
13
13
  # Verquest::Query::Parameters.new(schema:, options: {}).call
14
14
  # # => [{name: "page", in: :query, required: false, schema: {type: "integer"}}]
15
15
  class Parameters
@@ -157,10 +157,13 @@ module Verquest
157
157
 
158
158
  # Validate the schema against the metaschema
159
159
  #
160
+ # Under `:openapi30` the document (`schema`) is checked, since the validation schema keeps JSON Schema forms
161
+ # OpenAPI 3.0 forbids, such as "null" types.
162
+ #
160
163
  # @return [Boolean] true if the schema is valid, false otherwise
161
164
  def valid_schema?
162
165
  JSONSchemer.valid_schema?(
163
- validation_schema,
166
+ checked_schema,
164
167
  meta_schema: Verquest.configuration.json_schema_uri
165
168
  )
166
169
  end
@@ -169,13 +172,14 @@ module Verquest
169
172
  #
170
173
  # This method validates the schema against the configured JSON Schema metaschema
171
174
  # and returns detailed validation errors if any are found. It uses the JSONSchemer
172
- # library with the schema version specified in the configuration.
175
+ # library with the schema version specified in the configuration. Under `:openapi30` it checks the document,
176
+ # so the pointers refer to `schema`.
173
177
  #
174
178
  # @return [Array<Hash>] An array of validation error details, empty if schema is valid
175
179
  # @see #valid_schema?
176
180
  def validate_schema
177
181
  JSONSchemer.validate_schema(
178
- validation_schema,
182
+ checked_schema,
179
183
  meta_schema: Verquest.configuration.json_schema_uri
180
184
  ).map do |error|
181
185
  {
@@ -239,11 +243,11 @@ module Verquest
239
243
  parameters? ? query_coercer.call(params) : params
240
244
  end
241
245
 
242
- # Returns OpenAPI parameter objects for this query or path version
246
+ # Returns OpenAPI parameter objects for this query or path version, in OpenAPI 3.0 forms under :openapi30
243
247
  #
244
248
  # @return [Array<Hash>] A new array of parameter objects on each call
245
249
  def parameters
246
- Query::Parameters.new(schema: validation_schema, options: query_options, location:).call
250
+ Query::Parameters.new(schema: document_schema(validation_schema), options: query_options, location:).call
247
251
  end
248
252
 
249
253
  # Map request parameters to internal representation using the transformer
@@ -341,13 +345,14 @@ module Verquest
341
345
  def prepare_schema
342
346
  @schema = {
343
347
  "type" => "object",
344
- "required" => required_properties,
348
+ **required_keyword,
345
349
  "properties" => all_properties.transform_values { |property| property.to_schema[property.name] }
346
350
  }.merge(schema_options).tap do |schema|
347
351
  schema["dependentRequired"] = dependent_required_properties if dependent_required_properties.any?
348
352
  schema["description"] = description if description
349
353
  add_conditions(schema, documentation: true)
350
- end.freeze
354
+ end
355
+ @schema = document_schema(@schema).freeze
351
356
  end
352
357
 
353
358
  # Generates the JSON schema for combination schemas (oneOf at root level)
@@ -360,7 +365,20 @@ module Verquest
360
365
  def prepare_combination_schema
361
366
  raise ArgumentError, "Conditions can not be declared next to a root-level one_of" if conditions.any?
362
367
 
363
- @schema = properties.values.first.to_schema
368
+ @schema = document_schema(properties.values.first.to_schema)
369
+ end
370
+
371
+ # @return [Hash] The schema the meta-schema checks: the document under OpenAPI 3.0, the validation schema otherwise
372
+ def checked_schema
373
+ Verquest.configuration.nullable_keyword? ? schema : validation_schema
374
+ end
375
+
376
+ # Converts a document to OpenAPI 3.0 forms when the configured version needs them
377
+ #
378
+ # @param schema [Hash] The schema in JSON Schema forms
379
+ # @return [Hash] The schema for documents
380
+ def document_schema(schema)
381
+ Verquest.configuration.nullable_keyword? ? Openapi30.document(schema) : schema
364
382
  end
365
383
 
366
384
  # Generates the validation schema for this version
@@ -372,7 +390,7 @@ module Verquest
372
390
  def prepare_validation_schema
373
391
  @validation_schema = {
374
392
  "type" => "object",
375
- "required" => required_properties,
393
+ **required_keyword,
376
394
  "properties" => all_properties.transform_values { |property| property.to_validation_schema(version: name)[property.name] }
377
395
  }.merge(schema_options).tap do |schema|
378
396
  schema["dependentRequired"] = dependent_required_properties if dependent_required_properties.any?
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: verquest
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.7.1
4
+ version: 0.8.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Petr Hlavicka
@@ -85,6 +85,7 @@ files:
85
85
  - lib/verquest/helper_methods/conditional_properties.rb
86
86
  - lib/verquest/helper_methods/required_properties.rb
87
87
  - lib/verquest/helper_methods/unnamed_one_of.rb
88
+ - lib/verquest/openapi30.rb
88
89
  - lib/verquest/properties.rb
89
90
  - lib/verquest/properties/array.rb
90
91
  - lib/verquest/properties/base.rb