inertia_rails 3.23.0 → 3.24.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 (48) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +19 -0
  3. data/app/channels/inertia_rails/live_channel.rb +16 -0
  4. data/app/jobs/inertia_rails/live_broadcast_job.rb +9 -0
  5. data/lib/generators/inertia/install/install_generator.rb +7 -0
  6. data/lib/generators/inertia/install/templates/application_cable/channel.rb +6 -0
  7. data/lib/generators/inertia/install/templates/inertia_channel.rb +14 -0
  8. data/lib/generators/inertia_templates/scaffold/templates/svelte/edit.ts.svelte.tt +1 -1
  9. data/lib/generators/inertia_templates/scaffold/templates/svelte/form.ts.svelte.tt +2 -2
  10. data/lib/generators/inertia_templates/scaffold/templates/svelte/index.ts.svelte.tt +2 -2
  11. data/lib/generators/inertia_templates/scaffold/templates/svelte/new.ts.svelte.tt +1 -1
  12. data/lib/generators/inertia_templates/scaffold/templates/svelte/one.ts.svelte.tt +1 -1
  13. data/lib/generators/inertia_templates/scaffold/templates/svelte/show.ts.svelte.tt +2 -2
  14. data/lib/generators/inertia_tw_templates/scaffold/templates/svelte/edit.ts.svelte.tt +1 -1
  15. data/lib/generators/inertia_tw_templates/scaffold/templates/svelte/form.ts.svelte.tt +2 -2
  16. data/lib/generators/inertia_tw_templates/scaffold/templates/svelte/index.ts.svelte.tt +2 -2
  17. data/lib/generators/inertia_tw_templates/scaffold/templates/svelte/new.ts.svelte.tt +1 -1
  18. data/lib/generators/inertia_tw_templates/scaffold/templates/svelte/one.ts.svelte.tt +1 -1
  19. data/lib/generators/inertia_tw_templates/scaffold/templates/svelte/show.ts.svelte.tt +2 -2
  20. data/lib/inertia_rails/always_prop.rb +1 -0
  21. data/lib/inertia_rails/cached_prop.rb +1 -0
  22. data/lib/inertia_rails/configuration.rb +13 -2
  23. data/lib/inertia_rails/defer_prop.rb +1 -0
  24. data/lib/inertia_rails/devtools/collector.rb +3 -1
  25. data/lib/inertia_rails/devtools/prop_classifier.rb +1 -0
  26. data/lib/inertia_rails/devtools/redaction.rb +19 -11
  27. data/lib/inertia_rails/engine.rb +21 -0
  28. data/lib/inertia_rails/live_broadcast.rb +52 -0
  29. data/lib/inertia_rails/live_broadcastable.rb +40 -0
  30. data/lib/inertia_rails/live_prop.rb +7 -0
  31. data/lib/inertia_rails/live_stream.rb +79 -0
  32. data/lib/inertia_rails/merge_prop.rb +1 -0
  33. data/lib/inertia_rails/minitest.rb +4 -0
  34. data/lib/inertia_rails/once_prop.rb +1 -0
  35. data/lib/inertia_rails/optional_prop.rb +1 -0
  36. data/lib/inertia_rails/prop_liveable.rb +36 -0
  37. data/lib/inertia_rails/props_resolver/dotted_keys.rb +102 -0
  38. data/lib/inertia_rails/props_resolver/partial_filter.rb +54 -0
  39. data/lib/inertia_rails/props_resolver.rb +190 -181
  40. data/lib/inertia_rails/raw_json.rb +13 -3
  41. data/lib/inertia_rails/renderer.rb +19 -9
  42. data/lib/inertia_rails/rspec.rb +4 -0
  43. data/lib/inertia_rails/scroll_prop.rb +1 -0
  44. data/lib/inertia_rails/testing.rb +4 -7
  45. data/lib/inertia_rails/version.rb +1 -1
  46. data/lib/inertia_rails.rb +21 -2
  47. data/lib/puma/plugin/inertia_ssr.rb +49 -22
  48. metadata +13 -2
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: f12c422cd3da5a02e05eabd6c2dd2e8a702024709f1e9cebf7050d5d21af5492
4
- data.tar.gz: cb131811d666ee1db0f4974cfdf18ec1f692584d5bbc250f77b1498d771ac4a0
3
+ metadata.gz: a61fb8406033968919f21fd6f1e909087711d7aacc6ceb93cb2f83d7dd79e977
4
+ data.tar.gz: a6db5c09d1caa451ac13582481e8591835288105c3a3a9412bae83e12e6b6c8e
5
5
  SHA512:
