skyward-api 0.3.0 → 0.4.1

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 (39) hide show
  1. checksums.yaml +4 -4
  2. data/LICENSE +21 -0
  3. data/README.md +60 -56
  4. data/lib/skyward/api/assembly/boot.rb +239 -91
  5. data/lib/skyward/api/assembly/builder.rb +2 -2
  6. data/lib/skyward/api/assembly/dispatcher.rb +12 -12
  7. data/lib/skyward/api/assembly/static.rb +36 -36
  8. data/lib/skyward/api/cli/app_file.rb +2 -2
  9. data/lib/skyward/api/cli/check.rb +9 -9
  10. data/lib/skyward/api/cli/routes.rb +2 -2
  11. data/lib/skyward/api/cli/serve/reloader.rb +6 -6
  12. data/lib/skyward/api/cli/serve.rb +15 -15
  13. data/lib/skyward/api/cli/serve.ru +2 -2
  14. data/lib/skyward/api/commands.rb +10 -10
  15. data/lib/skyward/api/endpoints/declarations.rb +7 -3
  16. data/lib/skyward/api/endpoints/route.rb +3 -1
  17. data/lib/skyward/api/inputs/coercer.rb +53 -20
  18. data/lib/skyward/api/inputs.rb +9 -9
  19. data/lib/skyward/api/middleware/request_id.rb +3 -3
  20. data/lib/skyward/api/middleware/request_log.rb +5 -5
  21. data/lib/skyward/api/middleware/rescue.rb +7 -7
  22. data/lib/skyward/api/openapi/docs.rb +5 -5
  23. data/lib/skyward/api/openapi.rb +52 -50
  24. data/lib/skyward/api/request.rb +8 -8
  25. data/lib/skyward/api/routing/percent_encoding.rb +1 -1
  26. data/lib/skyward/api/routing/router.rb +68 -27
  27. data/lib/skyward/api/serializer/writers.rb +27 -16
  28. data/lib/skyward/api/serializer.rb +39 -21
  29. data/lib/skyward/api/test/client.rb +25 -25
  30. data/lib/skyward/api/version.rb +1 -1
  31. data/lib/skyward/api.rb +15 -14
  32. data/sig/generated/skyward/api/assembly/boot.rbs +99 -29
  33. data/sig/generated/skyward/api/endpoints/route.rbs +8 -4
  34. data/sig/generated/skyward/api/inputs/coercer.rbs +20 -2
  35. data/sig/generated/skyward/api/routing/router.rbs +52 -9
  36. data/sig/generated/skyward/api/serializer/writers.rbs +6 -0
  37. data/sig/generated/skyward/api/serializer.rbs +13 -1
  38. metadata +19 -4
  39. /data/sig/{manual/zeitwerk/loader.rbs → _private/zeitwerk.rbs} +0 -0
@@ -1,32 +1,32 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require "time"
3
+ require 'time'
4
4
 
5
5
  class Skyward::API::Assembly::Static
6
6
  TYPES = {
7
- ".avif" => "image/avif",
8
- ".css" => "text/css",
9
- ".csv" => "text/csv",
10
- ".gif" => "image/gif",
11
- ".htm" => "text/html",
12
- ".html" => "text/html",
13
- ".ico" => "image/vnd.microsoft.icon",
14
- ".jpeg" => "image/jpeg",
15
- ".jpg" => "image/jpeg",
16
- ".js" => "text/javascript",
17
- ".json" => "application/json",
18
- ".map" => "application/json",
19
- ".mjs" => "text/javascript",
20
- ".pdf" => "application/pdf",
21
- ".png" => "image/png",
22
- ".svg" => "image/svg+xml",
23
- ".txt" => "text/plain",
24
- ".wasm" => "application/wasm",
25
- ".webmanifest" => "application/manifest+json",
26
- ".webp" => "image/webp",
27
- ".woff" => "font/woff",
28
- ".woff2" => "font/woff2",
29
- ".xml" => "application/xml"
7
+ '.avif' => 'image/avif',
8
+ '.css' => 'text/css',
9
+ '.csv' => 'text/csv',
10
+ '.gif' => 'image/gif',
11
+ '.htm' => 'text/html',
12
+ '.html' => 'text/html',
13
+ '.ico' => 'image/vnd.microsoft.icon',
14
+ '.jpeg' => 'image/jpeg',
15
+ '.jpg' => 'image/jpeg',
16
+ '.js' => 'text/javascript',
17
+ '.json' => 'application/json',
18
+ '.map' => 'application/json',
19
+ '.mjs' => 'text/javascript',
20
+ '.pdf' => 'application/pdf',
21
+ '.png' => 'image/png',
22
+ '.svg' => 'image/svg+xml',
23
+ '.txt' => 'text/plain',
24
+ '.wasm' => 'application/wasm',
25
+ '.webmanifest' => 'application/manifest+json',
26
+ '.webp' => 'image/webp',
27
+ '.woff' => 'font/woff',
28
+ '.woff2' => 'font/woff2',
29
+ '.xml' => 'application/xml'
30
30
  }.freeze #: Hash[String, String]
