assinafy 2.3.0 → 2.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.
@@ -7,7 +7,8 @@ module Assinafy
7
7
  # pagination header parsing, and a single `request`/`call` pipeline that
8
8
  # wraps Faraday and Assinafy errors into the SDK's own error hierarchy.
9
9
  class BaseResource
10
- PATH_SEGMENT = /\A[A-Za-z0-9._~-]+\z/
10
+ include Validation
11
+
11
12
  MAX_UPLOAD_BYTES = 25 * 1024 * 1024
12
13
  STATS_GRANULARITIES = %w[monthly daily].freeze
13
14
  AUTH_HEADERS = %w[X-Api-Key Authorization].freeze
@@ -28,7 +29,6 @@ module Assinafy
28
29
  # @param logger [Logger, nil]
29
30
  def initialize(connection, default_account_id = nil, logger = nil)
30
31
  @connection = connection
31
- @connection.headers['User-Agent'] = USER_AGENT
32
32
  @default_account_id = default_account_id.is_a?(String) ? default_account_id.dup.freeze : default_account_id
33
33
  @logger = logger || NullLogger.new
34
34
  end
@@ -39,50 +39,6 @@ module Assinafy
39
39
  require_id(explicit.nil? ? @default_account_id : explicit, 'Account ID')
40
40
  end
41
41
 
42
- # Ensure a required scalar argument is present (not nil/blank).
43
- # `require_id` is kept as an intention-revealing alias for path IDs.
44
- def require_present(value, name)
45
- return value unless value.nil? || value.to_s.strip.empty?
46
-
47
- raise ValidationError.new("#{name} is required")
48
- end
49
-
50
- def require_id(value, name)
51
- id = require_string(value, name)
52
-
53
- return id if PATH_SEGMENT.match?(id) && id != '.' && id != '..'
54
-
55
- raise ValidationError.new("#{name} contains invalid characters")
56
- end
57
-
58
- def require_string(value, name, max_length: nil)
59
- string = require_present(value, name)
60
- raise ValidationError.new("#{name} must be a String") unless string.is_a?(String)
61
- if max_length && string.length > max_length
62
- raise ValidationError.new("#{name} must be at most #{max_length} characters")
63
- end
64
-
65
- string
66
- end
67
-
68
- def require_boolean(value, name)
69
- return value if [true, false].include?(value)
70
-
71
- raise ValidationError.new("#{name} must be true or false")
72
- end
73
-
74
- def require_payload(payload, name = 'Payload')
75
- raise ValidationError.new("#{name} must be a Hash") unless payload.is_a?(Hash)
76
-
77
- payload
78
- end
79
-
80
- def require_array(value, name)
81
- return value if value.is_a?(Array) && !value.empty?
82
-
83
- raise ValidationError.new("#{name} must be a non-empty Array")
84
- end
85
-
86
42
  def require_preferences(value, allowed, name = 'Notification preferences')
87
43
  preferences = require_payload(value, name)
88
44
  raise ValidationError.new("#{name} must not be empty") if preferences.empty?
@@ -123,6 +79,14 @@ module Assinafy
123
79
  Utils.body_params(params)
124
80
  end
125
81
 
82
+ # {Utils.body_params} drops every nil; `keys` names the fields the API
83
+ # clears with JSON null, whose explicit nil must reach the wire.
84
+ def nullable_body(params, keys)
85
+ body = body_params(params)
86
+ params.each { |key, value| body[key.to_s] = nil if value.nil? && keys.include?(key.to_s) }
87
+ body
88
+ end
89
+
126
90
  # Normalise an upload source into `[buffer, file_name]`. Shared by every
127
91
  # multipart upload endpoint (document upload, template create, account
128
92
  # logo). Accepts a path String, or a Hash with `:file_path` (path) **or**
@@ -173,19 +137,23 @@ module Assinafy
173
137
  Faraday::FilePart.new(StringIO.new(buffer), content_type || mime_type_for(file_name), file_name)
174
138
  end
175
139
 
176
- def validate_pdf_source!(buffer, file_name, max_bytes: nil)
177
- unless file_name.downcase.end_with?('.pdf')
178
- raise ValidationError.new('Only PDF files are supported', { file_name: file_name })
140
+ # Only a PDF is checked for its header; the other accepted formats are
141
+ # converted by the API, which is the authority on their structure.
142
+ def validate_document_source!(buffer, file_name, extensions = %w[.pdf])
143
+ extension = File.extname(file_name).downcase
144
+ unless extensions.include?(extension)
145
+ names = extensions.map { |ext| ext.delete('.').upcase }.join(', ')
146
+ raise ValidationError.new("Only #{names} files are supported", { file_name: file_name })
179
147
  end