6
- metadata.gz: 4e846a1e5c73767b155d5087c2cdb2af0e06c0cf489387ac253cc647b8da1c0d56ec5edbb7fa33364b6ed391074422cd4735b7bd10668e44b9efc9e482032ede
7
- data.tar.gz: 27e2d1c62868602a4408372e932f3549631cc92c08e5b10583fad67f04e456e21dd22e3821de0904423b38c8ab785cc5364d7916d18bd42f5801ea6f1dfd799c
6
+ metadata.gz: 8848665f17dec5f9a398d9b04ce6a1bc0a636fb7a417868cfef83eb24d9191d6abbfeaaefec97665e598f4b2f728a02c38ecfa95436bfc66dcf7dec3e37598be
7
+ data.tar.gz: 01d6d04badf532579bbe8b9a31e3d416a0225d13e0780acb3a49b1d29c018697db0e19752cfdd8764e7fdf8773e8407ae21975fe9b40037a5dd0c4268c375717
data/CHANGELOG.md CHANGED
@@ -6,6 +6,25 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
6
6
 
7
7
  ## [Unreleased]
8
8
 
9
+ ## [3.24.0] - 2026-11-26
10
+
11
+ * Honor `to_inertia` on arrays and hashes nested in array props, and speed up partial reloads with nested `only` and `except` paths. Pass `ActiveSupport::OrderedOptions` as `options.to_h` to send its keys (@skryukov).
12
+ * Fix the Puma SSR plugin dying when Puma's cluster master reaps the SSR process: an already reaped process now counts as exited and is restarted instead of raising `Errno::ECHILD` in the plugin thread
13
+ * Stopping the Puma SSR plugin kills an SSR process that ignores `/shutdown` after 5 seconds, instead of waiting for it forever
14
+ * Let `ssr_runtime` carry arguments for the runtime, e.g. `"node --max-old-space-size=256"`
15
+ * Resolve nested `to_inertia` objects returned by prop types through their public projections instead of exposing internal instance variables, including deferred and partial responses (@thomasklemm)
16
+ * Send plain prop values that respond to `deferred?`, `once?` or `rescue?` as data instead of treating them as prop types, and resolve plain props with fewer allocations (@thomasklemm)
17
+ * Reduce controller configuration binding and plain-data prop scanning overhead without caching request-dependent configuration or changing prop evaluation order (@thomasklemm)
18
+ * Skip HTML escaping of Inertia JSON responses when the app sets `config.action_controller.escape_json_responses = false` (the Rails 8.1 default), as `render json:` does (@brodienguyen)
19
+ * Redact URL fragments containing sensitive parameters before DevTools stores URL headers or redirect locations. Harmless fragments and live redirect responses are unchanged (@thomasklemm)
20
+ * Read Inertia request headers by their Rack env keys in the renderer, as the middleware does (@thomasklemm)
21
+ * Embed cached props (`InertiaRails.cache` and `cache:` options) into the page as they are, instead of parsing the cached JSON and encoding it again on every request. This needs Active Support 8.1, which embeds `JSON::Fragment` values; with older versions, or an encoder that doesn't embed fragments, cached props work as before (@brodienguyen)
22
+ * Keep dot-notation prop keys that come before a closure or `to_inertia` object they extend, so `{ 'user.name' => 'J', user: -> { { id: 1 } } }` resolves the same in either order (@skryukov)
23
+ * Apply the `only` and `except` paths of partial reloads inside closures and prop types too, and send always props whole (@skryukov)
24
+ * Fix crashes with dot-notation prop keys over non-hash or String-keyed values, and with a defer group named as both a Symbol and a String (@skryukov)
25
+ * Resolve plain props faster (@skryukov)
26
+ * Add live props: `InertiaRails.live` and the `live:` option on deferred, optional, once, always and cached props subscribe a prop to an Action Cable stream, and `InertiaRails.broadcast` or `inertia_broadcasts` in a model reloads it on every page that shows it. Requires Inertia.js v3.11+. The testing helpers check the live props of a page with `have_live_props` and `assert_inertia_live_props` (@skryukov, @cole-robertson)
27
+
9
28
  ## [3.23.0] - 2026-10-16
