Class: Rhales::LinkBasedInjectionDetector

Inherits:
Object
  • Object
show all
Defined in:
lib/rhales/hydration/link_based_injection_detector.rb

Overview

Generates link-based hydration strategies that use browser resource hints and API endpoints instead of inline scripts

Supported Strategies

  • :link - Basic link reference: <link href="/api/hydration/template">
  • :prefetch - Background prefetch: <link rel="prefetch" href="..." as="fetch">
  • :preload - High priority preload: <link rel="preload" href="..." as="fetch">
  • :modulepreload - ES module preload: <link rel="modulepreload" href="..."
  • :lazy - Lazy loading with intersection observer

All strategies generate both link tags and accompanying JavaScript for data fetching and assignment to window objects.

Instance Method Summary collapse

Constructor Details

#initialize(hydration_config) ⇒ LinkBasedInjectionDetector

Returns a new instance of LinkBasedInjectionDetector.



25
26
27
28
29
# File 'lib/rhales/hydration/link_based_injection_detector.rb', line 25

def initialize(hydration_config)
  @hydration_config = hydration_config
  @api_endpoint_path = hydration_config.api_endpoint_path || '/api/hydration'
  @crossorigin_enabled = hydration_config.link_crossorigin.nil? ? true : hydration_config.link_crossorigin
end

Instance Method Details



50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/rhales/hydration/link_based_injection_detector.rb', line 50