31
31
 
32
32
  # @rbs @statics: Array[Skyward::API::Assembly::Builder::Static]
@@ -34,15 +34,15 @@ class Skyward::API::Assembly::Static
34
34
  # @rbs statics: Array[Skyward::API::Assembly::Builder::Static]
35
35
  # @rbs return: void
36
36
  def initialize(statics)
37
- @statics = statics.map { |static| static.with(prefix: static.prefix.delete_suffix("/")) }
37
+ @statics = statics.map { |static| static.with(prefix: static.prefix.delete_suffix('/')) }
38
38
  end
39
39
 
40
40
  # @rbs env: Hash[String, untyped]
41
41
  # @rbs return: Skyward::API::Assembly::Dispatcher::response?
42
42
  def call(env)
43
- return unless %w[GET HEAD].include?(env["REQUEST_METHOD"])
43
+ return unless %w[GET HEAD].include?(env['REQUEST_METHOD'])
44
44
 
45
- file = file(env["PATH_INFO"])
45
+ file = file(env['PATH_INFO'])
46
46
  serve(file, env) if file
47
47
  end
48
48
 
@@ -59,11 +59,11 @@ class Skyward::API::Assembly::Static
59
59
  return unless path == static.prefix || path.start_with?("#{static.prefix}/")
60
60
 
61
61
  rest = path.delete_prefix(static.prefix)
62
- rest = "#{rest}index.html" if rest.empty? || rest.end_with?("/")
63
- names = rest.split("/").map { |segment| Skyward::API::Routing::PercentEncoding.decode(segment) }
62
+ rest = "#{rest}index.html" if rest.empty? || rest.end_with?('/')
63
+ names = rest.split('/').map { |segment| Skyward::API::Routing::PercentEncoding.decode(segment) }
64
64
  # Each segment is decoded after splitting, so an escaped / stays inside a
65
65
  # name, where joining would make it a separator. File raises on a NUL.
66
- return if names.any? { |name| name == ".." || name.include?("/") || name.include?("\0") }
66
+ return if names.any? { |name| name == '..' || name.include?('/') || name.include?("\0") }
67
67
 
68
68
  # File.file? follows a symlink under from: whoever deployed it put it there.
69
69
  file = File.join(static.from, *names)
@@ -76,11 +76,11 @@ class Skyward::API::Assembly::Static
76
76
  def serve(file, env)
77
77
  stat = File.stat(file)
78
78
  etag = etag(stat)
79
- validators = { "last-modified" => stat.mtime.httpdate, "etag" => etag, "cache-control" => "no-cache" }
79
+ validators = { 'last-modified' => stat.mtime.httpdate, 'etag' => etag, 'cache-control' => 'no-cache' }
80
80
  return [304, validators, []] if fresh?(env, etag, stat.mtime)
81
81
 
82
- type = TYPES.fetch(File.extname(file).downcase(:ascii), "application/octet-stream")
83
- headers = { "content-type" => type, "content-length" => stat.size.to_s, **validators }
82
+ type = TYPES.fetch(File.extname(file).downcase(:ascii), 'application/octet-stream')
83
+ headers = { 'content-type' => type, 'content-length' => stat.size.to_s, **validators }
84
84
  [200, headers, [File.binread(file)]]
85
85
  end
86
86
 
@@ -98,10 +98,10 @@ class Skyward::API::Assembly::Static
98
98
  # @rbs modified: Time
99
99
  # @rbs return: bool
100
100
  def fresh?(env, etag, modified)
101
- tags = env["HTTP_IF_NONE_MATCH"]
102
- return tags.b.split(",").any? { |tag| ["*", etag].include?(tag.strip.delete_prefix("W/")) } if tags
101
+ tags = env['HTTP_IF_NONE_MATCH']
102
+ return tags.b.split(',').any? { |tag| ['*', etag].include?(tag.strip.delete_prefix('W/')) } if tags
103
103
 
104
- since = http_date(env["HTTP_IF_MODIFIED_SINCE"])
104
+ since = http_date(env['HTTP_IF_MODIFIED_SINCE'])
105
105
  since ? since.to_i >= modified.to_i : false
106
106
  end
107
107
 
@@ -3,9 +3,9 @@
3
3
  module Skyward::API::CLI::AppFile
4
4
  extend self
5
5
 
6
- FILE = "app.rb" #: String
6
+ FILE = 'app.rb' #: String
7
7
 
8
- ASSIGNMENT = "App = Skyward.app { ... }" #: String
8
+ ASSIGNMENT = 'App = Skyward.app { ... }' #: String
9
9
 