10
29
 
11
30
  * Accept a block in `inertia_ssr_head` for fallback head elements, rendered when the response isn't server-side rendered, like inertia-laravel's `<x-inertia::head>` (@skryukov)
@@ -0,0 +1,16 @@
1
+ # frozen_string_literal: true
2
+
3
+ module InertiaRails
4
+ # A valid signed stream name is the only check, as with Turbo's streams channel.
5
+ module LiveChannel
6
+ private
7
+
8
+ def subscribed
9
+ if (name = LiveStream.verified(params[:stream]))
10
+ stream_from name
11
+ else
12
+ reject
13
+ end
14
+ end
15
+ end
16
+ end
@@ -0,0 +1,9 @@
1
+ # frozen_string_literal: true
2
+
3
+ module InertiaRails
4
+ class LiveBroadcastJob < ActiveJob::Base
5
+ def perform(names, socket_id)
6
+ LiveBroadcast.publish(names, socket_id: socket_id)
7
+ end
8
+ end
9
+ end
@@ -119,6 +119,7 @@ module Inertia
119
119
 
120
120
  say 'Copying InertiaController'
121
121
  copy_file 'inertia_controller.rb', file_path('app/controllers/inertia_controller.rb')
122
+ install_channels if defined?(ActionCable)
122
123
 
123
124
  if application_layout.exist?
124
125
  say "Adding #{inertia_entrypoint} script tag to the application layout"
@@ -146,6 +147,12 @@ module Inertia
146
147
  end
147
148
  end
148
149
 
150
+ def install_channels
151
+ base_channel = 'app/channels/application_cable/channel.rb'
152
+ copy_file 'application_cable/channel.rb', file_path(base_channel) unless file?(base_channel)
153
+ copy_file 'inertia_channel.rb', file_path('app/channels/inertia_channel.rb')
154
+ end
155
+
149
156
  def install_typescript
150
157
  say 'Adding TypeScript support'
151
158
 
@@ -0,0 +1,6 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ApplicationCable
4
+ class Channel < ActionCable::Channel::Base
5
+ end
6
+ end
@@ -0,0 +1,14 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Streams live props to the browser. Inertia's Action Cable transport subscribes here by default.
4
+ # see https://inertia-rails.dev/guide/live-props
5
+ class InertiaChannel < ApplicationCable::Channel
6
+ include InertiaRails::LiveChannel
7
+
8
+ # Add authorization on top of the signed stream names:
9
+ # private
10
+ #
11
+ # def subscribed
12
+ # current_user ? super : reject
13
+ # end
14
+ end
@@ -4,7 +4,7 @@
4
4
  import type { <%= inertia_model_type %> } from './types'
5
5
  import Form from './form.svelte'
6
6
 
7
- let { <%= singular_table_name %> } = $props<{ <%= singular_table_name %>: <%= inertia_model_type %> }>()
7
+ let { <%= singular_table_name %> }: { <%= singular_table_name %>: <%= inertia_model_type %> } = $props()
8
8
  </script>
9
9
 
10
10
  <svelte:head>
@@ -5,10 +5,10 @@
5
5
 
6
6
  import type { <%= inertia_model_type %> } from './types'
7
7
 
8
- let { <%= singular_table_name %>, submitText, ...restProps } = $props<{
8
+ let { <%= singular_table_name %>, submitText, ...restProps }: {
9
9
  <%= singular_table_name %>: <%= inertia_model_type %>
10
10
  submitText: string
11
- } & ComponentProps<typeof Form>>()
11
+ } & ComponentProps<typeof Form> = $props()
12
12
  </script>
13
13
 
14
14
  <Form