def generate_basic_link(template_name, window_attr, nonce)
  endpoint_url = "#{@api_endpoint_path}/#{template_name}"
  window_attr_html = ERB::Util.html_escape(window_attr)
  window_attr_js   = JSONSerializer.dump_html_safe(window_attr)
  endpoint_url_html = ERB::Util.html_escape(endpoint_url)
  endpoint_url_js   = JSONSerializer.dump_html_safe(endpoint_url)

  link_tag = %(<link href="#{endpoint_url_html}" type="application/json">)

  script_tag = <<~HTML.strip
    <script#{nonce_attribute(nonce)} data-hydration-target="#{window_attr_html}">
    // Load hydration data
    window.__rhales__ = window.__rhales__ || {};
    if (!window.__rhales__.loadData) {
      window.__rhales__.loadData = function(target, url) {
        fetch(url)
          .then(r => r.json())
          .then(data => window[target] = data);
      };
    }
    window.__rhales__.loadData(#{window_attr_js}, #{endpoint_url_js});
    </script>
  HTML

  "#{link_tag}\n#{script_tag}"
end

#generate_for_strategy(strategy, template_name, window_attr, nonce = nil) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/rhales/hydration/link_based_injection_detector.rb', line 31

def generate_for_strategy(strategy, template_name, window_attr, nonce = nil)
  case strategy
  when :link
    generate_basic_link(template_name, window_attr, nonce)
  when :prefetch
    generate_prefetch_link(template_name, window_attr, nonce)
  when :preload
    generate_preload_link(template_name, window_attr, nonce)
  when :modulepreload
    generate_modulepreload_link(template_name, window_attr, nonce)
  when :lazy
    generate_lazy_loading(template_name, window_attr, nonce)
  else
    raise ArgumentError, "Unsupported link strategy: #{strategy}"
  end
end

#generate_lazy_loading(template_name, window_attr, nonce) ⇒ Object (private)



159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
# File 'lib/rhales/hydration/link_based_injection_detector.rb', line 159

def generate_lazy_loading(template_name, window_attr, nonce)
  endpoint_url = "#{@api_endpoint_path}/#{template_name}"
  mount_selector = @hydration_config.lazy_mount_selector || '#app'
  window_attr_html = ERB::Util.html_escape(window_attr)
  window_attr_js   = JSONSerializer.dump_html_safe(window_attr)
  endpoint_url_html = ERB::Util.html_escape(endpoint_url)
  endpoint_url_js   = JSONSerializer.dump_html_safe(endpoint_url)
  mount_selector_js = JSONSerializer.dump_html_safe(mount_selector)

  # No link tag for lazy loading - purely script-driven
  script_tag = <<~HTML.strip
    <script#{nonce_attribute(nonce)} data-hydration-target="#{window_attr_html}" data-lazy-src="#{endpoint_url_html}">
    // Lazy loading strategy with intersection observer
    window.__rhales__ = window.__rhales__ || {};
    window.__rhales__.initLazyLoading = function() {
      const mountElement = document.querySelector(#{mount_selector_js});
      if (!mountElement) {
        console.warn('Rhales: Mount element ' + #{mount_selector_js} + ' not found for lazy loading');
        return;
      }

      const observer = new IntersectionObserver((entries) => {
        entries.forEach(entry => {
          if (entry.isIntersecting) {
            fetch(#{endpoint_url_js})
              .then(r => r.json())
              .then(data => {
                window[#{window_attr_js}] = data;
                window.dispatchEvent(new CustomEvent('rhales:hydrated', {
                  detail: { target: #{window_attr_js}, data: data }
                }));
              })
              .catch(err => console.error('Rhales lazy hydration error:', err));

            observer.unobserve(entry.target);
          }
        });
      });

      observer.observe(mountElement);
    };

    // Initialize when DOM is ready
    if (document.readyState === 'loading') {
      document.addEventListener('DOMContentLoaded', window.__rhales__.initLazyLoading);
    } else {
      window.__rhales__.initLazyLoading();
    }
    </script>
  HTML

  script_tag
end


134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
# File 'lib/rhales/hydration/link_based_injection_detector.rb', line 134

def generate_modulepreload_link(template_name, window_attr, nonce)
  endpoint_url = "#{@api_endpoint_path}/#{template_name}.js"
  window_attr_html = ERB::Util.html_escape(window_attr)
  window_attr_js   = JSONSerializer.dump_html_safe(window_attr)
  endpoint_url_html = ERB::Util.html_escape(endpoint_url)
  endpoint_url_js   = JSONSerializer.dump_html_safe(endpoint_url)

  link_tag = %(<link rel="modulepreload" href="#{endpoint_url_html}">)

  script_tag = <<~HTML.strip
    <script type="module"#{nonce_attribute(nonce)} data-hydration-target="#{window_attr_html}">
    // Module preload strategy
    import data from #{endpoint_url_js};
    window[#{window_attr_js}] = data;

    // Dispatch ready event
    window.dispatchEvent(new CustomEvent('rhales:hydrated', {
      detail: { target: #{window_attr_js}, data: data }
    }));
    </script>
  HTML

  "#{link_tag}\n#{script_tag}"
end


77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
# File 'lib/rhales/hydration/link_based_injection_detector.rb', line 77

def generate_prefetch_link(template_name, window_attr, nonce)
  endpoint_url = "#{@api_endpoint_path}/#{template_name}"
  crossorigin_attr = @crossorigin_enabled ? ' crossorigin' : ''
  window_attr_html = ERB::Util.html_escape(window_attr)
  window_attr_js   = JSONSerializer.dump_html_safe(window_attr)
  endpoint_url_html = ERB::Util.html_escape(endpoint_url)
  endpoint_url_js   = JSONSerializer.dump_html_safe(endpoint_url)

  link_tag = %(<link rel="prefetch" href="#{endpoint_url_html}" as="fetch"#{crossorigin_attr}>)

  script_tag = <<~HTML.strip
    <script#{nonce_attribute(nonce)} data-hydration-target="#{window_attr_html}">
    // Prefetch hydration data
    window.__rhales__ = window.__rhales__ || {};
    if (!window.__rhales__.loadPrefetched) {
      window.__rhales__.loadPrefetched = function(target, url) {
        fetch(url)
          .then(r => r.json())
          .then(data => window[target] = data);
      };
    }
    window.__rhales__.loadPrefetched(#{window_attr_js}, #{endpoint_url_js});
    </script>
  HTML

  "#{link_tag}\n#{script_tag}"
end


105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
# File 'lib/rhales/hydration/link_based_injection_detector.rb', line 105

def generate_preload_link(template_name, window_attr, nonce)
  endpoint_url = "#{@api_endpoint_path}/#{template_name}"
  crossorigin_attr = @crossorigin_enabled ? ' crossorigin' : ''
  window_attr_html = ERB::Util.html_escape(window_attr)
  window_attr_js   = JSONSerializer.dump_html_safe(window_attr)
  endpoint_url_html = ERB::Util.html_escape(endpoint_url)
  endpoint_url_js   = JSONSerializer.dump_html_safe(endpoint_url)

  link_tag = %(<link rel="preload" href="#{endpoint_url_html}" as="fetch"#{crossorigin_attr}>)

  script_tag = <<~HTML.strip
    <script#{nonce_attribute(nonce)} data-hydration-target="#{window_attr_html}">
    // Preload strategy - high priority fetch
    fetch(#{endpoint_url_js})
      .then(r => r.json())
      .then(data => {
        window[#{window_attr_js}] = data;
        // Dispatch ready event
        window.dispatchEvent(new CustomEvent('rhales:hydrated', {
          detail: { target: #{window_attr_js}, data: data }
        }));
      })
      .catch(err => console.error('Rhales hydration error:', err));
    </script>
  HTML

  "#{link_tag}\n#{script_tag}"
end

#nonce_attribute(nonce) ⇒ Object (private)



213
214
215
216
# File 'lib/rhales/hydration/link_based_injection_detector.rb', line 213

def nonce_attribute(nonce)
  require 'erb'
  nonce ? " nonce=\"#{ERB::Util.html_escape(nonce)}\"" : ''
end