davixlabs-h2i 1.2.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.
@@ -0,0 +1,102 @@
1
+ # frozen_string_literal: true
2
+
3
+ # GENERATED from the Davix H2I API contract 3.0.0. Do not edit.
4
+
5
+ module DavixH2I
6
+ # if error.code == DavixH2I::ErrorCodes::RATE_LIMIT_EXCEEDED
7
+ module ErrorCodes
8
+ AI_CONFIGURATION_ERROR = 'ai_configuration_error'
9
+ AI_FEATURE_UNAVAILABLE = 'ai_feature_unavailable'
10
+ AI_GENERATION_FAILED = 'ai_generation_failed'
11
+ AI_INPUT_INVALID = 'ai_input_invalid'
12
+ AI_INPUT_TOO_LARGE = 'ai_input_too_large'
13
+ AI_MODEL_INCOMPATIBLE = 'ai_model_incompatible'
14
+ AI_MODEL_NOT_FOUND = 'ai_model_not_found'
15
+ AI_NOT_CONFIGURED = 'ai_not_configured'
16
+ AI_OUTPUT_INVALID = 'ai_output_invalid'
17
+ AI_PARAMETER_UNSUPPORTED = 'ai_parameter_unsupported'
18
+ AI_PROCESSING_FAILED = 'ai_processing_failed'
19
+ AI_PROVIDER_UNAVAILABLE = 'ai_provider_unavailable'
20
+ AI_QUOTA_EXCEEDED = 'ai_quota_exceeded'
21
+ AI_RATE_LIMITED = 'ai_rate_limited'
22
+ AI_SECURITY_REJECTED = 'ai_security_rejected'
23
+ AI_TIMEOUT = 'ai_timeout'
24
+ API_KEY_LOCATION_NOT_ALLOWED = 'api_key_location_not_allowed'
25
+ ASSISTANT_UNAVAILABLE = 'assistant_unavailable'
26
+ ASYNC_LIMIT_REACHED = 'async_limit_reached'
27
+ ASYNC_NOT_ALLOWED = 'async_not_allowed'
28
+ ASYNC_REQUIRES_CUSTOMER_KEY = 'async_requires_customer_key'
29
+ CERTIFICATE_LIMIT_REACHED = 'certificate_limit_reached'
30
+ CERTIFICATES_UNAVAILABLE = 'certificates_unavailable'
31
+ CONVERSATION_FULL = 'conversation_full'
32
+ DATA_CONVERSION_FAILED = 'data_conversion_failed'
33
+ DEMO_BUSY = 'demo_busy'
34
+ DEMO_FORBIDDEN = 'demo_forbidden'
35
+ DEMO_LIMIT_REACHED = 'demo_limit_reached'
36
+ DEMO_NOT_AVAILABLE = 'demo_not_available'
37
+ DEMO_UNAVAILABLE = 'demo_unavailable'
38
+ DEPENDENCY_UNAVAILABLE = 'dependency_unavailable'
39
+ DIMENSION_EXCEEDED = 'dimension_exceeded'
40
+ DUPLICATE_CERTIFICATE_NAME = 'duplicate_certificate_name'
41
+ DUPLICATE_PRESET_NAME = 'duplicate_preset_name'
42
+ DUPLICATE_TEMPLATE_NAME = 'duplicate_template_name'
43
+ ENDPOINT_API_DISABLED = 'endpoint_api_disabled'
44
+ ENDPOINT_DISABLED = 'endpoint_disabled'
45
+ ENDPOINT_NOT_ALLOWED = 'endpoint_not_allowed'
46
+ EXPIRED = 'expired'
47
+ FILE_TOO_LARGE = 'file_too_large'
48
+ FONT_UNAVAILABLE = 'font_unavailable'
49
+ FORBIDDEN = 'forbidden'
50
+ FORMAT_NOT_ALLOWED = 'format_not_allowed'
51
+ HTML_RENDER_FAILED = 'html_render_failed'
52
+ HTML_TOO_LARGE = 'html_too_large'
53
+ IDEMPOTENCY_KEY_CONFLICT = 'idempotency_key_conflict'
54
+ IMAGE_PROCESSING_FAILED = 'image_processing_failed'
55
+ INTERNAL_ERROR = 'internal_error'
56
+ INVALID_API_KEY = 'invalid_api_key'
57
+ INVALID_IDEMPOTENCY_KEY = 'invalid_idempotency_key'
58
+ INVALID_PARAMETER = 'invalid_parameter'
59
+ INVALID_SIGNATURE = 'invalid_signature'
60
+ INVALID_UPLOAD = 'invalid_upload'
61
+ JOB_NOT_CANCELLABLE = 'job_not_cancellable'
62
+ JOB_NOT_FOUND = 'job_not_found'
63
+ KEY_EXPIRED = 'key_expired'
64
+ KEY_LIMIT_REACHED = 'key_limit_reached'
65
+ KEY_NOT_FOUND = 'key_not_found'
66
+ KEY_QUOTA_EXCEEDED = 'key_quota_exceeded'
67
+ MESSAGE_TOO_LONG = 'message_too_long'
68
+ MISSING_FIELD = 'missing_field'
69
+ MONTHLY_QUOTA_EXCEEDED = 'monthly_quota_exceeded'
70
+ NO_SPEECH = 'no_speech'
71
+ NOT_FOUND = 'not_found'
72
+ NOT_LINKED = 'not_linked'
73
+ PDF_PAGE_LIMIT_EXCEEDED = 'pdf_page_limit_exceeded'
74
+ PDF_TOOL_FAILED = 'pdf_tool_failed'
75
+ PLAN_QUOTA_NOT_CONFIGURED = 'plan_quota_not_configured'
76
+ PLAN_RESOLUTION_FAILED = 'plan_resolution_failed'
77
+ RATE_LIMIT_EXCEEDED = 'rate_limit_exceeded'
78
+ RATE_LIMIT_STORE_UNAVAILABLE = 'rate_limit_store_unavailable'
79
+ RATE_LIMIT_UNAVAILABLE = 'rate_limit_unavailable'
80
+ RATE_LIMITED = 'rate_limited'
81
+ RENDER_SIZE_EXCEEDED = 'render_size_exceeded'
82
+ REQUEST_OPEN = 'request_open'
83
+ REVOKE_FAILED = 'revoke_failed'
84
+ ROTATE_FAILED = 'rotate_failed'
85
+ SERVER_BUSY = 'server_busy'
86
+ STORAGE_FULL = 'storage_full'
87
+ SUBSCRIPTION_CHARGEBACK = 'subscription_chargeback'
88
+ SUBSCRIPTION_DISABLED = 'subscription_disabled'
89
+ SUBSCRIPTION_PAUSED = 'subscription_paused'
90
+ SUBSCRIPTION_REFUNDED = 'subscription_refunded'
91
+ TIMEOUT = 'timeout'
92
+ TOO_MANY_CHATS = 'too_many_chats'
93
+ TOO_MANY_FILES = 'too_many_files'
94
+ TOTAL_UPLOAD_EXCEEDED = 'total_upload_exceeded'
95
+ TRANSCRIPTION_FAILED = 'transcription_failed'
96
+ UNAUTHORIZED = 'unauthorized'
97
+ UNSUPPORTED_MEDIA_TYPE = 'unsupported_media_type'
98
+ URL_BLOCKED = 'url_blocked'
99
+ URL_FETCH_FAILED = 'url_fetch_failed'
100
+ WORDPRESS_UNAVAILABLE = 'wordpress_unavailable'
101
+ end
102
+ end
@@ -0,0 +1,119 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'json'
4
+
5
+ module DavixH2I
6
+ def self.bundled_contract
7
+ @bundled_contract ||= JSON.parse(::File.read(::File.join(__dir__, 'contract.json'), encoding: 'UTF-8'))
8
+ end
9
+
10
+ # h2i.contract: the copy shipped with this SDK, or the live one after refresh. The slice methods are one small live GET each.
11
+ class ContractView
12
+ attr_reader :live
13
+
14
+ def initialize(client)
15
+ @client = client
16
+ @live = nil
17
+ end
18
+
19
+ def bundled
20
+ DavixH2I.bundled_contract
21
+ end
22
+
23
+ def active
24
+ live || bundled
25
+ end
26
+
27
+ def version
28
+ active['contractVersion']
29
+ end
30
+
31
+ def fetch
32
+ @client.send(:perform, 'GET', '/v1/contract', attach_key: false).data
33
+ end
34
+
35
+ def refresh
36
+ contract = fetch
37
+ @client.send(:check_contract, contract)
38
+ @live = contract
39
+ @client.send(:forget_schemas)
40
+ contract
41
+ end
42
+
43
+ def reset
44
+ @live = nil
45
+ @client.send(:forget_schemas)
46
+ end
47
+
48
+ def endpoints
49
+ slice('contract.endpoints')
50
+ end
51
+
52
+ def endpoint(id)
53
+ slice('contract.endpoints.{id}', id: id)
54
+ end
55
+
56
+ def fields(id)
57
+ slice('contract.endpoints.{id}.fields', id: id)
58
+ end
59
+
60
+ def field(id, name)
61
+ slice('contract.endpoints.{id}.fields.{name}', id: id, name: name)
62
+ end
63
+
64
+ def categories
65
+ slice('contract.categories')
66
+ end
67
+
68
+ def enums
69
+ slice('contract.enums')
70
+ end
71
+
72
+ def error(code)
73
+ slice('contract.errors.{code}', code: code)
74
+ end
75
+
76
+ private
77
+
78
+ def slice(id, params = {})
79
+ @client.call(id, params).data
80
+ end
81
+ end
82
+
83
+ # h2i.capabilities.runtime asks this server; static reads the contract without a request; account is about your key.
84
+ class Capabilities
85
+ def initialize(client)
86
+ @client = client
87
+ end
88
+
89
+ def runtime(category = nil)
90
+ answer = @client.call('capabilities')
91
+ return answer if category.nil?
92
+
93
+ data = answer.data
94
+ raise ConfigError, "No runtime capability group \"#{category}\"." unless data.is_a?(Hash) && data.key?(category)
95
+
96
+ Response.new(status: answer.status, headers: answer.headers, data: data[category], request_id: answer.request_id, attempts: answer.attempts)
97
+ end
98
+
99
+ def static(category = nil)
100
+ capabilities = @client.contract.active['capabilities']
101
+ return capabilities if category.nil?
102
+
103
+ capabilities['categories'].fetch(category) { raise ConfigError, "Unknown category \"#{category}\"." }
104
+ end
105
+
106
+ def account
107
+ answers = %w[subscription usage account].to_h { |name| [name.to_sym, @client.call(name)] }
108
+ answers.transform_values(&:data).merge(request_ids: answers.values.map(&:request_id))
109
+ end
110
+
111
+ def section(name)
112
+ @client.call('capabilities.{section}', { section: name }).data
113
+ end
114
+
115
+ def feature(section, feature)
116
+ @client.call('capabilities.{section}.{feature}', { section: section, feature: feature }).data
117
+ end
118
+ end
119
+ end
@@ -0,0 +1,121 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'json'
4
+ require 'pathname'
5
+ require 'securerandom'
6
+
7
+ module DavixH2I
8
+ # A file made of bytes you already have: DavixH2I::FileInput.new(data: bytes, filename: 'a.png')
9
+ class FileInput
10
+ attr_reader :data, :filename, :content_type
11
+
12
+ def initialize(data:, filename: nil, content_type: nil)
13
+ @data = data
14
+ @filename = filename
15
+ @content_type = content_type
16
+ end
17
+ end
18
+
19
+ # multipart/form-data bodies. A plain String is read from disk ONLY for a field the contract calls a file.
20
+ module Multipart
21
+ TYPES = {
22
+ '.jpg' => 'image/jpeg', '.jpeg' => 'image/jpeg', '.png' => 'image/png', '.webp' => 'image/webp', '.gif' => 'image/gif', '.avif' => 'image/avif',
23
+ '.svg' => 'image/svg+xml', '.tif' => 'image/tiff', '.tiff' => 'image/tiff', '.pdf' => 'application/pdf', '.json' => 'application/json',
24
+ '.csv' => 'text/csv', '.xml' => 'application/xml', '.txt' => 'text/plain', '.md' => 'text/markdown', '.html' => 'text/html',
25
+ '.docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
26
+ '.xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
27
+ '.pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
28
+ '.odt' => 'application/vnd.oasis.opendocument.text', '.ods' => 'application/vnd.oasis.opendocument.spreadsheet',
29
+ '.odp' => 'application/vnd.oasis.opendocument.presentation', '.rtf' => 'application/rtf', '.epub' => 'application/epub+zip'
30
+ }.freeze
31
+
32
+ module_function
33
+
34
+ def content_type_for(filename)
35
+ TYPES.fetch(::File.extname(filename.to_s).downcase, 'application/octet-stream')
36
+ end
37
+
38
+ def file_like?(value)
39
+ return true if value.is_a?(FileInput) || value.is_a?(Pathname) || value.respond_to?(:read)
40
+
41
+ value.is_a?(Hash) && (value.key?(:data) || value.key?('data') || value[:path].is_a?(String) || value['path'].is_a?(String))
42
+ end
43
+
44
+ # [bytes, filename, content type] for a path, a Pathname, an IO, FileInput, { path: } or { data:, filename: }
45
+ def to_file(value, fallback)
46
+ filename = type = nil
47
+ if value.is_a?(FileInput)
48
+ filename = value.filename
49
+ type = value.content_type
50
+ value = Bytes.new(value.data)
51
+ elsif value.is_a?(Hash)
52
+ hash = value.transform_keys(&:to_s)
53
+ filename = hash['filename']
54
+ type = hash['content_type'] || hash['contentType']
55
+ value = hash.key?('data') ? (hash['data'].respond_to?(:read) ? hash['data'] : Bytes.new(hash['data'])) : hash.fetch('path')
56
+ end
57
+ data =
58
+ case value
59
+ when Bytes then value.value.to_s.b
60
+ when String, Pathname
61
+ filename ||= ::File.basename(value.to_s)
62
+ read_path(value.to_s)
63
+ else
64
+ raise ConfigError, 'Unsupported file value: use a path, an IO or FileInput.new(data:, filename:).' unless value.respond_to?(:read)
65
+
66
+ filename ||= ::File.basename(value.path) if value.respond_to?(:path) && value.path
67
+ value.read.to_s.b
68
+ end
69
+ filename ||= fallback
70
+ [data, filename, type || content_type_for(filename)]
71
+ end
72
+
73
+ Bytes = Struct.new(:value)
74
+
75
+ def read_path(path)
76
+ ::File.binread(path)
77
+ rescue SystemCallError => e
78
+ raise ConfigError, "Cannot read file \"#{path}\": #{e.message}"
79
+ end
80
+
81
+ # How the server expects a non-file value: booleans as true/false, objects and lists as compact JSON.
82
+ def to_text(value)
83
+ case value
84
+ when Hash, Array then JSON.generate(value)
85
+ else value.to_s
86
+ end
87
+ end
88
+
89
+ def quote(text)
90
+ text.to_s.gsub("\r", '%0D').gsub("\n", '%0A').gsub('"', '%22')
91
+ end
92
+
93
+ # fields: the endpoint's form fields, or nil for an endpoint this SDK does not know. Returns [body, content type].
94
+ def build(fields, params)
95
+ known = Array(fields).to_h { |f| [f['name'], f] }
96
+ boundary = "h2i-#{SecureRandom.hex(16)}"
97
+ body = +''.b
98
+ part = lambda do |headers, bytes|
99
+ body << "--#{boundary}\r\n#{headers}\r\n\r\n".b << bytes.b << "\r\n".b
100
+ end
101
+ params.each do |name, value|
102
+ next if value.nil?
103
+
104
+ name = name.to_s
105
+ field = known[name]
106
+ as_files = field ? field['type'] == 'file' : (file_like?(value) || (value.is_a?(Array) && !value.empty? && value.all? { |v| file_like?(v) }))
107
+ if as_files
108
+ items = value.is_a?(Array) ? value : [value]
109
+ items.each_with_index do |item, index|
110
+ data, filename, type = to_file(item, items.length > 1 ? "#{name}-#{index + 1}" : name)
111
+ part.call("Content-Disposition: form-data; name=\"#{quote(name)}\"; filename=\"#{quote(filename)}\"\r\nContent-Type: #{quote(type)}", data)
112
+ end
113
+ else
114
+ part.call("Content-Disposition: form-data; name=\"#{quote(name)}\"", to_text(value))
115
+ end
116
+ end
117
+ body << "--#{boundary}--\r\n".b
118
+ [body, "multipart/form-data; boundary=#{boundary}"]
119
+ end
120
+ end
121
+ end
@@ -0,0 +1,61 @@
1
+ # frozen_string_literal: true
2
+
3
+ module DavixH2I
4
+ # What keeps the generic request() inside the public API: only /v1/... and the public OpenAPI documents.
5
+ module Paths
6
+ module_function
7
+
8
+ def assert_public(path, policy)
9
+ refuse('path must be a non-empty string.') unless path.is_a?(String) && !path.empty?
10
+ refuse('path contains forbidden characters.') if path.match?(/[\x00-\x1f\x7f\s\\]/)
11
+ refuse('path must be a site-relative path starting with a single "/"; absolute URLs are not allowed.') if !path.start_with?('/') || path.start_with?('//')
12
+ refuse('absolute URLs are not allowed.') if path.include?('://') || path.match?(%r{\A/[a-z][a-z0-9+.-]*:}i)
13
+ refuse('put the query string in the `query` option, not in the path.') if path.match?(/[?#]/)
14
+ refuse('path is not valid percent-encoding.') if path.match?(/%(?![0-9A-Fa-f]{2})/)
15
+
16
+ decoded = decode(path)
17
+ # a second decode catches double-encoded traversal (%252e%252e)
18
+ [path, decoded, decode(decoded)].each do |candidate|
19
+ refuse('path traversal is not allowed.') if candidate.match?(%r{(\A|/)\.\.?(/|\z)})
20
+ refuse('empty path segments are not allowed.') if candidate[1..].to_s.include?('//')
21
+ lower = candidate.downcase
22
+ Array(policy['blockedPrefixes']).each do |prefix|
23
+ refuse("#{prefix} is not part of the public API and cannot be called through this SDK.") if lower == prefix || lower.start_with?("#{prefix}/")
24
+ end
25
+ end
26
+ return path if Array(policy['extraAllowedPaths']).include?(path)
27
+
28
+ pattern = Regexp.new(policy['allowedPathPattern'] || '^/v1/')
29
+ refuse('only public API paths under /v1/ (and the /openapi/ documents) are allowed.') unless path.match?(pattern) && (path.start_with?('/v1/') || path.start_with?('/openapi/'))
30
+ path
31
+ end
32
+
33
+ def refuse(why)
34
+ raise ConfigError, "request(): #{why}"
35
+ end
36
+
37
+ def decode(text)
38
+ text.b.gsub(/%([0-9A-Fa-f]{2})/) { Regexp.last_match(1).hex.chr }.force_encoding(Encoding::UTF_8).scrub
39
+ end
40
+
41
+ # A value can never add a path separator or a traversal: "/" and "." are encoded.
42
+ def encode_segment(value)
43
+ value.to_s.b.gsub(/[^A-Za-z0-9\-_!~*'()]/n) { |ch| format('%%%02X', ch.ord) }
44
+ end
45
+
46
+ def expand(template, values)
47
+ template.gsub(/\{([A-Za-z0-9_]+)\}/) do
48
+ name = Regexp.last_match(1)
49
+ value = values[name]
50
+ raise ConfigError, "Missing required path parameter \"#{name}\"." if value.nil? || value.to_s.empty?
51
+
52
+ encode_segment(value)
53
+ end
54
+ end
55
+
56
+ def match_template?(template, concrete)
57
+ parts = template.split(/\{[A-Za-z0-9_]+\}/, -1)
58
+ concrete.match?(Regexp.new("\\A#{parts.map { |p| Regexp.escape(p) }.join('[^/]+')}\\z"))
59
+ end
60
+ end
61
+ end
@@ -0,0 +1,41 @@
1
+ # frozen_string_literal: true
2
+
3
+ module DavixH2I
4
+ # The answer to a successful call.
5
+ class Response
6
+ attr_reader :status, :headers, :data, :request_id, :idempotency_key, :attempts
7
+
8
+ def initialize(status:, headers:, data:, request_id: nil, idempotency_key: nil, attempts: 1)
9
+ @status = status
10
+ @headers = headers
11
+ @data = data
12
+ @request_id = request_id
13
+ @idempotency_key = idempotency_key
14
+ @attempts = attempts
15
+ end
16
+
17
+ # Every result object with a "url" (a signed download address) in the answer.
18
+ def files
19
+ found = []
20
+ walk = lambda do |value|
21
+ case value
22
+ when Array then value.each { |v| walk.call(v) }
23
+ when Hash
24
+ found << value if value['url'].is_a?(String)
25
+ value.each_value { |v| walk.call(v) }
26
+ end
27
+ end
28
+ walk.call(data)
29
+ found
30
+ end
31
+
32
+ # True when the server accepted an async job (HTTP 202).
33
+ def accepted?
34
+ status == 202
35
+ end
36
+
37
+ def job_id
38
+ data.is_a?(Hash) ? data['job_id'] : nil
39
+ end
40
+ end
41
+ end
@@ -0,0 +1,124 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'json'
4
+
5
+ module DavixH2I
6
+ # Read-only metadata of one endpoint, with advisory validation: what the server would silently clamp or replace is a warning,
7
+ # what it would reject is an error. The server stays the final authority.
8
+ class Schema
9
+ attr_reader :endpoint, :id, :method_name, :path, :fields
10
+
11
+ def initialize(endpoint)
12
+ @endpoint = endpoint
13
+ @id = endpoint['id']
14
+ @method_name = endpoint['method']
15
+ @path = endpoint['path']
16
+ @fields = endpoint['request']['fields'].to_h { |f| [f['name'], f] }
17
+ end
18
+
19
+ def idempotent?
20
+ endpoint.dig('idempotency', 'supported') ? true : false
21
+ end
22
+
23
+ def required
24
+ fields.values.select { |f| f['required'] }.map { |f| f['name'] }
25
+ end
26
+
27
+ def validate(params = {})
28
+ params = (params || {}).transform_keys(&:to_s)
29
+ errors = []
30
+ warnings = []
31
+ fields.each do |name, field|
32
+ next if field['standard'] && field['location'] == 'header'
33
+
34
+ check(field, params[name], params.key?(name), name, errors, warnings)
35
+ end
36
+ { valid: errors.empty?, errors: errors, warnings: warnings, unknown: params.keys - fields.keys }
37
+ end
38
+
39
+ private
40
+
41
+ def number(value)
42
+ return value if value.is_a?(Numeric) && value.to_f.finite?
43
+ return nil unless value.is_a?(String)
44
+
45
+ Float(value, exception: false)
46
+ end
47
+
48
+ def check(field, value, given, path, errors, warnings)
49
+ push = ->(list, rule, message) { list << { path: path, rule: rule, message: "#{path} #{message}" } }
50
+ if value.nil?
51
+ if field['required'] && !given
52
+ push.call(errors, 'required', 'is required.')
53
+ elsif given && field['required'] && !field['nullable']
54
+ push.call(errors, 'nullable', 'must not be null.')
55
+ end
56
+ return
57
+ end
58
+ behavior = field['behavior'] || {}
59
+ ranges = %w[clamp fallback passthrough].include?(behavior['onOutOfRange']) ? warnings : errors
60
+ invalid = %w[ignore fallback normalize passthrough].include?(behavior['onInvalid']) ? warnings : errors
61
+ case field['type']
62
+ when 'string'
63
+ return push.call(invalid, 'type', 'must be a string.') unless value.is_a?(String)
64
+
65
+ push.call(ranges, 'minLength', "must be at least #{field['minLength']} characters.") if field['minLength'] && value.length < field['minLength']
66
+ push.call(ranges, 'maxLength', "must be at most #{field['maxLength']} characters.") if field['maxLength'] && value.length > field['maxLength']
67
+ push.call(invalid, 'pattern', 'has an invalid format.') if field['pattern'] && pattern_fails?(field['pattern'], value)
68
+ push.call(invalid, 'enum', "must be one of: #{field['enum'].join(', ')}.") if field['enum'] && !field['enum'].include?(value) && !field['enum'].include?(value.downcase)
69
+ when 'integer', 'number'
70
+ n = number(value)
71
+ return push.call(invalid, 'type', 'must be a number.') if n.nil?
72
+ return push.call(invalid, 'type', 'must be an integer.') if field['type'] == 'integer' && n != n.to_i
73
+
74
+ push.call(invalid, 'enum', "must be one of: #{field['enum'].join(', ')}.") if field['enum'] && !field['enum'].include?(n)
75
+ push.call(ranges, 'minimum', "must be >= #{field['minimum']}.") if field['minimum'] && n < field['minimum']
76
+ push.call(ranges, 'maximum', "must be <= #{field['maximum']}.") if field['maximum'] && n > field['maximum']
77
+ push.call(ranges, 'exclusiveMinimum', "must be > #{field['exclusiveMinimum']}.") if field['exclusiveMinimum'] && n <= field['exclusiveMinimum']
78
+ push.call(ranges, 'exclusiveMaximum', "must be < #{field['exclusiveMaximum']}.") if field['exclusiveMaximum'] && n >= field['exclusiveMaximum']
79
+ when 'boolean'
80
+ push.call(invalid, 'type', 'must be a boolean.') unless [true, false, 'true', 'false'].include?(value)
81
+ when 'file'
82
+ check_files(field['file'] || {}, value, push, errors)
83
+ when 'array', 'object'
84
+ if value.is_a?(String) && field['encoding'] == 'json-string'
85
+ begin
86
+ value = JSON.parse(value)
87
+ rescue JSON::ParserError
88
+ return push.call(invalid, 'type', 'must be JSON.')
89
+ end
90
+ end
91
+ field['type'] == 'array' ? check_array(field, value, path, push, invalid, ranges, errors, warnings) : check_object(field, value, path, push, invalid, errors, warnings)
92
+ end
93
+ end
94
+
95
+ def check_files(limits, value, push, errors)
96
+ items = value.is_a?(Array) ? value : [value]
97
+ push.call(errors, 'maxFiles', 'accepts a single file.') if !limits['multiple'] && items.length > 1
98
+ push.call(errors, 'minFiles', "needs at least #{limits['minFiles']} files.") if limits['minFiles'] && items.length < limits['minFiles']
99
+ push.call(errors, 'maxFiles', "accepts at most #{limits['maxFiles']} files.") if limits['maxFiles'] && items.length > limits['maxFiles']
100
+ push.call(errors, 'type', 'must be a file path, an IO or FileInput.') unless items.all? { |i| i.is_a?(String) || Multipart.file_like?(i) }
101
+ end
102
+
103
+ def check_array(field, value, path, push, invalid, ranges, errors, warnings)
104
+ return push.call(invalid, 'type', 'must be an array.') unless value.is_a?(Array)
105
+
106
+ push.call(ranges, 'minItems', "needs at least #{field['minItems']} items.") if field['minItems'] && value.length < field['minItems']
107
+ push.call(ranges, 'maxItems', "accepts at most #{field['maxItems']} items.") if field['maxItems'] && value.length > field['maxItems']
108
+ value.each_with_index { |item, i| check(field['items'], item, true, "#{path}[#{i}]", errors, warnings) } if field['items']
109
+ end
110
+
111
+ def check_object(field, value, path, push, invalid, errors, warnings)
112
+ return push.call(invalid, 'type', 'must be an object.') unless value.is_a?(Hash)
113
+
114
+ hash = value.transform_keys(&:to_s)
115
+ Array(field['properties']).each { |p| check(p, hash[p['name']], hash.key?(p['name']), "#{path}.#{p['name']}", errors, warnings) }
116
+ end
117
+
118
+ def pattern_fails?(pattern, value)
119
+ !Regexp.new(pattern).match?(value)
120
+ rescue RegexpError
121
+ false # a pattern written for JavaScript: the server checks it
122
+ end
123
+ end
124
+ end
@@ -0,0 +1,39 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'net/http'
4
+ require 'openssl'
5
+ require 'uri'
6
+
7
+ module DavixH2I
8
+ # One HTTP request with the standard library. Net::HTTP does not follow redirects, so the key cannot travel to another address.
9
+ module Transport
10
+ CLASSES = { 'GET' => Net::HTTP::Get, 'POST' => Net::HTTP::Post, 'PUT' => Net::HTTP::Put, 'PATCH' => Net::HTTP::Patch, 'DELETE' => Net::HTTP::Delete }.freeze
11
+
12
+ module_function
13
+
14
+ # Returns [status, headers with lower-cased names, raw body].
15
+ def call(method, url, headers, body, timeout)
16
+ uri = URI.parse(url)
17
+ request = CLASSES.fetch(method).new(uri.request_uri)
18
+ headers.each { |name, value| request[name] = value }
19
+ if body
20
+ request.body = body
21
+ end
22
+ http = Net::HTTP.new(uri.hostname, uri.port)
23
+ http.use_ssl = uri.scheme == 'https'
24
+ http.max_retries = 0 # this SDK decides what may be repeated
25
+ http.open_timeout = http.read_timeout = http.write_timeout = timeout if timeout
26
+ response = http.start { |connection| connection.request(request) }
27
+ status = response.code.to_i
28
+ raise NetworkError, "Network error: the server answered with a redirect (#{status}), which is refused." if status >= 300 && status < 400
29
+
30
+ result = {}
31
+ response.each_header { |name, value| result[name.downcase] = value }
32
+ [status, result, response.body.to_s.b]
33
+ rescue Net::OpenTimeout, Net::ReadTimeout, Net::WriteTimeout => e
34
+ raise TimeoutError, "Request timed out after #{timeout} seconds. (#{e.class})"
35
+ rescue SocketError, SystemCallError, IOError, OpenSSL::SSL::SSLError, Net::HTTPBadResponse => e
36
+ raise NetworkError, "Network error: #{e.message}"
37
+ end
38
+ end
39
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module DavixH2I
4
+ VERSION = '1.2.1'
5
+ end
data/lib/davix_h2i.rb ADDED
@@ -0,0 +1,20 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Official Ruby SDK for the Davix H2I API.
4
+ #
5
+ # require 'davix_h2i'
6
+ # h2i = DavixH2I::Client.new(api_key: ENV['DAVIX_H2I_API_KEY'])
7
+ # result = h2i.images.resize(images: 'photo.jpg', width: 800)
8
+ # puts result.files
9
+ require_relative 'davix_h2i/version'
10
+ require_relative 'davix_h2i/errors'
11
+ require_relative 'davix_h2i/paths'
12
+ require_relative 'davix_h2i/multipart'
13
+ require_relative 'davix_h2i/transport'
14
+ require_relative 'davix_h2i/response'
15
+ require_relative 'davix_h2i/schema'
16
+ require_relative 'davix_h2i/metadata'
17
+ require_relative 'davix_h2i/generated/api'
18
+ require_relative 'davix_h2i/generated/enums'
19
+ require_relative 'davix_h2i/generated/error_codes'
20
+ require_relative 'davix_h2i/client'