@@ -3,9 +3,9 @@
3
3
  import <%= inertia_component_name %> from './<%= singular_name %>.svelte'
4
4
  import type { <%= inertia_model_type %> } from './types'
5
5
 
6
- let { <%= plural_table_name %> } = $props<{
6
+ let { <%= plural_table_name %> }: {
7
7
  <%= plural_table_name %>: <%= inertia_model_type %>[]
8
- }>()
8
+ } = $props()
9
9
  </script>
10
10
 
11
11
  <svelte:head>
@@ -4,7 +4,7 @@
4
4
  import type { <%= inertia_model_type %> } from './types'
5
5
  import Form from './form.svelte'
6
6
 
7
- let { <%= singular_table_name %> } = $props<{ <%= singular_table_name %>: <%= inertia_model_type %> }>()
7
+ let { <%= singular_table_name %> }: { <%= singular_table_name %>: <%= inertia_model_type %> } = $props()
8
8
  </script>
9
9
 
10
10
  <svelte:head>
@@ -1,7 +1,7 @@
1
1
  <script lang="ts">
2
2
  import type { <%= inertia_model_type %> } from './types'
3
3
 
4
- let { <%= singular_table_name %> } = $props<{ <%= singular_table_name %>: <%= inertia_model_type %> }>()
4
+ let { <%= singular_table_name %> }: { <%= singular_table_name %>: <%= inertia_model_type %> } = $props()
5
5
  </script>
6
6
 
7
7
  <div>
@@ -3,9 +3,9 @@
3
3
  import <%= inertia_component_name %> from './<%= singular_name %>.svelte'
4
4
  import type { <%= inertia_model_type %> } from './types'
5
5
 
6
- let { <%= singular_table_name %> } = $props<{
6
+ let { <%= singular_table_name %> }: {
7
7
  <%= singular_table_name %>: <%= inertia_model_type %>
8
- }>()
8
+ } = $props()
9
9
  </script>
10
10
 
11
11
  <svelte:head>
@@ -4,7 +4,7 @@
4
4
  import type { <%= inertia_model_type %> } from './types'
5
5
  import Form from './form.svelte'
6
6
 
7
- let { <%= singular_table_name %> } = $props<{ <%= singular_table_name %>: <%= inertia_model_type %> }>()
7
+ let { <%= singular_table_name %> }: { <%= singular_table_name %>: <%= inertia_model_type %> } = $props()
8
8
  </script>
9
9
 
10
10
  <svelte:head>
@@ -5,10 +5,10 @@
5
5
 
6
6
  import type { <%= inertia_model_type %> } from './types'
7
7
 
8
- let { <%= singular_table_name %>, submitText, ...restProps } = $props<{
8
+ let { <%= singular_table_name %>, submitText, ...restProps }: {
9
9
  <%= singular_table_name %>: <%= inertia_model_type %>
10
10
  submitText: string
11
- } & ComponentProps<typeof Form>>()
11
+ } & ComponentProps<typeof Form> = $props()
12
12
  </script>
13
13
 
14
14
  <Form
@@ -3,9 +3,9 @@
3
3
  import <%= inertia_component_name %> from './<%= singular_name %>.svelte'
4
4
  import type { <%= inertia_model_type %> } from './types'
5
5
 
6
- let { <%= plural_table_name %> } = $props<{
6
+ let { <%= plural_table_name %> }: {
7
7
  <%= plural_table_name %>: <%= inertia_model_type %>[]
8
- }>()
8
+ } = $props()
9
9
  </script>
10
10
 
11
11
  <svelte:head>
@@ -4,7 +4,7 @@
4
4
  import type { <%= inertia_model_type %> } from './types'
5
5
  import Form from './form.svelte'
6
6
 
7
- let { <%= singular_table_name %> } = $props<{ <%= singular_table_name %>: <%= inertia_model_type %> }>()
7
+ let { <%= singular_table_name %> }: { <%= singular_table_name %>: <%= inertia_model_type %> } = $props()
8
8
  </script>
9
9
 
10
10
  <svelte:head>
@@ -1,7 +1,7 @@
1
1
  <script lang="ts">
2
2
  import type { <%= inertia_model_type %> } from './types'
3
3
 