10
10
  # @rbs (String directory, out: _Writer, kernel: singleton(Kernel), generate: ^() -> String?)
11
11
  # { (Skyward::API::Assembly::Application) -> String } -> void
@@ -10,11 +10,11 @@ module Skyward::API::CLI::Check
10
10
  :detail #: String
11
11
  )
12
12
 
13
- PASSED = Outcome.new(passed: true, detail: "") #: Outcome
13
+ PASSED = Outcome.new(passed: true, detail: '') #: Outcome
14
14
 
15
15
  GENERATED = Skyward::Core::Signatures::Inline::OUTPUT #: String
16
16
 
17
- STEEPFILE = "Steepfile" #: String
17
+ STEEPFILE = 'Steepfile' #: String
18
18
 
19
19
  # The strict boot's own Ruby runs it, so the forced strict mode, the app's
20
20
  # side effects and an exit or crash stay out of skyward check. The require
@@ -33,13 +33,13 @@ module Skyward::API::CLI::Check
33
33
  # @rbs (String directory, out: _Writer, capture: capture, rbs_inline: String?, steep: String?) -> Integer
34
34
  def run(directory, out:, capture:, rbs_inline:, steep:)
35
35
  checks = {
36
- "Signatures" => -> { signatures(directory, capture:, rbs_inline:) },
37
- "Strict boot" => -> { strict_boot(directory, capture:) },
38
- "Steep" => -> { type_check(directory, capture:, steep:) }
36
+ 'Signatures' => -> { signatures(directory, capture:, rbs_inline:) },
37
+ 'Strict boot' => -> { strict_boot(directory, capture:) },
38
+ 'Steep' => -> { type_check(directory, capture:, steep:) }
39
39
  }
40
40
  passed = checks.map do |name, check|
41
41
  outcome = check.call
42
- out.write("#{name}: #{outcome.passed ? "passed" : "failed"}\n", outcome.detail)
42
+ out.write("#{name}: #{outcome.passed ? 'passed' : 'failed'}\n", outcome.detail)
43
43
  outcome.passed
44
44
  end
45
45
  passed.all? ? 0 : 1
@@ -54,7 +54,7 @@ module Skyward::API::CLI::Check
54
54
 
55
55
  inline = Skyward::Core::Signatures::Inline
56
56
  paths = inline.sources(directory)
57
- generate = "bundle exec rbs-inline --output=#{GENERATED} #{paths.join(" ")}"
57
+ generate = "bundle exec rbs-inline --output=#{GENERATED} #{paths.join(' ')}"
58
58
  generated = File.join(directory, GENERATED)
59
59
  unless File.directory?(generated)
60
60
  return failed("There's no #{GENERATED}. Run `#{generate}` and commit the result.\n")
@@ -81,7 +81,7 @@ module Skyward::API::CLI::Check
81
81
  # @rbs capture: capture
82
82
  # @rbs return: Outcome
83
83
  def strict_boot(directory, capture:)
84
- output, ok = capture.call({ "SKYWARD_STRICT" => "1" }, [Gem.ruby, "-e", BOOT], directory)
84
+ output, ok = capture.call({ 'SKYWARD_STRICT' => '1' }, [Gem.ruby, '-e', BOOT], directory)
85
85
  Outcome.new(passed: ok, detail: output)
86
86
  end
87
87
 
@@ -100,7 +100,7 @@ module Skyward::API::CLI::Check
100
100
 
101
101
  # Steep otherwise checks through any language server it finds running,
102
102
  # which can report stale results.
103
- output, ok = capture.call({}, [Gem.ruby, steep, "check", "--no-daemon"], directory)
103
+ output, ok = capture.call({}, [Gem.ruby, steep, 'check', '--no-daemon'], directory)
104
104
  Outcome.new(passed: ok, detail: output)
105
105
  end
106
106
 
@@ -9,7 +9,7 @@ module Skyward::API::CLI::Routes
9
9
  # @rbs return: String
10
10
  def table(endpoints)
11
11
  rows = endpoints.map do |endpoint|
12
- [endpoint.verb, path(endpoint.pattern), handler(endpoint), endpoint.signature.gsub(/\s*\R\s*/, " ")]
12
+ [endpoint.verb, path(endpoint.pattern), handler(endpoint), endpoint.signature.gsub(/\s*\R\s*/, ' ')]
13
13
  end
14
14
  widths = rows.transpose.map { |column| (column.map(&:length).max || 0) + GAP }
15
15
  rows.map do |row|
@@ -22,7 +22,7 @@ module Skyward::API::CLI::Routes
22
22
 
23
23
  # @rbs pattern: Array[String | Symbol]
24
24
  # @rbs return: String
25
- def path(pattern) = pattern.map { |part| part.is_a?(Symbol) ? ":#{part}" : part }.join("/")
25
+ def path(pattern) = pattern.map { |part| part.is_a?(Symbol) ? ":#{part}" : part }.join('/')
26
26
 
