Class: ReactOnRails::SystemChecker

Inherits:
Object
  • Object
show all
Includes:
ConfigPathResolver, ShakapackerConfigHelpers
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

Defined Under Namespace

Classes: PackageManagerDetection

Constant Summary collapse

SUPPORTED_ASSETS_BUNDLERS =
ShakapackerConfigHelpers::SUPPORTED_ASSETS_BUNDLERS

Constants included from ShakapackerConfigHelpers

ReactOnRails::ShakapackerConfigHelpers::DEFAULT_SHAKAPACKER_CONFIG_PATH

Constants included from ConfigPathResolver

ConfigPathResolver::ALL_DEFAULT_CONFIG_CANDIDATES, ConfigPathResolver::RSPACK_DEFAULT_CONFIG_CANDIDATES, ConfigPathResolver::WEBPACK_DEFAULT_CONFIG_CANDIDATES

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeSystemChecker

Returns a new instance of SystemChecker.



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

def initialize
  @messages = []
end

Instance Attribute Details

#messagesObject (readonly)

Returns the value of attribute messages.



17
18
19
# File 'lib/react_on_rails/system_checker.rb', line 17

def messages
  @messages
end

Instance Method Details

#add_error(message) ⇒ Object



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

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

#add_info(message) ⇒ Object



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

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

#add_success(message) ⇒ Object



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

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

#add_warning(message) ⇒ Object



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

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

#bundle_analyzer_available?Boolean

Returns:

  • (Boolean)


397
398
399
400
401
402
403
404
405
406
407
408
# File 'lib/react_on_rails/system_checker.rb', line 397

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



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

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



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

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



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
131
132
133
134
135
136
# File 'lib/react_on_rails/system_checker.rb', line 99

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
  package_manager_detection = detect_package_manager_from_lockfile
  used_manager = package_manager_detection.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(', ')}")
    unless package_manager_detection.lockfile_scan_blocked
      add_info("ℹ️  No lock file detected - run npm/yarn/pnpm install to establish which manager is used")
    end
  end
  true
end

#check_package_version_syncObject



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
# File 'lib/react_on_rails/system_checker.rb', line 221

def check_package_version_sync
  package_json_path = package_json_path_for("React on Rails package version sync")
  return unless 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)

    # Skip workspace/local-link specs and non-exact range specs silently.
    # Non-exact version checks are handled by Doctor#check_version_wildcards
    # to avoid duplicate diagnostics.
    return if npm_version.match?(/\A(?:workspace:|file:|link:|npm:)/)
    return if non_exact_range_spec?(npm_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})")
    else
      report_version_mismatch(package_name, npm_version, normalized_npm_version, gem_version)
    end
  rescue JSON::ParserError
    # Ignore parsing errors, already handled elsewhere
  rescue StandardError
    # Handle other errors gracefully
  end
end

#check_react_dependenciesObject

React dependencies validation



290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
# File 'lib/react_on_rails/system_checker.rb', line 290

def check_react_dependencies
  package_json_path = package_json_path_for("React dependencies")
  return unless package_json_path

  package_json = parse_package_json(package_json_path)
  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)
  report_bundler_version
end

#check_react_on_rails_gemObject



186
187
188
189
190
191
192
193
194
195
196
197
198
# File 'lib/react_on_rails/system_checker.rb', line 186

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



312
313
314
315
316
317
318
319
320
321
322
323
324
# File 'lib/react_on_rails/system_checker.rb', line 312

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



200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
# File 'lib/react_on_rails/system_checker.rb', line 200

def check_react_on_rails_npm_package
  package_json_path = package_json_path_for("react-on-rails npm package")
  return unless 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 NOTE: Wildcard/non-exact version checks (Gemfile and npm) are handled by Doctor#check_version_wildcards to avoid duplicate error messages.



180
181
182
183
184
# File 'lib/react_on_rails/system_checker.rb', line 180

def check_react_on_rails_packages
  check_react_on_rails_gem
  check_react_on_rails_npm_package
  check_package_version_sync
end

#check_shakapacker_configurationObject

Shakapacker validation



139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
# File 'lib/react_on_rails/system_checker.rb', line 139

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}
      • assets_bundler_config_path target declared by Shakapacker (when configured)

      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



162
163
164
165
166
167
168
169
170
171
172
173
174
175
# File 'lib/react_on_rails/system_checker.rb', line 162

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



410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
# File 'lib/react_on_rails/system_checker.rb', line 410

def check_webpack_config_content(config_path)
  content = File.read(config_path)
  bundler_name = bundler_name_for_config_path(config_path)

  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



327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
# File 'lib/react_on_rails/system_checker.rb', line 327

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}
      Also checks Shakapacker's configured assets_bundler_config_path when available.
      Run: rails generate react_on_rails:install
    MSG
  end
end

#detect_bundler_config_pathObject



344
345
346
347
348
349
350
351
352
353
354
355
356
357
# File 'lib/react_on_rails/system_checker.rb', line 344

def detect_bundler_config_path
  resolved_config_path = resolved_webpack_config_path
  return nil unless resolved_config_path
  # Explicit shakapacker assets_bundler_config_path matches are treated as
  # authoritative and intentionally bypass cross-bundler ambiguity warnings.
  return resolved_config_path if explicit_shakapacker_bundler_config_path?(resolved_config_path)

  # Re-scan candidate configs by bundler so we can emit clear warnings when
  # both webpack and rspack configs exist in the project. If a future
  # candidate falls outside the `<bundler>.config.*` naming convention used
  # by `existing_bundler_config_paths`, fall back to the originally
  # discovered file.
  resolve_default_bundler_config_path || resolved_config_path
end

#errors?Boolean

Returns:

  • (Boolean)


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

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

#non_exact_range_spec?(npm_version) ⇒ Boolean

Returns:

  • (Boolean)


256
257
258
# File 'lib/react_on_rails/system_checker.rb', line 256

def non_exact_range_spec?(npm_version)
  npm_version.match?(/\A[\^~><*]/) || npm_version.include?(" ")
end

#report_version_mismatch(package_name, npm_version, normalized_npm_version, gem_version) ⇒ Object



260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
# File 'lib/react_on_rails/system_checker.rb', line 260

def report_version_mismatch(package_name, npm_version, normalized_npm_version, gem_version)
  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.

      Fix: bundle exec rake react_on_rails:sync_versions WRITE=true
    MSG
  else
    add_error(<<~MSG.strip)
      🚫 Version mismatch detected:
      • Gem version: #{gem_version}
#{package_name} version: #{npm_version}

      The gem and npm package versions must match exactly. Mismatched versions
      will cause a runtime error on app startup.

      Fix: bundle exec rake react_on_rails:sync_versions WRITE=true
    MSG
  end
end

#suggest_webpack_inspection(config_path) ⇒ Object



359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
# File 'lib/react_on_rails/system_checker.rb', line 359

def suggest_webpack_inspection(config_path)
  bundler_name = bundler_name_for_config_path(config_path)
  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)


46
47
48
# File 'lib/react_on_rails/system_checker.rb', line 46

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