api_recipes 2.10.3 → 3.0.0.beta1

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.
@@ -0,0 +1,680 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ApiRecipes
4
+ module Internals
5
+ # Turns configuration Hashes into trees of Definition::Api and
6
+ # Definition::Endpoint. Every rule of the configuration is checked here, once;
7
+ # all the problems found are reported together in one ConfigurationError.
8
+ class Compiler
9
+ API_KEYS = %i[protocol host port base_url timeout on_bad_code mime_type verify_with default_headers
10
+ endpoints auth variables recipe].freeze
11
+ WITH_API_KEYS = %i[protocol host port base_url timeout on_bad_code mime_type verify_with default_headers
12
+ variables authorization basic_auth].freeze
13
+ ENDPOINT_KEYS = %i[path verb route ok_code timeout on_bad_code mime_type verify_with endpoints].freeze
14
+ WITH_ENDPOINT_KEYS = %i[timeout on_bad_code ok_code mime_type verify_with].freeze
15
+ SCOPE_KEYS = { api: API_KEYS, with_api: WITH_API_KEYS, endpoint: ENDPOINT_KEYS,
16
+ with_endpoint: WITH_ENDPOINT_KEYS }.freeze
17
+
18
+ PROTOCOLS = %w[http https].freeze
19
+ ON_BAD_CODE = %w[raise ignore].freeze
20
+ AUTH_TYPES = %w[none bearer basic header query].freeze
21
+ TOKEN = /\A[A-Za-z0-9!#$%&'*+.^_|~-]+\z/
22
+ METHOD_NAME = /\A[A-Za-z_]\w*[?!]?\z/
23
+ VARIABLE_NAME = /\A[A-Za-z_]\w*\z/
24
+ HOST_FIXED = /\A[A-Za-z0-9._-]*\z/
25
+ VARIABLE_TOKEN = /(\{[A-Za-z_]\w*\})/
26
+ CONTROL = /[\x00-\x1F\x7F]/
27
+ IGNORED_KEY = /\Ax[-_]/
28
+
29
+ class << self
30
+ def compile(name, config)
31
+ compile_all({ name => config }).values.first
32
+ end
33
+
34
+ # given: the variable values of configure ({ api_name => { name => value } });
35
+ # a name that its api does not declare is reported with the other problems.
36
+ def compile_all(configs, given = nil)
37
+ compiler = new
38
+ apis = compiler.compile_all(configs)
39
+ compiler.check_given_variables(apis, given)
40
+ compiler.finish!
41
+ apis
42
+ end
43
+
44
+ # The problems of the names in values (Symbol keys, as the compiler
45
+ # resolves them) that definition does not declare. where is the
46
+ # location of the api, or empty.
47
+ def unknown_variables(values, definition, where = '')
48
+ return [] if values.nil? || values.empty?
49
+
50
+ declared = definition.variables.keys.sort
51
+ shown = declared.empty? ? 'none declared' : "declared: #{declared.join(', ')}"
52
+ prefix = where.empty? ? 'variables' : "#{where}.variables"
53
+ values.keys.reject { |name| definition.variables.key?(name) }.map do |name|
54
+ "#{prefix}: unknown variable '#{name}' (#{shown})"
55
+ end
56
+ end
57
+
58
+ # scope: :api, :with_api or :with_endpoint. Returns the problems, never raises.
59
+ # variables, for :api only: the names that the options may use beside
60
+ # those they declare; :any when they are not known yet.
61
+ def check_options(options, scope, variables: [])
62
+ raise ArgumentError, "unknown scope '#{scope}'" unless %i[api with_api with_endpoint].include?(scope)
63
+
64
+ compiler = new
65
+ compiler.check(options, scope, variables)
66
+ compiler.errors
67
+ end
68
+
69
+ # The validated options of a `with`, in the form the tree stores them.
70
+ def resolve_options(options, scope)
71
+ raise ArgumentError, "unknown scope '#{scope}'" unless %i[with_api with_endpoint].include?(scope)
72
+
73
+ compiler = new
74
+ resolved = compiler.resolve(options, scope)
75
+ compiler.finish!
76
+ resolved
77
+ end
78
+
79
+ def normalize(value, kind = :options)
80
+ compiler = new
81
+ normalized = compiler.normalize(value, '', kind)
82
+ compiler.finish!
83
+ normalized
84
+ end
85
+
86
+ def deep_merge(base, override)
87
+ merge(normalize(base), normalize(override))
88
+ end
89
+
90
+ # A deep copy whose Hashes, Arrays and Strings are frozen: input kept
91
+ # for a later compilation cannot be changed by the caller.
92
+ def frozen_copy(value) = new.frozen_copy(value)
93
+
94
+ private
95
+
96
+ # A nil option keeps what the base has. Among endpoints a nil value
97
+ # for a name that the base does not have is kept: it is an endpoint
98
+ # given without options.
99
+ def merge(base, override, endpoints = false)
100
+ merged = base.dup
101
+ override.each do |key, value|
102
+ next if value.nil? && (!endpoints || merged.key?(key))
103
+
104
+ merged[key] = if IGNORED_KEY.match?(key.to_s) || !(value.is_a?(Hash) && merged[key].is_a?(Hash))
105
+ value
106
+ else
107
+ merge(merged[key], value, !endpoints && key == :endpoints)
108
+ end
109
+ end
110
+ merged
111
+ end
112
+ end
113
+
114
+ attr_reader :errors
115
+
116
+ def initialize
117
+ @errors = []
118
+ end
119
+
120
+ def compile_all(configs)
121
+ return {}.freeze if configs.nil?
122
+
123
+ unless configs.is_a?(Hash)
124
+ add('apis', 'must be a Hash')
125
+ return {}
126
+ end
127
+ normalize(configs, '', :options_map).each_with_object({}) do |(name, config), out|
128
+ api = compile_one(name, config)
129
+ out[name] = api if api
130
+ end.freeze
131
+ end
132
+
133
+ def check(options, scope, variables = [])
134
+ unless options.is_a?(Hash)
135
+ add('', 'options must be a Hash')
136
+ return
137
+ end
138
+ options = normalize(options, '')
139
+ scope == :api ? api_attrs(nil, options, '', variables) : validate_with(options, scope)
140
+ end
141
+
142
+ def resolve(options, scope)
143
+ unless options.is_a?(Hash)
144
+ add('', 'options must be a Hash')
145
+ return {}
146
+ end
147
+ validate_with(normalize(options, ''), scope)
148
+ end
149
+
150
+ # A copy with Symbol keys at every level. Strings are checked for their
151
+ # encoding; two keys that become the same Symbol are reported.
152
+ #
153
+ # kind is :options for a Hash of options (the value of an x- key is left
154
+ # alone), :options_map for a Hash of names to options, :free otherwise.
155
+ def normalize(value, location, kind = :options)
156
+ case value
157
+ when Hash, Array then guard_cycle(value, location) { normalize_container(value, location, kind) }
158
+ when String then clean_string(value, location)
159
+ else value
160
+ end
161
+ end
162
+
163
+ # The unknown names in given, which can still be raw: what is not a Hash
164
+ # is left to the caller, which reports it.
165
+ def check_given_variables(apis, given)
166
+ return unless given.is_a?(Hash)
167
+
168
+ normalize(given, 'variables', :free).each do |name, values|
169
+ definition = apis[name]
170
+ next unless definition && values.is_a?(Hash)
171
+
172
+ @errors.concat(self.class.unknown_variables(values, definition, name.to_s))
173
+ end
174
+ end
175
+
176
+ def finish!
177
+ raise ConfigurationError.new(@errors) unless @errors.empty?
178
+ end
179
+
180
+ def frozen_copy(value) = deep_freeze(value)
181
+
182
+ private
183
+
184
+ def guard_cycle(value, location)
185
+ @visiting ||= []
186
+ if @visiting.any? { |other| other.equal?(value) }
187
+ add(location, 'must not contain itself')
188
+ return value.is_a?(Hash) ? {} : []
189
+ end
190
+ @visiting.push(value)
191
+ begin
192
+ yield
193
+ ensure
194
+ @visiting.pop
195
+ end
196
+ end
197
+
198
+ def normalize_container(value, location, kind)
199
+ return value.map { |item| normalize(item, location, :free) } if value.is_a?(Array)
200
+
201
+ normalize_hash(value, location, kind)
202
+ end
203
+
204
+ def normalize_hash(hash, location, kind)
205
+ seen = {}
206
+ hash.each_with_object({}) do |(key, item), out|
207
+ unless key.is_a?(String) || key.is_a?(Symbol)
208
+ add(location, 'name must be a String or a Symbol')
209
+ next
210
+ end
211
+ text = key.is_a?(String) ? clean_string(key, location) : key.to_s
212
+ next if text.nil?
213
+
214
+ name = text.to_sym
215
+ if seen.key?(name)
216
+ kinds = seen[name] == key.class ? "two #{key.class}s" : 'a String and as a Symbol'
217
+ add(location, "option #{shown(name)} is given twice (as #{kinds})")
218
+ next
219
+ end
220
+ seen[name] = key.class
221
+ out[name] = normalize_item(name, item, location, kind)
222
+ end
223
+ end
224
+
225
+ def normalize_item(name, item, location, kind)
226
+ return item if kind == :options && IGNORED_KEY.match?(name.to_s)
227
+
228
+ child = kind == :options_map ? :options : :free
229
+ child = :options_map if kind == :options && name == :endpoints
230
+ normalize(item, join(location, name), child)
231
+ end
232
+
233
+ def clean_string(string, location)
234
+ text = [Encoding::UTF_8, Encoding::US_ASCII].include?(string.encoding) ? string : string.encode(Encoding::UTF_8)
235
+ return text if text.valid_encoding?
236
+
237
+ add(location, 'must be valid UTF-8')
238
+ nil
239
+ rescue EncodingError
240
+ add(location, 'must be valid UTF-8')
241
+ nil
242
+ end
243
+
244
+ def compile_one(name, config)
245
+ config = {} if config.nil?
246
+ return nil unless valid_name?(name, '', 'an api')
247
+
248
+ unless config.is_a?(Hash)
249
+ add(label(name), 'must be a Hash')
250
+ return nil
251
+ end
252
+ attrs = api_attrs(name, config, label(name))
253
+ build_api(name, attrs) if @errors.empty?
254
+ end
255
+
256
+ def valid_name?(name, location, what)
257
+ text = name.to_s
258
+ if text.empty?
259
+ add(location, "#{what} name must not be empty")
260
+ elsif CONTROL.match?(text)
261
+ add(location, "#{what} name #{shown(name)} must not contain control characters")
262
+ else
263
+ return true
264
+ end
265
+ false
266
+ end
267
+
268
+ def add(location, message)
269
+ @errors << (location.empty? ? message : "#{location}: #{message}")
270
+ end
271
+
272
+ def label(value)
273
+ value.to_s.gsub(/[^[:print:]]/, '?')[0, 40]
274
+ end
275
+
276
+ def join(location, key)
277
+ location.empty? ? label(key) : "#{location}.#{label(key)}"
278
+ end
279
+
280
+ def shown(value)
281
+ "'#{label(value)}'"
282
+ end
283
+
284
+ def check_keys(hash, allowed, location)
285
+ hash.each_key do |key|
286
+ next if IGNORED_KEY.match?(key.to_s)
287
+
288
+ add(location, "unknown option #{shown(key)}") unless allowed.include?(key)
289
+ end
290
+ end
291
+
292
+ # ---- api ----
293
+
294
+ # known: names of variables declared elsewhere, or :any to accept every name.
295
+ def api_attrs(_name, config, location, known = [])
296
+ check_keys(config, API_KEYS, location)
297
+ variables = config[:variables].is_a?(Hash) ? config[:variables] : {}
298
+ declared = known == :any ? nil : variables.keys + known
299
+ attrs = {}
300
+ attrs[:protocol] = option(:protocol, config, location, :api, declared)
301
+ host = option(:host, config, location, :api, declared)
302
+ attrs[:host] = host
303
+ attrs[:port] = option(:port, config, location, :api, declared)
304
+ attrs[:base_url] = option(:base_url, config, location, :api, declared)
305
+ attrs[:timeout] = option(:timeout, config, location, :api, declared)
306
+ attrs[:on_bad_code] = option(:on_bad_code, config, location, :api, declared)
307
+ attrs[:mime_type] = option(:mime_type, config, location, :api, declared)
308
+ attrs[:verify_with] = option(:verify_with, config, location, :api, declared)
309
+ attrs[:default_headers] = option(:default_headers, config, location, :api, declared)
310
+ attrs[:auth] = option(:auth, config, location, :api, declared)
311
+ attrs[:variables] = option(:variables, config, location, :api, declared)
312
+ attrs[:recipe] = option(:recipe, config, location, :api, declared)
313
+ attrs[:endpoints] = endpoints_attrs(config[:endpoints], join(location, :endpoints))
314
+ attrs
315
+ end
316
+
317
+ def validate_with(options, scope)
318
+ allowed = SCOPE_KEYS.fetch(scope)
319
+ check_keys(options, allowed, '')
320
+ options.each_with_object({}) do |(key, value), out|
321
+ next unless allowed.include?(key)
322
+
323
+ resolved = %i[authorization basic_auth].include?(key) ? deep_freeze(value) : option(key, options, '', scope, nil)
324
+ out[key] = resolved unless resolved.nil?
325
+ end.freeze
326
+ end
327
+
328
+ # ---- endpoints ----
329
+
330
+ def endpoints_attrs(value, location)
331
+ return {} if value.nil?
332
+
333
+ unless value.is_a?(Hash)
334
+ add(location, 'must be a Hash')
335
+ return {}
336
+ end
337
+ value.each_with_object({}) do |(name, options), out|
338
+ node_location = join(location, name)
339
+ next unless valid_name?(name, location, 'an endpoint')
340
+
341
+ if options.nil?
342
+ options = {}
343
+ elsif !options.is_a?(Hash)
344
+ add(node_location, 'must be a Hash or empty')
345
+ next
346
+ end
347
+ out[name.to_sym] = endpoint_attrs(name.to_sym, options, node_location)
348
+ end
349
+ end
350
+
351
+ def endpoint_attrs(name, options, location)
352
+ check_keys(options, ENDPOINT_KEYS, location)
353
+ own = {}
354
+ (ENDPOINT_KEYS - %i[endpoints]).each do |key|
355
+ value = option(key, options, location, :endpoint, nil)
356
+ own[key] = value unless value.nil?
357
+ end
358
+ path = own[:path] || name.to_s
359
+ template = parse_path(path, join(location, :path), options.key?(:path) && !options[:path].nil?)
360
+ { own: own, template: template, children: endpoints_attrs(options[:endpoints], join(location, :endpoints)) }
361
+ end
362
+
363
+ def parse_path(path, location, written)
364
+ PathTemplate.parse(path)
365
+ rescue ArgumentError => e
366
+ repeated = e.message[/\Aplaceholder '(.*?)' is repeated/m, 1]
367
+ problem = repeated ? "placeholder #{shown(repeated)} is repeated" : 'is not a valid path'
368
+ add(location, written ? problem : "the endpoint name makes an invalid path: #{problem}")
369
+ PathTemplate.parse('')
370
+ end
371
+
372
+ # ---- options ----
373
+
374
+ # Validates options[key] and returns its normalized value (nil when absent or invalid).
375
+ def option(key, options, location, scope, declared)
376
+ value = options[key]
377
+ return nil if value.nil?
378
+
379
+ where = join(location, key)
380
+ case key
381
+ when :protocol then one_of(value, PROTOCOLS, where)
382
+ when :host then host(value, where, declared)
383
+ when :port then positive_integer(value, where)
384
+ when :base_url then base_url(value, where, declared)
385
+ when :timeout then positive_number(value, where)
386
+ when :on_bad_code then one_of(value, ON_BAD_CODE, where)
387
+ when :mime_type then mime_type(value, where)
388
+ when :verify_with then method_name(value, where)
389
+ when :default_headers then headers(value, where, declared)
390
+ when :auth then auth(value, where)
391
+ when :variables then scope == :with_api ? variable_values(value, where) : variable_declarations(value, where)
392
+ when :recipe then recipe(value, where)
393
+ when :path then path(value, where)
394
+ when :verb then verb(value, where)
395
+ when :route then route(value, where)
396
+ when :ok_code then ok_code(value, where)
397
+ end
398
+ end
399
+
400
+ def one_of(value, allowed, where)
401
+ text = value.is_a?(String) || value.is_a?(Symbol) ? value.to_s : nil
402
+ return text.dup.freeze if text && allowed.include?(text)
403
+
404
+ add(where, "#{shown(value)} is not one of #{allowed.join(', ')}")
405
+ nil
406
+ end
407
+
408
+ # A String of digits is read as its number, as 2.x did.
409
+ def positive_integer(value, where)
410
+ value = value.to_i if value.is_a?(String) && value.match?(/\A[0-9]{1,5}\z/)
411
+ return value if value.is_a?(Integer) && value.between?(1, 65_535)
412
+
413
+ add(where, 'must be an integer from 1 to 65535')
414
+ nil
415
+ end
416
+
417
+ def positive_number(value, where)
418
+ return value if (value.is_a?(Integer) || value.is_a?(Rational) || (value.is_a?(Float) && value.finite?)) && value.positive?
419
+
420
+ add(where, 'must be a positive number')
421
+ nil
422
+ end
423
+
424
+ # A Symbol stays a Symbol: http.rb reads it as one of its aliases (:json).
425
+ def mime_type(value, where)
426
+ text = value.is_a?(String) || value.is_a?(Symbol) ? value.to_s : nil
427
+ if text && !text.empty? && !CONTROL.match?(text)
428
+ return value.is_a?(Symbol) ? value : text.dup.freeze
429
+ end
430
+
431
+ add(where, 'must be a string without control characters')
432
+ nil
433
+ end
434
+
435
+ def method_name(value, where)
436
+ text = value.is_a?(String) || value.is_a?(Symbol) ? value.to_s : nil
437
+ return text.to_sym if text && METHOD_NAME.match?(text)
438
+
439
+ add(where, 'must be a valid method name')
440
+ nil
441
+ end
442
+
443
+ def check_variables(string, where, declared)
444
+ return if declared.nil?
445
+
446
+ names = string.scan(Template::VARIABLE).flatten.map(&:to_sym).uniq
447
+ names.each { |name| add(where, "unknown variable #{shown(name)}") unless declared.include?(name) }
448
+ end
449
+
450
+ def host(value, where, declared)
451
+ unless value.is_a?(String) || value.is_a?(Symbol)
452
+ add(where, 'must be a string')
453
+ return nil
454
+ end
455
+ string = value.to_s
456
+ fixed = string.gsub(Template::VARIABLE, '')
457
+ problem = nil
458
+ if string.empty?
459
+ problem = 'must not be empty'
460
+ elsif !HOST_FIXED.match?(fixed)
461
+ problem = "must be a plain host name (letters, digits, '-', '_' and '.'): no scheme, path, port, user, space or other characters"
462
+ elsif fixed == string && (!string.match?(/[A-Za-z0-9]/) || string.include?('..'))
463
+ problem = "must contain a letter or a digit and must not contain '..'"
464
+ end
465
+ if problem
466
+ add(where, problem)
467
+ return nil
468
+ end
469
+
470
+ check_variables(string, where, declared)
471
+ string.dup.freeze
472
+ end
473
+
474
+ def base_url(value, where, declared)
475
+ unless value.is_a?(String) || value.is_a?(Symbol)
476
+ add(where, 'must be a string')
477
+ return nil
478
+ end
479
+ string = value.to_s
480
+ check_variables(string, where, declared)
481
+ placeholder = false
482
+ encoded = string.split(VARIABLE_TOKEN).map do |piece|
483
+ next piece if VARIABLE_TOKEN.match?(piece)
484
+
485
+ begin
486
+ template = PathTemplate.parse(piece)
487
+ placeholder ||= !template.param_names.empty?
488
+ template.to_s
489
+ rescue ArgumentError
490
+ placeholder = true
491
+ piece
492
+ end
493
+ end.join
494
+ if placeholder
495
+ add(where, 'path placeholders are not allowed here; declare a variable and write {name}')
496
+ return nil
497
+ end
498
+ encoded.freeze
499
+ end
500
+
501
+ def headers(value, where, declared)
502
+ unless value.is_a?(Hash)
503
+ add(where, 'must be a Hash')
504
+ return nil
505
+ end
506
+ value.each_with_object({}) do |(name, header), out|
507
+ name = name.to_s
508
+ header_where = join(where, name)
509
+ add(header_where, 'is not a valid header name') unless TOKEN.match?(name)
510
+ unless header.is_a?(String) || header.is_a?(Symbol) || header.is_a?(Numeric)
511
+ add(header_where, 'must be a string')
512
+ next
513
+ end
514
+ text = header.to_s
515
+ add(header_where, 'must not contain control characters') if CONTROL.match?(text.gsub(Template::VARIABLE, ''))
516
+ check_variables(text, header_where, declared)
517
+ out[name.dup.freeze] = text.dup.freeze
518
+ end.freeze
519
+ end
520
+
521
+ def auth(value, where)
522
+ unless value.is_a?(Hash)
523
+ add(where, 'must be a Hash')
524
+ return nil
525
+ end
526
+ check_keys(value, %i[type name], where)
527
+ type = one_of(value[:type], AUTH_TYPES, join(where, :type)) unless value[:type].nil?
528
+ add(join(where, :type), 'is required') if value[:type].nil?
529
+ name = value[:name]
530
+ if %w[header query].include?(type) && name.nil?
531
+ add(join(where, :name), "is required when type is #{type}")
532
+ elsif !name.nil?
533
+ if (name.is_a?(String) || name.is_a?(Symbol)) && TOKEN.match?(name.to_s)
534
+ name = name.to_s.dup.freeze
535
+ else
536
+ add(join(where, :name), 'must be made of letters, digits and the characters ! # $ % & \' * + . ^ _ | ~ -')
537
+ name = nil
538
+ end
539
+ end
540
+ return nil unless type
541
+
542
+ { type: type.to_sym, name: name }.compact.freeze
543
+ end
544
+
545
+ def variable_declarations(value, where)
546
+ unless value.is_a?(Hash)
547
+ add(where, 'must be a Hash')
548
+ return nil
549
+ end
550
+ value.each_with_object({}) do |(name, spec), out|
551
+ spec_where = join(where, name)
552
+ add(spec_where, 'is not a valid variable name') unless VARIABLE_NAME.match?(name.to_s)
553
+ spec = {} if spec.nil?
554
+ unless spec.is_a?(Hash)
555
+ add(spec_where, 'must be a Hash or empty')
556
+ next
557
+ end
558
+ check_keys(spec, %i[default description], spec_where)
559
+ default = variable_text(spec[:default], join(spec_where, :default))
560
+ description = variable_text(spec[:description], join(spec_where, :description), numbers: false)
561
+ out[name.to_sym] = { default: default, description: description }.freeze
562
+ end.freeze
563
+ end
564
+
565
+ def variable_text(value, where, numbers: true)
566
+ return nil if value.nil?
567
+ return value.to_s.dup.freeze if value.is_a?(String) || (numbers && (value.is_a?(Symbol) || value.is_a?(Numeric)))
568
+
569
+ add(where, 'must be a string')
570
+ nil
571
+ end
572
+
573
+ def variable_values(value, where)
574
+ unless value.is_a?(Hash)
575
+ add(where, 'must be a Hash')
576
+ return nil
577
+ end
578
+ value.each_key { |name| add(join(where, name), 'is not a valid variable name') unless VARIABLE_NAME.match?(name.to_s) }
579
+ deep_freeze(value)
580
+ end
581
+
582
+ def recipe(value, where)
583
+ return deep_freeze(value) if value.is_a?(Hash)
584
+
585
+ add(where, 'must be a Hash')
586
+ nil
587
+ end
588
+
589
+ # memo maps what is being copied to its copy, so that the content of an x-
590
+ # option, which is not inspected, can hold a structure that contains itself.
591
+ def deep_freeze(value, memo = {}.compare_by_identity)
592
+ case value
593
+ when Hash
594
+ return memo[value] if memo.key?(value)
595
+
596
+ copy = memo[value] = {}
597
+ value.each { |key, item| copy[key] = deep_freeze(item, memo) }
598
+ copy.freeze
599
+ when Array
600
+ return memo[value] if memo.key?(value)
601
+
602
+ copy = memo[value] = []
603
+ value.each { |item| copy << deep_freeze(item, memo) }
604
+ copy.freeze
605
+ when String then value.dup.freeze
606
+ else value
607
+ end
608
+ end
609
+
610
+ def path(value, where)
611
+ return value.dup.freeze if value.is_a?(String)
612
+
613
+ add(where, 'must be a string')
614
+ nil
615
+ end
616
+
617
+ def verb(value, where)
618
+ text = value.is_a?(String) || value.is_a?(Symbol) ? value.to_s.downcase : nil
619
+ return text.to_sym if text && HTTP::Request::METHODS.include?(text.to_sym)
620
+
621
+ add(where, "#{shown(value)} is not a verb known to http.rb")
622
+ nil
623
+ end
624
+
625
+ def route(value, where)
626
+ case value
627
+ when true, 'yes' then true
628
+ when false, 'no' then false
629
+ else
630
+ add(where, "#{shown(value)} is not one of true, false, yes, no")
631
+ nil
632
+ end
633
+ end
634
+
635
+ def ok_code(value, where)
636
+ return value if value.is_a?(Integer)
637
+ return value.dup.freeze if value.is_a?(Array) && !value.empty? && value.all?(Integer)
638
+
639
+ add(where, 'must be an integer or a list of integers')
640
+ nil
641
+ end
642
+
643
+ # ---- build ----
644
+
645
+ def build_api(name, attrs)
646
+ host = attrs[:host] || 'localhost'
647
+ base_url = attrs[:base_url]
648
+ headers = attrs[:default_headers] || {}
649
+ Definition::Api.new(
650
+ name: name,
651
+ protocol: attrs[:protocol] || 'https',
652
+ host: host,
653
+ port: attrs[:port],
654
+ base_url: base_url,
655
+ timeout: attrs[:timeout] || 3,
656
+ on_bad_code: attrs[:on_bad_code] || 'raise',
657
+ mime_type: attrs[:mime_type],
658
+ verify_with: attrs[:verify_with],
659
+ default_headers: headers.freeze,
660
+ auth: attrs[:auth],
661
+ variables: (attrs[:variables] || {}).freeze,
662
+ recipe: attrs[:recipe],
663
+ host_template: Template.new(host, :host),
664
+ base_url_template: base_url && Template.new(base_url, :base_url),
665
+ header_templates: headers.transform_values { |text| Template.new(text, :header) }.freeze,
666
+ children: ->(api) { build_endpoints(attrs[:endpoints], api) }
667
+ )
668
+ end
669
+
670
+ def build_endpoints(specs, parent)
671
+ specs.each_with_object({}) do |(name, spec), out|
672
+ out[name] = Definition::Endpoint.new(
673
+ name: name, parent: parent, own: spec[:own], template: spec[:template],
674
+ children: ->(node) { build_endpoints(spec[:children], node) }
675
+ )
676
+ end
677
+ end
678
+ end
679
+ end
680
+ end