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
# 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?

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

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

Instance Method Details

#add_package_json_build_scriptObject



257
258
259
260
261
# File 'lib/generators/svelte_on_rails/install/install_generator.rb', line 257

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



210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
# File 'lib/generators/svelte_on_rails/install/install_generator.rb', line 210

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



269
270
271
272
273
274
# File 'lib/generators/svelte_on_rails/install/install_generator.rb', line 269

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

#completed_noteObject



276
277
278
279
280
# File 'lib/generators/svelte_on_rails/install/install_generator.rb', line 276

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

#config_baseObject



248
249
250
251
252
253
254
255
# File 'lib/generators/svelte_on_rails/install/install_generator.rb', line 248

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



230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
# File 'lib/generators/svelte_on_rails/install/install_generator.rb', line 230

def initial_questions

  @vite_source_code_dir = SvelteOnRails::Lib::Utils.vite_source_code_dir
  if @vite_source_code_dir != 'app/frontend'
    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

#installer_noteObject



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

def installer_note
  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
  puts '=' * 80
end

#npm_package_to_application_jsObject



263
264
265
266
267
# File 'lib/generators/svelte_on_rails/install/install_generator.rb', line 263

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



84
85
86
87
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
# File 'lib/generators/svelte_on_rails/install/install_generator.rb', line 84

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
    say "✓ required npm packages are already installed", :green
    return
  end

  always_required_packages = [
    '@csedl/svelte-on-rails@latest',
    'typescript@latest',
    '@types/node@latest'
  ]

  candidate_sets = [
    [
      ('svelte@latest' unless svelte),
      ('vite@latest' unless vite),
      ('@sveltejs/vite-plugin-svelte@latest' unless vite_plugin_svelte)
    ].compact + always_required_packages,
    [
      'svelte@latest',
      'vite@latest',
      '@sveltejs/vite-plugin-svelte@latest'
    ] + always_required_packages,
    [
      '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

  failed_packages = []
  i = 0
  passing_set = candidate_sets.find do |packages_to_try|
    i += 1
    tit = if i == 1
            "Checking npm dependencies in isolated sandbox"
          else
            "FALLBACK #{i}"
          end
    r = SvelteOnRails::Installer::NpmSandbox.dry_run(
      packages_to_try,
      project_root: Rails.root.to_s,
      sandboxes_root: @sandboxes_dir,
      title: tit
    )
    @tmpdirs.push(r[:tmpdir])
    if r[:success]
      true
    else
      failed_packages.push(packages_to_try)
      false
    end
  end

  if passing_set.present?
    say "✓ Dependency check passed", :green
  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.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

  if passing_set.any?
    say "Ready to install:", :yellow unless svelte
    say "" + passing_set.join("\n • "), :yellow if passing_set.any?
    loop do
      break if @installation_type == :virgin
      say "Continue? (Y/n)", :yellow unless svelte
      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.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

#vite_railsObject



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

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