qube_sync 0.4.0 → 0.6.0

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 (99) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +94 -3
  3. data/README.md +106 -7
  4. data/exe/qube_sync +11 -0
  5. data/lib/qube_sync/client.rb +58 -7
  6. data/lib/qube_sync/operations/account.rb +21 -20
  7. data/lib/qube_sync/operations/ar_refund_credit_card.rb +17 -14
  8. data/lib/qube_sync/operations/bill.rb +148 -104
  9. data/lib/qube_sync/operations/bill_payment_check.rb +29 -22
  10. data/lib/qube_sync/operations/bill_payment_credit_card.rb +21 -16
  11. data/lib/qube_sync/operations/bill_to_pay.rb +7 -6
  12. data/lib/qube_sync/operations/billing_rate.rb +10 -9
  13. data/lib/qube_sync/operations/build_assembly.rb +13 -12
  14. data/lib/qube_sync/operations/charge.rb +36 -34
  15. data/lib/qube_sync/operations/check.rb +144 -100
  16. data/lib/qube_sync/operations/class.rb +11 -11
  17. data/lib/qube_sync/operations/credit_card_charge.rb +144 -100
  18. data/lib/qube_sync/operations/credit_card_credit.rb +144 -100
  19. data/lib/qube_sync/operations/credit_memo.rb +142 -108
  20. data/lib/qube_sync/operations/currency.rb +7 -7
  21. data/lib/qube_sync/operations/customer.rb +54 -53
  22. data/lib/qube_sync/operations/customer_msg.rb +5 -5
  23. data/lib/qube_sync/operations/customer_type.rb +7 -7
  24. data/lib/qube_sync/operations/data_ext.rb +7 -6
  25. data/lib/qube_sync/operations/date_driven_terms.rb +5 -5
  26. data/lib/qube_sync/operations/deposit.rb +53 -38
  27. data/lib/qube_sync/operations/employee.rb +27 -23
  28. data/lib/qube_sync/operations/entity.rb +5 -5
  29. data/lib/qube_sync/operations/estimate.rb +119 -90
  30. data/lib/qube_sync/operations/fields.rb +4058 -0
  31. data/lib/qube_sync/operations/form1099_category_account_mapping.rb +3 -2
  32. data/lib/qube_sync/operations/inventory_adjustment.rb +43 -34
  33. data/lib/qube_sync/operations/inventory_site.rb +11 -11
  34. data/lib/qube_sync/operations/invoice.rb +142 -108
  35. data/lib/qube_sync/operations/item.rb +5 -5
  36. data/lib/qube_sync/operations/item_assemblies_can_build.rb +2 -2
  37. data/lib/qube_sync/operations/item_discount.rb +25 -24
  38. data/lib/qube_sync/operations/item_fixed_asset.rb +17 -16
  39. data/lib/qube_sync/operations/item_group.rb +17 -15
  40. data/lib/qube_sync/operations/item_inventory.rb +45 -44
  41. data/lib/qube_sync/operations/item_inventory_assembly.rb +51 -48
  42. data/lib/qube_sync/operations/item_non_inventory.rb +55 -44
  43. data/lib/qube_sync/operations/item_other_charge.rb +51 -40
  44. data/lib/qube_sync/operations/item_payment.rb +21 -20
  45. data/lib/qube_sync/operations/item_receipt.rb +144 -100
  46. data/lib/qube_sync/operations/item_sales_tax.rb +21 -20
  47. data/lib/qube_sync/operations/item_sales_tax_group.rb +11 -11
  48. data/lib/qube_sync/operations/item_service.rb +55 -44
  49. data/lib/qube_sync/operations/item_sites.rb +10 -8
  50. data/lib/qube_sync/operations/item_subtotal.rb +7 -7
  51. data/lib/qube_sync/operations/job_type.rb +7 -7
  52. data/lib/qube_sync/operations/journal_entry.rb +49 -34
  53. data/lib/qube_sync/operations/lead.rb +7 -7
  54. data/lib/qube_sync/operations/list.rb +2 -2
  55. data/lib/qube_sync/operations/list_display.rb +2 -2
  56. data/lib/qube_sync/operations/list_merge.rb +6 -4
  57. data/lib/qube_sync/operations/other_name.rb +7 -7
  58. data/lib/qube_sync/operations/payment_method.rb +6 -5
  59. data/lib/qube_sync/operations/payroll_item_non_wage.rb +5 -5
  60. data/lib/qube_sync/operations/payroll_item_wage.rb +7 -7
  61. data/lib/qube_sync/operations/price_level.rb +23 -19
  62. data/lib/qube_sync/operations/purchase_order.rb +113 -86
  63. data/lib/qube_sync/operations/receive_payment.rb +37 -30
  64. data/lib/qube_sync/operations/sales_order.rb +117 -90
  65. data/lib/qube_sync/operations/sales_receipt.rb +142 -108
  66. data/lib/qube_sync/operations/sales_rep.rb +11 -11
  67. data/lib/qube_sync/operations/sales_tax_code.rb +15 -15
  68. data/lib/qube_sync/operations/sales_tax_payment_check.rb +18 -14
  69. data/lib/qube_sync/operations/sales_tax_return_line.rb +2 -2
  70. data/lib/qube_sync/operations/ship_method.rb +5 -5
  71. data/lib/qube_sync/operations/special_account.rb +2 -2
  72. data/lib/qube_sync/operations/standard_terms.rb +5 -5
  73. data/lib/qube_sync/operations/terms.rb +5 -5
  74. data/lib/qube_sync/operations/time_tracking.rb +23 -22
  75. data/lib/qube_sync/operations/to_do.rb +23 -23
  76. data/lib/qube_sync/operations/transaction.rb +15 -10
  77. data/lib/qube_sync/operations/transfer.rb +12 -12
  78. data/lib/qube_sync/operations/transfer_inventory.rb +35 -26
  79. data/lib/qube_sync/operations/txn_display.rb +2 -2
  80. data/lib/qube_sync/operations/unit_of_measure_set.rb +5 -5
  81. data/lib/qube_sync/operations/vehicle.rb +7 -7
  82. data/lib/qube_sync/operations/vehicle_mileage.rb +8 -8
  83. data/lib/qube_sync/operations/vendor.rb +54 -52
  84. data/lib/qube_sync/operations/vendor_credit.rb +144 -100
  85. data/lib/qube_sync/operations/vendor_type.rb +7 -7
  86. data/lib/qube_sync/operations/workers_comp_code.rb +8 -8
  87. data/lib/qube_sync/operations.rb +267 -262
  88. data/lib/qube_sync/version.rb +1 -1
  89. data/lib/qube_sync/webhooks/event.rb +80 -6
  90. data/lib/qube_sync/workflow_types/cli.rb +120 -0
  91. data/lib/qube_sync/workflow_types/rbs_renderer.rb +290 -0
  92. data/lib/qube_sync/workflow_types/ruby_renderer.rb +391 -0
  93. data/lib/qube_sync/workflow_types/workflow.rb +153 -0
  94. data/lib/qube_sync/workflow_types.rb +219 -0
  95. data/sig/qube_sync/client.rbs +6 -2
  96. data/sig/qube_sync/operations.rbs +2 -1
  97. data/sig/qube_sync/webhooks.rbs +148 -0
  98. data/sig/qube_sync/workflow_types.rbs +59 -0
  99. metadata +13 -3
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module QubeSync
4
- VERSION = "0.4.0"
4
+ VERSION = "0.6.0"
5
5
  end
