api_recipes 3.0.0.beta4 → 3.0.0.beta6

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.
Files changed (37) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +340 -107
  3. data/UPGRADING.md +197 -49
  4. data/lib/api_recipes/cli/calls.rb +27 -0
  5. data/lib/api_recipes/cli/convert/migration.rb +201 -6
  6. data/lib/api_recipes/cli/convert.rb +130 -23
  7. data/lib/api_recipes/cli/description.rb +65 -0
  8. data/lib/api_recipes/cli/import/server.rb +20 -9
  9. data/lib/api_recipes/cli/import/writer.rb +16 -4
  10. data/lib/api_recipes/cli/import.rb +23 -9
  11. data/lib/api_recipes/cli/recipes/summary.rb +7 -5
  12. data/lib/api_recipes/cli/recipes.rb +5 -2
  13. data/lib/api_recipes/cli/routes.rb +62 -7
  14. data/lib/api_recipes/cli/tags.rb +19 -0
  15. data/lib/api_recipes/cli/upgrade/fix.rb +206 -0
  16. data/lib/api_recipes/cli/upgrade/screen.rb +165 -0
  17. data/lib/api_recipes/cli/upgrade/tree_rules.rb +290 -0
  18. data/lib/api_recipes/cli/upgrade.rb +385 -63
  19. data/lib/api_recipes/cli.rb +84 -17
  20. data/lib/api_recipes/configuration.rb +17 -108
  21. data/lib/api_recipes/errors.rb +20 -3
  22. data/lib/api_recipes/internals/compiler.rb +77 -70
  23. data/lib/api_recipes/internals/context.rb +7 -2
  24. data/lib/api_recipes/internals/declaration.rb +17 -15
  25. data/lib/api_recipes/internals/definition.rb +15 -2
  26. data/lib/api_recipes/internals/level.rb +6 -1
  27. data/lib/api_recipes/internals/origins.rb +70 -0
  28. data/lib/api_recipes/internals/path_template.rb +23 -6
  29. data/lib/api_recipes/internals/recipe.rb +31 -5
  30. data/lib/api_recipes/internals/recipe_lock.rb +12 -9
  31. data/lib/api_recipes/internals/registry.rb +21 -10
  32. data/lib/api_recipes/internals/request.rb +2 -2
  33. data/lib/api_recipes/internals/template.rb +32 -2
  34. data/lib/api_recipes/response.rb +125 -6
  35. data/lib/api_recipes/version.rb +1 -1
  36. data/lib/api_recipes.rb +1 -0
  37. metadata +8 -1
@@ -22,6 +22,9 @@ module ApiRecipes
22
22
  TOKEN = /\A[A-Za-z0-9!#$%&'*+.^_|~-]+\z/
23
23
  METHOD_NAME = /\A[A-Za-z_]\w*[?!]?\z/
24
24
  VARIABLE_NAME = /\A[A-Za-z_]\w*\z/
25
+ # What a variable that is used and not declared has: no default, so a
26
+ # value must be given, and no description.
27
+ UNDECLARED = { default: nil, description: nil }.freeze
25
28
  HOST_FIXED = /\A[A-Za-z0-9._-]*\z/
26
29
  VARIABLE_TOKEN = /(\{[A-Za-z_]\w*\})/
27
30
  CONTROL = /[\x00-\x1F\x7F]/
@@ -37,19 +40,13 @@ module ApiRecipes
37
40
  delete: { path: '/:id', verb: :delete }.freeze
38
41
  }.freeze
39
42
 
40
- # What the endpoints of one api are checked against. variables: the
41
- # names a path, a header or a parameter may use, nil when they are not
42
- # known. credential_param: the query parameter that carries the
43
- # credential, which default_params cannot set.
44
- Names = Data.define(:variables, :credential_param)
45
-
46
43
  class << self
47
44
  def compile(name, config)
48
45
  compile_all({ name => config }).values.first
49
46
  end
50
47
 
51
48
  # given: the variable values of configure ({ api_name => { name => value } });
