# frozen_string_literal: true require 'English' module SewingKit module Webpack class Dev class NodeSewingKitNotInstalled < StandardError def initialize super( "sewing-kit is not installed. " \ "Try `yarn add @shopify/sewing-kit`" ) end end attr_accessor :pid def start @pid = spawn at_exit { handle_exit } detach end private def spawn Kernel.spawn( { 'NODE_ENV' => 'development', 'BLUEBIRD_DEBUG' => '0', 'BLUEBIRD_LONG_STACK_TRACES' => '0', }, command, chdir: Rails.root.to_s, out: $stdout, err: $stderr, ) || exit(1) end def handle_exit return if $ERROR_INFO.nil? Process.kill 'SIGTERM', pid rescue Errno::ESRCH nil end def detach Process.detach pid end def command command_list = [ sewing_kit_bin, 'dev', '--logLevel', log_level, ].concat(options) if debug_mode? command_list.push(['--debug']) end command_list.join(' ') end def sewing_kit_bin heap_size = SewingKit.configuration.development_options[:heap] heap_config = if heap_size "node --max-old-space-size=#{heap_size} " end bin = "#{heap_config}#{SewingKit.configuration.dev_server_sewing_kit_bin}" raise NodeSewingKitNotInstalled unless File.exist?(bin) bin end def log_level if SewingKit.configuration.log_level == :inherit log_level_from_rails else SewingKit.configuration.log_level.to_s end end def options development_options = SewingKit.configuration.development_options || {} focus = focus_sections development_options .reject { |key| key == :heap } .map { |key, value| ["--#{key.to_s.tr('_', '-')}", value] }.flatten + focus.flatten end def log_level_from_rails case Rails.logger.level when 0 :debug when 1 :info when 2 :warn else :error end end def debug_mode? !ENV['SK_DEBUG'].nil? end def focus_sections return [] if ENV['SK_FOCUS'].nil? ENV['SK_FOCUS'] .split(',') .map { |section| ["--focus", section] } end end end end