@@ -124,11 +124,39 @@ module QubeSync
124
124
  class RequestEvent < Event
125
125
  TYPE = "request"
126
126
 
127
- fields :id, :page_request_id, :state, :page, :iteration_state, :response_json, :error
127
+ fields :id, :page_request_id, :state, :page, :iteration_state, :response_json, :response_xml, :error, :links
128
128
 
129
129
  def dedupe_key
130
130
  "#{page_request_id}:#{state}"
131
131
  end
132
+
133
+ # `error.error_type` ("timed_out", "outcome_unknown", "retryable", ...), nil without an error.
134
+ def error_type
135
+ error.is_a?(Hash) ? error["error_type"] : nil
136
+ end
137
+
138
+ PERHAPS_APPLIED_ERROR_TYPES = %w[timed_out outcome_unknown response_too_large].freeze
139
+
140
+ # True when QuickBooks may have applied the request though no answer says so (`timed_out`,
141
+ # `outcome_unknown`, `response_too_large`). Look in QuickBooks before sending a write again;
142
+ # a query is safe to resend, and a `response_too_large` one should be paged (`iterator`,
143
+ # smaller `max_returned`) or narrowed.
144
+ def perhaps_applied?
145
+ state == "timed_out" || PERHAPS_APPLIED_ERROR_TYPES.include?(error_type)
146
+ end
147
+
148
+ # True when the body would have been over 1 MB, so it came without `response_xml` (nil).
149
+ # `response_json` still came; fetch `self_link` (`Client#get_request(event.self_link)`) for
150
+ # the request with `response_xml`.
151
+ def response_xml_omitted?
152
+ @body["response_xml_omitted"] == true
153
+ end
154
+
155
+ # `links.self`, the request's URL (v1 or v2, as it was queued). Sent with an omitted
156
+ # `response_xml`; nil otherwise.
157
+ def self_link
158
+ links.is_a?(Hash) ? links["self"] : nil
159
+ end
132
160
  end