27
27
  # @rbs endpoint: Skyward::API::Routing::Router::Endpoint
28
28
  # @rbs return: String
@@ -1,6 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require "json"
3
+ require 'json'
4
4
 
5
5
  class Skyward::API::CLI::Serve::Reloader
6
6
  INTERVAL = 0.5 #: Float
@@ -82,7 +82,7 @@ class Skyward::API::CLI::Serve::Reloader
82
82
  # @rbs files: Hash[String, Time]
83
83
  # @rbs return: String?
84
84
  def generate(files)
85
- sources = files.select { |file, _time| file.end_with?(".rb") }
85
+ sources = files.select { |file, _time| file.end_with?('.rb') }
86
86
  return @failure if sources == @sources
87
87
 
88
88
  @failure = @generate.call
@@ -105,14 +105,14 @@ class Skyward::API::CLI::Serve::Reloader
105
105
  # A message can quote a source line's bytes, and JSON.generate raises on invalid UTF-8.
106
106
  message = String.new(error.message, encoding: Encoding::UTF_8).scrub
107
107
  problem = {
108
- type: "about:blank",
109
- title: "Internal Server Error",
108
+ type: 'about:blank',
109
+ title: 'Internal Server Error',
110
110
  status: 500,
111
111
  detail: "#{error.class}: #{message}",
112
112
  # rbs-inline's failure is never raised, so has no backtrace.
113
113
  backtrace: error.backtrace || []
114
114
  }
115
- body = env["REQUEST_METHOD"] == "HEAD" ? [] : [JSON.generate(problem)] #: Array[String]
116
- [500, { "content-type" => "application/problem+json" }, body]
115
+ body = env['REQUEST_METHOD'] == 'HEAD' ? [] : [JSON.generate(problem)] #: Array[String]
116
+ [500, { 'content-type' => 'application/problem+json' }, body]
117
117
  end
118
118
  end
@@ -5,7 +5,7 @@ module Skyward::API::CLI::Serve
5
5
 
6
6
  RACKUP = "#{__dir__}/serve.ru".freeze #: String
7
7
 
8
- CONFIG = "config.ru" #: String
8
+ CONFIG = 'config.ru' #: String
9
9
 
10
10
  # Neither watched nor reloaded, and nor is any hidden directory: the app's
11
11
  # gems can be installed under vendor/ or .bundle/.
@@ -26,20 +26,20 @@ module Skyward::API::CLI::Serve
26
26
  unless falcon
27
27
  return kernel.abort(
28
28
  "skyward: Falcon isn't installed. Add `gem \"falcon\"` to the Gemfile and run `bundle install`, " \
29
- "or run config.ru under any Rack server, such as Puma."
29
+ 'or run config.ru under any Rack server, such as Puma.'
30
30
  )
31
31
  end
32
32
 
33
33
  kernel.exec(
34
- { "RACK_ENV" => env.fetch("RACK_ENV", "development") },
34
+ { 'RACK_ENV' => env.fetch('RACK_ENV', 'development') },
35
35
  Gem.ruby,
36
36
  falcon,
37
- "serve",
38
- "--bind",
39
- "http://localhost:#{env.fetch("PORT", "9292")}",
40
- "--count",
41
- "1",
42
- "--config",
37
+ 'serve',
38
+ '--bind',
39
+ "http://localhost:#{env.fetch('PORT', '9292')}",
40
+ '--count',
41
+ '1',
42
+ '--config',
43
43
  RACKUP,
44
44
  chdir: directory
45
45
  )
@@ -73,7 +73,7 @@ module Skyward::API::CLI::Serve
73
73
  # @rbs directory: String
74
74
  # @rbs return: Hash[String, Time]
75
75
  def watch(directory)
76
- roots = Dir.glob("*/", base: directory).map { |root| root.delete_suffix("/") }.reject { |root| ignored?(root) }
76
+ roots = Dir.glob('*/', base: directory).map { |root| root.delete_suffix('/') }.reject { |root| ignored?(root) }
77
77
  files = Dir.glob([WATCHED, *roots.map { |root| "#{root}/**/#{WATCHED}" }], base: directory)
78
78
  files.to_h { |file| [file, File.mtime(File.join(directory, file))] }
79
79
  end
@@ -93,8 +93,8 @@ module Skyward::API::CLI::Serve
93
93
  stuck = app_loaders.find { |loader| !loader.reloading_enabled? }
94
94
  if stuck
95
95
  raise Skyward::Core::BootError,
96
- "skyward serve can't reload the Zeitwerk loader for #{stuck.dirs.join(", ")}. Call " \
97
- "`loader.enable_reloading` before `loader.setup` in development, then restart skyward serve."
96
+ "skyward serve can't reload the Zeitwerk loader for #{stuck.dirs.join(', ')}. Call " \
97
+ '`loader.enable_reloading` before `loader.setup` in development, then restart skyward serve.'
98
98
  end