4
- let { <%= singular_table_name %> } = $props<{ <%= singular_table_name %>: <%= inertia_model_type %> }>()
4
+ let { <%= singular_table_name %> }: { <%= singular_table_name %>: <%= inertia_model_type %> } = $props()
5
5
  </script>
6
6
 
7
7
  <div>
@@ -3,9 +3,9 @@
3
3
  import <%= inertia_component_name %> from './<%= singular_name %>.svelte'
4
4
  import type { <%= inertia_model_type %> } from './types'
5
5
 
6
- let { <%= singular_table_name %> } = $props<{
6
+ let { <%= singular_table_name %> }: {
7
7
  <%= singular_table_name %>: <%= inertia_model_type %>
8
- }>()
8
+ } = $props()
9
9
  </script>
10
10
 
11
11
  <svelte:head>
@@ -2,5 +2,6 @@
2
2
 
3
3
  module InertiaRails
4
4
  class AlwaysProp < BaseProp
5
+ prepend PropLiveable
5
6
  end
6
7
  end
@@ -3,6 +3,7 @@
3
3
  module InertiaRails
4
4
  class CachedProp < BaseProp
5
5
  include PropCacheable
6
+ prepend PropLiveable
6
7
 
7
8
  def initialize(key, **options, &block)
8
9
  super(cache: options.merge!(key: key), &block)
@@ -29,6 +29,9 @@ module InertiaRails
29
29
  # that Inertia.js (v3.8+) turns into BigInt values.
30
30
  preserve_big_integers: false,
31
31
 
32
+ # Set to AnyCable.config.streams_secret to allow direct signed-stream subscriptions.
33
+ live_streams_secret: nil,
34
+
32
35
  # SSR options.
33
36
  ssr_enabled: false,
34
37
  # URL of the SSR server. When nil, defaults to DEFAULT_SSR_URL.
@@ -122,7 +125,7 @@ module InertiaRails
122
125
  end
123
126
  end
124
127
 
125
- protected attr_reader :controller
128
+ protected attr_accessor :controller
126
129
  protected attr_reader :options
127
130
 
128
131
  def initialize(controller: nil, **attrs)
@@ -134,8 +137,11 @@ module InertiaRails
134
137
  raise ArgumentError, "Unknown options for #{self.class}: #{attrs.keys}"
135
138
  end
136
139
 
140
+ # Copy already validated options; binding happens several times per request.
137
141
  def bind_controller(controller)
138
- Configuration.new(**@options, controller: controller)
142
+ bound = dup
143
+ bound.controller = controller
144
+ bound
139
145
  end
140
146
 
141
147
  def freeze
@@ -230,6 +236,11 @@ module InertiaRails
230
236
 
231
237
  private
232
238
 
239
+ def initialize_dup(source)
240
+ super
241
+ @options = @options.dup
242
+ end
243
+
233
244
  def evaluate_option(value)
234
245
  return value unless value.respond_to?(:call)
235
246
  return value.call unless controller
@@ -5,6 +5,7 @@ module InertiaRails
5
5
  prepend PropOnceable
6
6
  prepend PropMergeable
7
7
  prepend PropCacheable
8
+ prepend PropLiveable
8
9
 
9
10
  DEFAULT_GROUP = 'default'
10
11
 
@@ -54,8 +54,10 @@ module InertiaRails
54
54
 
55
55
  private
56
56
 
57
+ # The page as the client receives it. as_json would leave a cached prop
58
+ # as a JSON::Fragment, so the page goes through the encoder.
57
59
  def page_json
58
- @page_json ||= @page.as_json
60
+ @page_json ||= JSON.parse(ActiveSupport::JSON.encode(@page))
59
61
  end
60
62
 
61
63
  def component_path
@@ -14,6 +14,7 @@ module InertiaRails
14
14
  inertiaType: inertia_type(prop),
15
15
  deferGroup: defer_group(prop),
16
16
  once: prop.try(:once?),
17
+ live: prop.try(:live?),
17
18
  mergeDirection: merge_direction(prop),
18
19
  deepMerge: deep_merge?(prop),
19
20
  }
@@ -29,8 +29,11 @@ module InertiaRails
29
29
  headers.to_h do |name, value|