52
- # a name that its api does not declare is reported with the other problems.
49
+ # a name that is not a variable of its api is reported with the other problems.
53
50
  def compile_all(configs, given = nil)
54
51
  compiler = new
55
52
  apis = compiler.compile_all(configs)
@@ -59,13 +56,13 @@ module ApiRecipes
59
56
  end
60
57
 
61
58
  # The problems of the names in values (Symbol keys, as the compiler
62
- # resolves them) that definition does not declare. where is the
63
- # location of the api, or empty.
59
+ # resolves them) that are not variables of definition: it neither
60
+ # declares nor uses them. where is the location of the api, or empty.
64
61
  def unknown_variables(values, definition, where = '')
65
62
  return [] if values.nil? || values.empty?
66
63
 
67
- declared = definition.variables.keys.sort
68
- shown = declared.empty? ? 'none declared' : "declared: #{declared.join(', ')}"
64
+ names = definition.variables.keys.sort
65
+ shown = names.empty? ? 'the api has no variables' : "variables of the api: #{names.join(', ')}"
69
66
  prefix = where.empty? ? 'variables' : "#{where}.variables"
70
67
  values.keys.reject { |name| definition.variables.key?(name) }.map do |name|
71
68
  "#{prefix}: unknown variable '#{name}' (#{shown})"
@@ -73,16 +70,14 @@ module ApiRecipes
73
70
  end
74
71
 
75
72
  # scope: :api, :with_api or :with_endpoint. Returns the problems, never raises.
76
- # variables, for :api only: the names that the options may use beside
77
- # those they declare; :any when they are not known yet.
78
73
  # credential_param, for :api only: the query parameter that carries
79
74
  # the credential of the api the options are merged with, which they
80
75
  # cannot set unless they give an auth of their own.
81
- def check_options(options, scope, variables: [], credential_param: nil)
76
+ def check_options(options, scope, credential_param: nil)
82
77
  raise ArgumentError, "unknown scope '#{scope}'" unless %i[api with_api with_endpoint].include?(scope)
83
78
 
84
79
  compiler = new
85
- compiler.check(options, scope, variables, credential_param)
80
+ compiler.check(options, scope, credential_param)
86
81
  compiler.errors
87
82
  end
88
83
 
@@ -173,13 +168,13 @@ module ApiRecipes
173
168
  end.freeze
174
169
  end
175
170
 
176
- def check(options, scope, variables = [], credential_param = nil)
171
+ def check(options, scope, credential_param = nil)
177
172
  unless options.is_a?(Hash)
178
173
  add('', 'options must be a Hash')
179
174
  return
180
175
  end
181
176
  options = normalize(options, '')
182
- scope == :api ? api_attrs(nil, options, '', variables, credential_param) : validate_with(options, scope)
177
+ scope == :api ? api_attrs(nil, options, '', credential_param) : validate_with(options, scope)
183
178
  end
184
179
 
185
180
  def resolve(options, scope)
@@ -334,36 +329,48 @@ module ApiRecipes
334
329
 
335
330
  # ---- api ----
336
331
 
337
- # known: names of variables declared elsewhere, or :any to accept every name.
338
332
  # credential_param: the one of the api these options are merged with,
339
333
  # used when they give no auth.
340
- def api_attrs(_name, config, location, known = [], credential_param = nil)
334
+ #
335
+ # A {name} that the options use and nothing declares is a variable of
336
+ # the api all the same, with no default: the declaration is where a
337
+ # default and a description are written, not what makes a variable.
338
+ def api_attrs(_name, config, location, credential_param = nil)
341
339
  check_keys(config, API_KEYS, location)
342
340
  @option_uses = nil
343
- variables = config[:variables].is_a?(Hash) ? config[:variables] : {}
344
- declared = known == :any ? nil : variables.keys + known
341
+ @used_variables = []
345
342
  attrs = {}
346
- attrs[:protocol] = option(:protocol, config, location, :api, declared)
347
- host = option(:host, config, location, :api, declared)
343
+ attrs[:protocol] = option(:protocol, config, location, :api)
344
+ host = option(:host, config, location, :api)
348
345
  attrs[:host] = host
