class SvelteOnRails::Lib::Utils

def self.precompile(last_mtime = nil)

def self.precompile(last_mtime = nil)
  config = SvelteOnRails::Configuration.instance
  mtime = (File.exist?(config.ssr_dist_folder.join('last_mtime')) ? File.read(config.ssr_dist_folder.join('last_mtime')).to_f : 0.0)
  Dir.chdir(config.rails_root) do
    # run build
    cmd = "./node_modules/.bin/vite build --config vite-ssr.config.ts"
    stdout, stderr, status = Open3.capture3(cmd)
    mtime2 = (File.exist?(config.ssr_dist_folder.join('last_mtime')) ? File.read(config.ssr_dist_folder.join('last_mtime')).to_f : 0.0)
    # error handling
    if stderr.present?
      nothing_done = mtime2 == mtime
      color = (nothing_done ? "\033[97;41m" : "\033[30;106m")
      msg = "  +++  #{nothing_done ? 'ERROR' : 'WARNING'} compiling Svelte components#{nothing_done ? ' failed' : ''}#{cmd}»)  +++  "
      puts "#{color}#{msg}\033[0m"
      errs = stderr.split("\n")
      errs.each { |e| puts "#{color}  \033[0m #{e}" }
      puts "#{color}  +++  End of error message  +++  \033[0m"
      puts "#{color}  +++  Run «npm run build:ssr» on the console to see the original error message  +++  \033[0m"
      if nothing_done
        critical_lines = errs.select { |e| e.match(/Could not resolve/i) }
        cl_str = if critical_lines.present?
               "#{critical_lines.join("\n")}\n\n"
             end
        raise "Svelte components compilation failed\n\n#{cl_str}Full message:\n+++\n#{stderr}+++\n\nYou can run «npm run build:ssr» on the console to see the original error message\n"
      end
    end
    puts stdout
  end
  unless Dir.exist?(config.ssr_dist_folder)
    raise "Could not find dist folder: #{config.ssr_dist_folder}"
  end
  if last_mtime
    mtime_path = config.ssr_dist_folder.join('last_mtime')
    File.write(mtime_path, last_mtime.to_s)
  end
end