30
30
  next [name, REDACTED] if keys.include?(name)
31
31
 
32
- value = Array(value).map { |part| utf8(part) }.join(', ')
33
- [name, URL_HEADERS.include?(name) ? redact_url(value) : value]
32
+ value = Array(value).map do |part|
33
+ part = utf8(part)
34
+ URL_HEADERS.include?(name) ? redact_url(part) : part
35
+ end.join(', ')
36
+ [name, value]
34
37
  end
35
38
  end
36
39
 
@@ -38,23 +41,28 @@ module InertiaRails
38
41
  def redact_url(url)
39
42
  base, fragment = url.split('#', 2)
40
43
  path, query = base.split('?', 2)
41
- return url if query.nil? || query.empty?
44
+ return url if query.to_s.empty? && fragment.to_s.empty?
42
45
 
43
46
  filter = log_filter
44
- query = query.gsub(/[^&;]+/) do |pair|
45
- key, value = pair.split('=', 2)
46
- sensitive = value && sensitive_query_key?(URI.decode_www_form_component(key), filter)
47
- sensitive ? "#{key}=#{ENCODED_REDACTED}" : pair
47
+ query = query&.gsub(/[^&;]+/) do |pair|
48
+ sensitive_pair?(pair, filter) ? pair.sub(/=.*/m) { "=#{ENCODED_REDACTED}" } : pair
48
49
  end
49
-
50
- fragment ? "#{path}?#{query}##{fragment}" : "#{path}?#{query}"
50
+ # Fragment syntax is up to the app, so a fragment with a secret is hidden whole.
51
+ fragment = REDACTED if fragment&.split(/[?&;]/)&.any? { |pair| sensitive_pair?(pair, filter) }
52
+ base = query.nil? ? path : "#{path}?#{query}"
53
+ fragment ? "#{base}##{fragment}" : base
51
54
  rescue StandardError
52
- # If the query can't be read, hide all of it.
53
- "#{url.split('?').first}?#{REDACTED}"
55
+ # If URL parameters can't be read, retain neither the query nor the fragment.
56
+ "#{url.split(/[?#]/, 2).first}?#{REDACTED}"
54
57
  end
55
58
 
56
59
  private
57
60
 
61
+ def sensitive_pair?(pair, filter)
62
+ key, value = pair.split('=', 2)
63
+ value && sensitive_query_key?(URI.decode_www_form_component(key), filter)
64
+ end
65
+
58
66
  def redact(value, filter)
59
67
  case value
60
68
  when Hash then filter.filter(value)
@@ -7,6 +7,27 @@ module InertiaRails
7
7
  app.middleware.use ::InertiaRails::Middleware
8
8
  end
9
9
 
10
+ # app/channels and app/jobs reference ActionCable and ActiveJob, so an app without them can't eager
11
+ # load those directories. Same guard as turbo-rails.
12
+ initializer 'inertia_rails.live_frameworks', before: :set_eager_load_paths do
13
+ { 'app/channels' => defined?(ActionCable), 'app/jobs' => defined?(ActiveJob) }.each do |dir, loaded|
14
+ next if loaded
15
+
16
+ path = root.join(dir).to_s
17
+ if Rails.autoloaders.zeitwerk_enabled?
18
+ Rails.autoloaders.main.do_not_eager_load(path)
19
+ else
20
+ config.eager_load_paths.delete(path)
21
+ end
22
+ end
23
+ end
24
+
25
+ initializer 'inertia_rails.live_broadcastable' do
26
+ ActiveSupport.on_load(:active_record) do
27
+ include ::InertiaRails::LiveBroadcastable
28
+ end
29
+ end
30
+
10
31
  initializer 'inertia_rails.action_controller' do
11
32
  ActiveSupport.on_load(:action_controller_base) do
12
33
  include ::InertiaRails::Controller