180
148
 
181
- if max_bytes && buffer.bytesize > max_bytes
149
+ if buffer.bytesize > MAX_UPLOAD_BYTES
182
150
  raise ValidationError.new(
183
- "File size exceeds maximum allowed (#{max_bytes / (1024 * 1024)}MB)",
184
- { file_size: buffer.bytesize, max_size: max_bytes }
151
+ "File size exceeds maximum allowed (#{MAX_UPLOAD_BYTES / (1024 * 1024)}MB)",
152
+ { file_size: buffer.bytesize, max_size: MAX_UPLOAD_BYTES }
185
153
  )
186
154
  end
187
155
 
188
- return if buffer.byteslice(0, 1024).to_s.include?('%PDF-')
156
+ return if extension != '.pdf' || buffer.byteslice(0, 1024).to_s.include?('%PDF-')
189
157
 
190
158
  raise ValidationError.new('File content is not a PDF', { file_name: file_name })
191
159
  end
@@ -193,6 +161,9 @@ module Assinafy
193
161
  def mime_type_for(file_name)
194
162
  case File.extname(file_name.to_s).downcase
195
163
  when '.pdf' then 'application/pdf'
164
+ when '.doc' then 'application/msword'
165
+ when '.docx' then 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
166
+ when '.odt' then 'application/vnd.oasis.opendocument.text'
196
167
  when '.png' then 'image/png'
197
168
  when '.jpg', '.jpeg' then 'image/jpeg'
198
169
  when '.gif' then 'image/gif'
@@ -203,65 +174,47 @@ module Assinafy
203
174
  end
204
175
 
205
176
  def http_get(path, params = {}, workspace_auth: true)
206
- @connection.get(path) do |request|
207
- prepare_request(request, params, workspace_auth: workspace_auth)
208
- end
177
+ send_request(:get, path, nil, params, workspace_auth)
209
178
  end
210
179
 
211
180
  def http_post(path, body = nil, params = {}, workspace_auth: true, headers: {})
212
- @connection.post(path) do |request|
213
- request.headers.update(headers)
214
- prepare_request(request, params, workspace_auth: workspace_auth)
215
- request.body = body unless body.nil?
216
- end
181
+ send_request(:post, path, body, params, workspace_auth, headers)
217
182
  end
218
183
 
219
- def idempotency_headers(key)
220
- return {} if key.nil?
221
-
222
- require_string(key, 'Idempotency key')
223
- raise ValidationError.new('Idempotency key contains invalid characters') if key.match?(/[\r\n]/)
224
-
225
- { 'Idempotency-Key' => key }
184
+ def http_put(path, body = nil, params = {}, workspace_auth: true)
185
+ send_request(:put, path, body, params, workspace_auth)
226
186
  end
227
187
 
228
- def signing_expansion(value)
229
- return nil if value.nil?
230
- return 'envelope' if ['envelope', ['envelope']].include?(value)
188
+ def http_patch(path, body = nil, params = {}, workspace_auth: true)
189
+ send_request(:patch, path, body, params, workspace_auth)
190
+ end
231
191
 
232
- raise ValidationError.new('expand must be envelope')
192
+ def http_delete(path, params = {}, body: nil, workspace_auth: true)
193
+ send_request(:delete, path, body, params, workspace_auth)
233
194
  end
234
195
 
235
196
  # RFC 6749 §4.1.3/§6 and RFC 7009 §2.1 define token and revocation
236
197
  # requests as form posts. The connection's JSON and multipart middleware
237
198
  # leave a pre-encoded String body alone.
238
199
  def http_post_form(path, form, workspace_auth: true)
239
- @connection.post(path) do |request|
240
- prepare_request(request, {}, workspace_auth: workspace_auth)
241
- request.headers['Content-Type'] = 'application/x-www-form-urlencoded'
242
- request.body = URI.encode_www_form(form)
243
- end
200
+ headers = { 'Content-Type' => 'application/x-www-form-urlencoded' }
201
+ http_post(path, URI.encode_www_form(form), workspace_auth: workspace_auth, headers: headers)
244
202
  end
245
203
 