133
161
 
134
162
  # A workflow run that is waiting for an answer, or has ended. Store by `reference` and skip
@@ -138,8 +166,14 @@ module QubeSync
138
166
 
139
167
  TYPE = "workflow_run"
140
168
 
141
- fields :run_id, :reference, :run_state, :workflow, :connection_id, :prompt, :outcome, :output,
142
- :error, :summary, :cancel_reason, :links
169
+ fields :run_id, :reference, :run_state, :workflow, :workflow_id, :connection_id, :headline, :prompt,
170
+ :outcome, :output, :summary, :cancel_reason, :links
171
+
172
+ # What failed the run (on `workflow_run.failed`), as a WorkflowRunError; nil otherwise.
173
+ # An older server's String error reads as one with only `message`. `self["error"]` is the raw value.
174
+ def error
175
+ WorkflowRunError.from(@body["error"])
176
+ end
143
177
 
144
178
  def awaiting_input?
145
179
  event == "workflow_run.awaiting_input"
@@ -158,19 +192,53 @@ module QubeSync
158
192
  end
159
193
  end
160
194
 
195
+ # What failed a workflow run: QuickBooks' status `code` and a stable `type` to branch on, a
196
+ # plain `message` safe to show, QuickBooks' own text and a `hint`. All but `message` may be nil.
197
+ WorkflowRunError = Data.define(:code, :type, :message, :quickbooks_message, :hint) do
198
+ # From the body's `error`: an object, or an older server's String. nil for anything else.
199
+ def self.from(value)
200
+ case value
201
+ when Hash
202
+ new(code: value["code"], type: value["type"], message: value["message"],
203
+ quickbooks_message: value["quickbooks_message"], hint: value["hint"])
204
+ when String
205
+ new(code: nil, type: nil, message: value, quickbooks_message: nil, hint: nil)
206
+ end
207
+ end
208
+
209
+ # Reads a field by name, as the Hash did: error["message"].
210
+ def [](key)
211
+ name = key.to_sym
212
+ members.include?(name) ? public_send(name) : nil
213
+ end
214
+
215
+ def to_s
216
+ message.to_s
217
+ end
218
+
219
+ # JSON keeps every field, with the wire's keys; Data alone would serialize as its to_s.
220
+ def as_json(*)
221
+ to_h.transform_keys(&:to_s)
222
+ end
223
+
224
+ def to_json(*args)
225
+ as_json.to_json(*args)
226
+ end
227
+ end
228
+
161
229
  # Data a running workflow sent along. Deduplicate on `delivery_id`; never skip one by revision.
162
230
  class NotificationEvent < Event