@@ -0,0 +1,52 @@
1
+ # frozen_string_literal: true
2
+
3
+ module InertiaRails
4
+ module LiveBroadcast
5
+ SOCKET_ID_HEADER = 'X-Socket-Id'
6
+
7
+ class << self
8
+ def broadcast(live, props: nil, to_others: false)
9
+ raise ArgumentError, '`props:` must be a hash of prop names to values' unless props.nil? || props.is_a?(Hash)
10
+
11
+ publish(LiveStream.names(live), props: props && pushed(props), socket_id: to_others ? current_socket_id : nil)
12
+ end
13
+
14
+ # Stream names are computed now, so a destroyed record still broadcasts from the job.
15
+ def broadcast_later(live, to_others: false)
16
+ LiveBroadcastJob.perform_later(LiveStream.names(live), to_others ? current_socket_id : nil)
17
+ end
18
+
19
+ def publish(names, props: nil, socket_id: nil)
20
+ message = { '__inertia' => { 'event' => LiveStream::EVENT, 'socketId' => socket_id, 'props' => props }.compact }
21
+ names.each { |name| ActionCable.server.broadcast(name, message) }
22
+ end
23
+
24
+ private
25
+
26
+ def current_socket_id
27
+ Current.request&.headers&.[](SOCKET_ID_HEADER)
28
+ end
29
+
30
+ # Like a page, with the global settings: a controller's `inertia_config` is out of reach here.
31
+ def pushed(props)
32
+ resolved = props.transform_values { |value| resolve(value) }
33
+ InertiaRails.configuration.prop_transformer(props: resolved)
34
+ end
35
+
36
+ # Keys stay literal: the client writes "order.total" by path, and only for props it listens to.
37
+ def resolve(value)
38
+ if value.is_a?(BaseProp) || value.is_a?(Proc)
39
+ raise ArgumentError, 'Broadcast props take values, not prop types or closures'
40
+ end
41
+
42
+ return resolve(value.to_inertia) if PropsResolver.serializer?(value)
43
+
44
+ case value
45
+ when Hash then value.transform_values { |inner| resolve(inner) }
46
+ when Array then value.map { |inner| resolve(inner) }
47
+ else value
48
+ end
49
+ end
50
+ end
51
+ end
52
+ end
@@ -0,0 +1,40 @@
1
+ # frozen_string_literal: true
2
+
3
+ module InertiaRails
4
+ module LiveBroadcastable
5
+ extend ActiveSupport::Concern
6
+
7
+ included do
8
+ thread_mattr_accessor :suppressed_inertia_broadcasts, instance_accessor: false
9
+ end
10
+
11
+ class_methods do
12
+ def inertia_broadcasts(stream = model_name.plural)
13
+ after_create_commit -> { inertia_broadcast_later(stream) }
14
+ after_update_commit -> { inertia_broadcast_later(self) }
15
+ after_destroy_commit -> { inertia_broadcast_later(self) }
16
+ end
17
+
18
+ def inertia_broadcasts_to(stream)
19
+ after_commit do
20
+ target = stream.respond_to?(:call) ? stream.call(self) : send(stream)
21
+ inertia_broadcast_later(target) unless target.nil?
22
+ end
23
+ end
24
+
25
+ def suppressing_inertia_broadcasts
26
+ original = suppressed_inertia_broadcasts
27
+ self.suppressed_inertia_broadcasts = true
28
+ yield
29
+ ensure
30
+ self.suppressed_inertia_broadcasts = original
31
+ end
32
+ end
33
+
34
+ private
35
+
36
+ def inertia_broadcast_later(stream)
37
+ LiveBroadcast.broadcast_later(stream) unless self.class.suppressed_inertia_broadcasts
38
+ end
39
+ end
40
+ end
@@ -0,0 +1,7 @@
1
+ # frozen_string_literal: true
2
+
3
+ module InertiaRails
4
+ class LiveProp < BaseProp
5
+ prepend PropLiveable
6
+ end
7
+ end
@@ -0,0 +1,79 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'base64'
4
+ require 'openssl'
5
+
6
+ module InertiaRails
7
+ # Turbo's stream names under an "inertia:" prefix, signed in AnyCable's format for its `$pubsub` channel.
8
+ module LiveStream
9
+ PREFIX = 'inertia'
10
+ EVENT = 'refresh'
11
+
12
+ class << self
13
+ # The `live:` option: a streamable, an array naming one stream, or `{ streams: [...] }`.
14
+ def names(live)
15
+ streams =
16
+ if live.is_a?(Hash)
17
+ unless live.keys == [:streams]
18
+ raise ArgumentError, "A `live:` hash only takes `streams:`, got #{live.keys.inspect}"
19
+ end
20
+ unless live[:streams].is_a?(Array) && live[:streams].any?
21
+ raise ArgumentError, '`streams:` must be a non-empty array'
22
+ end
23
+
24
+ live[:streams]
25
+ else
26
+ [live]
27
+ end
28
+
29
+ streams.map { |streamable| "#{PREFIX}:#{name_part(streamable)}" }
30
+ end
31
+
32
+ def option(streamables, streams)
33
+ raise ArgumentError, 'Pass streams as arguments or as `streams:`, not both' if streamables.any? && streams
34
+
35
+ streams.nil? ? streamables : { streams: streams }
36
+ end
37
+
38
+ def signed(name)
39
+ encoded = Base64.urlsafe_encode64(JSON.dump(name))
40
+ "#{encoded}--#{signature(encoded)}"
41
+ end
42
+
43
+ def verified(signed_name)
44
+ return unless signed_name.is_a?(String)
45
+
46
+ encoded, _, digest = signed_name.rpartition('--')
47
+ return unless ActiveSupport::SecurityUtils.secure_compare(digest, signature(encoded))
48
+
49
+ # With AnyCable, Turbo signs with the same secret; its names are valid here otherwise.
50
+ name = JSON.parse(Base64.urlsafe_decode64(encoded))
51
+ name if name.start_with?("#{PREFIX}:")
52
+ end
53
+
54
+ private
55
+
56
+ def name_part(streamable)
57
+ case streamable
58
+ when Array
59
+ raise ArgumentError, 'A live stream needs at least one streamable' if streamable.empty?
60
+
61
+ streamable.map { |part| name_part(part) }.join(':')
62
+ when nil
63
+ raise ArgumentError, "Can't name a live stream after #{streamable.inspect}"
64
+ else
65
+ streamable.try(:to_gid_param) || streamable.to_param
66
+ end
67
+ end
68
+
69
+ def signature(value)
70
+ OpenSSL::HMAC.hexdigest('SHA256', secret, value)
71
+ end
72
+
73
+ def secret
74
+ InertiaRails.configuration.live_streams_secret.presence ||
75
+ Rails.application.key_generator.generate_key('inertia_rails/live_streams')
76
+ end
77
+ end
78
+ end
79
+ end
@@ -4,6 +4,7 @@ module InertiaRails
4
4
  class MergeProp < BaseProp