349
- attrs[:port] = option(:port, config, location, :api, declared)
350
- attrs[:base_url] = option(:base_url, config, location, :api, declared)
351
- attrs[:timeout] = option(:timeout, config, location, :api, declared)
352
- attrs[:on_bad_code] = option(:on_bad_code, config, location, :api, declared)
353
- attrs[:mime_type] = option(:mime_type, config, location, :api, declared)
354
- attrs[:verify_with] = option(:verify_with, config, location, :api, declared)
355
- attrs[:default_headers] = option(:default_headers, config, location, :api, declared)
356
- attrs[:auth] = option(:auth, config, location, :api, declared)
346
+ attrs[:port] = option(:port, config, location, :api)
347
+ attrs[:base_url] = option(:base_url, config, location, :api)
348
+ attrs[:timeout] = option(:timeout, config, location, :api)
349
+ attrs[:on_bad_code] = option(:on_bad_code, config, location, :api)
350
+ attrs[:mime_type] = option(:mime_type, config, location, :api)
351
+ attrs[:verify_with] = option(:verify_with, config, location, :api)
352
+ attrs[:default_headers] = option(:default_headers, config, location, :api)
353
+ attrs[:auth] = option(:auth, config, location, :api)
357
354
  credential_param = credential_param(attrs[:auth]) unless config[:auth].nil?
358
- names = Names.new(variables: declared, credential_param: credential_param)
359
- attrs[:default_params] = option(:default_params, config, location, :api, names)
360
- attrs[:variables] = option(:variables, config, location, :api, declared)
361
- attrs[:recipe] = option(:recipe, config, location, :api, declared)
362
- attrs[:endpoints] = endpoints_attrs(config[:endpoints], join(location, :endpoints), names)
355
+ attrs[:default_params] = option(:default_params, config, location, :api, credential_param)
356
+ attrs[:variables] = option(:variables, config, location, :api)
357
+ attrs[:recipe] = option(:recipe, config, location, :api)
358
+ attrs[:endpoints] = endpoints_attrs(config[:endpoints], join(location, :endpoints), credential_param)
363
359
  check_option_defaults(attrs[:variables], location)
360
+ attrs[:variables] = with_used_variables(attrs[:variables])
364
361
  attrs
365
362
  end
366
363
 
364
+ # The declared variables, then those that are only used, in the order
365
+ # they are first written.
366
+ def with_used_variables(variables)
367
+ used = @used_variables.uniq - (variables || {}).keys
368
+ @used_variables = nil
369
+ return variables if used.empty?
370
+
371
+ (variables || {}).merge(used.to_h { |name| [name, UNDECLARED] }).freeze
372
+ end
373
+
367
374
  def credential_param(auth)
368
375
  auth && auth[:type] == :query ? auth[:name] : nil
369
376
  end
@@ -374,14 +381,14 @@ module ApiRecipes
374
381
  options.each_with_object({}) do |(key, value), out|
375
382
  next unless allowed.include?(key)
376
383
 
377
- resolved = %i[authorization basic_auth].include?(key) ? deep_freeze(value) : option(key, options, '', scope, nil)
384
+ resolved = %i[authorization basic_auth].include?(key) ? deep_freeze(value) : option(key, options, '', scope)
378
385
  out[key] = resolved unless resolved.nil?
379
386
  end.freeze
380
387
  end
381
388
 
382
389
  # ---- endpoints ----
383
390
 
384
- def endpoints_attrs(value, location, names)
391
+ def endpoints_attrs(value, location, credential_param)
385
392
  return {} if value.nil?
386
393
 
387
394
  unless value.is_a?(Hash)
@@ -398,26 +405,23 @@ module ApiRecipes
398
405
  add(node_location, 'must be a Hash or empty')
399
406
  next
400
407
  end
401
- out[name.to_sym] = endpoint_attrs(name.to_sym, options, node_location, names)
408
+ out[name.to_sym] = endpoint_attrs(name.to_sym, options, node_location, credential_param)
402
409
  end
403
410
  end
404
411
 
