formfeed 0.3.32

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,155 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Formfeed
4
+ module Internal
5
+ # Auth, retries and problems, the rules every Formfeed SDK keeps (plan 34, decision 3): up to
6
+ # +max_retries+ retries on 429, 503 and network errors, waiting a positive numeric +Retry-After+
7
+ # in seconds, else 0.5 s doubling, plus up to 0.25 s of jitter, at most 30 s; a problem becomes
8
+ # one Formfeed::Error with the code, the detail (else the title), the status and +X-Request-Id+.
9
+ # +packages/api-types/fixtures/sdk+ holds the cases, which every SDK's tests play.
10
+ class Transport
11
+ USER_AGENT = "formfeed-sdk-ruby/0.3"
12
+ MAX_JITTER = 0.25
13
+ NUMBER = /\A[+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?\z/
14
+
15
+ def initialize(api_key:, base_url:, max_retries:, timeout:, headers:, sleep:, jitter:)
16
+ @api_key = api_key
17
+ @base_url = base_url
18
+ @max_retries = max_retries
19
+ @connection = Connection.new(timeout)
20
+ @headers = headers.to_h { |name, value| [name.to_s, value.to_s] }
21
+ @sleep = sleep || ->(seconds) { Kernel.sleep(seconds) }
22
+ @jitter = jitter || -> { Random.rand(0..250_000) / 1_000_000.0 }
23
+ end
24
+
25
+ # The key stays out of logs and consoles.
26
+ def inspect
27
+ "#<#{self.class.name} #{@base_url}>"
28
+ end
29
+
30
+ # The decoded JSON answer, nil for one without a body (204).
31
+ def json(method, path, body = nil, idempotency_key = nil)
32
+ response = send_request(method, path, body, idempotency_key)
33
+ status = response.code.to_i
34
+ text = response.body.to_s
35
+ return nil if status == 204 || text.empty?
36
+
37
+ begin
38
+ JSON.parse(text)
39
+ rescue JSON::ParserError, EncodingError
40
+ raise Error.new("invalid_response", "the API answered HTTP #{status} with a body that is not JSON",
41
+ status: status)
42
+ end
43
+ end
44
+
45
+ # An answer that is a JSON object.
46
+ def object(method, path, body = nil, idempotency_key = nil)
47
+ value = json(method, path, body, idempotency_key)
48
+ return value if value.is_a?(Hash)
49
+
50
+ raise Error.new("invalid_response", "the API answered #{method} #{path} without a JSON object")
51
+ end
52
+
53
+ # Waits, the way the client was told to (seconds).
54
+ def wait(seconds)
55
+ @sleep.call(seconds)
56
+ end
57
+
58
+ # The seconds to wait before retry number +attempt+ (from 1), with the server's Retry-After.
59
+ def backoff(attempt, retry_after)
60
+ base = 0.5 * (2**(attempt - 1))
61
+ header = retry_after.to_s.strip
62
+ value = NUMBER.match?(header) ? Float(header, exception: false) : nil
63
+ base = value if value&.positive? && value.finite?
64
+ [30.0, base + @jitter.call.to_f.clamp(0.0, MAX_JITTER)].min
65
+ end
66
+
67
+ # A signed link of the CDN: the bytes, or with +target+ (a path or an IO) the number of bytes
68
+ # written there.
69
+ def download(url, target = nil)
70
+ Download.new(@connection, USER_AGENT).call(url, target)
71
+ end
72
+
73
+ private
74
+
75
+ def send_request(method, path, body, idempotency_key)
76
+ uri = URI.parse("#{@base_url}#{path}")
77
+ headers = request_headers(body, idempotency_key)
78
+ payload = payload_of(body)
79
+ attempt = 0
80
+ loop do
81
+ begin
82
+ response = @connection.perform(method, uri, headers, payload)
83
+ rescue *Connection::NETWORK_ERRORS => e
84
+ raise Error.new("network_error", e.message) if attempt >= @max_retries
85
+
86
+ attempt += 1
87
+ wait(backoff(attempt, nil))
88
+ next
89
+ end
90
+
91
+ status = response.code.to_i
92
+ if [429, 503].include?(status) && attempt < @max_retries
93
+ attempt += 1
94
+ wait(backoff(attempt, response["Retry-After"]))
95
+ next
96
+ end
97
+ raise problem(response) if status >= 400
98
+
99
+ return response
100
+ end
101
+ end
102
+
103
+ def request_headers(body, idempotency_key)
104
+ headers = {
105
+ "Authorization" => "Bearer #{@api_key}",
106
+ "Accept" => "application/json",
107
+ "User-Agent" => USER_AGENT
108
+ }.merge(@headers)
109
+ headers["Idempotency-Key"] = idempotency_key unless idempotency_key.nil?
110
+ if body.is_a?(Multipart)
111
+ headers["Content-Type"] = body.content_type
112
+ elsif !body.nil?
113
+ headers["Content-Type"] = "application/json"
114
+ end
115
+ headers
116
+ end
117
+
118
+ # The bytes of the body, made once, so every attempt sends the same ones.
119
+ def payload_of(body)
120
+ case body
121
+ when nil then nil
122
+ when Multipart then body.body
123
+ else JSON.generate(body)
124
+ end
125
+ end
126
+
127
+ def problem(response)
128
+ status = response.code.to_i
129
+ fields = problem_fields(response.body.to_s)
130
+ Error.new(
131
+ present(Fields.string_or_nil(fields, "code")) || "http_#{status}",
132
+ present(Fields.string_or_nil(fields, "detail")) || present(Fields.string_or_nil(fields, "title")) ||
133
+ "HTTP #{status}",
134
+ status: status,
135
+ problem: fields.empty? ? nil : Problem.from_hash(fields),
136
+ request_id: present(response["X-Request-Id"])
137
+ )
138
+ end
139
+
140
+ def problem_fields(text)
141
+ return {} if text.empty?
142
+
143
+ decoded = JSON.parse(text)
144
+ decoded.is_a?(Hash) ? decoded : {}
145
+ rescue JSON::ParserError, EncodingError
146
+ # a body that is not JSON, such as a proxy's page: the status speaks for it
147
+ {}
148
+ end
149
+
150
+ def present(text)
151
+ text.nil? || text.empty? ? nil : text
152
+ end
153
+ end
154
+ end
155
+ end
@@ -0,0 +1,100 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Formfeed
4
+ # What the resources share; not part of the SDK's interface.
5
+ module Internal
6
+ module_function
7
+
8
+ # One component of a path or query, percent-encoded as RFC 3986 asks (a space is %20).
9
+ def escape(text)
10
+ text.to_s.b.gsub(/[^A-Za-z0-9\-._~]/n) { |byte| format("%%%<byte>02X", byte: byte.ord) }
11
+ .force_encoding(Encoding::US_ASCII)
12
+ end
13
+
14
+ # A request or query given as a Hash, as keywords or as both, with the top-level keys as
15
+ # strings, so that +{ "template" => ... }+ and +template: ...+ name the same member.
16
+ def params(given, fields)
17
+ raise ArgumentError, "expected a Hash, got #{given.class}" unless given.is_a?(Hash)
18
+
19
+ given.to_h { |key, value| [key.to_s, value] }.merge(fields.to_h { |key, value| [key.to_s, value] })
20
+ end
21
+
22
+ # Every item of a list, page by page as it is iterated: +fetch+ answers the page of a cursor.
23
+ def pages(&fetch)
24
+ Enumerator.new do |out|
25
+ cursor = nil
26
+ loop do
27
+ page = fetch.call(cursor)
28
+ page.data.each { |item| out << item }
29
+ cursor = page.next_cursor
30
+ break if cursor.nil?
31
+ end
32
+ end
33
+ end
34
+
35
+ # Asks for a render or job until it is finished, at most +timeout+ seconds, waiting +interval+
36
+ # seconds between the questions; the time counts the waits, so an injected sleep counts too.
37
+ def poll(transport, timeout, interval, what)
38
+ started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
39
+ waited = 0.0
40
+ loop do
41
+ current = yield
42
+ return current if current.finished?
43
+
44
+ elapsed = Process.clock_gettime(Process::CLOCK_MONOTONIC) - started
45
+ raise Error.new("timeout", "#{what} did not finish within the wait time") if
46
+ [elapsed, waited].max + interval > timeout
47
+
48
+ transport.wait(interval)
49
+ waited += interval
50
+ end
51
+ end
52
+
53
+ # The id of a render, job, library file or webhook endpoint, or the string given (an id or a
54
+ # library file's name).
55
+ module Ids
56
+ module_function
57
+
58
+ def of(item)
59
+ return item if item.is_a?(String)
60
+ return item.id if item.respond_to?(:id)
61
+
62
+ raise ArgumentError, "expected an id or a Formfeed object with an id, got #{item.class}"
63
+ end
64
+
65
+ # A fresh Idempotency-Key: every call that creates a render sends one, so a retry cannot
66
+ # charge twice.
67
+ def key
68
+ SecureRandom.uuid
69
+ end
70
+
71
+ # One path segment, encoded.
72
+ def path(item)
73
+ Internal.escape(of(item))
74
+ end
75
+ end
76
+
77
+ # The query string of the values that are set.
78
+ module Query
79
+ module_function
80
+
81
+ # +?a=1&b=2+ of the values that are set, or an empty string; booleans as +true+ and +false+,
82
+ # anything that is not a string, symbol or number left out.
83
+ def string(query)
84
+ pairs = query.filter_map do |key, value|
85
+ text = scalar(value)
86
+ "#{Internal.escape(key)}=#{Internal.escape(text)}" unless text.nil? || text.empty?
87
+ end
88
+ pairs.empty? ? "" : "?#{pairs.join("&")}"
89
+ end
90
+
91
+ def scalar(value)
92
+ case value
93
+ when true then "true"
94
+ when false then "false"
95
+ when String, Symbol, Integer, Float then value.to_s
96
+ end
97
+ end
98
+ end
99
+ end
100
+ end
@@ -0,0 +1,34 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Formfeed
4
+ # A batch, or a render queued with its own webhook URL: its renders in the order of the request
5
+ # (+items+, each a Formfeed::Render) and, once they are done, a ZIP of their files (+zip_url+).
6
+ Job = Data.define(
7
+ :id, :type, :status, :total, :succeeded, :failed, :zip_url, :zip_expires_at, :storage, :items,
8
+ :meta, :created_at, :completed_at, :raw
9
+ ) do
10
+ def self.from_hash(data)
11
+ new(
12
+ id: Internal::Fields.string(data, "id"),
13
+ type: Internal::Fields.string(data, "type"),
14
+ status: Internal::Fields.string(data, "status"),
15
+ total: Internal::Fields.int(data, "total"),
16
+ succeeded: Internal::Fields.int(data, "succeeded"),
17
+ failed: Internal::Fields.int(data, "failed"),
18
+ zip_url: Internal::Fields.string_or_nil(data, "zip_url"),
19
+ zip_expires_at: Internal::Fields.string_or_nil(data, "zip_expires_at"),
20
+ storage: Internal::Fields.map_or_nil(data, "storage"),
21
+ items: Internal::Fields.objects(data, "items").map { |item| Render.from_hash(item) },
22
+ meta: Internal::Fields.map(data, "meta"),
23
+ created_at: Internal::Fields.string(data, "created_at"),
24
+ completed_at: Internal::Fields.string_or_nil(data, "completed_at"),
25
+ raw: data
26
+ )
27
+ end
28
+
29
+ # No render of it is queued or running any more.
30
+ def finished?
31
+ !%w[queued processing].include?(status)
32
+ end
33
+ end
34
+ end
@@ -0,0 +1,22 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Formfeed
4
+ # A file of the workspace's library: an image or PDF a template names, served at +url+.
5
+ LibraryFile = Data.define(
6
+ :id, :name, :content_type, :bytes, :sha256, :url, :created_at, :updated_at, :raw
7
+ ) do
8
+ def self.from_hash(data)
9
+ new(
10
+ id: Internal::Fields.string(data, "id"),
11
+ name: Internal::Fields.string(data, "name"),
12
+ content_type: Internal::Fields.string(data, "content_type"),
13
+ bytes: Internal::Fields.int(data, "bytes"),
14
+ sha256: Internal::Fields.string(data, "sha256"),
15
+ url: Internal::Fields.string(data, "url"),
16
+ created_at: Internal::Fields.string(data, "created_at"),
17
+ updated_at: Internal::Fields.string(data, "updated_at"),
18
+ raw: data
19
+ )
20
+ end
21
+ end
22
+ end
@@ -0,0 +1,49 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Formfeed
4
+ # One page of a list, newest first, and the cursor of the next (nil on the last). It enumerates
5
+ # its items, so +page.map(&:id)+ works; the +all+ methods follow the cursor through every page.
6
+ class Page
7
+ include Enumerable
8
+
9
+ attr_reader :data, :next_cursor
10
+
11
+ def initialize(data:, next_cursor:)
12
+ @data = data.freeze
13
+ @next_cursor = next_cursor
14
+ freeze
15
+ end
16
+
17
+ # A page of the answer +page+, each item read with +model+ (a class with +from_hash+).
18
+ def self.from_hash(page, model)
19
+ new(
20
+ data: Internal::Fields.objects(page, "data").map { |item| model.from_hash(item) },
21
+ next_cursor: Internal::Fields.string_or_nil(page, "next_cursor")
22
+ )
23
+ end
24
+
25
+ def each(&)
26
+ return enum_for(:each) unless block_given?
27
+
28
+ @data.each(&)
29
+ self
30
+ end
31
+
32
+ def size
33
+ @data.size
34
+ end
35
+
36
+ def empty?
37
+ @data.empty?
38
+ end
39
+
40
+ # Whether no page follows this one.
41
+ def last?
42
+ @next_cursor.nil?
43
+ end
44
+
45
+ def inspect
46
+ "#<#{self.class.name} #{@data.size} items, next_cursor=#{@next_cursor.inspect}>"
47
+ end
48
+ end
49
+ end
@@ -0,0 +1,20 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Formfeed
4
+ # What a PDF holds: its pages and their sizes (+pages+: width_pt, height_pt, width_mm and
5
+ # height_mm of each), whether it is encrypted, its metadata, and its form (+form+: the fields, each
6
+ # with name, type, value and options, by the full names +pdf.fill+ takes).
7
+ PdfInfo = Data.define(:source, :page_count, :pages, :encrypted, :metadata, :form, :raw) do
8
+ def self.from_hash(data)
9
+ new(
10
+ source: Internal::Fields.string(data, "source"),
11
+ page_count: Internal::Fields.int(data, "page_count"),
12
+ pages: Internal::Fields.objects(data, "pages"),
13
+ encrypted: Internal::Fields.bool(data, "encrypted"),
14
+ metadata: Internal::Fields.map(data, "metadata"),
15
+ form: Internal::Fields.map_or_nil(data, "form"),
16
+ raw: data
17
+ )
18
+ end
19
+ end
20
+ end
@@ -0,0 +1,32 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Formfeed
4
+ # A problem the API answered (RFC 9457), as Formfeed::Error#problem carries it. +type+ names the
5
+ # page that explains the code; +location+, +errors+, +issues+ and +field+ appear with the codes
6
+ # that have them; +raw+ is the whole document, members of later API versions included, and
7
+ # +problem["period_end"]+ reads any member of it.
8
+ Problem = Data.define(
9
+ :type, :title, :status, :detail, :code, :request_id, :location, :errors, :issues, :field, :raw
10
+ ) do
11
+ def self.from_hash(data)
12
+ new(
13
+ type: Internal::Fields.string(data, "type"),
14
+ title: Internal::Fields.string(data, "title"),
15
+ status: Internal::Fields.int_or_nil(data, "status"),
16
+ detail: Internal::Fields.string(data, "detail"),
17
+ code: Internal::Fields.string(data, "code"),
18
+ request_id: Internal::Fields.string_or_nil(data, "request_id"),
19
+ location: Internal::Fields.map_or_nil(data, "location"),
20
+ errors: Internal::Fields.objects(data, "errors"),
21
+ issues: Internal::Fields.objects(data, "issues"),
22
+ field: Internal::Fields.string_or_nil(data, "field"),
23
+ raw: data
24
+ )
25
+ end
26
+
27
+ # A member of the document by its name.
28
+ def [](member)
29
+ raw[member.to_s]
30
+ end
31
+ end
32
+ end
@@ -0,0 +1,48 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Formfeed
4
+ # A render: its status, its output's signed link and what it cost. +raw+ holds the answer as the
5
+ # API sent it, fields of later API versions included. +template+ (id, slug, version, and channel
6
+ # and canary where they apply), +storage+, +einvoice+, +accessibility+, +pdfa+, +form+, +timings+
7
+ # and +error+ are hashes as the API sends them, or nil.
8
+ Render = Data.define(
9
+ :id, :status, :output, :download_url, :expires_at, :bytes, :page_count, :units, :region,
10
+ :environment, :template, :engine_version, :output_sha256, :deduplicated, :storage, :einvoice,
11
+ :accessibility, :pdfa, :form, :timings, :error, :meta, :created_at, :completed_at, :raw
12
+ ) do
13
+ def self.from_hash(data) # rubocop:disable Metrics/MethodLength
14
+ new(
15
+ id: Internal::Fields.string(data, "id"),
16
+ status: Internal::Fields.string(data, "status"),
17
+ output: Internal::Fields.string(data, "output"),
18
+ download_url: Internal::Fields.string_or_nil(data, "download_url"),
19
+ expires_at: Internal::Fields.string_or_nil(data, "expires_at"),
20
+ bytes: Internal::Fields.int_or_nil(data, "bytes"),
21
+ page_count: Internal::Fields.int_or_nil(data, "page_count"),
22
+ units: Internal::Fields.float(data, "units"),
23
+ region: Internal::Fields.string(data, "region"),
24
+ environment: Internal::Fields.string(data, "environment"),
25
+ template: Internal::Fields.map_or_nil(data, "template"),
26
+ engine_version: Internal::Fields.string_or_nil(data, "engine_version"),
27
+ output_sha256: Internal::Fields.string_or_nil(data, "output_sha256"),
28
+ deduplicated: Internal::Fields.bool(data, "deduplicated"),
29
+ storage: Internal::Fields.map_or_nil(data, "storage"),
30
+ einvoice: Internal::Fields.map_or_nil(data, "einvoice"),
31
+ accessibility: Internal::Fields.map_or_nil(data, "accessibility"),
32
+ pdfa: Internal::Fields.map_or_nil(data, "pdfa"),
33
+ form: Internal::Fields.map_or_nil(data, "form"),
34
+ timings: Internal::Fields.map_or_nil(data, "timings"),
35
+ error: Internal::Fields.map_or_nil(data, "error"),
36
+ meta: Internal::Fields.map(data, "meta"),
37
+ created_at: Internal::Fields.string(data, "created_at"),
38
+ completed_at: Internal::Fields.string_or_nil(data, "completed_at"),
39
+ raw: data
40
+ )
41
+ end
42
+
43
+ # Succeeded or failed: nothing will change any more.
44
+ def finished?
45
+ %w[succeeded failed].include?(status)
46
+ end
47
+ end
48
+ end
@@ -0,0 +1,31 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Formfeed
4
+ # The stored request of a render, to render it again: a template render carries +template+ and
5
+ # +data+, an ad-hoc one +html+, +url+ or +markdown+. Passwords are never included.
6
+ RenderInput = Data.define(
7
+ :render_id, :template, :data, :html, :markdown, :url, :engine, :locale, :output, :settings,
8
+ :filename, :post, :meta, :environment, :created_at, :raw
9
+ ) do
10
+ def self.from_hash(data)
11
+ new(
12
+ render_id: Internal::Fields.string(data, "render_id"),
13
+ template: Internal::Fields.map_or_nil(data, "template"),
14
+ data: Internal::Fields.map_or_nil(data, "data"),
15
+ html: Internal::Fields.string_or_nil(data, "html"),
16
+ markdown: Internal::Fields.string_or_nil(data, "markdown"),
17
+ url: Internal::Fields.string_or_nil(data, "url"),
18
+ engine: Internal::Fields.string_or_nil(data, "engine"),
19
+ locale: Internal::Fields.string_or_nil(data, "locale"),
20
+ output: Internal::Fields.string_or_nil(data, "output"),
21
+ settings: Internal::Fields.map_or_nil(data, "settings"),
22
+ filename: Internal::Fields.string_or_nil(data, "filename"),
23
+ post: Internal::Fields.map_or_nil(data, "post"),
24
+ meta: Internal::Fields.map(data, "meta"),
25
+ environment: Internal::Fields.string(data, "environment"),
26
+ created_at: Internal::Fields.string(data, "created_at"),
27
+ raw: data
28
+ )
29
+ end
30
+ end
31
+ end
@@ -0,0 +1,26 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Formfeed
4
+ # A template of the workspace, without its versions' content.
5
+ Template = Data.define(
6
+ :id, :slug, :name, :description, :kind, :engine, :tags, :published_version, :latest_version,
7
+ :created_at, :updated_at, :raw
8
+ ) do
9
+ def self.from_hash(data)
10
+ new(
11
+ id: Internal::Fields.string(data, "id"),
12
+ slug: Internal::Fields.string(data, "slug"),
13
+ name: Internal::Fields.string(data, "name"),
14
+ description: Internal::Fields.string_or_nil(data, "description"),
15
+ kind: Internal::Fields.string(data, "kind"),
16
+ engine: Internal::Fields.string(data, "engine"),
17
+ tags: Internal::Fields.strings(data, "tags"),
18
+ published_version: Internal::Fields.int_or_nil(data, "published_version"),
19
+ latest_version: Internal::Fields.int(data, "latest_version"),
20
+ created_at: Internal::Fields.string(data, "created_at"),
21
+ updated_at: Internal::Fields.string(data, "updated_at"),
22
+ raw: data
23
+ )
24
+ end
25
+ end
26
+ end
@@ -0,0 +1,26 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Formfeed
4
+ # The units of a billing period, with a daily series (+daily+: date, units and renders of each day)
5
+ # and a breakdown per template (+by_template+: template and units).
6
+ Usage = Data.define(
7
+ :period, :period_start, :period_end, :included, :used, :overage_used, :overage_balance,
8
+ :hard_cap_units, :daily, :by_template, :raw
9
+ ) do
10
+ def self.from_hash(data)
11
+ new(
12
+ period: Internal::Fields.string(data, "period"),
13
+ period_start: Internal::Fields.string(data, "period_start"),
14
+ period_end: Internal::Fields.string(data, "period_end"),
15
+ included: Internal::Fields.float(data, "included"),
16
+ used: Internal::Fields.float(data, "used"),
17
+ overage_used: Internal::Fields.float(data, "overage_used"),
18
+ overage_balance: Internal::Fields.float(data, "overage_balance"),
19
+ hard_cap_units: Internal::Fields.float_or_nil(data, "hard_cap_units"),
20
+ daily: Internal::Fields.objects(data, "daily"),
21
+ by_template: Internal::Fields.objects(data, "by_template"),
22
+ raw: data
23
+ )
24
+ end
25
+ end
26
+ end
@@ -0,0 +1,25 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Formfeed
4
+ # A registered webhook endpoint. +secret+ is only in the answer that created it.
5
+ WebhookEndpoint = Data.define(
6
+ :id, :url, :events, :environments, :enabled, :description, :consecutive_failures, :secret,
7
+ :created_at, :updated_at, :raw
8
+ ) do
9
+ def self.from_hash(data)
10
+ new(
11
+ id: Internal::Fields.string(data, "id"),
12
+ url: Internal::Fields.string(data, "url"),
13
+ events: Internal::Fields.strings(data, "events"),
14
+ environments: Internal::Fields.strings(data, "environments"),
15
+ enabled: Internal::Fields.bool(data, "enabled", default: true),
16
+ description: Internal::Fields.string_or_nil(data, "description"),
17
+ consecutive_failures: Internal::Fields.int(data, "consecutive_failures"),
18
+ secret: Internal::Fields.string_or_nil(data, "secret"),
19
+ created_at: Internal::Fields.string(data, "created_at"),
20
+ updated_at: Internal::Fields.string(data, "updated_at"),
21
+ raw: data
22
+ )
23
+ end
24
+ end
25
+ end
@@ -0,0 +1,24 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Formfeed
4
+ module Resources
5
+ # The key's account and the units it used.
6
+ class Account
7
+ def initialize(transport)
8
+ @transport = transport
9
+ end
10
+
11
+ # The key's workspace and organisation, its environment, and the plan with the period's units
12
+ # and limits, as a Hash.
13
+ def get
14
+ @transport.object("GET", "/account")
15
+ end
16
+
17
+ # Units of the current period, or of +YYYY-MM+, with a daily series and a breakdown per
18
+ # template.
19
+ def usage(period = "current")
20
+ Usage.from_hash(@transport.object("GET", "/usage?period=#{Internal.escape(period)}"))
21
+ end
22
+ end
23
+ end
24
+ end
@@ -0,0 +1,28 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Formfeed
4
+ module Resources
5
+ # E-invoices: which rules one passed.
6
+ class Einvoices
7
+ def initialize(transport)
8
+ @transport = transport
9
+ end
10
+
11
+ # Which rules an e-invoice passed. A render of this workspace's own e-invoice (a Render or its
12
+ # id) is answered from the report it keeps, free; an XML Formfeed did not make (an Upload, up
13
+ # to 4 MB, from the Starter plan) takes one of the organisation's validations of the day. Needs
14
+ # +einvoice:validate+. +rules:+ is +auto+, +factur-x+, +xrechnung+ or +en16931+, the render's
15
+ # own when nil. Answers the report as a Hash: +result+, the +checks+ with their findings,
16
+ # +validator+, +rules+ and +versions+.
17
+ def validate(source, rules: nil, idempotency_key: nil)
18
+ body =
19
+ if source.is_a?(Upload)
20
+ Internal::Multipart.new({ "rules" => rules }, source)
21
+ else
22
+ { "render_id" => Internal::Ids.of(source) }.merge(rules.nil? ? {} : { "rules" => rules })
23
+ end
24
+ @transport.object("POST", "/einvoices/validate", body, idempotency_key || Internal::Ids.key)
25
+ end
26
+ end
27
+ end
28
+ end
@@ -0,0 +1,47 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Formfeed
4
+ module Resources
5
+ # The workspace's file library: images and PDFs a template names with +asset('logo.png')+, and
6
+ # the sources of image watermarks and merges. Needs +file:read+, +file:write+ or +file:delete+.
7
+ # Files are served without a signature, so keep confidential documents out of it.
8
+ class Files
9
+ def initialize(transport)
10
+ @transport = transport
11
+ end
12
+
13
+ # Uploads a Formfeed::Upload; one of the same name is replaced in place and keeps its URL.
14
+ def upload(file)
15
+ LibraryFile.from_hash(
16
+ @transport.object("POST", "/files", Internal::Multipart.new({ "name" => file.name }, file))
17
+ )
18
+ end
19
+
20
+ # One page of files, newest first: +prefix:+ keeps the names that start with it, +limit:+,
21
+ # +cursor:+.
22
+ def list(query = {}, **fields)
23
+ Page.from_hash(
24
+ @transport.object("GET", "/files#{Internal::Query.string(Internal.params(query, fields))}"), LibraryFile
25
+ )
26
+ end
27
+
28
+ # Every file the query matches, page by page as it is iterated.
29
+ def all(query = {}, **fields, &)
30
+ params = Internal.params(query, fields)
31
+ files = Internal.pages { |cursor| list(params.merge("cursor" => cursor)) }
32
+ block_given? ? files.each(&) : files
33
+ end
34
+
35
+ # A file by its id (+fil_...+).
36
+ def get(file)
37
+ LibraryFile.from_hash(@transport.object("GET", "/files/#{Internal::Ids.path(file)}"))
38
+ end
39
+
40
+ # Removes the file and its bytes; templates that name it render a missing image afterwards.
41
+ def delete(file)
42
+ @transport.json("DELETE", "/files/#{Internal::Ids.path(file)}")
43
+ nil
44
+ end
45
+ end
46
+ end
47
+ end