grape_openapi3 0.1.5 → 0.1.7

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.
@@ -25,13 +25,16 @@ module GrapeOpenapi3
25
25
  "delete" => ->(_) { "delete" },
26
26
  }.freeze
27
27
 
28
- def self.call(http_method, path)
29
- new(http_method, path).call
28
+ # action: overrides the derived verb (e.g. "patch" → patchProduct). Used by
29
+ # Document to disambiguate operations that would otherwise share an id.
30
+ def self.call(http_method, path, action: nil)
31
+ new(http_method, path, action: action).call
30
32
  end
31
33
 
32
- def initialize(http_method, path)
34
+ def initialize(http_method, path, action: nil)
33
35
  @method = http_method.downcase
34
36
  @path = path
37
+ @action = action
35
38
  end
36
39
 
37
40
  def call
@@ -47,7 +50,7 @@ module GrapeOpenapi3
47
50
 
48
51
  return fallback if resources.empty?
49
52
 
50
- action = ACTIONS.fetch(@method, ->(_) { @method }).call(trailing_param)
53
+ action = @action || ACTIONS.fetch(@method, ->(_) { @method }).call(trailing_param)
51
54
  # For known verbs, "list" signals a collection. For unknown verbs (HEAD, OPTIONS…),
52
55
  # infer from path: no trailing param means collection → keep last segment plural.
53
56
  collection = action == "list" || (!ACTIONS.key?(@method) && !trailing_param)
@@ -23,15 +23,16 @@ module GrapeOpenapi3
23
23
  BODY_METHODS = %w[post put patch].freeze
24
24
  PATH_SEGMENT = /\{(\w+)\}/
25
25
 
26
- def self.call(route_data)
27
- new(route_data).call
26
+ def self.call(route_data, diagnostics: Diagnostics.new)
27
+ new(route_data, diagnostics: diagnostics).call
28
28
  end
29
29
 
30
- def initialize(route_data)
31
- @route = route_data
32
- @path = route_data[:path]
33
- @method = route_data[:http_method]
34
- @path_names = @path.scan(PATH_SEGMENT).flatten.to_set
30
+ def initialize(route_data, diagnostics: Diagnostics.new)
31
+ @route = route_data
32
+ @path = route_data[:path]
33
+ @method = route_data[:http_method]
34
+ @path_names = @path.scan(PATH_SEGMENT).flatten.to_set
35
+ @diagnostics = diagnostics
35
36
  end
36
37
 
37
38
  def call
@@ -53,13 +54,29 @@ module GrapeOpenapi3
53
54
  end
54
55
 
55
56
  {
56
- parameters: inline,
57
+ parameters: inline + header_parameters,
57
58
  request_body: build_request_body(json, formdata),
58
59
  }
59
60
  end
60
61
 
61
62
  private
62
63
 
64
+ # `desc "...", headers: { "X-Tenant" => { description: "...", required: true } }`
65
+ def header_parameters
66
+ (@route[:headers] || {}).map do |name, spec|
67
+ spec = spec.is_a?(Hash) ? spec : {}
68
+ param = {
69
+ "name" => name.to_s,
70
+ "in" => "header",
71
+ "required" => (spec[:required] || spec["required"]) == true,
72
+ "schema" => TypeMapper.call(spec[:type] || spec["type"] || String),
73
+ }
74
+ desc = spec[:description] || spec["description"] || spec[:desc] || spec["desc"]
75
+ param["description"] = desc.to_s if desc
76
+ param
77
+ end
78
+ end
79
+
63
80
  # Group every param entry under its top-level name, keeping the full bracket
64
81
  # keys so the body schema can be rebuilt with nesting.
65
82
  def grouped_by_top
@@ -108,7 +125,7 @@ module GrapeOpenapi3
108
125
  end
109
126
 
110
127
  def build_parameter(name, defn, loc)
111
- schema = leaf_schema(defn, nullable: false)
128
+ schema = leaf_schema(defn, name: name, nullable: false)
112
129
 