246
- def http_put(path, body = nil, params = {}, workspace_auth: true)
247
- @connection.put(path) do |request|
248
- prepare_request(request, params, workspace_auth: workspace_auth)
249
- request.body = body unless body.nil?
250
- end
251
- end
204
+ def idempotency_headers(key)
205
+ return {} if key.nil?
252
206
 
253
- def http_patch(path, body = nil, params = {}, workspace_auth: true)
254
- @connection.patch(path) do |request|
255
- prepare_request(request, params, workspace_auth: workspace_auth)
256
- request.body = body unless body.nil?
257
- end
207
+ require_string(key, 'Idempotency key')
208
+ raise ValidationError.new('Idempotency key contains invalid characters') if key.match?(/[\r\n]/)
209
+
210
+ { 'Idempotency-Key' => key }
258
211
  end
259
212
 
260
- def http_delete(path, params = {}, body: nil, workspace_auth: true)
261
- @connection.delete(path) do |request|
262
- prepare_request(request, params, workspace_auth: workspace_auth)
263
- request.body = body unless body.nil?
264
- end
213
+ def signing_expansion(value)
214
+ return nil if value.nil?
215
+ return 'envelope' if ['envelope', ['envelope']].include?(value)
216
+
217
+ raise ValidationError.new('expand must be envelope')
265
218
  end
266
219
 
267
220
  def prepare_request(request, params, workspace_auth:)
@@ -274,10 +227,12 @@ module Assinafy
274
227
  unwrap(request(label) { yield })
275
228
  end
276
229
 
277
- def call_optional(label)
230
+ # `error_code` narrows "absent" to one refusal code, for routes whose
231
+ # other 404s mean the parent resource itself is missing.
232
+ def call_optional(label, error_code: nil)
278
233
  call(label) { yield }
279
234
  rescue ApiError => e
280
- raise unless e.status_code == 404
235
+ raise unless e.status_code == 404 && (error_code.nil? || e.error_code == error_code)
281
236
 
282
237
  nil
283
238
  end
@@ -311,7 +266,6 @@ module Assinafy
311
266
  def call_list(label)
312
267
  response = request(label) { yield }
313
268
  body = unwrap(response)
314
- # @type var result: Assinafy::list_result
315
269
  result = { data: extract_list_data(body, label, response) }
316
270
  meta = parse_pagination_meta(response.headers)
317
271
  result[:meta] = meta if meta
@@ -320,17 +274,23 @@ module Assinafy
320
274
 
321
275
  private
322
276
 
277
+ def send_request(method, path, body, params, workspace_auth, headers = {})
278
+ @connection.run_request(method, path, nil, nil) do |request|
279
+ request.headers.update(headers)
280
+ prepare_request(request, params, workspace_auth: workspace_auth)
281
+ request.body = body unless body.nil?
282
+ end
283
+ end
284
+
285
+ # Only transport-layer failures are wrapped; anything else is a defect
286
+ # that must surface as itself rather than as an SDK error.
323
287
  def request(label)
324
288
  response = yield
325
- check_status!(response, label)
289
+ check_status!(response)
326
290
  response
327
291
  rescue Faraday::ConnectionFailed, Faraday::TimeoutError, Faraday::SSLError => e
328
292
  raise NetworkError.new("#{label}: #{e.message}", { cause: e.class.name })
329
- rescue Assinafy::Error
330
- raise
331
- rescue StandardError => e
332
- # Preserve the original class for debugging; Ruby keeps the original
333
- # exception accessible via #cause since we re-raise inside the rescue.
293
+ rescue Faraday::Error => e
334
294
  raise Assinafy::Error.new("#{label}: #{e.message}", { cause: e.class.name })
335
295
  end
336
296
 
@@ -338,7 +298,7 @@ module Assinafy
338
298
  # token is missing, which tells "reconnect with more scope" apart from
339
299
  # "wrong workspace or role", so it travels with the error, as do the
340
300
  # rate-limit headers a `429` needs for backing off.
341
- def check_status!(response, _label)
301
+ def check_status!(response)
342
302
  return if (200..299).cover?(response.status)
343
303
 
344
304
  raise with_response_headers(error_class.from_response(response.status, response.body), response)
@@ -356,11 +316,11 @@ module Assinafy
356
316
  challenge = headers['www-authenticate']
357
317
  error.context[:www_authenticate] = challenge if challenge
358
318
  rate_limit = RATE_LIMIT_HEADERS.filter_map do |key, header|
359
- value = to_int(headers[header])
319
+ value = Integer(headers[header], exception: false)
360
320
  [key, value] if value
