Class: SvelteOnRails::Generators::InstallGenerator

Inherits:
Rails::Generators::Base
  • Object
show all
Defined in:
lib/generators/svelte_on_rails/install/install_generator.rb

Instance Method Summary collapse

Constructor Details

#initialize(*args) ⇒ InstallGenerator

Returns a new instance of InstallGenerator.



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/generators/svelte_on_rails/install/install_generator.rb', line 14

def initialize(*args)

  super
  validate_raw_options!(args)
  @utils = SvelteOnRails::Installer::Utils
  @gem_utils = SvelteOnRails::GemUtils
  @npm_utils = SvelteOnRails::Installer::Npm
  @template_placeholders = []
  @tmpdirs = []
  @sandboxes_dir = Rails.root.join('tmp', 'svelte-on-rails-installer-sandbox-tests')
  FileUtils.rm_rf(@sandboxes_dir) if @sandboxes_dir.exist?

  nvi = [
    'config/svelte_on_rails.yml',
    'config/vite.json',
    'vite.config.ts',
    'vite-ssr.config.ts',
  ].find { |f| Rails.root.join(f).exist? }
  if nvi
    @non_virgin_indicator = "#{nvi} found"
  elsif @gem_utils.vite_rails_in_gemfile?
    @non_virgin_indicator = 'vite_rails found in Gemfile'
  end

  @installation_type = if options[:force]
                         :force
                       elsif !@non_virgin_indicator
                         :virgin
                       else
                         :careful
                       end
end

Instance Method Details

#add_package_json_build_scriptObject



288
289
290
291
292
# File 'lib/generators/svelte_on_rails/install/install_generator.rb', line 288

def add_package_json_build_script
  pkg_js = JSON.parse(File.read('package.json'))
  pkg_js['scripts'] ||= { 'build:ssr': "vite build --config vite-ssr.config.ts" }
  File.write('package.json', JSON.pretty_generate(pkg_js))
end

#add_svelte_to_vite_configObject



241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
# File 'lib/generators/svelte_on_rails/install/install_generator.rb', line 241