113
130
  param = {
114
131
  "name" => name,
@@ -155,13 +172,14 @@ module GrapeOpenapi3
155
172
  node = node[:children][seg]
156
173
  end
157
174
  node[:defn] = defn
175
+ node[:key] = key
158
176
  end
159
177
 
160
178
  node_to_schema(root)
161
179
  end
162
180
 
163
181
  def node_to_schema(node)
164
- return leaf_schema(node[:defn] || {}) if node[:children].empty?
182
+ return leaf_schema(node[:defn] || {}, name: node[:key]) if node[:children].empty?
165
183
 
166
184
  object = build_object(node[:children])
167
185
  array_container?(node[:defn]) ? wrap_array(object, node[:defn]) : decorate(object, node[:defn])
@@ -193,17 +211,30 @@ module GrapeOpenapi3
193
211
  end
194
212
 
195
213
  # A scalar/terminal param: map its type and attach enum/default/desc/nullable.
196
- def leaf_schema(defn, nullable: nil)
214
+ def leaf_schema(defn, name:, nullable: nil)
215
+ report_type_gap(name, defn[:type])
197
216
  schema = TypeMapper.call(defn[:type] || String)
198
217
  decorate(schema, defn, nullable: nullable)
199
218
  end
200
219
 
201
- # Attach enum/default/description and (for body params) nullable when optional.
220
+ def report_type_gap(name, type)
221
+ location = "#{@method.upcase} #{@path}"
222
+ if type.nil?
223
+ @diagnostics.report(location, "param #{name} has no type — documented as string")
224
+ elsif (unknown = TypeMapper.unknown_type(type))
225
+ @diagnostics.report(location, "param #{name} has unknown type #{unknown} — documented as string")
226
+ end
227
+ end
228
+
229
+ # Attach values/default/description and (for body params) nullable when optional.
230
+ # `values:` constrains each element of an array param, so it goes on `items`.
202
231
  def decorate(schema, defn, nullable: nil)
203
232
  return schema unless defn
204
233
 
205
- schema["enum"] = Array(defn[:values]) if defn[:values]
206
- schema["default"] = defn[:default] unless defn[:default].nil?
234
+ constrained = schema["type"] == "array" && schema["items"].is_a?(Hash) ? schema["items"] : schema
235
+ constrained.merge!(ValuesMapper.call(defn[:values]))
236
+ apply_constraints(schema, constrained, defn)
237
+ schema["default"] = defn[:default] unless defn[:default].nil?
207
238
 
208
239
  desc = defn[:desc] || defn[:description]
209
240
  schema["description"] = desc.to_s if desc
@@ -213,6 +244,28 @@ module GrapeOpenapi3
213
244
 
214
245
  schema
215
246
  end
247
+
248
+ # Validator constraints (regexp:, length:, allow_blank:) plus any keywords
249
+ # in the param's documentation: hash. Grape's length: counts characters on
250
+ # a string and elements on an array; regexp: checks each array element.
251
+ def apply_constraints(schema, constrained, defn)
252
+ scalar, own = KeywordMapper.call(defn[:documentation])
253
+ array = !constrained.equal?(schema)
254
+
255
+ min = defn[:length_is] || defn[:min_length]
256
+ max = defn[:length_is] || defn[:max_length]
257
+ target, min_key, max_key = array ? [own, "minItems", "maxItems"] : [scalar, "minLength", "maxLength"]
258
+ target[min_key] ||= min if min
259
+ target[max_key] ||= max if max
260
+
261
+ scalar["minLength"] ||= 1 if defn[:allow_blank] == false && constrained["type"] == "string"
262
+
263
+ pattern = KeywordMapper.pattern(defn[:regexp])
264
+ scalar["pattern"] ||= pattern if pattern
265
+
266
+ constrained.merge!(scalar)
267
+ schema.merge!(own)
268
+ end
216
269
  end
217
270
  end
218
271
  end
@@ -7,7 +7,7 @@ module GrapeOpenapi3
7
7
  # same short name (e.g. V2::Mentors::MenteeResponse vs V2::Kids::MenteeResponse
8
8
  # become "Mentors_MenteeResponse" / "Kids_MenteeResponse"). Default "_".
9
9
  Config = Struct.new(
10
- :info, :servers, :security_schemes, :security, :tags, :schema_name_separator,
10
+ :info, :servers, :security_schemes, :security, :tags, :schema_name_separator, :strict,
11
11
  keyword_init: true
12
12
  ) do
13
13
  def schema_name_separator
@@ -0,0 +1,46 @@
1
+ # frozen_string_literal: true
2
+
3
+ module GrapeOpenapi3
4
+ # Raised by `generate(..., strict: true)` when the API has documentation gaps.
5
+ class StrictModeError < Error
6
+ attr_reader :issues
7
+
8
+ def initialize(issues)
9
+ @issues = issues
10
+ super("OpenAPI documentation has #{issues.size} gap(s):\n #{issues.join("\n ")}")
11
+ end
12
+ end
13
+
14
+ # Collects documentation gaps — every place where the generator had to guess
15
+ # (untyped exposure or param, unknown type, unresolvable entity, 200 without
16
+ # a schema) — and reports them according to the `strict:` mode:
17
+ # false → ignore (default)
18
+ # :warn → one warning per gap on stderr
19
+ # true / :raise → raise StrictModeError listing all of them
20
+ class Diagnostics
21
+ MODES = [nil, false, true, :warn, :raise].freeze
22
+
23
+ attr_reader :issues
24
+
25
+ def initialize(mode = false)
26
+ raise ArgumentError, "strict: must be one of false, true, :warn, :raise (got #{mode.inspect})" unless MODES.include?(mode)
27
+
28
+ @mode = mode
29
+ @issues = []
30
+ end
31
+
32
+ def report(location, message)
33
+ issue = "#{location}: #{message}"
34
+ @issues << issue unless @issues.include?(issue)
35
+ end
36
+
37
+ def finish!
38
+ return if @issues.empty?
39
+
40
+ case @mode
41
+ when :warn then @issues.each { |issue| warn "[grape_openapi3] #{issue}" }
42
+ when true, :raise then raise StrictModeError, @issues
43
+ end
44
+ end
45
+ end
46
+ end
@@ -15,14 +15,16 @@ module GrapeOpenapi3
15
15
  end
16
16
 
17
17
  def build
18
- entity_reader = Readers::EntityReader.new(separator: @config.schema_name_separator)
18
+ @diagnostics = Diagnostics.new(@config.strict)
19
+ entity_reader = Readers::EntityReader.new(separator: @config.schema_name_separator, diagnostics: @diagnostics)
19
20
 
20
21
  route_list = @app.routes
21
22
  .map { |r| Readers::RouteReader.call(r) }
22
23
  .compact
23
24
 
24
25
  # Pre-scan all reachable entities so schema names are stable and collision-free.
25
- entity_reader.prepare(route_list.flat_map { |rd| success_entity_classes(rd) })
26
+ entity_reader.prepare(route_list.flat_map { |rd| referenced_entity_classes(rd) })
27
+ assign_operation_ids(route_list)
26
28
 
27
29
  paths = build_paths(route_list, entity_reader)
28
30
  components = build_components(entity_reader)
@@ -37,21 +39,59 @@ module GrapeOpenapi3
37
39
  "security" => @config.security.map { |s| deep_stringify(s) },
38
40
  }