361
321
  end.to_h
362
322
  error.context[:rate_limit] = rate_limit unless rate_limit.empty?
363
- retry_after = to_int(headers['retry-after'])
323
+ retry_after = Integer(headers['retry-after'], exception: false)
364
324
  error.context[:retry_after] = retry_after if retry_after
365
325
  error
366
326
  end
@@ -409,19 +369,11 @@ module Assinafy
409
369
  return nil unless headers
410
370
 
411
371
  meta = PAGINATION_HEADERS.each_with_object({}) do |(key, header), acc|
412
- value = to_int(headers[header])
372
+ value = Integer(headers[header], exception: false)
413
373
  acc[key] = value if value
414
374
  end
415
375
  meta.empty? ? nil : meta
416
376
  end
417
-
418
- def to_int(value)
419
- return nil if value.nil?
420
-
421
- Integer(value)
422
- rescue ArgumentError, TypeError
423
- nil
424
- end
425
377
  end
426
378
  end
427
379
  end
@@ -19,6 +19,8 @@ module Assinafy
19
19
  ].freeze
20
20
  RENEW_FIELDS = %w[end_date value term updated_at].freeze
21
21
  TERMINATE_FIELDS = %w[reason updated_at].freeze
22
+ NO_CONTRACT_TERMS = 'NoContractTerms'
23
+ private_constant :NO_CONTRACT_TERMS
22
24
 
23
25
  # List tracked contracts in a workspace, most recently updated first.
24
26
  #
@@ -63,7 +65,7 @@ module Assinafy
63
65
  # @param document_id [String]
64
66
  # @param account_id_override [String, nil]
65
67
  # @return [Hash, nil] a DocumentContract or DocumentContractAmendment
66
- # @raise [Assinafy::ApiError] on an unsuccessful response other than 404
68
+ # @raise [Assinafy::ApiError] on an unsuccessful response, including 404 for an unknown document
67
69
  # @raise [Assinafy::NetworkError] on transport or TLS failure
68
70
  # @raise [Assinafy::ValidationError] on an invalid ID
69
71
  # @see GET /accounts/{accountId}/documents/{documentId}/contract
@@ -91,7 +93,7 @@ module Assinafy
91
93
  # # 'created_at' => '2026-10-23T12:00:00Z', 'updated_at' => '2027-05-12T18:20:00Z'
92
94
  # # }
93
95
  def get(document_id, account_id_override = nil)
94
- call_optional('Failed to fetch contract') do
96
+ call_optional('Failed to fetch contract', error_code: NO_CONTRACT_TERMS) do
95
97
  http_get(contract_path(document_id, account_id_override))
96
98
  end
97
99
  end
@@ -153,7 +155,7 @@ module Assinafy
153
155
  # @param document_id [String]
154
156
  # @param account_id_override [String, nil]
155
157
  # @return [Hash, nil] root DocumentContract with `amendments`
156
- # @raise [Assinafy::ApiError] on an unsuccessful response other than 404
158
+ # @raise [Assinafy::ApiError] on an unsuccessful response, including 404 for an unknown document
157
159
  # @raise [Assinafy::NetworkError] on transport or TLS failure
158
160
  # @raise [Assinafy::ValidationError] on an invalid ID
159
161
  # @param expand [String, nil] `document` embeds the root document, including its name
@@ -175,7 +177,7 @@ module Assinafy
175
177
  raise ValidationError.new('expand must be document')
176
178
  end
177
179
 
178
- call_optional('Failed to fetch related contracts') do
180
+ call_optional('Failed to fetch related contracts', error_code: NO_CONTRACT_TERMS) do
179
181
  http_get("#{contract_path(document_id, account_id_override)}/related", { expand: expand })
180
182
  end
181
183
  end
@@ -251,7 +253,7 @@ module Assinafy
251
253
 
252
254
  def contract_list_params(params)
253
255
  query = query_params(require_payload(params, 'Contract filters'))
254
- reject_unknown_fields!(query, LIST_FIELDS, 'contract filters')
256
+ reject_unknown_keys!(query, LIST_FIELDS, 'contract filters')
255
257
  validate_status_filter!(query)
256
258
  %w[counterparty search external_system external_id].each do |field|
257
259
  validate_optional_string!(query, field, field)
@@ -262,10 +264,10 @@ module Assinafy
262
264
  end
263
265
 
264
266
  if query.key?('ending_within_days')
