Class: HTMLProofer::Middleware

Inherits:
Object
  • Object
show all
Includes:
Utils
Defined in:
lib/html-proofer/middleware.rb

Defined Under Namespace

Classes: InvalidHtmlError

Constant Summary collapse

HTML_SIGNATURE =
[
  '<!DOCTYPE HTML',
  '<HTML',
  '<HEAD',
  '<SCRIPT',
  '<IFRAME',
  '<H1',
  '<DIV',
  '<FONT',
  '<TABLE',
  '<A',
  '<STYLE',
  '<TITLE',
  '<B',
  '<BODY',
  '<BR',
  '<P',
  '<!--'
].freeze

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Utils

#create_nokogiri, #pluralize, #swap

Constructor Details

#initialize(app) ⇒ Middleware

Returns a new instance of Middleware.



28
29
30
# File 'lib/html-proofer/middleware.rb', line 28

def initialize(app)
  @app = app
end

Class Method Details

.optionsObject



17
18
19
20
21
22
23
24
25
26
# File 'lib/html-proofer/middleware.rb', line 17

def self.options
  @options ||= {
    type: :file,
    allow_missing_href: true, # Permitted in html5
    allow_hash_href: true,
    check_external_hash: true,
    check_html: true,
    url_ignore: [/.*/] # Don't try to check local files exist
  }
end

Instance Method Details

#call(env) ⇒ Object



52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/html-proofer/middleware.rb', line 52

def call(env)
  result = @app.call(env)
  return result if env['REQUEST_METHOD'] != 'GET'
  return result if env['QUERY_STRING'] =~ /proofer-ignore/
  return result if result.first != 200

  body = []
  result.last.each { |e| body << e }

  body = body.join('')
  begin
    html = body.lstrip
  rescue StandardError
    return result # Invalid encoding; it's not gonna be html.
  end
  if HTML_SIGNATURE.any? { |sig| html.upcase.start_with? sig }
    parsed = HTMLProofer::Runner.new(
      'response',
      Middleware.options
    ).check_parsed(
      Nokogiri::HTML5(html, max_errors: -1), 'response'
    )

    raise InvalidHtmlError, parsed[:failures] unless parsed[:failures].empty?
  end
  result
end