99
99
 
100
100
  apis.select { |api| reloaded_api?(directory, api) }.each(&:clear_declarations)
@@ -120,7 +120,7 @@ module Skyward::API::CLI::Serve
120
120
  def reloaded_api?(directory, api)
121
121
  name = api.name
122
122
  # const_source_location refuses the name of a class under an anonymous module.
123
- return false if name.nil? || name.start_with?("#")
123
+ return false if name.nil? || name.start_with?('#')
124
124
  # A class left over from an earlier load keeps its name after its namespace
125
125
  # is gone, and const_source_location raises for a missing namespace.
126
126
  return false unless Object.const_defined?(name)
@@ -135,10 +135,10 @@ module Skyward::API::CLI::Serve
135
135
  def reloaded?(directory, path)
136
136
  return false unless path == directory || path.start_with?("#{directory}/")
137
137
 
138
- !ignored?(path.delete_prefix(directory).delete_prefix("/").partition("/").first)
138
+ !ignored?(path.delete_prefix(directory).delete_prefix('/').partition('/').first)
139
139
  end
140
140
 
141
141
  # @rbs root: String
142
142
  # @rbs return: bool
143
- def ignored?(root) = root.start_with?(".") || IGNORED.include?(root)
143
+ def ignored?(root) = root.start_with?('.') || IGNORED.include?(root)
144
144
  end
@@ -2,9 +2,9 @@
2
2
 
3
3
  # skyward serve's composition root. Rack is reached for only here: Skyward API
4
4
  # doesn't depend on it, and Falcon brings it.
5
- require "skyward/api"
5
+ require 'skyward/api'
6
6
 
7
- rbs_inline = Skyward::Core::CLI::Executable.find("rbs-inline", feature: "rbs/inline")
7
+ rbs_inline = Skyward::Core::CLI::Executable.find('rbs-inline', feature: 'rbs/inline')
8
8
 
9
9
  capture = Skyward::Core::CLI::Executable::CAPTURE
10
10
  generate = rbs_inline && -> { Skyward::Core::Signatures::Inline.generate(Dir.pwd, rbs_inline:, capture:) }
@@ -1,44 +1,44 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require "json"
4
- require "skyward/api"
3
+ require 'json'
4
+ require 'skyward/api'
5
5
 
6
6
  generate = lambda do
7
7
  Skyward::Core::Signatures::Inline.generate(
8
8
  Dir.pwd,
9
- rbs_inline: Skyward::Core::CLI::Executable.find("rbs-inline", feature: "rbs/inline"),
9
+ rbs_inline: Skyward::Core::CLI::Executable.find('rbs-inline', feature: 'rbs/inline'),
10
10
  capture: Skyward::Core::CLI::Executable::CAPTURE
11
11
  )
12
12
  end
13
13
 
14
- Skyward::Core::CLI.register("serve", "Serve config.ru with Falcon in development, on PORT (default 9292)") do |_args|
14
+ Skyward::Core::CLI.register('serve', 'Serve config.ru with Falcon in development, on PORT (default 9292)') do |_args|
15
15
  Skyward::API::CLI::Serve.run(
16
16
  Dir.pwd,
17
17
  env: ENV.to_h,
18
- falcon: Skyward::Core::CLI::Executable.find("falcon"),
18
+ falcon: Skyward::Core::CLI::Executable.find('falcon'),
19
19
  kernel: Kernel
20
20
  )
21
21
  end
22
22
 
23
- Skyward::Core::CLI.register("check", "Check signatures, boot app.rb in strict mode and run Steep") do |_args|
23
+ Skyward::Core::CLI.register('check', 'Check signatures, boot app.rb in strict mode and run Steep') do |_args|
24
24
  # So CI shows each check as it finishes, not all of them at exit.
25
25
  $stdout.sync = true
26
26
  exit Skyward::API::CLI::Check.run(
27
27
  Dir.pwd,
28
28
  out: $stdout,
29
29
  capture: Skyward::Core::CLI::Executable::CAPTURE,
30
- rbs_inline: Skyward::Core::CLI::Executable.find("rbs-inline", feature: "rbs/inline"),
31
- steep: Skyward::Core::CLI::Executable.find("steep")
30
+ rbs_inline: Skyward::Core::CLI::Executable.find('rbs-inline', feature: 'rbs/inline'),
31
+ steep: Skyward::Core::CLI::Executable.find('steep')
32
32
  )
33
33
  end
34
34
 
35
- Skyward::Core::CLI.register("routes", "Print every route with its handler and signature") do |_args|
35
+ Skyward::Core::CLI.register('routes', 'Print every route with its handler and signature') do |_args|
36
36
  Skyward::API::CLI::AppFile.run(Dir.pwd, out: $stdout, kernel: Kernel, generate:) do |app|
