ratalada-contrib 2.0.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.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 7dc83505ef9f19515c7d724d845243d929745c808b001eda6d701a5a05a5303a
4
+ data.tar.gz: ab848595fb7a33d79f798da713a0abe2413a7105ce422ed3c80aca2ffaed89c2
5
+ SHA512:
6
+ metadata.gz: f337a60798f1ae83ceafaa3ec6e653399ac10790337cd0977a63e868193e383a89a7097333bc60c4de1b5e9ae8daf52bccedea645caf368121cabf401438e491
7
+ data.tar.gz: 71bb0c9027acc6a087c953704860688bc3b5b92be4ee7123d0ebedd58052687dca310bf5eb5f1da62331a95ff77be9de6ff03073f2b1d50722a669265a39bddd
data/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ # The gem's PropsResolver is plain Ruby except for three ActiveSupport core
4
+ # extensions it calls on every resolve. We don't load ActiveSupport, so here
5
+ # they are, AS-compatible.
6
+ class Object
7
+ def try(method_name, ...) = respond_to?(method_name) ? public_send(method_name, ...) : nil
8
+
9
+ def blank? = respond_to?(:empty?) ? !!empty? : !self
10
+
11
+ def present? = !blank?
12
+ end
@@ -0,0 +1,101 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "securerandom"
4
+ require "rack/utils"
5
+
6
+ module Ratalada
7
+ module Contrib
8
+ module Inertia
9
+ class CSRFMiddleware
10
+ COOKIE_NAME = "XSRF-TOKEN"
11
+ HEADER_KEY = "HTTP_X_XSRF_TOKEN"
12
+ ENV_TOKEN_KEY = "ratalada.inertia.csrf_token"
13
+ SAFE_METHODS = %w[GET HEAD OPTIONS].freeze
14
+
15
+ def initialize(app, same_site: :Lax)
16
+ @app = app
17
+ @same_site = same_site
18
+ end
19
+
20
+ def call(env)
21
+ existing = read_cookie(env)
22
+ token = existing || SecureRandom.urlsafe_base64(32)
23
+ env[ENV_TOKEN_KEY] = token
24
+
25
+ if token_mismatch?(env, existing)
26
+ forbidden(
27
+ "CSRF token mismatch (expected matching X-XSRF-TOKEN header to XSRF-TOKEN cookie)",
28
+ )
29
+ else
30
+ status, headers, body = @app.call(env)
31
+ unless existing == token
32
+ set_cookie!(headers, token)
33
+ end
34
+ [status, headers, body]
35
+ end
36
+ end
37
+
38
+ private
39
+
40
+ def safe_method?(env)
41
+ SAFE_METHODS.include?(env["REQUEST_METHOD"])
42
+ end
43
+
44
+ def token_mismatch?(env, existing)
45
+ if safe_method?(env)
46
+ false
47
+ else
48
+ header = env[HEADER_KEY].to_s
49
+ existing.nil? || header.empty? || !secure_compare(header, existing)
50
+ end
51
+ end
52
+
53
+ def read_cookie(env)
54
+ pairs = env["HTTP_COOKIE"].to_s.split(/;\s*/).map { |pair| pair.split("=", 2) }
55
+ match = pairs.find { |name, _value| name == COOKIE_NAME }
56
+ match && match[1]
57
+ end
58
+
59
+ def secure_compare(a, b)
60
+ a = a.to_s
61
+ b = b.to_s
62
+ if a.bytesize != b.bytesize
63
+ false
64
+ else
65
+ diff = 0
66
+ a.bytes.zip(b.bytes) { |ai, bi| diff |= ai ^ bi }
67
+ diff.zero?
68
+ end
69
+ end
70
+
71
+ def set_cookie!(headers, token)
72
+ cookie = ::Rack::Utils.set_cookie_header(
73
+ COOKIE_NAME,
74
+ value: token,
75
+ path: "/",
76
+ same_site: @same_site,
77
+ )
78
+
79
+ existing = headers["set-cookie"]
80
+ if existing
81
+ headers["set-cookie"] = Array(existing) + [cookie]
82
+ else
83
+ headers["set-cookie"] = cookie
84
+ end
85
+ end
86
+
87
+ def forbidden(message)
88
+ body = "#{message}\n"
89
+ [
90
+ 403,
91
+ {
92
+ "content-type" => "text/plain; charset=utf-8",
93
+ "content-length" => body.bytesize.to_s,
94
+ },
95
+ [body]
96
+ ]
97
+ end
98
+ end
99
+ end
100
+ end
101
+ end
@@ -0,0 +1,10 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Ratalada
4
+ module Contrib
5
+ module Inertia
6
+ Error = Class.new(StandardError)
7
+ InvalidProtocol = Class.new(Error)
8
+ end
9
+ end
10
+ end
@@ -0,0 +1,213 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+
5
+ require_relative "response"
6
+
7
+ module Ratalada
8
+ module Contrib
9
+ module Inertia
10
+ module Helpers
11
+ def inertia(component, props: {}, layout: nil)
12
+ if layout.nil?
13
+ layout = current_page_layout
14
+ end
15
+
16
+ version = current_inertia_version
17
+ shared = current_inertia_shared
18
+
19
+ if !@inertia_encrypt_history_override.nil?
20
+ encrypt = @inertia_encrypt_history_override == true
21
+ else
22
+ encrypt = Ratalada.config.inertia_encrypt_history == true
23
+ end
24
+
25
+ clear = @inertia_clear_history == true
26
+
27
+ if inertia_request?
28
+ content_type("application/json; charset=utf-8")
29
+ headers("x-inertia" => "true", "vary" => "X-Inertia")
30
+ end
31
+
32
+ errors_payload = inertia_errors_payload
33
+ sweep_inertia_session!
34
+
35
+ response_obj = Ratalada::Contrib::Inertia::Response.new(
36
+ component: component,
37
+ props: props,
38
+ request: request,
39
+ context: self,
40
+ version: version,
41
+ url: request.fullpath,
42
+ encrypt_history: encrypt,
43
+ clear_history: clear,
44
+ shared: shared,
45
+ errors: errors_payload,
46
+ )
47
+ page_hash = response_obj.to_h
48
+ page_json = page_hash.to_json
49
+
50
+ if inertia_request?
51
+ page_json
52
+ else
53
+ @page = page_hash
54
+ @page_json = ::Rack::Utils.escape_html(page_json)
55
+ erb(layout, layout: false)
56
+ end
57
+ end
58
+
59
+ def render(*args, **kwargs, &block)
60
+ first = args.first
61
+ if args.length == 1 && first.is_a?(Hash) && first.key?(:inertia)
62
+ inertia(
63
+ first[:inertia],
64
+ props: first[:props] || {},
65
+ layout: first[:layout],
66
+ )
67
+ elsif kwargs.key?(:inertia) && args.empty?
68
+ inertia(
69
+ kwargs[:inertia],
70
+ props: kwargs[:props] || {},
71
+ layout: kwargs[:layout],
72
+ )
73
+ elsif first.is_a?(String) &&
74
+ args.length <= 2 &&
75
+ (args.length == 1 || args[1].is_a?(Hash))
76
+ layout = kwargs.delete(:layout)
77
+ props = {}
78
+ if args[1].is_a?(Hash)
79
+ props.merge!(args[1])
80
+ end
81
+ explicit_props = kwargs.delete(:props)
82
+ if explicit_props.is_a?(Hash)
83
+ props.merge!(explicit_props)
84
+ end
85
+ props.merge!(kwargs)
86
+ inertia(first, props: props, layout: layout)
87
+ else
88
+ super(*args, **kwargs, &block)
89
+ end
90
+ end
91
+
92
+ def render_modal(background:, background_props:, component:, props:, url:)
93
+ inertia(
94
+ background,
95
+ props: background_props.merge(
96
+ modal: {
97
+ component: component,
98
+ props: props,
99
+ url: url,
100
+ },
101
+ ),
102
+ )
103
+ end
104
+
105
+ def inertia_request?
106
+ request.env["HTTP_X_INERTIA"] == "true"
107
+ end
108
+
109
+ def page_request?
110
+ inertia_request?
111
+ end
112
+
113
+ def csrf_token
114
+ request.env["ratalada.inertia.csrf_token"]
115
+ end
116
+
117
+ # The prop factories are the gem's (Ratalada::Contrib::Inertia delegates to
118
+ # InertiaRails).
119
+ def always(value = nil, &block) = Ratalada::Contrib::Inertia.always(value, &block)
120
+ def defer(group: "default", &block) = Ratalada::Contrib::Inertia.defer(group: group, &block)
121
+ def optional(&block) = Ratalada::Contrib::Inertia.optional(&block)
122
+ def lazy(&block) = Ratalada::Contrib::Inertia.lazy(&block)
123
+ def merge(value = nil, &block) = Ratalada::Contrib::Inertia.merge(value, &block)
124
+ def deep_merge(&block) = Ratalada::Contrib::Inertia.deep_merge(&block)
125
+ def once(...) = Ratalada::Contrib::Inertia.once(...)
126
+ def cache(...) = Ratalada::Contrib::Inertia.cache(...)
127
+ def scroll(...) = Ratalada::Contrib::Inertia.scroll(...)
128
+
129
+ def current_inertia_shared
130
+ blocks = Ratalada.config.inertia_share_blocks || []
131
+ merged = {}
132
+ blocks.each do |b|
133
+ v = instance_exec(&b)
134
+ if v.is_a?(Hash)
135
+ merged = deep_merge_hashes(merged, v)
136
+ end
137
+ end
138
+
139
+ merged
140
+ end
141
+
142
+ def current_inertia_version
143
+ Ratalada::Contrib::Inertia.current_version
144
+ end
145
+
146
+ def inertia_errors(payload = nil)
147
+ if payload.nil?
148
+ (session[:_inertia_errors] || {}).dup
149
+ else
150
+ session[:_inertia_errors] = payload
151
+ payload
152
+ end
153
+ end
154
+
155
+ def page_errors(payload = nil)
156
+ inertia_errors(payload)
157
+ end
158
+
159
+ def inertia_clear_history!
160
+ @inertia_clear_history = true
161
+ end
162
+
163
+ def clear_history!
164
+ inertia_clear_history!
165
+ end
166
+
167
+ def inertia_encrypt_history!(flag = true)
168
+ @inertia_encrypt_history_override = flag
169
+ end
170
+
171
+ def encrypt_history!(flag = true)
172
+ inertia_encrypt_history!(flag)
173
+ end
174
+
175
+ def inertia_errors_payload
176
+ errors = session[:_inertia_errors]
177
+ if errors.nil?
178
+ nil
179
+ else
180
+ if errors.respond_to?(:empty?) && errors.empty?
181
+ nil
182
+ else
183
+ errors
184
+ end
185
+ end
186
+ end
187
+
188
+ def sweep_inertia_session!
189
+ if session.respond_to?(:[]=)
190
+ session[:_inertia_errors] = nil
191
+ end
192
+ end
193
+
194
+ private
195
+
196
+ def current_page_layout
197
+ config = Ratalada.config
198
+ if config.respond_to?(:page_layout)
199
+ config.page_layout
200
+ else
201
+ config.inertia_layout
202
+ end
203
+ end
204
+
205
+ def deep_merge_hashes(a, b)
206
+ a.merge(b) do |_k, av, bv|
207
+ (av.is_a?(Hash) && bv.is_a?(Hash)) ? deep_merge_hashes(av, bv) : bv
208
+ end
209
+ end
210
+ end
211
+ end
212
+ end
213
+ end
@@ -0,0 +1,143 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Ratalada
4
+ module Contrib
5
+ module Inertia
6
+ # Rack middleware for the Inertia protocol. Mirrors
7
+ # InertiaRails::Middleware but built on plain Rack rather than
8
+ # ActionDispatch — the gem's version also manages its Rails flash and
9
+ # session keys, which this app does not use (errors live in
10
+ # session[:_inertia_errors] and are swept by the render helpers).
11
+ class Middleware
12
+ INERTIA_HEADER = "HTTP_X_INERTIA"
13
+ INERTIA_VERSION_HEADER = "HTTP_X_INERTIA_VERSION"
14
+ REDIRECT_STATUSES = [301, 302, 303].freeze
15
+ REWRITABLE_REDIRECT_STATUSES = [301, 302].freeze
16
+
17
+ def initialize(app, version: -> { Ratalada::Contrib::Inertia.current_version })
18
+ @app = app
19
+ @version = version
20
+ end
21
+
22
+ def call(env)
23
+ copy_xsrf_to_csrf!(env)
24
+ status, headers, body = @app.call(env)
25
+
26
+ if external_redirect?(env, status, headers)
27
+ status, headers, body = convert_to_location_response!(headers, body)
28
+ end
29
+
30
+ # Only 301/302 are rewritten to 303: a 303 already forces a GET on
31
+ # follow, and 307/308 preserve the request method by design.
32
+ if inertia_non_get_redirect?(env, status)
33
+ status = 303
34
+ end
35
+
36
+ # A response with X-Inertia-Location is already a full page visit —
37
+ # nothing to refresh.
38
+ if stale_inertia_get?(env) && !headers["X-Inertia-Location"]
39
+ force_refresh(env)
40
+ else
41
+ [status, headers, body]
42
+ end
43
+ end
44
+
45
+ private
46
+
47
+ # XHR follows redirects transparently, so a cross-origin target is only
48
+ # reachable through a window.location visit (409 + X-Inertia-Location).
49
+ # 307/308 are excluded: a full page visit is always a GET.
50
+ def external_redirect?(env, status, headers)
51
+ inertia_request?(env) &&
52
+ REDIRECT_STATUSES.include?(status) &&
53
+ external_origin?(env, headers["Location"])
54
+ end
55
+
56
+ def external_origin?(env, location)
57
+ uri = URI.parse(location.to_s)
58
+ if uri.host.nil? || uri.host.empty?
59
+ false
60
+ else
61
+ request = Rack::Request.new(env)
62
+ scheme = uri.scheme || request.scheme
63
+ port = uri.port || (scheme == "https" ? 443 : 80)
64
+
65
+ scheme != request.scheme ||
66
+ !uri.host.casecmp?(request.host) ||
67
+ port != request.port
68
+ end
69
+ rescue URI::InvalidURIError
70
+ false
71
+ end
72
+
73
+ # Mutates the headers in place to keep the rest of the response,
74
+ # notably Set-Cookie (which matters mid-OAuth).
75
+ def convert_to_location_response!(headers, body)
76
+ headers["X-Inertia-Location"] = headers.delete("Location")
77
+ headers.delete("Content-Type")
78
+ headers.delete("Content-Length")
79
+ if body.respond_to?(:close)
80
+ body.close
81
+ end
82
+
83
+ [409, headers, []]
84
+ end
85
+
86
+ def inertia_non_get_redirect?(env, status)
87
+ inertia_request?(env) &&
88
+ REWRITABLE_REDIRECT_STATUSES.include?(status) &&
89
+ %w[POST PUT PATCH DELETE].include?(env["REQUEST_METHOD"])
90
+ end
91
+
92
+ def stale_inertia_get?(env)
93
+ env["REQUEST_METHOD"] == "GET" && inertia_request?(env) && version_mismatch?(env)
94
+ end
95
+
96
+ def inertia_request?(env)
97
+ env[INERTIA_HEADER] == "true"
98
+ end
99
+
100
+ def version_mismatch?(env)
101
+ current = current_version
102
+ if current.nil? || current.empty?
103
+ false
104
+ else
105
+ env[INERTIA_VERSION_HEADER].to_s != current
106
+ end
107
+ end
108
+
109
+ def current_version
110
+ if @version.respond_to?(:call)
111
+ v = @version.call
112
+ else
113
+ v = @version
114
+ end
115
+ v.to_s
116
+ end
117
+
118
+ def force_refresh(env)
119
+ location = env["REQUEST_URI"] || build_url(env)
120
+ [409, { "x-inertia-location" => location, "vary" => "X-Inertia" }, []]
121
+ end
122
+
123
+ def copy_xsrf_to_csrf!(env)
124
+ if env["HTTP_X_XSRF_TOKEN"]
125
+ env["HTTP_X_CSRF_TOKEN"] = env["HTTP_X_XSRF_TOKEN"]
126
+ end
127
+ end
128
+
129
+ def build_url(env)
130
+ scheme = env["rack.url_scheme"] || "http"
131
+ host = env["HTTP_HOST"] || env["SERVER_NAME"]
132
+ path = env["PATH_INFO"]
133
+ qs = env["QUERY_STRING"]
134
+ full = +"#{scheme}://#{host}#{path}"
135
+ if qs && !qs.empty?
136
+ full << "?#{qs}"
137
+ end
138
+ full
139
+ end
140
+ end
141
+ end
142
+ end
143
+ end
@@ -0,0 +1,112 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+
5
+ module Ratalada
6
+ module Contrib
7
+ module Inertia
8
+ # Builds the Inertia page object for a render. Shared data is deep-merged
9
+ # under the page props and errors are merged on top; prop resolution —
10
+ # partial reloads, deferred/optional/merge/once/scroll metadata — is the
11
+ # gem's PropsResolver, evaluating blocks in the request context via the
12
+ # gem's PropEvaluator.
13
+ class Response
14
+ attr_reader(
15
+ :component,
16
+ :props,
17
+ :request,
18
+ :context,
19
+ :version,
20
+ :url,
21
+ :encrypt_history,
22
+ :clear_history,
23
+ :shared,
24
+ :errors,
25
+ )
26
+
27
+ def initialize(
28
+ component:,
29
+ props:,
30
+ request:,
31
+ context:,
32
+ version:,
33
+ url: nil,
34
+ encrypt_history: false,
35
+ clear_history: false,
36
+ shared: {},
37
+ errors: nil
38
+ )
39
+ @component = component
40
+ @props = props || {}
41
+ @request = request
42
+ @context = context
43
+ @version = version.to_s
44
+ @url = url || request.fullpath
45
+ @encrypt_history = encrypt_history
46
+ @clear_history = clear_history
47
+ @shared = shared || {}
48
+ @errors = errors
49
+ end
50
+
51
+ def to_h
52
+ merged = deep_merge(shared, props)
53
+ if errors
54
+ merged = merged.merge(errors: errors)
55
+ end
56
+
57
+ resolved, metadata = ::InertiaRails::PropsResolver.new(
58
+ merged,
59
+ evaluator: ::InertiaRails::PropEvaluator.new(
60
+ context,
61
+ scroll_intent: request.env["HTTP_X_INERTIA_INFINITE_SCROLL_MERGE_INTENT"],
62
+ ),
63
+ visit: {
64
+ component: partial_request?,
65
+ only: header_list("HTTP_X_INERTIA_PARTIAL_DATA"),
66
+ except: header_list("HTTP_X_INERTIA_PARTIAL_EXCEPT"),
67
+ reset: header_list("HTTP_X_INERTIA_RESET"),
68
+ except_once: header_list("HTTP_X_INERTIA_EXCEPT_ONCE_PROPS"),
69
+ },
70
+ ).resolve
71
+
72
+ page = {
73
+ component: component,
74
+ props: resolved,
75
+ url: url,
76
+ version: version,
77
+ }
78
+ if encrypt_history
79
+ page[:encryptHistory] = true
80
+ end
81
+ if clear_history
82
+ page[:clearHistory] = true
83
+ end
84
+ page.merge!(metadata)
85
+ page
86
+ end
87
+
88
+ def to_json(*) = to_h.to_json
89
+
90
+ private
91
+
92
+ def partial_request?
93
+ request.env["HTTP_X_INERTIA_PARTIAL_COMPONENT"] == component
94
+ end
95
+
96
+ def header_list(key)
97
+ request.env[key].to_s.split(",").map(&:strip).reject(&:empty?)
98
+ end
99
+
100
+ def deep_merge(a, b)
101
+ a.merge(b) do |_k, av, bv|
102
+ if av.is_a?(Hash) && bv.is_a?(Hash)
103
+ deep_merge(av, bv)
104
+ else
105
+ bv
106
+ end
107
+ end
108
+ end
109
+ end
110
+ end
111
+ end
112
+ end
@@ -0,0 +1,89 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "ratalada"
4
+
5
+ # Prop system only... no rails-coupled stuff.
6
+ require "inertia_rails/raw_json"
7
+ require "inertia_rails/prop_onceable"
8
+ require "inertia_rails/prop_mergeable"
9
+ require "inertia_rails/prop_cacheable"
10
+ require "inertia_rails/base_prop"
11
+ require "inertia_rails/ignore_on_first_load_prop"
12
+ require "inertia_rails/always_prop"
13
+ require "inertia_rails/lazy_prop"
14
+ require "inertia_rails/optional_prop"
15
+ require "inertia_rails/cached_prop"
16
+ require "inertia_rails/defer_prop"
17
+ require "inertia_rails/merge_prop"
18
+ require "inertia_rails/once_prop"
19
+ require "inertia_rails/scroll_metadata"
20
+ require "inertia_rails/scroll_prop"
21
+ require "inertia_rails/prop_evaluator"
22
+ require "inertia_rails/props_resolver"
23
+
24
+ require_relative "inertia/errors"
25
+ require_relative "inertia/core_ext"
26
+ require_relative "inertia/response"
27
+ require_relative "inertia/middleware"
28
+ require_relative "inertia/csrf_middleware"
29
+ require_relative "inertia/helpers"
30
+
31
+ # LazyProp reports deprecation through code that's tied to rails.
32
+ module InertiaRails
33
+ def self.deprecator = Kernel
34
+ end
35
+
36
+ module Ratalada
37
+ module Contrib
38
+ module Inertia
39
+ module_function
40
+
41
+ def always(value = nil, &block) = ::InertiaRails::AlwaysProp.new(&block || proc { value })
42
+ def defer(group: "default", &block) = ::InertiaRails::DeferProp.new(group: group, &block)
43
+ def optional(&block) = ::InertiaRails::OptionalProp.new(&block)
44
+ def lazy(value = nil, &block) = ::InertiaRails::LazyProp.new(value, &block)
45
+ def merge(value = nil, &block) = ::InertiaRails::MergeProp.new(&block || proc { value })
46
+ def deep_merge(match_on: nil, &block) = ::InertiaRails::MergeProp.new(deep_merge: true, match_on: match_on, &block)
47
+ def once(...) = ::InertiaRails::OnceProp.new(...)
48
+ def cache(...) = ::InertiaRails::CachedProp.new(...)
49
+ def scroll(metadata = nil, **options, &block) = ::InertiaRails::ScrollProp.new(metadata: metadata, **options, &block)
50
+
51
+ # Registers a shared-prop block, run in the request context on every
52
+ # inertia render and deep-merged under the page props.
53
+ def share(&block)
54
+ unless block
55
+ raise ArgumentError, "share requires a block"
56
+ end
57
+
58
+ Ratalada.config.inertia_share_blocks = Ratalada.config.inertia_share_blocks + [block]
59
+ end
60
+
61
+ def share_props(&block) = share(&block)
62
+
63
+ # The asset version sent with every page object. An app-defined
64
+ # page_version setting wins over inertia_version; either may be
65
+ # callable, and whatever comes out is stringified.
66
+ def current_version
67
+ config = Ratalada.config
68
+ if config.respond_to?(:page_version)
69
+ version = config.page_version
70
+ else
71
+ version = config.inertia_version
72
+ end
73
+
74
+ version.respond_to?(:call) ? version.call.to_s : version.to_s
75
+ end
76
+ end
77
+ end
78
+ end
79
+
80
+ unless defined?(::Inertia)
81
+ ::Inertia = Ratalada::Contrib::Inertia
82
+ end
83
+
84
+ # Contrib settings, registered on the core config exactly like the core's own.
85
+ Ratalada.setting :inertia_version, default: "1"
86
+ Ratalada.setting :inertia_layout, default: :layout
87
+ Ratalada.setting :inertia_encrypt_history, default: false
88
+ Ratalada.setting :inertia_csrf_protection, default: true
89
+ Ratalada.setting :inertia_share_blocks, default: []
@@ -0,0 +1,7 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Ratalada
4
+ module Contrib
5
+ VERSION = "2.0.0"
6
+ end
7
+ end
@@ -0,0 +1,66 @@
1
+ require "vite_ruby"
2
+
3
+ module Ratalada
4
+ module Contrib
5
+ module Vite
6
+ # Rack middleware that fronts the app with vite's dev-server proxy while
7
+ # `bin/vite dev` is running, and is a pass-through otherwise (production,
8
+ # or a build served from the manifest). The decision is ViteRuby's
9
+ # `run_proxy?`, read once at boot like any other `Server.use` argument.
10
+ #
11
+ # Server.use(Ratalada::Contrib::Vite::DevServerProxy).run { ... }
12
+ class DevServerProxy
13
+ def initialize(app, ssl_verify_none: true)
14
+ if ::ViteRuby.run_proxy?
15
+ @app = ::ViteRuby::DevServerProxy.new(app, ssl_verify_none: ssl_verify_none)
16
+ else
17
+ @app = app
18
+ end
19
+ end
20
+
21
+ def call(env) = @app.call(env)
22
+ end
23
+
24
+ module TagHelpers
25
+ def vite_client_tag
26
+ src = vite_manifest.vite_client_src
27
+
28
+ if src
29
+ %(<script type="module" src="#{src}"></script)
30
+ end
31
+ end
32
+
33
+ def vite_react_refresh_tag = vite_manifest.react_refresh_preamble
34
+
35
+ def vite_asset_path(name, **options) = vite_manifest.path_for(name, **options)
36
+
37
+ def vite_javascript_tag(*names, type: "module", crossorigin: "anonymous", **options)
38
+ entries = vite_manifest.resolve_entries(*names, **options)
39
+
40
+ scripts = entries.fetch(:scripts).map do |src|
41
+ %(<script type="#{type}" crossorigin="#{crossorigin}" src="#{src}"></script>)
42
+ end
43
+ preloads = entries.fetch(:imports).map do |href|
44
+ %(<link rel="modulepreload" as="script" crossorigin="#{crossorigin}" href="#{href}">)
45
+ end
46
+ styles = entries.fetch(:stylesheets).map { |href| %(<link rel="stylesheet" href="#{href}">) }
47
+
48
+ (scripts + preloads + styles).join("\n")
49
+ end
50
+
51
+ def vite_styleshee_tag(*name, **options)
52
+ name
53
+ .map { |name| vite_asset_path(name, type: :stylesheet, **options) }
54
+ .map { |href| %(<link rel="stylesheet" href="#{href}">) }
55
+ .join("\n")
56
+ end
57
+
58
+ private
59
+
60
+ def vite_manifest
61
+ ViteRuby.instance.manifest
62
+ end
63
+ end
64
+ end
65
+ end
66
+ end
metadata ADDED
@@ -0,0 +1,71 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: ratalada-contrib
3
+ version: !ruby/object:Gem::Version
4
+ version: 2.0.0
5
+ platform: ruby
6
+ authors:
7
+ - Nathan K
8
+ bindir: bin
9
+ cert_chain: []
10
+ date: 1980-01-01 00:00:00.000000000 Z
11
+ dependencies:
12
+ - !ruby/object:Gem::Dependency
13
+ name: ratalada
14
+ requirement: !ruby/object:Gem::Requirement
15
+ requirements:
16
+ - - "~>"
17
+ - !ruby/object:Gem::Version
18
+ version: '2.0'
19
+ type: :runtime
20
+ prerelease: false
21
+ version_requirements: !ruby/object:Gem::Requirement
22
+ requirements:
23
+ - - "~>"
24
+ - !ruby/object:Gem::Version
25
+ version: '2.0'
26
+ description: |
27
+ Optional add-on modules for ratalada that do not belong in the core gem.
28
+ Require only the ones you use; each pulls its own framework (the
29
+ file-based routing module expects Sinatra, supplied by your app).
30
+ email:
31
+ - nathankidd@hey.com
32
+ executables: []
33
+ extensions: []
34
+ extra_rdoc_files: []
35
+ files:
36
+ - LICENSE
37
+ - lib/ratalada/contrib/inertia.rb
38
+ - lib/ratalada/contrib/inertia/core_ext.rb
39
+ - lib/ratalada/contrib/inertia/csrf_middleware.rb
40
+ - lib/ratalada/contrib/inertia/errors.rb
41
+ - lib/ratalada/contrib/inertia/helpers.rb
42
+ - lib/ratalada/contrib/inertia/middleware.rb
43
+ - lib/ratalada/contrib/inertia/response.rb
44
+ - lib/ratalada/contrib/version.rb
45
+ - lib/ratalada/contrib/vite.rb
46
+ homepage: https://github.com/n-at-han-k/ratalada
47
+ licenses:
48
+ - MIT
49
+ metadata:
50
+ homepage_uri: https://github.com/n-at-han-k/ratalada
51
+ source_code_uri: https://github.com/n-at-han-k/ratalada
52
+ documentation_uri: https://github.com/n-at-han-k/ratalada
53
+ rubygems_mfa_required: 'true'
54
+ rdoc_options: []
55
+ require_paths:
56
+ - lib
57
+ required_ruby_version: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - ">="
60
+ - !ruby/object:Gem::Version
61
+ version: 3.2.0
62
+ required_rubygems_version: !ruby/object:Gem::Requirement
63
+ requirements:
64
+ - - ">="
65
+ - !ruby/object:Gem::Version
66
+ version: '0'
67
+ requirements: []
68
+ rubygems_version: 3.7.2
69
+ specification_version: 4
70
+ summary: Contrib add-ons for ratalada.
71
+ test_files: []