163
231
  TYPE = "notification"
164
232
 
165
- fields :run_id, :reference, :revision, :delivery_id, :seq, :name, :state, :from, :data
233
+ fields :run_id, :reference, :revision, :delivery_id, :seq, :name, :state, :from, :data, :headline
166
234
 
167
235
  def dedupe_key
168
236
  delivery_id
169
237
  end
170
238
  end
171
239
 
172
- # A connection was set up, cancelled, stalled or resumed. Deduplicate on `delivery_id`, and
173
- # skip it unless `newer_than?` the connection's stored revision.
240
+ # A connection was set up, cancelled, stalled, resumed or switched to another company file.
241
+ # Deduplicate on `delivery_id`, and skip it unless `newer_than?` the connection's stored revision.
174
242
  class ConnectionEvent < Event
175
243
  include Event::Revisioned
176
244
 
@@ -206,6 +274,12 @@ module QubeSync
206
274
  event == "connection.resumed"
207
275
  end
208
276
 
277
+ # The customer chose another company file: stop using the ListIDs/TxnIDs stored for this
278
+ # connection until they're checked on the new file, and wait for `connected?` again.
279
+ def company_file_changed?
280
+ event == "connection.company_file_changed"
281
+ end
282
+
209
283
  private
210
284
 
211
285
  def connection_hash