39
41
 
42
+ @diagnostics.finish!
40
43
  reject_blank(doc)
41
44
  end
42
45
 
43
46
  private
44
47
 
45
- # The Grape::Entity class(es) referenced by a route's success response, if any.
46
- # Handles both the bare-class form and the hash form ({ model: SomeEntity }).
47
- def success_entity_classes(route_data)
48
- entity = route_data[:success_entity]
49
- klass = if entity.is_a?(Class)
50
- entity
51
- elsif entity.is_a?(Hash)
52
- entity[:model] || entity["model"]
53
- end
54
- klass.is_a?(Class) ? [klass] : []
48
+ # Methods that yield to another method's conventional id on the same path
49
+ # (PUT keeps updateProduct; a PATCH on the same path becomes patchProduct).
50
+ SECONDARY_METHODS = %w[patch].freeze
51
+
52
+ # operationIds must be unique across the document. Explicit ids (nickname: /
53
+ # operation_id:) are kept as-is; derived ids that collide fall back to the
54
+ # HTTP verb as the action, then to a numeric suffix.
55
+ def assign_operation_ids(route_list)
56
+ used = route_list.filter_map { |rd| rd[:operation_id] }.to_set
57
+
58
+ derived = route_list.each_with_index.reject { |rd, _| rd[:operation_id] }
59
+ derived.sort_by { |rd, i| [SECONDARY_METHODS.include?(rd[:http_method]) ? 1 : 0, i] }.each do |rd, _|
60
+ id = Builders::OperationIdBuilder.call(rd[:http_method], rd[:path])
61
+ id = Builders::OperationIdBuilder.call(rd[:http_method], rd[:path], action: rd[:http_method]) if used.include?(id)
62
+
63
+ base = id
64
+ suffix = 2
65
+ while used.include?(id)
66
+ id = "#{base}#{suffix}"
67
+ suffix += 1
68
+ end
69
+
70
+ used << id
71
+ rd[:operation_id] = id
72
+ end
73
+ end
74
+
75
+ # Every Grape::Entity class referenced by a route — success AND failure
76
+ # responses — so the pre-scan can assign collision-free names to all of them.
77
+ def referenced_entity_classes(route_data)
78
+ successes = route_data[:success_entity].is_a?(Array) ? route_data[:success_entity] : [route_data[:success_entity]]
79
+ classes = successes.map { |s| entity_class_of(s) }
80
+ Array(route_data[:failure_codes]).each do |info|
81
+ classes << entity_class_of(info) if info.is_a?(Hash)
82
+ end
83
+ classes.compact
84
+ end
85
+
86
+ # Extracts a Grape::Entity class from the bare-class form or the hash form
87
+ # ({ model: SomeEntity }). Returns nil when there is none.
88
+ def entity_class_of(entity)
89
+ klass = if entity.is_a?(Class)
90
+ entity
91
+ elsif entity.is_a?(Hash)
92
+ entity[:model] || entity["model"]
93
+ end
94
+ klass if klass.is_a?(Class)
55
95
  end