265
- validate_integer!(query['ending_within_days'], 'ending_within_days', 0, 3650)
267
+ require_integer(query['ending_within_days'], 'ending_within_days', 0, 3650)
266
268
  end
267
- validate_integer!(query['page'], 'page', 1) if query.key?('page')
268
- validate_integer!(query['per-page'], 'per_page', 1, 100) if query.key?('per-page')
269
+ require_integer(query['page'], 'page', 1) if query.key?('page')
270
+ require_integer(query['per-page'], 'per_page', 1) if query.key?('per-page')
269
271
  validate_enum!(query, 'sort', SORTS)
270
272
  validate_enum!(query, 'expand', %w[document])
271
273
  query
@@ -283,10 +285,8 @@ module Assinafy
283
285
  end
284
286
 
285
287
  def contract_payload(payload, allowed, name)
286
- raw = require_payload(payload, name)
287
- body = body_params(raw)
288
- raw.each { |key, value| body[key.to_s] = nil if value.nil? }
289
- reject_unknown_fields!(body, allowed, name.downcase)
288
+ body = require_payload(payload, name).transform_keys(&:to_s)
289
+ reject_unknown_keys!(body, allowed, name.downcase)
290
290
  body
291
291
  end
292
292
 
@@ -321,10 +321,10 @@ module Assinafy
321
321
  end
322
322
  validate_boolean!(body, 'auto_renew')
323
323
  unless body['renewal_term_months'].nil?
324
- validate_integer!(body['renewal_term_months'], 'renewal_term_months', 1, 600)
324
+ require_integer(body['renewal_term_months'], 'renewal_term_months', 1, 600)
325
325
  end
326
326
  unless body['notice_period_days'].nil?
327
- validate_integer!(body['notice_period_days'], 'notice_period_days', 0, 3650)
327
+ require_integer(body['notice_period_days'], 'notice_period_days', 0, 3650)
328
328
  end
329
329
  end
330
330
 
@@ -341,7 +341,7 @@ module Assinafy
341
341
  end
342
342
 
343
343
  validate_optional_date!(body, 'end_date')
344
- validate_integer!(body['term'], 'term', 1) if body.key?('term')
344
+ require_integer(body['term'], 'term', 1) if body.key?('term')
345
345
  validate_number!(body['value'], 'value', 0, 9_999_999_999_999.99) if body.key?('value') && !body['value'].nil?
346
346
  validate_optional_timestamp!(body, 'updated_at')
347
347
  end
@@ -378,10 +378,7 @@ module Assinafy
378
378
  def validate_enum!(body, field, allowed)
379
379
  return unless body.key?(field)
380
380
 
381
- value = require_string(body[field], field)
382
- return if allowed.include?(value)
383
-
384
- raise ValidationError.new("#{field} must be one of: #{allowed.join(', ')}")
381
+ require_one_of(require_string(body[field], field), allowed, field)
385
382
  end
386
383
 
387
384
  def validate_boolean!(body, field)
@@ -393,21 +390,13 @@ module Assinafy
393
390
 
394
391
  value = require_string(body[field], field)
395
392
  DateTime.iso8601(value)
396
- return if value.match?(/\A\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})\z/)
393
+ return if value.match?(ZONED_ISO8601)
397
394
 
398
395
  raise ArgumentError
399
396
  rescue ArgumentError
400
397
  raise ValidationError.new("#{field} must be an ISO 8601 timestamp with a timezone")
401
398
  end
402
399
 
403
- def validate_integer!(value, name, minimum, maximum = nil)
404
- valid = value.is_a?(Integer) && value >= minimum && (maximum.nil? || value <= maximum)
405
- return if valid
406
-
407
- range = maximum ? "between #{minimum} and #{maximum}" : "at least #{minimum}"
408
- raise ValidationError.new("#{name} must be an Integer #{range}")
409
- end
410
-
411
400
  def validate_number!(value, name, minimum, maximum = nil)
412
401
  number = value.is_a?(Integer) || value.is_a?(Float)
413
402
  finite = number && (!value.respond_to?(:finite?) || value.finite?)
@@ -449,11 +438,6 @@ module Assinafy
449
438
  end
450
439
  end
451
440
  end
452
-
453
- def reject_unknown_fields!(body, allowed, name)
454
- unknown = body.keys - allowed
455
- raise ValidationError.new("Unknown #{name}: #{unknown.join(', ')}") unless unknown.empty?
456
- end
457
441
  end
458
442
  end
459
443
  end