37
37
  Skyward::API::CLI::Routes.table(app.endpoints)
38
38
  end
39
39
  end
40
40
 
41
- Skyward::Core::CLI.register("openapi", "Write the OpenAPI document to stdout") do |_args|
41
+ Skyward::Core::CLI.register('openapi', 'Write the OpenAPI document to stdout') do |_args|
42
42
  Skyward::API::CLI::AppFile.run(Dir.pwd, out: $stdout, kernel: Kernel, generate:) do |app|
43
43
  "#{JSON.pretty_generate(app.openapi)}\n"
44
44
  end
@@ -95,12 +95,16 @@ module Skyward::API::Endpoints::Declarations
95
95
  problem = problem_with(path, to)
96
96
  raise ArgumentError, "#{self} #{verb.upcase} #{path.inspect}: #{problem}" if problem
97
97
 
98
+ # The caller of get, post, put, patch or delete, which is the app's declaration.
99
+ location = caller_locations(2, 1)&.first
98
100
  route = Skyward::API::Endpoints::Route.new(
99
101
  verb:,
100
102
  path: path.dup.freeze,
101
103
  to:,
102
104
  summary: summary.dup.freeze,
103
- description: description.dup.freeze
105
+ description: description.dup.freeze,
106
+ file: location&.path,
107
+ line: location&.lineno
104
108
  )
105
109
  @routes = [*routes, route].freeze
106
110
  end
@@ -110,9 +114,9 @@ module Skyward::API::Endpoints::Declarations
110
114
  # @rbs to: untyped
111
115
  # @rbs return: String?
112
116
  def problem_with(path, to)
113
- return "the path must be a String that starts with /" unless path.is_a?(String) && path.start_with?("/")
117
+ return 'the path must be a String that starts with /' unless path.is_a?(String) && path.start_with?('/')
114
118
 
115
- names = path.split("/").filter_map { |segment| segment.delete_prefix(":") if segment.start_with?(":") }
119
+ names = path.split('/').filter_map { |segment| segment.delete_prefix(':') if segment.start_with?(':') }
116
120
  invalid = names.find { |name| !PARAMETER_NAME.match?(name) }
117
121
  return "path parameter #{invalid.inspect} isn't a valid keyword name" if invalid
118
122
 
@@ -8,6 +8,8 @@ module Skyward::API::Endpoints
8
8
  :path, #: String
9
9
  :to, #: Symbol
10
10
  :summary, #: String?
11
- :description #: String?
11
+ :description, #: String?
12
+ :file, #: String?
13
+ :line #: Integer?
12
14
  )
13
15
  end
@@ -1,7 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require "date"
4
- require "json"
3
+ require 'date'
4
+ require 'json'
5
5
 
6
6
  module Skyward::API::Inputs::Coercer
7
7
  extend self
@@ -36,13 +36,18 @@ module Skyward::API::Inputs::Coercer
36
36
 
37
37
  # Stands for every problem a union's member finds, since the union reports
38
38
  # none of them.
39
- MISFIT = Invalid.new(errors: [Error.new(at: "", message: "doesn't fit")]) #: Invalid
39
+ MISFIT = Invalid.new(errors: [Error.new(at: '', message: "doesn't fit")]) #: Invalid
40
40
 
41
- # INTEGER, DATE and TIME match a String's bytes, because a path parameter
42
- # can be any bytes, and Regexp#match raises on a String that isn't UTF-8.
41
+ # INTEGER, DECIMAL, DATE and TIME match a String's bytes, because a path
42
+ # parameter can be any bytes, and Regexp#match raises on a String that isn't
43
+ # UTF-8.
43
44
  INTEGER = /\A-?\d+\z/ #: Regexp
44
45
 
45
- BOOLEANS = { "true" => true, "false" => false, "1" => true, "0" => false }.freeze #: Hash[String, bool]
46
+ # No exponent, NaN or Infinity: "1e1000000000" is short, but written without
47
+ # an exponent it's a billion digits long.
48
+ DECIMAL = /\A-?\d+(?:\.\d+)?\z/ #: Regexp
49
+
50
+ BOOLEANS = { 'true' => true, 'false' => false, '1' => true, '0' => false }.freeze #: Hash[String, bool]
46
51
 
47
52
  DATE = /\A(\d{4})-(\d{2})-(\d{2})\z/ #: Regexp
48
53
 
@@ -54,16 +59,28 @@ module Skyward::API::Inputs::Coercer
54
59
  /x #: Regexp
55
60
 