def add_svelte_to_vite_config
  path = Rails.root.join('vite.config.ts')
  return unless path.exist?

  source = File.read(path)
  return if source.match?(/plugins\s*:\s*\[[\s\S]*?\bsvelte\s*\(/m)
  unless [:virgin, :force].include?(@installation_type)
    return unless @utils.ask_yn('vite.config.ts has no svelte() plugin. Add it now?')
  end

  r = @utils.edit_vite_config_ts(path)

  if r[:success]
    say 'Added svelte() and @sveltejs/vite-plugin-svelte import to vite.config.ts', :green
  else
    say 'ERROR: Failed to add svelte() and @sveltejs/vite-plugin-svelte import to vite.config.ts', :red
    exit(1)
  end
end

#cleanupObject



300
301
302
303
304
305
# File 'lib/generators/svelte_on_rails/install/install_generator.rb', line 300

def cleanup
  if @sandboxes_dir.exist?
    FileUtils.rm_rf(@sandboxes_dir)
    say "Removed #{@sandboxes_dir}", :green
  end
end

#completed_noteObject



307
308
309
310
311
# File 'lib/generators/svelte_on_rails/install/install_generator.rb', line 307

def completed_note
  puts '-' * 80
  puts ' ▶︎▶︎▶︎ INSTALLATION COMPLETE'
  puts '-' * 80
end

#config_baseObject



279
280
281
282
283
284
285
286
# File 'lib/generators/svelte_on_rails/install/install_generator.rb', line 279

def config_base
  @utils.write_templates(
    ['config_base'],
    ask_for_overwrite: !options[:force],
    placeholders: @template_placeholders,
    vite_dir: @vite_source_code_dir
  )
end

#initial_questionsObject



261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
# File 'lib/generators/svelte_on_rails/install/install_generator.rb', line 261

def initial_questions

  @vite_source_code_dir = SvelteOnRails::Lib::Utils.vite_source_code_dir
  if @vite_source_code_dir != 'app/frontend' && @installation_type == :careful
    say "WARNING: The Vite source code directory is «#{@vite_source_code_dir}», instead of the usual «app/frontend», in config/vite.json.", :yellow
    q = "         Do you want to continue with «#{@vite_source_code_dir}»?"
    exit(0) unless @utils.ask_yn(q)
  end

  @template_placeholders.push(['$$vite-source-code-dir$$', @vite_source_code_dir])

  unless @utils.write_templates(['config_base'], ask_for_overwrite: !options[:force], dry_run: true)
    say "Installation aborted.", :red
    exit(0)
  end

end

#npm_package_to_application_jsObject



294
295
296
297
298
# File 'lib/generators/svelte_on_rails/install/install_generator.rb', line 294

def npm_package_to_application_js
  js_i = SvelteOnRails::Installer::Javascript
  init_stat = '@csedl/svelte-on-rails'
  js_i.append_import_statement(application_js_path, init_stat, "import '#{init_stat}';")
end

#npm_packagesObject



88
89
90
91
92
93
94
95
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
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
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
212
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
# File 'lib/generators/svelte_on_rails/install/install_generator.rb', line 88

def npm_packages

  # check vite-rails installation

  svelte = @npm_utils.inspect_package('svelte')
  vite = @npm_utils.inspect_package('vite')
  vite_plugin_svelte = @npm_utils.inspect_package('@sveltejs/vite-plugin-svelte')

  if svelte && vite && vite_plugin_svelte && !@installation_type == :force
    if @package_set
      say "Packages are already installed but force to #{@package_set}", :yellow
    else
      say "✓ required npm packages are already installed", :green
      return
    end
  end

  candidate_sets = [
    {
      key: :minimal,
      title: 'Install missing packages only',
      set: [
        ('svelte@latest' unless svelte),
        ('vite@latest' unless vite),
        ('@sveltejs/vite-plugin-svelte@latest' unless vite_plugin_svelte),
        '@csedl/svelte-on-rails@latest',
        'typescript@latest',
        '@types/node@latest'
      ].compact
    },
    {
      key: :latest,
      title: 'Force latest package versions',
      set: [
        'svelte@latest',
        'vite@latest',
        '@sveltejs/vite-plugin-svelte@latest',
        '@csedl/svelte-on-rails@latest',
        'typescript@latest',
        '@types/node@latest'
      ]
    },
    {
      key: :pinned,
      title: 'Use pinned compatible versions',
      set: [
        'svelte@~5.55.4',
        'vite@~8.0.8',
        '@sveltejs/vite-plugin-svelte@~7.0.0',
        '@csedl/svelte-on-rails@latest',
        'typescript@~6.0.2',
        '@types/node@~25.6.0'
      ]
    }
  ]

  # test install

  dependencies_checked = false
  failed_packages = []
  set_keys = candidate_sets.map { |s| s[:key] }
  if @package_set && !set_keys.include?(@package_set)
    raise Thor::Error, "Invalid value for --package-set option: #{@package_set}, valid options are: #{set_keys.join(', ')}"
  end
  index = 0
  unless @package_set && @installation_type == :force
    puts "[Sandbox test] Running dependency checks in a isolated Sandbox within App-root/tmp"
  end
  passing_set = candidate_sets.find do |set_to_try|
    title_suffix = (index == 0) ? ' (default)' : " (FALLBACK)"
    index += 1
    if @package_set && set_to_try[:key] != @package_set
      next
    elsif @package_set && set_to_try[:key] == @package_set && @installation_type == :force
      true
    else

      r = SvelteOnRails::Installer::NpmSandbox.dry_run(
        set_to_try[:set],
        project_root: Rails.root.to_s,
        sandboxes_root: @sandboxes_dir,
        title: set_to_try[:title] + title_suffix
      )
      @tmpdirs.push(r[:tmpdir])
      if r[:success] || @package_set && set_to_try[:key] == @package_set
        dependencies_checked = true
        true
      else
        failed_packages.push(set_to_try)
        false
      end
    end
  end

  if passing_set.present?
    say "✓ Dependency check passed", :green if dependencies_checked
  else
    say '-' * 80
    say "ERROR: Unable to fix dependency issues", :red
    say "Tried to test-installation within a TempDir, outside the project.", :red
    say "Theese attemtpts failed to install required packages:", :red
    say "#{failed_packages[:set].map { |p| p.join(' + ') }.join("\n • ")}", :red
    say "Installer cannot continue.", :red
    say "You must install theese packages and resolve dependency issues manually.", :red
    say "After resolved it, you can run this command again.", :red
    say "The failed sandbox tests you can find in tmp/svelte-on-rails-installer-sandboxes", :red
    exit 1
  end

  # prompt developer

  say "Using Package-set: #{passing_set[:title]}", :yellow if passing_set.present?
  if passing_set.any? && @installation_type != :force
    say "Ready to install:", :yellow
    loop do
      say "Continue? (Y/n)", :yellow
      input = STDIN.gets
      answer = input.strip.downcase
      if answer == "n" || answer == "no"
        say "Installation aborted.", :red
        exit(0)
      elsif answer == "y" || answer == "yes"
        break
      end
    end
  end

  # install packages

  passing_set[:set].each do |package|

    stdout, stderr, status = Open3.capture3("npm install #{package}", chdir: Rails.root)

    success_regex = /
        (?:^|\n)\s*(?:added|changed|removed|up\ to\ date)\b[^\n]*\n
        [\s\S]*?
        (?:^|\n)\s*found\s+\d+\s+vulnerabilities?\b
      /ix

    if status.success? && stdout.match?(success_regex)
      say "#{package}", :green
    else
      puts "#{package}"
      puts '-' * 80
      puts stdout
      puts '-' * 80
      warn stderr unless stderr.to_s.strip.empty?
      puts '-' * 80
    end
  end

end


47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/generators/svelte_on_rails/install/install_generator.rb', line 47

def print_header
  puts
  puts '=' * 80
  puts ' ▶︎▶︎▶︎ INSTALLING SVELTE-ON-RAILS'
  if @installation_type == :force
    puts "  • FORCED (option --force was given)"
  elsif @installation_type == :virgin
    puts "  • Virgin installation"
  elsif @installation_type == :careful
    puts "  • Careful installation (#{@non_virgin_indicator})"
  end
  if @package_set
    puts "  • Package set: #{@package_set}"
  end
  puts '=' * 80
end

#vite_railsObject



64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/generators/svelte_on_rails/install/install_generator.rb', line 64

def vite_rails

  vite_installed = Rails.root.join('config', 'vite.json').exist? && Rails.root.join('vite.config.ts').exist?

  if @gem_utils.vite_rails_in_gemfile?
    say "✓ vite_rails gem already present in Gemfile", :green
  else
    say '-' * 80, :yellow
    say "Adding vite_rails gem to Gemfile...", :yellow
    @gem_utils.install_gem('vite_rails', force: true)
  end

  if vite_installed
    say "✓ vite_rails installer appears to have already run (found config/vite.json and vite.config.ts)", :green
    return
  end

  say '-' * 80, :yellow
  say "running: bundle exec vite install...", :yellow
  stdout, stderr, status = Open3.capture3('bundle exec vite install', chdir: Rails.root)
  puts stdout
  raise(stderr.presence || "bundle exec vite install failed") unless status.success?
end