56
96
 
57
97
  def build_paths(route_list, entity_reader)
@@ -63,6 +103,7 @@ module GrapeOpenapi3
63
103
  paths[path][method] = Builders::OperationBuilder.call(
64
104
  route_data, entity_reader,
65
105
  global_security: @config.security.any?,
106
+ diagnostics: @diagnostics,
66
107
  )
67
108
  end
68
109
  end
@@ -0,0 +1,63 @@
1
+ # frozen_string_literal: true
2
+
3
+ module GrapeOpenapi3
4
+ # Maps schema keywords from a `documentation:` hash (entity exposures and
5
+ # params) to OpenAPI. Both snake_case and camelCase keys are accepted:
6
+ # documentation: { min_length: 3, pattern: /\A[a-z]+\z/, read_only: true }
7
+ #
8
+ # Returns [scalar, own]:
9
+ # scalar → keywords for the value schema (the items of an array of scalars)
10
+ # own → keywords for the property itself
11
+ class KeywordMapper
12
+ SCALAR = {
13
+ "minLength" => %i[min_length minLength],
14
+ "maxLength" => %i[max_length maxLength],
15
+ "multipleOf" => %i[multiple_of multipleOf],
16
+ }.freeze
17
+
18
+ OWN = {
19
+ "minItems" => %i[min_items minItems],
20
+ "maxItems" => %i[max_items maxItems],
21
+ "uniqueItems" => %i[unique_items uniqueItems],
22
+ "readOnly" => %i[read_only readOnly],
23
+ "writeOnly" => %i[write_only writeOnly],
24
+ "deprecated" => %i[deprecated],
25
+ }.freeze
26
+
27
+ def self.call(doc)
28
+ doc ||= {}
29
+ scalar = pick(doc, SCALAR)
30
+ pattern = pattern(doc[:pattern] || doc["pattern"])
31
+ scalar["pattern"] = pattern if pattern
32
+
33
+ [scalar, pick(doc, OWN)]
34
+ end
35
+
36
+ # Ruby Regexp → ECMA-262 pattern string (what OpenAPI expects).
37
+ # Converts the Ruby-only anchors \A, \z, \Z; returns nil for an
38
+ # extended-mode (/x) regexp, whose whitespace and comments ECMA can't read.
39
+ def self.pattern(value)
40
+ value = value[:value] || value["value"] if value.is_a?(Hash)
41
+
42
+ case value
43
+ when Regexp
44
+ return nil if value.options.anybits?(Regexp::EXTENDED)
45
+
46
+ value.source.gsub("\\A", "^").gsub(/\\[zZ]/, "$")
47
+ when String
48
+ value
49
+ end
50
+ end
51
+
52
+ def self.pick(doc, table)
53
+ table.each_with_object({}) do |(keyword, keys), out|
54
+ key = keys.find { |k| doc.key?(k) || doc.key?(k.to_s) }
55
+ next unless key
56
+
57
+ value = doc.key?(key) ? doc[key] : doc[key.to_s]
58
+ out[keyword] = value unless value.nil?
59
+ end
60
+ end
61
+ private_class_method :pick
62
+ end
63
+ end
@@ -26,10 +26,11 @@ module GrapeOpenapi3
26
26
 