405
- def endpoint_attrs(name, options, location, names)
412
+ def endpoint_attrs(name, options, location, credential_param)
406
413
  check_keys(options, ENDPOINT_KEYS, location)
407
- declared = names.variables
408
414
  own = {}
409
415
  (ENDPOINT_KEYS - %i[endpoints resource]).each do |key|
410
- value = option(key, options, location, :endpoint, key == :default_params ? names : declared)
416
+ value = option(key, options, location, :endpoint, credential_param)
411
417
  own[key] = value unless value.nil?
412
418
  end
413
419
  children = with_resource(options[:resource], options[:endpoints], join(location, :resource))
414
420
  path = own[:path] || name.to_s
415
421
  template = parse_path(path, join(location, :path), options.key?(:path) && !options[:path].nil?)
416
- unless declared.nil?
417
- (template.variable_names - declared).each { |variable| add(join(location, :path), "unknown variable #{shown(variable)}") }
418
- end
422
+ use_variables(template.variable_names)
419
423
  { own: own, template: template,
420
- children: endpoints_attrs(children, join(location, :endpoints), names) }
424
+ children: endpoints_attrs(children, join(location, :endpoints), credential_param) }
421
425
  end
422
426
 
423
427
  # The endpoints written under an endpoint, with those its `resource`
@@ -452,24 +456,25 @@ module ApiRecipes
452
456
  # ---- options ----
453
457
 
454
458
  # Validates options[key] and returns its normalized value (nil when absent or invalid).
455
- def option(key, options, location, scope, declared)
459
+ # credential_param: what default_params cannot set, the only option that needs it.
460
+ def option(key, options, location, scope, credential_param = nil)
456
461
  value = options[key]
457
462
  return nil if value.nil?
458
463
 
459
464
  where = join(location, key)
460
- return option_with_variables(key, value, where, declared) if OptionValue.variable?(key, value)
465
+ return option_with_variables(key, value) if OptionValue.variable?(key, value)
461
466
 
462
467
  case key
463
468
  when :protocol then one_of(value, PROTOCOLS, where)
464
- when :host then host(value, where, declared)
469
+ when :host then host(value, where)
465
470
  when :port then positive_integer(value, where)
466
- when :base_url then base_url(value, where, declared)
471
+ when :base_url then base_url(value, where)
467
472
  when :timeout then positive_number(value, where)
468
473
  when :on_bad_code then one_of(value, ON_BAD_CODE, where)
469
474
  when :mime_type then mime_type(value, where)
470
475
  when :verify_with then method_name(value, where)
471
- when :default_headers then headers(value, where, declared)
472
- when :default_params then params(value, where, declared)
476
+ when :default_headers then headers(value, where)
477
+ when :default_params then params(value, where, credential_param)
473
478
  when :auth then auth(value, where)
474
479
  when :variables then scope == :with_api ? variable_values(value, where) : variable_declarations(value, where)
475
480
  when :recipe then recipe(value, where)
@@ -482,8 +487,8 @@ module ApiRecipes
482
487
 
483
488
  # An option of a request written with {variables}: kept as it is
484
489
  # written, and made when the request is built.
485
- def option_with_variables(key, value, where, declared)
486
- check_variables(value, where, declared)
490
+ def option_with_variables(key, value)
491
+ use_variables(variables_of(value))
487
492
  (@option_uses ||= []) << [key, value]
488
493
  value.dup.freeze
489
494
  end
@@ -547,14 +552,18 @@ module ApiRecipes
547
552
  nil
548
553
  end
549
554
 
550
- def check_variables(string, where, declared)
551
- return if declared.nil?
555
+ # The names written as {name} in the options of an api are its
556
+ # variables. In a `with` there is no api being compiled: the names are
557
+ # looked for when the request is built.
558
+ def use_variables(names)
559
+ @used_variables&.concat(names)
560
+ end
552
561
 
553
- names = string.scan(Template::VARIABLE).flatten.map(&:to_sym).uniq
554
- names.each { |name| add(where, "unknown variable #{shown(name)}") unless declared.include?(name) }
562
+ def variables_of(string)
563
+ string.scan(Template::VARIABLE).flatten.map(&:to_sym)
555
564
  end