5
5
  prepend PropOnceable
6
6
  prepend PropMergeable
7
+ prepend PropLiveable
7
8
 
8
9
  def initialize(**_props, &block)
9
10
  super(&block)
@@ -116,6 +116,10 @@ module InertiaRails
116
116
  AssertionFactory.define_exact_assertion(Helpers, :once_props, :once_props)
117
117
  AssertionFactory.define_key_absent_assertion(Helpers, :once_prop, :once_props)
118
118
 
119
+ AssertionFactory.define_partial_assertion(Helpers, :live_props, :live_props)
120
+ AssertionFactory.define_exact_assertion(Helpers, :live_props, :live_props)
121
+ AssertionFactory.define_key_absent_assertion(Helpers, :live_prop, :live_props)
122
+
119
123
  AssertionFactory.define_component_assertion(Helpers)
120
124
  AssertionFactory.define_response_assertion(Helpers)
121
125
  AssertionFactory.define_deferred_props_assertion(Helpers)
@@ -3,6 +3,7 @@
3
3
  module InertiaRails
4
4
  class OnceProp < BaseProp
5
5
  prepend PropOnceable
6
+ prepend PropLiveable
6
7
 
7
8
  def initialize(**, &block)
8
9
  @once = true
@@ -4,5 +4,6 @@ module InertiaRails
4
4
  class OptionalProp < IgnoreOnFirstLoadProp
5
5
  prepend PropOnceable
6
6
  prepend PropCacheable
7
+ prepend PropLiveable
7
8
  end
8
9
  end