56
61
  NAMES = {
57
- integer: "Integer",
58
- float: "Float",
59
- string: "String",
60
- bool: "bool",
61
- date: "Date",
62
- time: "Time",
63
- untyped: "untyped"
62
+ integer: 'Integer',
63
+ float: 'Float',
64
+ string: 'String',
65
+ bool: 'bool',
66
+ date: 'Date',
67
+ time: 'Time',
68
+ decimal: 'BigDecimal',
69
+ untyped: 'untyped'
70
+ }.freeze #: Hash[Skyward::Core::Types::scalar, String]
71
+
72
+ FORMATS = {
73
+ date: 'Date (YYYY-MM-DD)',
74
+ time: 'Time (ISO 8601)',
75
+ decimal: 'BigDecimal (a decimal string, such as "12.50")'
64
76
  }.freeze #: Hash[Skyward::Core::Types::scalar, String]
65
77
 
66
- FORMATS = { date: "Date (YYYY-MM-DD)", time: "Time (ISO 8601)" }.freeze #: Hash[Skyward::Core::Types::scalar, String]
78
+ # A Hash[String, T] says its keys are Strings, so an untyped value it holds
79
+ # keeps the JSON's String keys at every level.
80
+ AS_PARSED = [
81
+ Skyward::Core::Types::Scalar.new(name: :untyped),
82
+ Skyward::Core::Types::Nullable.new(type: Skyward::Core::Types::Scalar.new(name: :untyped))
83
+ ].freeze #: Array[Skyward::Core::Types::t]
67
84
 
68
85
  # Path and query values are Strings, so with strings: true a coercer parses them.
69
86
  # @rbs type: Skyward::Core::Types::t
@@ -82,7 +99,7 @@ module Skyward::API::Inputs::Coercer
82
99
  return unless required
83
100
  return Ok.new(value: nil) if type.is_a?(Skyward::Core::Types::Nullable)
84
101
 
85
- Invalid.new(errors: [Error.new(at:, message: "is required")])
102
+ Invalid.new(errors: [Error.new(at:, message: 'is required')])
86
103
  end
87
104
 
88
105
  # @rbs results: Hash[Symbol, result]
@@ -113,11 +130,14 @@ module Skyward::API::Inputs::Coercer
113
130
  when Skyward::Core::Types::Enum then enum(type.symbols, expected)
114
131
  when Skyward::Core::Types::Nullable then nullable(build(type.type, strings, member, unions))
115
132
  when Skyward::Core::Types::ArrayOf then array(build(type.type, strings, member, unions), strings, limit, expected)
116
- when Skyward::Core::Types::HashOf then hash_of(build(type.type, strings, member, unions), limit, expected)
133
+ when Skyward::Core::Types::HashOf
134
+ value = AS_PARSED.include?(type.type) ? as_parsed : build(type.type, strings, member, unions)
135
+ hash_of(value, limit, expected)
117
136
  when Skyward::Core::Types::Record then object(fields(type, strings, member, unions), limit, expected, &:itself)
118
137
  when Skyward::Core::Types::Named
119
138
  klass = type.klass
120
139
  object(fields(type, strings, member, unions), limit, expected) { |values| klass.new(**values) }
140
+ when Skyward::Core::Types::Refined then build(type.type, strings, member, unions)
121
141
  # Equal unions share one coercer, which is what lets one remember its results.
122
142
  else unions[[type, member]] ||= union(type.types.map { |one| build(one, strings, true, unions) }, member, expected)
123
143
  end
@@ -148,6 +168,7 @@ module Skyward::API::Inputs::Coercer
148
168
  when :string then ->(raw) { Ok.new(value: raw) if raw.is_a?(String) }
149
169
  when :date then ->(raw) { date(raw) }
150
170
  when :time then ->(raw) { time(raw) }
171
+ when :decimal then ->(raw) { decimal(raw) }
151
172
  else ->(raw) { Ok.new(value: strings ? last(raw) : symbolized(raw)) }
152
173
  end
153
174
  end
@@ -158,6 +179,9 @@ module Skyward::API::Inputs::Coercer
158
179
  # @rbs return: String?
159
180
  def last(raw) = raw.is_a?(Array) ? raw.last : raw
160
181
 
182
+ # @rbs return: coercer
183
+ def as_parsed = ->(raw, _at, _seen) { Ok.new(value: raw) }
184
+
161
185
  # @rbs raw: untyped
162
186
  # @rbs return: untyped
163
187
  def symbolized(raw)
@@ -224,6 +248,14 @@ module Skyward::API::Inputs::Coercer
224
248
  Ok.new(value: Time.new(on.year, on.month, on.day, hour.to_i, minute.to_i, seconds, zone))
225
249
  end
226
250
 
251
+ # A JSON number isn't one, because JSON.parse has already made it a Float,
252
+ # which may have lost digits.
253
+ # @rbs raw: untyped
254
+ # @rbs return: Ok?
255
+ def decimal(raw)
256
+ Ok.new(value: BigDecimal(raw)) if raw.is_a?(String) && DECIMAL.match?(raw.b)
257
+ end
258
+
227
259
  # @rbs value: Skyward::Core::Types::literal