556
565
 
557
- def host(value, where, declared)
566
+ def host(value, where)
558
567
  unless value.is_a?(String) || value.is_a?(Symbol)
559
568
  add(where, 'must be a string')
560
569
  return nil
@@ -574,11 +583,11 @@ module ApiRecipes
574
583
  return nil
575
584
  end
576
585
 
577
- check_variables(string, where, declared)
586
+ use_variables(variables_of(string))
578
587
  string.dup.freeze
579
588
  end
580
589
 
581
- def base_url(value, where, declared)
590
+ def base_url(value, where)
582
591
  unless value.is_a?(String) || value.is_a?(Symbol)
583
592
  add(where, 'must be a string')
584
593
  return nil
@@ -594,13 +603,11 @@ module ApiRecipes
594
603
  add(where, 'path placeholders are not allowed here; declare a variable and write {name}')
595
604
  return nil
596
605
  end
597
- unless declared.nil?
598
- (template.variable_names - declared).each { |name| add(where, "unknown variable #{shown(name)}") }
599
- end
606
+ use_variables(template.variable_names)
600
607
  template.to_s.freeze
601
608
  end
602
609
 
603
- def headers(value, where, declared)
610
+ def headers(value, where)
604
611
  unless value.is_a?(Hash)
605
612
  add(where, 'must be a Hash')
606
613
  return nil
@@ -621,14 +628,14 @@ module ApiRecipes
621
628
  end
622
629
  text = header.to_s
623
630
  add(header_where, 'must not contain control characters') if CONTROL.match?(text.gsub(Template::VARIABLE, ''))
624
- check_variables(text, header_where, declared)
631
+ use_variables(variables_of(text))
625
632
  out[name.dup.freeze] = text.dup.freeze
626
633
  end.freeze
627
634
  end
628
635
 
629
636
  # The query parameters sent with every request, as { name => text }.
630
- # names: a Names, or nil in a with, where nothing is known.
631
- def params(value, where, names)
637
+ # credential_param: the parameter of the credential, nil in a with.
638
+ def params(value, where, credential_param)
632
639
  unless value.is_a?(Hash)
633
640
  add(where, 'must be a Hash')
634
641
  return nil
@@ -641,7 +648,7 @@ module ApiRecipes
641
648
  end
642
649
  param_where = join(where, name)
643
650
  add(param_where, 'the name must not contain control characters') if CONTROL.match?(name)
644
- if names && name == names.credential_param
651
+ if credential_param && name == credential_param
645
652
  add(param_where, 'is the parameter of the credential (auth.name): it cannot be set here')
646
653
  end
647
654
  unless param.is_a?(String) || param.is_a?(Symbol) || param.is_a?(Numeric) || param == true || param == false
@@ -649,7 +656,7 @@ module ApiRecipes
649
656
  next
650
657
  end
651
658
  text = param.to_s
652
- check_variables(text, param_where, names&.variables)
659
+ use_variables(variables_of(text))
653
660
  out[name.dup.freeze] = text.dup.freeze
654
661
  end.freeze
655
662
  end
@@ -264,12 +264,17 @@ module ApiRecipes
264
264
  # The global level uses the global definition, the others the owner's one:
265
265
  # every other level of the chain was written through the declaration in
266
266
  # use, whose tree that is.
267
+ # The level of the application can name other origins for the
268
+ # credential it holds, with credential_origins: no other level is asked.
267
269
  def check_origin(chain, index, destination)
270
+ kind, level = chain[index]
271
+ return if kind == :global && Origins.name?(level.origins, destination)
272
+
268
273
  registry = chain.respond_to?(:registry) ? chain.registry : Registry.current
269
- bound = origin_from(definition_in_force(chain[index].first, registry), chain, index, with: false)
274
+ bound = origin_from(definition_in_force(kind, registry), chain, index, with: false)
270
275
  return if bound && destination && bound.casecmp?(destination)
271
276
 
272
- raise CredentialOriginMismatch.new(@definition.name, bound, destination)
277
+ raise CredentialOriginMismatch.new(@definition.name, bound, destination, application: kind == :global)
273
278
  end
