lib/svelte_on_rails/installer/vite.rb



module SvelteOnRails

  module Installer

    module Vite

      def self.install_vite
        iu = SvelteOnRails::Installer::Utils

        puts '-' * 80

        gu = SvelteOnRails::GemUtils
        if gu.check_gem_version('vite_rails')
          puts "vite_rails already installed, skipping this part."
        else

          # check non-existence

          iu.check_file_not_exists('config/vite.json')
          iu.check_file_not_exists('vite.config.ts')
          iu.check_folder_not_exists('app/frontend')

          # install

          gu.install_gem('vite_rails')

          Dir.chdir(Rails.root) do
            puts '++ running «bundle exec vite install» ++'
            `bundle exec vite install`
            puts '++ vite installer finished ++'
          end

        end

        # check existence

        iu.check_file_exists('config/vite.json')
        iu.check_file_exists('vite.config.ts')
        iu.check_file_exists('package.json')
        iu.check_file_exists('package-lock.json')
        iu.check_file_exists('app/frontend/entrypoints/application.js')
        iu.check_folder_exists('app/frontend')

        # check npm package version

        ni = SvelteOnRails::Installer::Npm
        ni.install_or_update_package('vite', minimal_version: [6, 1])

      end

      def self.configure_for_svelte

        # add import statement

        js_i = SvelteOnRails::Installer::Javascript
        pkg = '@sveltejs/vite-plugin-svelte'
        npm_i = SvelteOnRails::Installer::Npm
        npm_i.install_or_update_package(pkg)

        # add plugin

        file_path = 'vite.config.ts'

        if File.read(file_path).match?(/svelte/)
          puts "Svelte seams already configured in vite.config.ts, skipping here."
        else

          js_i.append_import_statement('vite.config.ts', pkg, "import {svelte} from '#{pkg}'")

          # Regex to match the plugins array and locate RubyPlugin()
          plugins_regex = /(plugins:\s*\[\s*)(\s*)RubyPlugin\(\),\s*([^\]]*?\])/m

          # Check if plugins array with RubyPlugin exists
          file_content = File.read(file_path)
          unless file_content.match?(plugins_regex)
            puts "Error: No plugins array with RubyPlugin() found in the input."
            return file_content
          end

          # Insert svelte({}), after RubyPlugin() with proper indentation
          modified_content = file_content.gsub(plugins_regex) do |match|
            prefix = $1 # Start of plugins array (e.g., "plugins: [")
            indent = '    ' # Indentation before RubyPlugin()
            rest = $3 # Remaining plugins and closing bracket
            "#{prefix}#{indent}RubyPlugin(),\n#{indent}svelte({}),\n#{indent}#{rest}"
          end

          File.write(file_path, modified_content)
          puts "Updated vite.config.ts with svelte() plugin."
        end
      end

    end
  end
end