27
27
  attr_reader :schemas
28
28
 
29
- def initialize(separator: "_")
30
- @schemas = {}
31
- @separator = separator
32
- @name_map = {} # full Ruby class name => assigned schema name
29
+ def initialize(separator: "_", diagnostics: Diagnostics.new)
30
+ @schemas = {}
31
+ @separator = separator
32
+ @diagnostics = diagnostics
33
+ @name_map = {} # full Ruby class name => assigned schema name
33
34
  end
34
35
 
35
36
  # Walk the entity graph reachable from the given root entities and assign a
@@ -64,11 +65,27 @@ module GrapeOpenapi3
64
65
  return if acc.include?(entity_class)
65
66
 
66
67
  acc << entity_class
67
- entity_class.root_exposures.each do |exposure|
68
- next unless represent_exposure?(exposure)
68
+ collect_exposures(entity_class.root_exposures, acc, [entity_class])
69
+ end
69
70
 
70
- nested = resolve_class(exposure.using_class_name)
71
- collect(nested, acc) if nested
71
+ # Walks block exposures and merged entities too: a merged entity gets no
72
+ # schema of its own, but the entities IT references still do.
73
+ def collect_exposures(exposures, acc, merging)
74
+ exposures.each do |exposure|
75
+ if exposure.nesting?
76
+ collect_exposures(exposure.nested_exposures, acc, merging)
77
+ elsif represent_exposure?(exposure)
78
+ nested = resolve_class(exposure.using_class_name)
79
+ next unless nested.respond_to?(:root_exposures)
80
+
81
+ if exposure.for_merge
82
+ next if merging.include?(nested)
83
+
84
+ collect_exposures(nested.root_exposures, acc, merging + [nested])
85
+ else
86
+ collect(nested, acc)
87
+ end
88
+ end
72
89
  end
73
90
  end
74
91
 
@@ -109,57 +126,105 @@ module GrapeOpenapi3
109
126
  # --- schema building -------------------------------------------------
110
127
 
111
128
  def build_schema(entity_class)
129
+ object_schema(entity_class.root_exposures, [entity_class], schema_name(entity_class))
130
+ end
131
+
132
+ # Object schema for a list of exposures — an entity's root exposures or the
133
+ # children of a block exposure. `merging` guards against merge cycles;
134
+ # `owner` names the object in strict-mode reports ("Entity.block").
135
+ def object_schema(exposures, merging, owner)
112
136
  properties = {}
113
137
  required = []
138
+ exposures.each { |exposure| add_exposure(exposure, properties, required, merging, owner) }
114
139
 
