Class: ReactOnRails::SystemChecker

Inherits:
Object
  • Object
show all
Includes:
ConfigPathResolver
Defined in:
lib/react_on_rails/system_checker.rb

Overview

SystemChecker provides validation methods for React on Rails setup Used by install generator and doctor rake task rubocop:disable Metrics/ClassLength

Constant Summary collapse

SUPPORTED_ASSETS_BUNDLERS =
%w[webpack rspack].freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeSystemChecker

Returns a new instance of SystemChecker.



19
20
21
# File 'lib/react_on_rails/system_checker.rb', line 19

def initialize
  @messages = []
end

Instance Attribute Details

#messagesObject (readonly)

Returns the value of attribute messages.



15
16
17
# File 'lib/react_on_rails/system_checker.rb', line 15

def messages
  @messages
end

Instance Method Details

#add_error(message) ⇒ Object



23
24
25
# File 'lib/react_on_rails/system_checker.rb', line 23

def add_error(message)
  @messages << { type: :error, content: message }
end

#add_info(message) ⇒ Object



35
36
37
# File 'lib/react_on_rails/system_checker.rb', line 35

def add_info(message)
  @messages << { type: :info, content: message }
end

#add_success(message) ⇒ Object



31
32
33
# File 'lib/react_on_rails/system_checker.rb', line 31

def add_success(message)
  @messages << { type: :success, content: message }
end

#add_warning(message) ⇒ Object



27
28
29
# File 'lib/react_on_rails/system_checker.rb', line 27

def add_warning(message)
  @messages << { type: :warning, content: message }
end

#bundle_analyzer_available?Boolean

Returns:

  • (Boolean)


381
382
383
384
385
386
387
388
389
390
391
392
# File 'lib/react_on_rails/system_checker.rb', line 381

def bundle_analyzer_available?
  package_json_path = resolved_package_json_path
  return false unless File.exist?(package_json_path)

  begin
    package_json = JSON.parse(File.read(package_json_path))
    all_deps = (package_json["dependencies"] || {}).merge(package_json["devDependencies"] || {})
    all_deps["webpack-bundle-analyzer"]
  rescue StandardError
    false
  end
end

#check_node_installationObject

Node.js validation



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/react_on_rails/system_checker.rb', line 48

def check_node_installation
  if node_missing?
    add_error(<<~MSG.strip)
      🚫 Node.js is required but not found on your system.

      Please install Node.js before continuing:
      • Download from: https://nodejs.org/en/
      • Recommended: Use a version manager like nvm, fnm, or volta
      • Minimum required version: Node.js 18+

      After installation, restart your terminal and try again.
    MSG
    return false
  end

  check_node_version
  true
end

#check_node_versionObject



67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
# File 'lib/react_on_rails/system_checker.rb', line 67

def check_node_version
  stdout, stderr, status = Open3.capture3("node", "--version")

  # Use stdout if available, fallback to stderr if stdout is empty
  node_version = stdout.strip
  node_version = stderr.strip if node_version.empty?

  # Return early if node is not found (non-zero status) or no output
  return if !status.success? || node_version.empty?

  # Extract major version number (e.g., "v18.17.0" -> 18)
  major_version = node_version[/v(\d+)/, 1]&.to_i
  return unless major_version

  if major_version < 18
    add_warning(<<~MSG.strip)
      ⚠️  Node.js version #{node_version} detected.

      React on Rails recommends Node.js 18+ for best compatibility.
      You may experience issues with older versions.

      Consider upgrading: https://nodejs.org/en/
    MSG
  else
    add_success("✅ Node.js #{node_version} is installed and compatible")
  end
end

#check_package_managerObject

Package manager validation



96
97
98
99
100
101
102
103
104
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
# File 'lib/react_on_rails/system_checker.rb', line 96