274
279
 
275
280
  # The tree a level reads now. An api or an endpoint kept across a
@@ -40,16 +40,14 @@ module ApiRecipes
40
40
  options = options.except(*Registry::VALUE_KEYS)
41
41
  level = Registry.level_from(given, api_name.to_s)
42
42
  variables = level.variables
43
- global = Registry.current.definitions[api_name]
44
- check_variables(api_name, variables, global)
45
- # The variables that the options use are those of the global api.
46
- # Without one yet, the tree compiled at the first use checks them.
43
+ registry = Registry.current
44
+ global = registry.definitions[api_name]
47
45
  auth = global && global.auth
48
- errors = Compiler.check_options(options, :api, variables: global ? global.variables.keys : :any,
49
- credential_param: auth && auth[:type] == :query ? auth[:name] : nil)
46
+ errors = Compiler.check_options(options, :api, credential_param: auth && auth[:type] == :query ? auth[:name] : nil)
50
47
  raise ConfigurationError.new(errors) unless errors.empty?
51
48
 
52
49
  declaration = new(klass, api_name, Compiler.frozen_copy(options), variables, level.credential)
50
+ declaration.check_variables(registry) if global
53
51
  declared = klass.instance_variable_get(IVAR)
54
52
  klass.instance_variable_set(IVAR, (declared.is_a?(Hash) ? declared : {}).merge(api_name => declaration).freeze)
55
53
  klass.define_method(method_name) { declaration.api(self) }
@@ -59,15 +57,6 @@ module ApiRecipes
59
57
 
60
58
  private
61
59
 
62
- # The names of variables against the global api, when it is configured
63
- # already; else refresh checks them at the first use.
64
- def check_variables(api_name, variables, definition)
65
- return unless definition
66
-
67
- problems = Compiler.unknown_variables(variables, definition, api_name.to_s)
68
- raise ConfigurationError.new(problems) unless problems.empty?
69
- end
70
-
71
60
  def method_for(as, name)
72
61
  return name.to_sym if as.nil?
73
62
  return as.to_sym if (as.is_a?(String) || as.is_a?(Symbol)) && Compiler::METHOD_NAME.match?(as.to_s)
@@ -147,6 +136,19 @@ module ApiRecipes
147
136
 
148
137
  def pretty_print(queue) = queue.text(inspect)
149
138
 
139
+ # A value given to `api` for a name that is not a variable of the tree
140
+ # of the class, reported where `api` is called when the api of the
141
+ # application is configured already; else the first use reports it.
142
+ # The tree is not kept: the first use compiles it from the registry
143
+ # current then.
144
+ # registry: the one that `api` read, so that a configure that runs
145
+ # meanwhile does not change what the values are checked against.
146
+ def check_variables(registry)
147
+ definition = @options.empty? ? registry.definitions[@name] : Compiler.compile(@name, own_config(registry.configs[@name]))
148
+ problems = Compiler.unknown_variables(@variables, definition, @name.to_s)
149
+ raise ConfigurationError.new(problems) unless problems.empty?
150
+ end
151
+
150
152
  private
151
153
 
152
154
  # Refuses an owner whose hierarchy holds another declaration of this api.
@@ -119,10 +119,23 @@ module ApiRecipes
119
119
  def call_of(node)
120
120
  steps = []
121
121
  while node.is_a?(Endpoint)