115
- entity_class.root_exposures.each do |exposure|
116
- key = exposure.key(nil).to_s
117
- doc = exposure.documentation || {}
118
-
119
- prop = build_property(exposure, doc)
120
- ref_like = prop.key?("$ref")
140
+ schema = { "type" => "object", "properties" => properties }
141
+ schema["required"] = required unless required.empty?
142
+ schema
143
+ end
121
144
 
122
- # OpenAPI 3.0: $ref cannot have sibling properties — wrap in allOf
123
- prop = { "allOf" => [prop] } if ref_like && (!doc[:desc].nil? || doc[:nullable])
145
+ def add_exposure(exposure, properties, required, merging, owner)
146
+ return merge_exposure(exposure, properties, required, merging, owner) if exposure.for_merge
124
147
 
125
- # enum/format/example/min/max only apply to value schemas, never to $refs
126
- apply_keywords(prop, doc) unless ref_like
148
+ key = exposure.key(nil).to_s
149
+ doc = exposure.documentation || {}
127
150
 
128
- prop["description"] = doc[:desc].to_s unless doc[:desc].nil?
129
- prop["nullable"] = true if doc[:nullable]
151
+ prop = build_property(exposure, doc, merging, "#{owner}.#{key}")
152
+ ref_like = prop.key?("$ref")
153
+ scalar_keywords, own_keywords = KeywordMapper.call(doc)
130
154
 
131
- properties[key] = prop
132
- required << key if doc[:required]
155
+ # OpenAPI 3.0: $ref cannot have sibling properties. A nullable $ref becomes
156
+ # anyOf [$ref, null] — `nullable` only widens a `type` in the same schema
157
+ # (3.0.3), so `allOf + nullable` would still reject null. Any other sibling
158
+ # (description, readOnly…) just wraps the $ref in allOf.
159
+ if ref_like && doc[:nullable]
160
+ prop = { "anyOf" => [prop, null_schema] }
161
+ elsif ref_like && (!doc[:desc].nil? || own_keywords.any?)
162
+ prop = { "allOf" => [prop] }
133
163
  end
134
164
 
135
- schema = { "type" => "object", "properties" => properties }
136
- schema["required"] = required unless required.empty?
137
- schema
165
+ # enum/format/example/min/max only apply to value schemas, never to $refs
166
+ apply_keywords(prop, doc, scalar_keywords) unless ref_like
167
+
168
+ prop.merge!(own_keywords)
169
+ prop["description"] = doc[:desc].to_s unless doc[:desc].nil?
170
+ prop["nullable"] = true if doc[:nullable] && !ref_like
171
+
172
+ properties[key] = prop
173
+ # A conditional exposure (if:/unless:) can be absent, so it is never required.
174
+ required << key if doc[:required] && !exposure.conditional?
175
+ end
176
+
177
+ # `merge: true` flattens the exposed fields into the parent object instead of
178
+ # nesting them under the exposure's key.
179
+ # Merged fields land in the parent, so they are reported under its name.
180
+ def merge_exposure(exposure, properties, required, merging, owner)
181
+ source = merge_source(exposure, merging, owner)
182
+ return unless source
183
+
184
+ properties.merge!(source["properties"])
185
+ required.concat(Array(source["required"])) unless exposure.conditional?
186
+ end
187
+
188
+ def merge_source(exposure, merging, owner)
189
+ return object_schema(exposure.nested_exposures, merging, owner) if exposure.nesting?
190
+ return nil unless represent_exposure?(exposure)
191
+
192
+ nested = resolve_class(exposure.using_class_name)
193
+ return nil if !nested.respond_to?(:root_exposures) || merging.include?(nested)
194
+
195
+ object_schema(nested.root_exposures, merging + [nested], owner)
138
196
  end
139
197
 
140
198
  # Attach OpenAPI value keywords from the entity's documentation hash.
141
199
  # enum (or values), format, minimum, maximum → the scalar schema
142
200
  # (the array's items when it's an array of scalars, otherwise the prop)