228
260
  # @rbs strings: bool
229
261
  # @rbs expected: String?
@@ -403,15 +435,16 @@ module Skyward::API::Inputs::Coercer
403
435
  case type
404
436
  when Skyward::Core::Types::Scalar then NAMES.fetch(type.name)
405
437
  when Skyward::Core::Types::Literal then type.value.inspect
406
- when Skyward::Core::Types::Enum then type.symbols.map(&:inspect).join(" | ")
438
+ when Skyward::Core::Types::Enum then type.symbols.map(&:inspect).join(' | ')
407
439
  when Skyward::Core::Types::Nullable then nullable_written(type.type)
408
440
  when Skyward::Core::Types::ArrayOf then "Array[#{written(type.type)}]"
409
441
  when Skyward::Core::Types::HashOf then "Hash[String, #{written(type.type)}]"
410
442
  when Skyward::Core::Types::Record
411
- fields = type.fields.map { |field| "#{"?" unless field.required}#{field.name}: #{written(field.type)}" }
412
- "{ #{fields.join(", ")} }"
443
+ fields = type.fields.map { |field| "#{'?' unless field.required}#{field.name}: #{written(field.type)}" }
444
+ "{ #{fields.join(', ')} }"
413
445
  when Skyward::Core::Types::Named then type.name
414
- else type.types.map { |member| written(member) }.join(" | ")
446
+ when Skyward::Core::Types::Refined then written(type.type)
447
+ else type.types.map { |member| written(member) }.join(' | ')
415
448
  end
416
449
  end
417
450
 
@@ -1,7 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require "json"
4
- require "uri"
3
+ require 'json'
4
+ require 'uri'
5
5
 
6
6
  class Skyward::API::Inputs
7
7
  # @rbs!
@@ -11,11 +11,11 @@ class Skyward::API::Inputs
11
11
  JSON_TYPE = %r{\A(?:application/json|[^/;\s]+/[^/;\s]+\+json)\s*(?:;|\z)}i #: Regexp
12
12
 
13
13
  MALFORMED_QUERY = Coercer::Invalid.new(
14
- errors: [Coercer::Error.new(at: "query", message: "is not a valid query string")]
14
+ errors: [Coercer::Error.new(at: 'query', message: 'is not a valid query string')]
15
15
  ) #: Coercer::Invalid
16
16
 
17
17
  INVALID_JSON = Coercer::Invalid.new(
18
- errors: [Coercer::Error.new(at: "body", message: "is not valid JSON")]
18
+ errors: [Coercer::Error.new(at: 'body', message: 'is not valid JSON')]
19
19
  ) #: Coercer::Invalid
20
20
 
21
21
  # @rbs @keywords: Array[[Skyward::API::Routing::Router::Keyword, Coercer::t]]
@@ -52,7 +52,7 @@ class Skyward::API::Inputs
52
52
  body = body(env) if @body
53
53
  case body
54
54
  when Symbol then body
55
- else arguments(params, query(env["QUERY_STRING"].to_s), body, given)
55
+ else arguments(params, query(env['QUERY_STRING'].to_s), body, given)
56
56
  end
57
57
  end
58
58
 
@@ -100,7 +100,7 @@ class Skyward::API::Inputs
100
100
  # @rbs return: [Symbol, Coercer::result]?
101
101
  def argument(keyword, coercer, params, query, body)
102
102
  name = keyword.name
103
- at = keyword.source == :body ? "body" : "#{keyword.source}.#{name}"
103
+ at = keyword.source == :body ? 'body' : "#{keyword.source}.#{name}"
104
104
  raw =
105
105
  case keyword.source
106
106
  when :path then Coercer::Ok.new(value: params.fetch(name))
@@ -140,13 +140,13 @@ class Skyward::API::Inputs
140
140
  # @rbs env: Hash[String, untyped]
141
141
  # @rbs return: body
142
142
  def body(env)
143
- return :content_too_large if env["CONTENT_LENGTH"].to_i > @max_body_size
143
+ return :content_too_large if env['CONTENT_LENGTH'].to_i > @max_body_size
144
144
 
145
145
  # One byte past the limit shows the body runs past it, without reading the rest.
146
- text = env["rack.input"]&.read(@max_body_size + 1).to_s
146
+ text = env['rack.input']&.read(@max_body_size + 1).to_s
147
147
  return :content_too_large if text.bytesize > @max_body_size
148
148
  return if text.empty?
149
- return :unsupported_media_type unless JSON_TYPE.match?(env["CONTENT_TYPE"].to_s)
149
+ return :unsupported_media_type unless JSON_TYPE.match?(env['CONTENT_TYPE'].to_s)
150
150
 
151
151
  parse(String.new(text, encoding: Encoding::UTF_8))
152
152
  end