122
- steps.unshift("#{node.name}#{"(#{node.path_params.join(', ')})" unless node.path_params.empty?}")
122
+ steps.unshift(Definition.step(node.name, node.path_params, !node.parent.is_a?(Endpoint)))
123
123
  node = node.parent
124
124
  end
125
- "#{name}.#{steps.join('.')}"
125
+ "#{name}#{steps.join}"
126
+ end
127
+ end
128
+
129
+ # How an endpoint called name is reached from the one that contains it:
130
+ # `.show(id)`, or `[:run, id]` and `["404"]` when the name has no method
131
+ # of its own. root: whether it is an endpoint of the api itself.
132
+ def self.step(name, path_params, root)
133
+ text = name.to_s
134
+ method = Compiler::METHOD_NAME.match?(text)
135
+ if method && !Handles.taken?(root ? ApiRecipes::Api : ApiRecipes::Endpoint, text.to_sym)
136
+ ".#{text}#{"(#{path_params.join(', ')})" unless path_params.empty?}"
137
+ else
138
+ "[#{[method ? ":#{text}" : text.inspect, *path_params].join(', ')}]"
126
139
  end
127
140
  end
128
141
 
@@ -4,7 +4,12 @@ module ApiRecipes
4
4
  module Internals
5
5
  # What was assigned to one api at one level: a credential (nil when never
6
6
  # assigned, Credential::NONE when removed on purpose) and variable values.
7
- Level = Data.define(:credential, :variables) do
7
+ # origins is what credential_origins gave with the credential, see
8
+ # Origins: only the level of the application has it, and a level that is
9
+ # written, sealed or read back from a serialized form never does.
10
+ Level = Data.define(:credential, :variables, :origins) do
11
+ def initialize(credential:, variables:, origins: nil) = super
12
+
8
13
  def inspect = "#<ApiRecipes::Internals::Level credential=#{credential.inspect} variables=[FILTERED]>"
9
14
 
10
15
  def to_s = inspect
@@ -0,0 +1,70 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ApiRecipes
4
+ module Internals
5
+ # The other origins a credential of the application may go to, as
6
+ # credential_origins says in config.values: :any, or a list of whole
7
+ # origins. The origin the credential was given for needs no entry.
8
+ module Origins
9
+ ANY = :any
10
+ KEY = :credential_origins
11
+ # A scheme, a host as the gem takes one and a port: nothing before,
12
+ # nothing after, so no user, no path and no line break. It is matched
13
+ # against ASCII text only: without its case, a letter of another
14
+ # alphabet is taken for one of these.
15
+ ENTRY = %r{\A(https?)://([A-Za-z0-9._-]+)(?::([0-9]{1,5}))?\z}i
16
+ PORTS = (1..65_535)
17
+ WHOLE = "'scheme://host' or 'scheme://host:port', with https or http as the scheme"
18
+
19
+ class << self
20
+ # nil, ANY, or a frozen list of origins written as a request writes
21
+ # its own. An entry that is refused is named by its position, never
22
+ # shown: it can hold a user and a password.
23
+ def from(value, where)
24
+ return nil if value.nil?
25
+ return ANY if ANY.equal?(value)
26
+ unless Array === value && !value.empty?
27
+ raise ConfigurationError.new(["#{where}.#{KEY}: must be :any or a list of origins, each written as #{WHOLE}"])
28
+ end
29
+
30
+ value.each_with_index.map do |entry, index|
31
+ written(entry) || raise(ConfigurationError.new(
32
+ ["#{where}.#{KEY}: entry #{index + 1} is not an origin: write it as #{WHOLE}, and nothing else"]
33
+ ))
34
+ end.uniq.freeze
35
+ end
36
+
37
+ # Whether origins, as from returned them, name destination.
38
+ def name?(origins, destination)
39
+ return true if origins == ANY
40
+ return false if origins.nil? || destination.nil?
41
+
42
+ origins.any? { |origin| origin.casecmp?(destination) }
43
+ end
44
+
45
+ private
46
+
47
+ # entry as Context#address writes an origin: without the default
48
+ # port. nil when it is not a whole origin. What is checked is a copy
49
+ # that is a String and nothing more: an object of a subclass is not
50
+ # asked what it holds.
51
+ def written(entry)
52
+ return nil unless String === entry
53
+
54
+ text = String.new(entry)
55
+ return nil unless text.ascii_only?
56
+
57
+ match = ENTRY.match(text)
58
+ return nil unless match
59
+
60
+ scheme = match[1].downcase
61
+ port = match[3]&.to_i
62
+ return nil unless port.nil? || PORTS.cover?(port)
63
+
64
+ port = nil if port == Context::DEFAULT_PORTS[scheme]
65
+ "#{scheme}://#{match[2]}#{":#{port}" if port}".freeze
66
+ end
67
+ end
68
+ end
69
+ end
70
+ end
@@ -10,6 +10,7 @@ module ApiRecipes
10
10
  FIXED_KEPT = /\A(?:[A-Za-z0-9\-._~!$&'()*+,;=:@\/]|%\h\h)/
11
11
  UNRESERVED = /[A-Za-z0-9\-._~]/
12
12
  ENCODED_SEQUENCE = /%25\h\h/
13
+ VARIABLE_KINDS = %i[variable segments].freeze
13
14
 
14
15
  # Percent-encodes every byte outside letters, digits and -._~
15
16
  def self.escape(string)
@@ -29,13 +30,27 @@ module ApiRecipes
29
30
  repeated = names.find { |name| names.count(name) > 1 }
30
31
  raise ArgumentError, "placeholder '#{repeated}' is repeated in '#{string}'" if repeated
31
32
  @param_names = names.freeze
32
- @variable_names = @parts.select { |kind, _| kind == :variable }.map(&:last).uniq.freeze
33
+ @variable_names = @parts.select { |kind, _| VARIABLE_KINDS.include?(kind) }.map(&:last).uniq.freeze
34
+ @segments = @parts.any? { |kind, _| kind == :segments }
35
+ end
36
+
37
+ # True when string, read as a path, has a {*name}. A string that is not
38
+ # a valid path answers false: whoever compiles it reports why.
39
+ def self.segments_variable?(string)
40
+ parse(string.to_s).segments?
41
+ rescue ArgumentError
42
+ false
33
43
  end
34
44
 
35
45
  # param_names: the placeholders, which take an argument each, in order.
36
- # variable_names: the {variables} of the api, each once.
46
+ # variable_names: the {variables} and {*variables} of the api, each once.
37
47
  attr_reader :param_names, :variable_names
38
48
 
49
+ # Whether the path has a {*name}, whose value spans several segments.
50
+ def segments?
51
+ @segments
52
+ end
53
+
39
54
  # The block, if given, is called with the name of a parameter, :slash when
40
55
  # its value (not a splat) contains '/' or :encoded when it contains a
41
56
  # sequence %XX, and the endpoint. It never receives the value.
@@ -68,14 +83,15 @@ module ApiRecipes
68
83
  encoded = encode_splat(remaining.shift, content, endpoint)
69
84
  out << encoded
70
85
  yield content, :encoded, endpoint if block_given? && encoded.include?('%25') && encoded.match?(ENCODED_SEQUENCE)
71
- when :variable
86
+ when :variable, :segments
72
87
  raise ArgumentError, 'a path with variables needs a context' if context.nil?
73
88
 
74
89
  variables ||= context.variables
75
90
  api = context.definition.name
76
91
  raise MissingVariable.new(api, content) unless variables.key?(content)
77
92
 
78
- out << Template.segment(variables[content], content, api)
93
+ value = variables[content]
94
+ out << (kind == :segments ? Template.segments(value, content, api) : Template.segment(value, content, api))
79
95
  end
80
96
  end
81
97
  out
@@ -88,6 +104,7 @@ module ApiRecipes
88
104
  when :param then ":#{content}"
89
105
  when :splat then "*#{content}"
90
106
  when :variable then "{#{content}}"
107
+ when :segments then "{*#{content}}"
91
108
  end
92
109
  end.join
93
110
  end
@@ -107,9 +124,9 @@ module ApiRecipes
107
124
  elsif rest.start_with?('\\{')
108
125
  text << '%7B'
109
126
  index += 2
110
- elsif (match = rest.match(/\A\{(#{NAME})\}/o))
127
+ elsif (match = rest.match(/\A\{(\*?)(#{NAME})\}/o))
111
128
  flush(parts, text)
112
- parts << [:variable, match[1].to_sym]
129
+ parts << [match[1].empty? ? :variable : :segments, match[2].to_sym]
113
130
  index += match[0].length
114
131
  elsif (match = rest.match(/\A:(#{NAME})/o))
115
132
  flush(parts, text)