201
+ # values: also takes a Range or a lazy proc (see ValuesMapper)
202
+ # min_length, max_length, pattern, multiple_of (see KeywordMapper)
143
203
  # default, example → the property itself
144
- def apply_keywords(prop, doc)
204
+ def apply_keywords(prop, doc, scalar_keywords)
145
205
  scalar = scalar_target(prop)
146
- enum = doc[:enum] || doc[:values]
147
206
 
148
207
  if scalar
149
- scalar["enum"] = Array(enum) if enum
208
+ scalar.merge!(ValuesMapper.call(doc[:enum] || doc[:values]))
209
+ scalar.merge!(scalar_keywords)
150
210
  scalar["format"] = doc[:format].to_s if doc[:format]
151
- scalar["minimum"] = doc[:minimum] unless doc[:minimum].nil?
152
- scalar["maximum"] = doc[:maximum] unless doc[:maximum].nil?
211
+ scalar["minimum"] = ValuesMapper.json_number(doc[:minimum]) unless doc[:minimum].nil?
212
+ scalar["maximum"] = ValuesMapper.json_number(doc[:maximum]) unless doc[:maximum].nil?
153
213
  end
154
214
 
155
215
  prop["default"] = doc[:default] unless doc[:default].nil?
156
216
  prop["example"] = doc[:example] unless doc[:example].nil?
157
217
  end
158
218
 
219
+ # OpenAPI 3.0 has no `type: null`; this is the 3.0 way to accept only null.
220
+ def null_schema
221
+ { "type" => "object", "nullable" => true, "enum" => [nil] }
222
+ end
223
+
159
224
  # The schema that scalar keywords belong to, or nil when there is none
160
225
  # (e.g. an array of $refs). For an array of scalars it is the `items` schema.
161
226
  def scalar_target(prop)
162
- return nil if prop.key?("$ref") || prop.key?("allOf")
227
+ return nil if prop.key?("$ref") || prop.key?("allOf") || prop.key?("anyOf")
163
228
 
164
229
  if prop["type"] == "array"
165
230
  items = prop["items"]
@@ -169,17 +234,38 @@ module GrapeOpenapi3
169
234
  end
170
235
  end
171
236
 
172
- def build_property(exposure, doc)
173
- if represent_exposure?(exposure)
174
- nested_class = resolve_class(exposure.using_class_name)
175
- nested_name = register(nested_class)
176
- ref = { "$ref" => "#/components/schemas/#{nested_name}" }
237
+ def build_property(exposure, doc, merging, location)
238
+ if exposure.nesting?
239
+ # Block exposure: `expose :stats do ... end` → inline object schema
240
+ object_schema(exposure.nested_exposures, merging, location)
241
+ elsif represent_exposure?(exposure)
242
+ ref = entity_ref(exposure, location)
177
243
  doc[:is_array] ? { "type" => "array", "items" => ref } : ref
178
244
  else
179
- TypeMapper.call(doc[:type] || String)
245
+ scalar_property(doc[:type], location)
180
246
  end
181
247
  end
182
248
 
249
+ # $ref to the `using:` entity; a plain object when it cannot be resolved
250
+ # (a $ref to a missing schema would make the whole document invalid).
251
+ def entity_ref(exposure, location)
252
+ nested_name = register(resolve_class(exposure.using_class_name))
253
+ return { "$ref" => "#/components/schemas/#{nested_name}" } if nested_name
254
+
255
+ @diagnostics.report(location, "using: #{exposure.using_class_name} cannot be resolved — documented as object")
256
+ { "type" => "object" }
257
+ end
258
+
259
+ def scalar_property(type, location)
260
+ if type.nil?
261
+ @diagnostics.report(location, "no documentation type — documented as string")
262
+ elsif (unknown = TypeMapper.unknown_type(type))
263
+ @diagnostics.report(location, "unknown type #{unknown} — documented as string")
264
+ end
265
+
266
+ TypeMapper.call(type || String)
267
+ end
268
+
183
269
  def represent_exposure?(exposure)
184
270
  exposure.class.name == REPRESENT_EXPOSURE
185
271
  end