module Opal::Cache

def digest(string)

def digest(string)
  ::Digest::SHA256.hexdigest(string)[-32..-1].to_i(16).to_s(36)
end

def fetch(cache, key, &block)

def fetch(cache, key, &block)
  # Extension to the Sprockets API of Cache, if a cache responds
  # to #fetch, then we call it instead of using #get and #set.
  return cache.fetch(key, &block) if cache.respond_to? :fetch
  key = digest(key.join('/')) + '-' + runtime_key
  data = cache.get(key)
  data || begin
            compiler = yield
            cache.set(key, compiler) unless compiler.dynamic_cache_result
            compiler
          end
end

def runtime_key

def runtime_key
  @runtime_key ||= begin
    files = Opal.dependent_files
    digest [
      files.sort.map { |f| "#{f}:#{File.size(f)}:#{File.mtime(f).to_f}" },
      RUBY_VERSION,
      RUBY_PATCHLEVEL
    ].join('/')
  end
end