@@ -0,0 +1,120 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "fileutils"
4
+ require "optparse"
5
+
6
+ module QubeSync
7
+ module WorkflowTypes
8
+ # `qube_sync workflows [--drafts] [--check] [--output lib/qube_workflows.rb] [--sig sig/qube_workflows.rbs]`
9
+ #
10
+ # Fetches the app's workflow types with QUBE_API_KEY (from QUBE_BASE_URL, default
11
+ # https://qubesync.com) and writes the typed Ruby file and its RBS. With --check it writes
12
+ # nothing: it exits 1 when the file is out of date (or QuBe Sync refuses the key), and 0 when
13
+ # it's current or QuBe Sync can't be reached, with a warning, so CI isn't held up by an
14
+ # outage. Returns the exit status.
15
+ class CLI
16
+ USAGE = "Usage: qube_sync workflows [--drafts] [--check] [--output PATH] [--sig PATH]"
17
+
18
+ # env, out and err are for tests; client_factory takes (api_key:, base_url:).
19
+ def initialize(env: ENV, out: $stdout, err: $stderr, client_factory: nil)
20
+ @env = env
21
+ @out = out
22
+ @err = err
23
+ @client_factory = client_factory || ->(api_key:, base_url:) { Client.new(api_key: api_key, base_url: base_url) }
24
+ end
25
+
26
+ def run(argv)
27
+ command, *rest = argv
28
+ unless command == "workflows"
29
+ @err.puts USAGE
30
+ return %w[-h --help help].include?(command) ? 0 : 1
31
+ end
32
+
33
+ options = {drafts: false, check: false, output: "lib/qube_workflows.rb", sig: "sig/qube_workflows.rbs"}
34
+ parser = OptionParser.new do |opts|
35
+ opts.banner = USAGE
36
+ opts.on("--drafts", "Type each workflow's draft where it has one") { options[:drafts] = true }
37
+ opts.on("--check", "Write nothing; exit 1 when the files are out of date") { options[:check] = true }
38
+ opts.on("--output PATH", "The Ruby file (lib/qube_workflows.rb)") { |path| options[:output] = path }
39
+ opts.on("--sig PATH", "The RBS file (sig/qube_workflows.rbs)") { |path| options[:sig] = path }
40
+ end
41
+ begin
42
+ parser.parse!(rest)
43
+ rescue OptionParser::ParseError => e
44
+ @err.puts "qube_sync: #{e.message}"
45
+ @err.puts parser.help
46
+ return 1
47
+ end
48
+ unless rest.empty?
49
+ @err.puts parser.help
50
+ return 1
51
+ end
52
+
53
+ api_key = @env["QUBE_API_KEY"].to_s
54
+ if api_key.strip.empty?
55
+ @err.puts "qube_sync: set QUBE_API_KEY to your app's API key"
56
+ return 1
57
+ end
58
+
59
+ base_url = @env["QUBE_BASE_URL"].to_s.strip
60
+ base_url = Client::DEFAULT_BASE_URL if base_url.empty?
61
+ # The site, or its API: QUBE_BASE_URL may name either.
62
+ base_url = base_url.sub(%r{/+\z}, "").delete_suffix(Client::API_PATH)
63
+ client = @client_factory.call(api_key: api_key, base_url: base_url)
64
+ source = "#{client.base_url}#{Client::API_PATH}/workflows/types"
65
+
66
+ options[:check] ? check(client, source, options) : generate(client, source, options)
67
+ rescue Error, ArgumentError => e
68
+ @err.puts "qube_sync: #{e.message}"
69
+ 1
70
+ end
71
+
72
+ private
73
+
74
+ def generate(client, source, options)
75
+ document = client.workflow_types(include_drafts: options[:drafts])
76
+ files = WorkflowTypes.render(document, source: source, drafts: options[:drafts])
77
+ files.warnings.each { |warning| @err.puts "warning: #{warning}" }
78
+ write(options[:output], files.ruby)
79
+ write(options[:sig], files.rbs)
80
+ count = WorkflowTypes.select(document, options[:drafts]).size
81
+ @out.puts "qube_sync: #{count} workflow#{"s" unless count == 1} from #{source}#{" (with drafts)" if options[:drafts]}"
82
+ 0
83
+ rescue APIError => e
84
+ @err.puts "qube_sync: #{e.message}"
85
+ 1
86
+ rescue *Client::NETWORK_ERRORS, SystemCallError => e
87
+ @err.puts "qube_sync: couldn't reach QuBe Sync (#{e.class}: #{e.message}); nothing was written"
88
+ 1
89
+ end
90
+
91
+ def check(client, source, options)
92
+ path = options[:output]
93
+ unless File.exist?(path)
94
+ @err.puts "qube_sync: #{path} isn't there: run `#{COMMAND}` to write it"
95
+ return 1
96
+ end
97
+
98
+ result = WorkflowTypes.check(File.read(path, encoding: "UTF-8"), client: client, source: source, path: path)
99
+ result.warnings.each { |warning| @err.puts "warning: #{warning}" }
100
+ case result.status
101
+ when :current then @out.puts "qube_sync: #{result.message}"
102
+ when :unreachable then @err.puts "warning: #{result.message}"
103
+ else @err.puts "qube_sync: #{result.message}"
104
+ end
105
+ result.exit_status
106
+ end
107
+
108
+ def write(path, content)
109
+ dir = File.dirname(path)
110
+ FileUtils.mkdir_p(dir) unless Dir.exist?(dir)
111
+ if File.exist?(path) && File.read(path, encoding: "UTF-8") == content
112
+ @out.puts "identical #{path}"
113
+ else
114
+ File.write(path, content)
115
+ @out.puts "wrote #{path}"
116
+ end
117
+ end
118
+ end
119
+ end
120
+ end
@@ -0,0 +1,290 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+
5
+ module QubeSync
6
+ module WorkflowTypes
7
+ # Writes the RBS half of a render: a type alias per input (`invoice_input`, or `input` for a
8
+ # workflow without branches), each operation body as that operation's params record
9
+ # (::QubeSync::Operations::Invoice::create_params), a nested discriminated object (an `adds`
10
+ # entry) as a union of a record per branch, and the start and input methods' signatures. JSON
11
+ # Schema maps to RBS as bin/generate-operations maps it.
12
+ class RBSRenderer
13
+ # Words RBS doesn't take as a type alias's name: one gets a trailing underscore.
14
+ RBS_KEYWORDS = %w[
15
+ alias as attr_accessor attr_reader attr_writer bool bot class def end extend false in include instance
16
+ interface module nil out prepend private public self singleton super top true type unchecked untyped
17
+ use void
18
+ ].freeze
19
+ # A string RBS can take as a literal type as it is.
20
+ PLAIN_STRING = %r{\A[\w .:/@+\-]*\z}
21
+ DATA = "::QubeSync::Client::data"
22
+
23
+ def initialize(workflows, header:, client:)
24
+ @workflows = workflows
25
+ @header = header
26
+ @setter = client == DEFAULT_CLIENT
27
+ end
28
+
29
+ def render
30
+ lines = @header + ["", "module QubeWorkflows"]
31
+ lines << " # Anything with a QuBe Sync connection id, such as a QubeRails::Connection."
32
+ lines << " interface _Connection"
33
+ lines << " def qube_id: () -> String?"
34
+ lines << " end"
35
+ lines << ""
36
+ lines << " type connection = String | _Connection"
37
+ lines << ""
38
+ if @setter
39
+ lines << " def self.client: () -> ::QubeSync::Client"
40
+ lines << " def self.client=: (::QubeSync::Client client) -> ::QubeSync::Client"
41
+ end
42
+ lines << " def self.connection_id: (connection connection) -> String?"
43
+ @workflows.each do |workflow|
44
+ lines << " def self.#{workflow.accessor}: () -> singleton(#{workflow.const})"
45
+ end
46
+ @workflows.each do |workflow|
47
+ lines << ""
48
+ lines.concat(workflow_rbs(workflow))
49
+ end
50
+ lines.concat(["end", ""])
51
+ lines.join("\n")
52
+ end
53
+
54
+ private
55
+
56
+ def workflow_rbs(workflow)
57
+ @aliases = {}
58
+ @memo = {}
59
+ @prefix = nil
60
+ @taken = ["input"] + workflow.branches.map { |branch| "#{branch.method}_input" }
61
+ inputs = {}
62
+ methods = []
63
+ if workflow.discriminated?
64
+ workflow.branches.each do |branch|
65
+ # A body's own record is named for its branch.
66
+ @prefix = branch.method
67
+ fields = [[workflow.discriminator, literal(branch.value), true]] +
68
+ branch.inputs.map { |input| [input.name, type(input.schema, input.name, " "), input.required] }
69
+ inputs["#{branch.method}_input"] = record(fields, " ")
70
+ params = RubyRenderer.params_for(branch.inputs, branch.body)
71
+ methods << " def self.#{branch.method}: (#{(connection + signature(params) + run).join(", ")}) -> #{DATA}"
72
+ methods << " def self.#{branch.method}_input: (#{signature(params).join(", ")}) -> #{branch.method}_input"
73
+ end
74
+ @prefix = nil
75
+ inputs["input"] = workflow.branches.map { |branch| "#{branch.method}_input" }.join(" | ")
76
+ methods << " def self.start: (#{(connection + ["input input"] + run).join(", ")}) -> #{DATA}"
77
+ else
78
+ fields = workflow.inputs.map { |input| [input.name, type(input.schema, input.name, " "), input.required] }
79
+ inputs["input"] = record(fields, " ")
80
+ params = RubyRenderer.params_for(workflow.inputs, nil)
81
+ methods << " def self.start: (#{(connection + signature(params) + run).join(", ")}) -> #{DATA}"
82
+ methods << " def self.input: (#{signature(params).join(", ")}) -> input"
83
+ end
84
+
85
+ lines = [" module #{workflow.const}", " WORKFLOW: String", " VERSION: #{workflow.version.nil? ? "nil" : "Integer"}", ""]
86
+ @aliases.sort.each do |name, rbs|
87
+ lines << " type #{name} = #{rbs}"
88
+ lines << ""
89
+ end
90
+ inputs.each do |name, rbs|
91
+ lines << " type #{name} = #{rbs}"
92
+ lines << ""
93
+ end
94
+ lines.concat(methods)
95
+ lines << " end"
96
+ end
97
+
98
+ def connection
99
+ ["::QubeWorkflows::connection connection"]
100
+ end
101
+
102
+ def run
103
+ ["reference: String", "webhook_url: String", "?version: Integer?", "?client: ::QubeSync::Client"]
104
+ end
105
+
106
+ # A method's inputs, named as the Ruby names them: required ones as `name: T`, the others as
107
+ # `?name: T?` (a nil is left out of the input).
108
+ def signature(params)
109
+ params.map do |param|
110
+ rbs = type(param.input.schema, param.input.name, nil)
111
+ if param.positional
112
+ RBS_KEYWORDS.include?(param.name) ? rbs : "#{rbs} #{param.name}"
113
+ elsif param.input.required
114
+ "#{param.name}: #{rbs}"
115
+ else
116
+ "?#{param.name}: #{optional(rbs)}"
117
+ end
118
+ end
119
+ end
120
+
121
+ # -- Types ------------------------------------------------------------------------------
122
+
123
+ def type(schema, path, indent)
124
+ union(members(schema, path, indent))
125
+ end
126
+
127
+ def members(schema, path, indent)
128
+ id = Workflow.operation(schema)
129
+ return [body_type(id, schema, path)] if id
130
+ return [named(schema, path)] if Workflow.discriminated?(schema)
131
+ return [literal(schema["const"])] if schema.key?("const")
132
+ return schema["enum"].map { |value| literal(value) } if schema["enum"].is_a?(Array)
133
+
134
+ types = Array(schema["type"])
135
+ if types.empty?
136
+ types << "object" if schema.key?("properties")
137
+ types << "array" if schema.key?("items")
138
+ end
139
+ return ["untyped"] if types.empty?
140
+
141
+ types.map do |kind|
142
+ case kind
143
+ when "string" then "String"
144
+ when "integer" then "Integer"
145
+ when "number" then "Numeric"
146
+ when "boolean" then "bool"
147
+ when "null" then "nil"
148
+ when "array" then "Array[#{type(schema["items"].is_a?(Hash) ? schema["items"] : {}, "#{path}_item", indent)}]"
149
+ when "object" then object_type(schema, path, indent)
150
+ else "untyped"
151
+ end
152
+ end
153
+ end
154
+
155
+ def union(members)
156
+ members = members.uniq
157
+ return "untyped" if members.include?("untyped")
158
+
159
+ others = members - ["nil"]
160
+ return members.join(" | ") if others.size == members.size
161
+ return "nil" if others.empty?
162
+
163
+ optional(others.join(" | "))
164
+ end
165
+
166
+ def optional(rbs)
167
+ return rbs if rbs == "untyped" || rbs == "nil" || rbs.end_with?("?")
168
+
169
+ top_level_union?(rbs) ? "(#{rbs})?" : "#{rbs}?"
170
+ end
171
+
172
+ # A `|` outside any brackets: `"a" | "b"`, not `Hash[String, "a" | "b"]`.
173
+ def top_level_union?(rbs)
174
+ depth = 0
175
+ rbs.each_char.each_cons(3) do |before, char, after|
176
+ depth += 1 if "[{(".include?(before)
177
+ depth -= 1 if "]})".include?(before)
178
+ return true if depth.zero? && char == "|" && before == " " && after == " "
179
+ end
180
+ false
181
+ end
182
+
183
+ def object_type(schema, path, indent)
184
+ properties = schema["properties"].is_a?(Hash) ? schema["properties"] : {}
185
+ extra = schema["additionalProperties"]
186
+ if properties.empty?
187
+ return "Hash[String, #{type(extra, "#{path}_value", indent)}]" if extra.is_a?(Hash)
188
+
189
+ return "Hash[untyped, untyped]"
190
+ end
191
+ # A field name a record can't hold types the object as a plain Hash.
192
+ return "Hash[untyped, untyped]" unless properties.keys.all? { |name| name.match?(Workflow::NAME) }
193
+
194
+ required = Array(schema["required"])
195
+ fields = properties.sort.map do |name, sub|
196
+ [name, type(sub.is_a?(Hash) ? sub : {}, "#{path}_#{name}", indent && "#{indent} "), required.include?(name)]
197
+ end
198
+ record(fields, indent)
199
+ end
200
+
201
+ # A record over lines at indent, or on one line when indent is nil (in a signature).
202
+ def record(fields, indent)
203
+ return "Hash[Symbol, untyped]" if fields.empty?
204
+ return "{ #{fields.map { |name, rbs, required| "#{required ? "" : "?"}#{name}: #{rbs}" }.join(", ")} }" if indent.nil?
205
+
206
+ lines = fields.map { |name, rbs, required| "#{indent} #{required ? "" : "?"}#{name}: #{rbs}" }
207
+ "{\n#{lines.join(",\n")}\n#{indent}}"
208
+ end
209
+
210
+ # A nested discriminated object's alias: a union of a record per branch, each named
211
+ # <alias>_<title>. The same schema at the same place shares one.
212
+ def named(schema, path)
213
+ key = [path, JSON.generate(schema)]
214
+ return @memo[key] if @memo.key?(key)
215
+
216
+ name = claim(path)
217
+ @memo[key] = name
218
+ # Shared by every branch of the workflow, so not named for one.
219
+ prefix = @prefix
220
+ @prefix = nil
221
+ discriminator = schema.dig("discriminator", "propertyName")
222
+ branches = Workflow.branch_schemas(schema).map do |title, properties, required|
223
+ branch = claim("#{name}_#{title}")
224
+ fields = properties.sort_by { |field, _| [field == discriminator ? 0 : 1, field] }.map do |field, sub|
225
+ sub = sub.is_a?(Hash) ? sub : {}
226
+ [field, type(sub, "#{name}_#{field}", " "), field == discriminator || required.include?(field)]
227
+ end
228
+ if fields.any? { |field, _, _| !field.match?(Workflow::NAME) }
229
+ @aliases[branch] = "Hash[untyped, untyped]"
230
+ else
231
+ @aliases[branch] = record(fields, " ")
232
+ end
233
+ branch
234
+ end
235
+ @aliases[name] = branches.empty? ? "Hash[untyped, untyped]" : branches.join(" | ")
236
+ @prefix = prefix
237
+ name
238
+ end
239
+
240
+ def claim(path)
241
+ base = RBS_KEYWORDS.include?(path) ? "#{path}_" : path
242
+ name = base
243
+ n = 2
244
+ while @taken.include?(name)
245
+ name = "#{base}_#{n}"
246
+ n += 1
247
+ end
248
+ @taken << name
249
+ name
250
+ end
251
+
252
+ # An operation body: the operation's params alias, or, when the workflow sets some of its
253
+ # required fields itself (set_by_workflow), a record of its own with those made optional,
254
+ # named <branch>_<input>_body (<input>_body without branches). A field or an operation this
255
+ # gem doesn't know is ignored.
256
+ def body_type(id, schema, path)
257
+ fields = Workflow.operation_fields(id)
258
+ return operation_type(id) unless fields
259
+
260
+ relaxed = Workflow.set_by_workflow(schema).select { |field| fields.key?(field) && fields[field][1] }
261
+ return operation_type(id) if relaxed.empty?
262
+
263
+ base = [@prefix, path].compact.join("_")
264
+ key = [:body, base, id, relaxed]
265
+ return @memo[key] if @memo.key?(key)
266
+
267
+ name = claim("#{base}_body")
268
+ @memo[key] = name
269
+ @aliases[name] = record(fields.sort.map { |field, (rbs, required)| [field, rbs, required && !relaxed.include?(field)] }, " ")
270
+ name
271
+ end
272
+
273
+ def operation_type(id)
274
+ known = Workflow.known_operation(id)
275
+ known ? "::QubeSync::Operations::#{known[0]}::#{known[1]}_params" : "Hash[untyped, untyped]"
276
+ end
277
+
278
+ def literal(value)
279
+ case value
280
+ when String then value.match?(PLAIN_STRING) ? JSON.generate(value) : "String"
281
+ when Integer then value.to_s
282
+ when Float then "Float"
283
+ when true, false then value.to_s
284
+ when nil then "nil"
285
+ else "untyped"
286
+ end
287
+ end
288
+ end
289
+ end
290
+ end