def check_package_manager
  package_managers = %w[npm pnpm yarn bun]
  available_managers = package_managers.select { |pm| cli_exists?(pm) }

  if available_managers.empty?
    add_error(<<~MSG.strip)
      🚫 No JavaScript package manager found on your system.

      React on Rails requires a JavaScript package manager to install dependencies.
      Please install one of the following:

      • npm: Usually comes with Node.js (https://nodejs.org/en/)
      • yarn: npm install -g yarn (https://yarnpkg.com/)
      • pnpm: npm install -g pnpm (https://pnpm.io/)
      • bun: Install from https://bun.sh/

      After installation, restart your terminal and try again.
    MSG
    return false
  end

  # Detect which package manager is actually being used
  used_manager = detect_used_package_manager
  if used_manager
    version_info = get_package_manager_version(used_manager)
    deprecation_note = get_deprecation_note(used_manager, version_info)
    message = "✅ Package manager in use: #{used_manager} #{version_info}"
    message += deprecation_note if deprecation_note
    add_success(message)
  else
    add_success("✅ Package managers available: #{available_managers.join(', ')}")
    add_info("ℹ️  No lock file detected - run npm/yarn/pnpm install to establish which manager is used")
  end
  true
end

#check_package_version_syncObject



213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
# File 'lib/react_on_rails/system_checker.rb', line 213

def check_package_version_sync
  package_json_path = resolved_package_json_path
  return unless File.exist?(package_json_path)

  begin
    package_json = JSON.parse(File.read(package_json_path))
    package_name, npm_version = react_on_rails_npm_package_details(package_json)

    return unless npm_version && defined?(ReactOnRails::VERSION)

    # Normalize NPM version format to Ruby gem format for comparison
    # Uses existing VersionSyntaxConverter to handle dash/dot differences
    # (e.g., "16.2.0-beta.10" → "16.2.0.beta.10")
    converter = ReactOnRails::VersionSyntaxConverter.new
    normalized_npm_version = converter.npm_to_rubygem(npm_version)
    gem_version = ReactOnRails::VERSION

    if normalized_npm_version == gem_version
      add_success("✅ React on Rails gem and #{package_name} NPM package versions match (#{gem_version})")
      check_version_patterns(npm_version, gem_version)
    else
      # Check for major version differences
      gem_major = gem_version.split(".")[0].to_i
      npm_major = normalized_npm_version.split(".")[0].to_i

      if gem_major != npm_major # rubocop:disable Style/NegatedIfElseCondition
        add_error(<<~MSG.strip)
          🚫 Major version mismatch detected:
          • Gem version: #{gem_version} (major: #{gem_major})
#{package_name} version: #{npm_version} (major: #{npm_major})

          Major version differences can cause serious compatibility issues.
          Update both packages to use the same major version immediately.
        MSG
      else
        add_warning(<<~MSG.strip)
          ⚠️  Version mismatch detected:
          • Gem version: #{gem_version}
#{package_name} version: #{npm_version}

          Consider updating to exact, fixed matching versions of gem and npm package for best compatibility.
        MSG
      end
    end
  rescue JSON::ParserError
    # Ignore parsing errors, already handled elsewhere
  rescue StandardError
    # Handle other errors gracefully
  end
end

#check_react_dependenciesObject

React dependencies validation



265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
# File 'lib/react_on_rails/system_checker.rb', line 265

def check_react_dependencies
  return unless File.exist?(resolved_package_json_path)

  package_json = parse_package_json
  return unless package_json

  # Check core React dependencies
  required_deps = required_react_dependencies
  missing_deps = find_missing_dependencies(package_json, required_deps)
  report_dependency_status(required_deps, missing_deps, package_json)

  # Check additional build dependencies (informational)
  check_build_dependencies(package_json)

  # Report versions
  report_dependency_versions(package_json)
end

#check_react_on_rails_gemObject



178
179
180
181
182
183
184
185
186
187
188
189
190
# File 'lib/react_on_rails/system_checker.rb', line 178

def check_react_on_rails_gem
  require "react_on_rails"
  add_success("✅ React on Rails gem #{ReactOnRails::VERSION} is loaded")
rescue LoadError
  add_error(<<~MSG.strip)
    🚫 React on Rails gem is not available.

    Add to your Gemfile:
    gem 'react_on_rails'

    Then run: bundle install
  MSG
end

#check_react_on_rails_initializerObject

Rails integration validation



285
286
287
288
289
290
291
292
293
294
295
296
297
# File 'lib/react_on_rails/system_checker.rb', line 285

def check_react_on_rails_initializer
  initializer_path = "config/initializers/react_on_rails.rb"
  if File.exist?(initializer_path)
    add_success("✅ React on Rails initializer exists")
  else
    add_warning(<<~MSG.strip)
      ⚠️  React on Rails initializer not found.

      Create: config/initializers/react_on_rails.rb
      Or run: rails generate react_on_rails:install
    MSG
  end
end

#check_react_on_rails_npm_packageObject



192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
# File 'lib/react_on_rails/system_checker.rb', line 192

def check_react_on_rails_npm_package
  package_json_path = resolved_package_json_path
  return unless File.exist?(package_json_path)

  package_json = JSON.parse(File.read(package_json_path))
  package_name, npm_version = react_on_rails_npm_package_details(package_json)

  if package_name
    add_success("#{package_name} NPM package #{npm_version} is declared")
  else
    add_warning(<<~MSG.strip)
      ⚠️  Neither react-on-rails nor react-on-rails-pro NPM package found in package.json.

      Install it with:
      npm install react-on-rails
    MSG
  end
rescue JSON::ParserError
  add_warning("⚠️  Could not parse package.json")
end

#check_react_on_rails_packagesObject

React on Rails package validation



171
172
173
174
175
176
# File 'lib/react_on_rails/system_checker.rb', line 171

def check_react_on_rails_packages
  check_react_on_rails_gem
  check_react_on_rails_npm_package
  check_package_version_sync
  check_gemfile_version_patterns
end

#check_shakapacker_configurationObject

Shakapacker validation



133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
# File 'lib/react_on_rails/system_checker.rb', line 133

def check_shakapacker_configuration
  unless shakapacker_configured?
    add_error(<<~MSG.strip)
      🚫 Shakapacker is not properly configured.

      Missing one or more required files:
      • bin/shakapacker
      • bin/shakapacker-dev-server
      • config/shakapacker.yml
      • config/webpack/webpack.config.{js,ts}
      • config/rspack/rspack.config.{js,ts}

      Run: bundle exec rails shakapacker:install
    MSG
    return false
  end

  report_shakapacker_version_with_threshold
  check_shakapacker_in_gemfile
  true
end

#check_shakapacker_in_gemfileObject



155
156
157
158
159
160
161
162
163
164
165
166
167
168
# File 'lib/react_on_rails/system_checker.rb', line 155

def check_shakapacker_in_gemfile
  if shakapacker_in_gemfile?
    add_success("✅ Shakapacker is declared in Gemfile")
  else
    add_warning(<<~MSG.strip)
      ⚠️  Shakapacker not found in Gemfile.

      While Shakapacker might be available as a dependency,
      it's recommended to add it explicitly to your Gemfile:

      bundle add shakapacker --strict
    MSG
  end
end

#check_webpack_config_content(config_path) ⇒ Object



394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
# File 'lib/react_on_rails/system_checker.rb', line 394

def check_webpack_config_content(config_path)
  content = File.read(config_path)
  bundler_name = config_path.include?("rspack") ? "rspack" : "webpack"

  if react_on_rails_config?(content)
    add_success("#{bundler_name.capitalize} config includes React on Rails environment configuration")
    add_info("    ℹ️  Environment-specific configs detected for optimal React on Rails integration")
  elsif standard_shakapacker_config?(content)
    add_warning(<<~MSG.strip)
      ⚠️  Standard Shakapacker #{bundler_name} config detected.

      React on Rails works better with environment-specific configuration.
      Consider running: rails generate react_on_rails:install --force
      This adds client and server environment configs for better performance.
    MSG
  else
    add_info("ℹ️  Custom #{bundler_name} config detected")
    add_info("    💡 Ensure config supports both client and server rendering")
    add_info("    💡 Verify React JSX transformation is configured")
    add_info("    💡 Check that asset output paths match Rails expectations")
  end
end

#check_webpack_configurationObject

Webpack configuration validation



300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
# File 'lib/react_on_rails/system_checker.rb', line 300

def check_webpack_configuration
  config_path = detect_bundler_config_path
  if config_path
    add_success("✅ Bundler configuration exists (#{config_path})")
    check_webpack_config_content(config_path)
    suggest_webpack_inspection(config_path)
  else
    add_error(<<~MSG.strip)
      🚫 Bundler configuration not found.

      Expected one of: config/webpack/webpack.config.{js,ts} or config/rspack/rspack.config.{js,ts}
      Run: rails generate react_on_rails:install
    MSG
  end
end

#detect_bundler_config_pathObject



316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
# File 'lib/react_on_rails/system_checker.rb', line 316

def detect_bundler_config_path
  paths_by_bundler = {
    "rspack" => existing_bundler_config_paths("rspack"),
    "webpack" => existing_bundler_config_paths("webpack")
  }

  present_paths = paths_by_bundler.select { |_bundler, paths| paths.any? }
  return nil if present_paths.empty?
  return present_paths.values.first.first if present_paths.one?

  configured_bundler = configured_assets_bundler
  if configured_bundler && paths_by_bundler[configured_bundler].any?
    add_warning(
      "⚠️  Found both webpack and rspack configs. Using #{configured_bundler} from config/shakapacker.yml."
    )
    return paths_by_bundler[configured_bundler].first
  end

  # Default to webpack when shakapacker.yml doesn't declare assets_bundler.
  # Webpack is the longer-established default; rspack users typically set
  # assets_bundler explicitly in shakapacker.yml.
  add_warning(
    "⚠️  Found both webpack and rspack configs. Could not determine active bundler; defaulting to webpack."
  )
  paths_by_bundler["webpack"].first || paths_by_bundler["rspack"].first
end

#errors?Boolean

Returns:

  • (Boolean)


39
40
41
# File 'lib/react_on_rails/system_checker.rb', line 39

def errors?
  @messages.any? { |msg| msg[:type] == :error }
end

#suggest_webpack_inspection(config_path) ⇒ Object



343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
# File 'lib/react_on_rails/system_checker.rb', line 343

def suggest_webpack_inspection(config_path)
  bundler_name = config_path.include?("rspack") ? "rspack" : "webpack"
  export_style = config_path.end_with?(".ts") ? "export default" : "module.exports"

  add_info("💡 To debug #{bundler_name} builds:")
  add_info("    bin/shakapacker --mode=development --progress")
  add_info("    bin/shakapacker --mode=production --progress")
  add_info("    bin/shakapacker --debug-shakapacker  # Debug Shakapacker configuration")

  add_info("💡 Advanced #{bundler_name} debugging:")
  add_info("    1. Add 'debugger;' before '#{export_style}' in #{config_path}")
  add_info("    2. Run: ./bin/shakapacker --debug-shakapacker")
  add_info("    3. Open Chrome DevTools to inspect config object")
  add_info(
    "    📖 See: https://github.com/shakacode/shakapacker/blob/main/docs/troubleshooting.md#debugging-your-webpack-config"
  )

  add_info("💡 To analyze bundle size:")
  if bundle_analyzer_available?
    add_info("    ANALYZE=true bin/shakapacker")
    add_info("    This opens the configured bundle analyzer in your browser")
  elsif bundler_name == "webpack"
    add_info("    1. yarn add --dev webpack-bundle-analyzer")
    add_info("    2. Add to #{config_path}:")
    add_info("       const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');")
    add_info("       // Add to plugins array when process.env.ANALYZE")
    add_info("    3. ANALYZE=true bin/shakapacker")
  else
    add_info("    1. Install a compatible analyzer for your rspack setup")
    add_info("    2. Run: ANALYZE=true bin/shakapacker")
  end

  stats_file = bundler_name == "rspack" ? "rspack-stats.json" : "webpack-stats.json"
  add_info("💡 Generate #{bundler_name} stats for analysis:")
  add_info("    bin/shakapacker --json > #{stats_file}")
  add_info("    Upload to webpack.github.io/analyse or webpack-bundle-analyzer.com")
end

#warnings?Boolean

Returns:

  • (Boolean)


43
44
45
# File 'lib/react_on_rails/system_checker.rb', line 43

def warnings?
  @messages.any? { |msg| msg[:type] == :warning }
end