crawlscope 0.10.2 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 9f1e7d817608a6023e7230e5568408576f375733ff0e466ab0ae9119b72cae8a
4
- data.tar.gz: 4c645137855354cdb4847e641d78969a2f6014698d142c7a446b5555d4cbfbbb
3
+ metadata.gz: b4873e04bb4a26d3fb4bd2fa4e5f08f879a03391df0f4b95fa1c1c9d454c333f
4
+ data.tar.gz: 0c6712a5c9187adc383d988cd8702f28201652d515d085de9a3604f754bcf1ba
5
5
  SHA512:
6
- metadata.gz: e341bfed169b466693ec2bf72aec7ca53bc4c3ebabbc5935491ecd523b2edfb594a1bc44e16b3c22499c4a97ac4a1b70c4f0f42012933f652e7ea4bd1248c301
7
- data.tar.gz: 6421dbc9dc6e15882b08a61f1a73ee23f2cdd02dbfdfc87136be363d65ac844d852065b6ef1041908278008627ecc740f66e979fe9be7ec57cca6fa71f158b90
6
+ metadata.gz: 6c6bad08e6e1a60df82a9b17fadaa556f1acbab71e9e46af2065dddae0846546c3298fc5941297c1c1944c9d6161ecd155f8e4da423b60ab9600865b0d459eb7
7
+ data.tar.gz: f967564ccb9e3dace5fbda693cf674e1b69f741437b2204c05eb61684e1d062ec25e2a2079fc75335349fb13ec51c0f64bdacd46b3f00e53d5d1f6645a08edfc
data/CHANGELOG.md CHANGED
@@ -5,6 +5,15 @@ All notable changes to this project will be documented in this file.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## [0.11.0] - 2026-11-28
9
+
10
+
11
+ ### Added
12
+
13
+ - add internal link maps and reachability reports
14
+
15
+
16
+
8
17
  ## [0.10.2] - 2026-11-15
9
18
 
10
19
 
data/README.md CHANGED
@@ -30,6 +30,13 @@ The default rule set includes:
30
30
  - content-quality checks
31
31
  - internal-link checks
32
32
 
33
+ ## Internal link map
34
+
35
+ Run `crawlscope link-map --url https://example.com` to export a sitemap-based
36
+ internal link graph, inspect observed click depth, and compare expected links.
37
+ The command also supports CSV, DOT, and before/after snapshots. See the
38
+ [link map guide](docs/link-map.md) for CLI, Ruby, and Rails examples.
39
+
33
40
  ## Documentation
34
41
 
35
42
  This README and the linked repository guides describe the checked-out code.
data/UPGRADE.md CHANGED
@@ -37,6 +37,14 @@ in the README; the shared workflow does not inherit another gem's permission.
37
37
 
38
38
  ## Next Release
39
39
 
40
+ ### Validation console output
41
+
42
+ `crawlscope validate` and `crawlscope:validate` now show a link map summary
43
+ using the pages validation fetched. Exit codes are unchanged. If a script
44
+ expects the previous console output, pass `--no-link-map` to the CLI or set
45
+ `LINK_MAP=0` for Rake. Ruby callers can pass
46
+ `Crawlscope::Reporter.new(io: io, link_map: false)` to `Crawlscope::Run.new`.
47
+
40
48
  ### Review publication dates
41
49
 
42
50
  Standalone and nested reviews now accept a date (`2026-09-16`) or timestamp for
data/docs/link-map.md ADDED
@@ -0,0 +1,203 @@
1
+ # Internal link map
2
+
3
+ Use `link-map` to see where internal links appear, which pages have a verified
4
+ path from an entry root, and where observed links differ from your site's
5
+ manifest. The standalone command reads public HTML over HTTP and has its own
6
+ exit status. Validation prints a summary from the pages it already fetched.
7
+
8
+ ## CLI
9
+
10
+ ```bash
11
+ bundle exec crawlscope link-map --url https://www.example.com > before.json
12
+ bundle exec crawlscope link-map --url https://www.example.com \
13
+ --inventory search-console.csv --manifest links.json --root / --root /guides/ \
14
+ --view contextual --cluster onboarding --priority --format csv --table pairs
15
+ bundle exec crawlscope link-map --url https://www.example.com \
16
+ --follow-limit 200 --follow-depth 3 --exclude-path /account > discovered.json
17
+ ```
18
+
19
+ Supply the public site origin with `--url` or `URL`. The default sitemap is
20
+ `/sitemap.xml`. Use `--sitemap` or `SITEMAP` for a local file or a same-origin
21
+ sitemap URL. A local sitemap index reads child files from its own directory
22
+ tree. A remote index reads same-origin child URLs. Sitemap and robots requests
23
+ are crawl control files and can be outside the configured page path prefixes.
24
+ Use direct URLs for these files, since the command needs a response at the
25
+ specified sitemap URL and at `/robots.txt`.
26
+
27
+ Inventory accepts one URL per line or a UTF-8 CSV with a `URL`, `Page`,
28
+ `Pages`, or `Top pages` header. The inventory and manifest annotate the graph.
29
+ To fetch an inventory URL outside the sitemap, include it as an entry root or
30
+ enable link following and reach it through an observed link.
31
+
32
+ JSON contains nodes, individual link occurrences, unique directed
33
+ source–target pairs, expected edges, unrooted clusters, coverage exclusions,
34
+ and structured issues. Use `--format text` for a console summary with export
35
+ commands. CSV exports one table at a time. Choose `nodes`,
36
+ `occurrences`, `pairs`, `expected_edges`, or `issues`. Array and object fields use
37
+ JSON within their CSV cells. Spreadsheet formula prefixes are escaped in CSV.
38
+ A completed report returns status 0 even when it contains diagnostics or
39
+ partial coverage. Invalid configuration or an unreadable root sitemap returns 1.
40
+
41
+ ## Rake and validation summary
42
+
43
+ ```bash
44
+ bundle exec rake crawlscope:link_map URL=https://www.example.com > link-map.json
45
+ bundle exec rake 'crawlscope:link_map[https://www.example.com,sitemap.xml,csv,nodes]' > nodes.csv
46
+ bundle exec rake 'crawlscope:link_map[,,text]' URL=https://www.example.com
47
+ bundle exec rake crawlscope:validate URL=https://www.example.com
48
+ bundle exec crawlscope link-map --url https://www.example.com --format text
49
+ ```
50
+
51
+ The export task also works with `bin/rails crawlscope:link_map` and uses the host
52
+ configuration. Validation prints a link map summary by default, including
53
+ reachability, missing coverage, unique link pairs, contextual inlink gaps,
54
+ and commands for exporting JSON, CSV, DOT, and rendering SVG with Graphviz.
55
+ Rake runs show Rake export commands. CLI runs show CLI export commands.
56
+ The summary reuses the sitemap pages already fetched by validation, including
57
+ browser-rendered HTML when enabled. If validation did not fetch the entry
58
+ root, the summary flags the missing coverage. Standalone exports use their
59
+ own public HTTP crawl and can start at the entry root even when it is absent
60
+ from the sitemap. Validation issues determine the exit status. Use
61
+ `--no-link-map` on the CLI or `LINK_MAP=0` with Rake to hide the section.
62
+
63
+ ## Coverage and limits
64
+
65
+ - Every occurrence has its source, href with query and fragment removed,
66
+ normalized target, anchor text, image alt text, recognized `rel` values, and
67
+ position. A pair lists counts for all, contextual, and followable occurrences
68
+ between the same URLs. Contextual means an anchor inside `main`, `article`, or a
69
+ main landmark outside a navigation, footer, or sidebar landmark. Unmarked
70
+ links have position `unknown` in the all-link view. Inbound source counts
71
+ exclude links from a page to itself.
72
+ - Click depth is the fewest observed HTML link clicks from any entry root, with
73
+ roots at depth 0. A verified same-origin redirect can connect to its final
74
+ HTML response at the same depth. Link and page-level `nofollow` stay in the
75
+ report and are excluded from traversal. A `noindex` HTML page can still be
76
+ reachable. Indexability reflects the observed HTTP response, HTML, canonical,
77
+ and noindex directives. Coverage marked `unobserved`, `fetch_failed`,
78
+ `robots_disallowed`, `robots_unavailable`, or `page_limit` is partial evidence.
79
+ - `sitemap_reached` and `inventory_reached` record observed reachability for
80
+ each membership. A sitemap-only node has neither an observed path from a
81
+ root nor a recorded incoming link. Unreachable clusters group two or more
82
+ fetched HTML pages connected to each other by followable links with no
83
+ observed path from a root. A limit or failed fetch can hide paths. Sitemap
84
+ membership and inventory membership cannot reveal links on pages the crawl
85
+ did not fetch.
86
+ - Default requests cover the sitemap, the configured roots (default `/`), and
87
+ allowed redirects from those URLs. A positive `--follow-limit` adds a
88
+ breadth-first crawl of observed links from the entry roots. `--follow-depth`
89
+ caps which newly linked pages are requested. The total cap on starting page
90
+ requests is `--max-pages` (default 10,000), with up to five redirect hops per
91
+ request. `--max-edges` caps retained occurrences (default 100,000). Pages
92
+ are read in batches with a 5 MiB body limit. `outgoing_complete` is false
93
+ when the occurrence cap cut short a page's extraction. The sitemap reader caps sitemap
94
+ files at 100, distinct sitemap URLs at 100,000, and each sitemap body at 50
95
+ MiB. Exclusions and per-node coverage show where these limits applied.
96
+ - Requests use the explicit origin and allowed path prefixes, including
97
+ redirects. Supply repeated `--path` and `--exclude-path` flags to control the
98
+ public area being audited. Query URLs are excluded from requests and pair
99
+ counts. The export may retain a query-bearing occurrence with a sanitized
100
+ href, no target, and `query` coverage. Credentials, headers, bodies, and
101
+ cross-origin URL values are omitted from artifacts. Use a public origin
102
+ and keep private data out of published paths, anchor text, and manifest
103
+ labels, which are report fields.
104
+ - The command sends no authentication or profiling token. It reads
105
+ `robots.txt` directives for `Crawlscope`, falling back to `*`. The
106
+ longest matching Allow or Disallow rule wins, with Allow winning ties.
107
+ HTTP 404 and 410 indicate an absent policy. Other failures, redirects, and
108
+ invalid or oversized policies prevent page requests. [Robots Exclusion Protocol (RFC 9309)](https://www.rfc-editor.org/rfc/rfc9309.html)
109
+
110
+ ## Intended links and a before/after comparison
111
+
112
+ Name priority pages and topic clusters in a host-app manifest, then add the
113
+ specific links you expect:
114
+
115
+ ```json
116
+ {
117
+ "pages": {
118
+ "/guides/setup": {"priority": true, "page_type": "guide", "cluster": "onboarding"},
119
+ "/guides/getting-started": {"page_type": "overview", "cluster": "onboarding"}
120
+ },
121
+ "edges": [
122
+ {
123
+ "source": "/guides/getting-started",
124
+ "target": "/guides/setup",
125
+ "type": "next_step",
126
+ "position": "main",
127
+ "reason": "Readers need the setup steps after choosing an installation method."
128
+ }
129
+ ]
130
+ }
131
+ ```
132
+
133
+ A manifest edge matches its exact normalized source and target URLs, plus
134
+ `position` when supplied. `type` names the intended relationship for reviewers.
135
+ Include an `approved_exception` string to record the reason a missing edge is
136
+ acceptable. An expected link can be observed, missing, excepted, or unknown
137
+ when the source or edge coverage is incomplete.
138
+
139
+ Run the audit with the manifest and save a baseline:
140
+
141
+ ```bash
142
+ bundle exec crawlscope link-map --url https://www.example.com --manifest links.json > before.json
143
+ ```
144
+
145
+ If `/guides/setup` has
146
+ only a nav link and the report identifies the missing main-content link from
147
+ `/guides/getting-started`, add a descriptive link where that guide introduces
148
+ setup. Use the same roots, inputs, and crawl limits for the second snapshot:
149
+
150
+ ```bash
151
+ bundle exec crawlscope link-map --url https://www.example.com --manifest links.json > after.json
152
+ bundle exec crawlscope link-map diff before.json after.json > changes.json
153
+ ```
154
+
155
+ In the diff, look for the added pair or occurrence and an expected edge moving from
156
+ `missing` to `observed`. A smaller click depth is only expected when the new
157
+ link shortens the route. The measurements describe the audited HTML. Track
158
+ any impact on visitors and search performance separately.
159
+
160
+ Export DOT and use Graphviz's scalable layout to render the full graph:
161
+
162
+ ```bash
163
+ bundle exec crawlscope link-map --url https://www.example.com --format dot > links.dot
164
+ sfdp -Gsplines=line -Tsvg links.dot -o links.svg
165
+ ```
166
+
167
+ Boxes identify entry roots, dashed outlines identify URLs with no observed
168
+ click depth, and double borders identify priority pages. Edge labels give
169
+ occurrence counts. The `sfdp` engine uses straight edges to keep rendering
170
+ practical for dense graphs. To get a left-to-right diagram of a smaller graph,
171
+ filter by cluster or priority before rendering with
172
+ `dot -Tsvg links.dot -o links.svg`. These filters keep links touching the selected pages and keep the
173
+ neighboring nodes for context. Depth and inbound counts reflect the original
174
+ audit, even when a filter or contextual view hides links.
175
+
176
+ ## Ruby and Rails
177
+
178
+ ```ruby
179
+ require "crawlscope"
180
+ require "json"
181
+
182
+ report = Crawlscope::Run.new.link_map(
183
+ base_url: "https://www.example.com",
184
+ sitemap_path: "https://www.example.com/sitemap.xml",
185
+ roots: ["/"],
186
+ manifest: JSON.parse(File.read("links.json"))
187
+ )
188
+ report.to_h[:issues]
189
+ File.open("nodes.csv", "w") { |io| report.write(io, format: :csv, table: :nodes) }
190
+ ```
191
+
192
+ In a Rails app with the installed initializer, apply it inside a task or
193
+ runner script before calling `Run#link_map`:
194
+
195
+ ```ruby
196
+ CrawlscopeConfiguration.apply
197
+ report = Crawlscope::Run.new.link_map
198
+ File.open(Rails.root.join("tmp", "link-map.json"), "w") { |io| report.write(io) }
199
+ ```
200
+
201
+ The run uses the configured base URL, sitemap, timeout, concurrency, and fetch
202
+ executor. You can pass audit options directly as keywords. See the Rails
203
+ integration guide for how to configure the initializer. [Rails integration](rails.md)
data/docs/rails.md CHANGED
@@ -103,6 +103,15 @@ because async fetch execution is only supported with HTTP rendering.
103
103
 
104
104
  `crawlscope:validate:ldjson` is separate because it directly checks the URL or semicolon-separated URLs in `URL`; it does not crawl the sitemap. Without `URL`, it checks the configured base URL, falling back to `http://localhost:3000`.
105
105
 
106
+ ## Internal link map
107
+
108
+ Run `bin/rails crawlscope:link_map` to export JSON using the application's
109
+ sitemap settings. `bin/rails crawlscope:validate` includes the link map
110
+ summary using the pages it already fetched. Set `LINK_MAP=0` to hide the
111
+ summary. In a runner script or task, use
112
+ `Crawlscope::Run.new.link_map` after applying the generated configuration.
113
+ [Link map guide](link-map.md)
114
+
106
115
  ## Structured Data URL Audit
107
116
 
108
117
  For one-off structured-data checks:
@@ -8,13 +8,14 @@ module Crawlscope
8
8
  new(argv, out: out, err: err, **options).call
9
9
  end
10
10
 
11
- def initialize(argv, out:, err:, configuration: Configuration.new, task: nil)
11
+ def initialize(argv, out:, err:, configuration: Configuration.new, task: nil, invocation: :cli)
12
12
  @argv = Array(argv).dup
13
13
  @out = out
14
14
  @err = err
15
15
  @configuration = configuration
16
16
  @configuration.output = out
17
17
  @task = task
18
+ @invocation = invocation
18
19
  end
19
20
 
20
21
  def call
@@ -28,6 +29,8 @@ module Crawlscope
28
29
  run_validate
29
30
  when "ldjson"
30
31
  run_ldjson
32
+ when "link-map"
33
+ run_link_map
31
34
  when "version", "--version", "-v"
32
35
  @out.puts(Crawlscope::VERSION)
33
36
  0
@@ -37,7 +40,7 @@ module Crawlscope
37
40
  @err.puts(general_usage)
38
41
  1
39
42
  end
40
- rescue OptionParser::InvalidOption, OptionParser::MissingArgument, ConfigurationError, ArgumentError => error
43
+ rescue OptionParser::ParseError, ConfigurationError, ArgumentError => error
41
44
  @err.puts(error.message)
42
45
  @err.puts("")
43
46
  @err.puts(general_usage)
@@ -54,15 +57,88 @@ module Crawlscope
54
57
  Usage:
55
58
  crawlscope validate --url https://example.com [options]
56
59
  crawlscope ldjson --url https://example.com/page [options]
60
+ crawlscope link-map --url https://example.com [options]
61
+ crawlscope link-map diff BEFORE.json AFTER.json
57
62
  crawlscope version
58
63
 
59
64
  Commands:
60
65
  validate Audit URLs for metadata, structured data, uniqueness, and links
61
66
  ldjson Validate structured data on one or more URLs
67
+ link-map Inspect and compare internal link graphs
62
68
  version Print the gem version
63
69
  TEXT
64
70
  end
65
71
 
72
+ def run_link_map
73
+ return diff_link_maps if @argv.first == "diff"
74
+
75
+ options = {base_url: normalized_string(ENV["URL"]), sitemap_path: normalized_string(ENV["SITEMAP"])}
76
+ output = {}
77
+ manifest_path = inventory_path = nil
78
+
79
+ parser = OptionParser.new do |opts|
80
+ opts.banner = "Usage: crawlscope link-map --url https://example.com [options]"
81
+ opts.on("--url URL", "Site origin") { |value| options[:base_url] = value }
82
+ opts.on("--sitemap PATH_OR_URL", "Local or same-origin sitemap") { |value| options[:sitemap_path] = value }
83
+ opts.on("--root URL", "Entry root (repeatable, default /)") { |value| (options[:roots] ||= []) << value }
84
+ opts.on("--path PREFIX", "Allowed path prefix (repeatable)") { |value| (options[:paths] ||= []) << value }
85
+ opts.on("--exclude-path PREFIX", "Excluded path prefix (repeatable)") { |value| (options[:exclude_paths] ||= []) << value }
86
+ opts.on("--inventory PATH", "Additional URLs, one per line or in a CSV URL column") { |value| inventory_path = value }
87
+ opts.on("--manifest PATH", "Expected links and page metadata as JSON") { |value| manifest_path = value }
88
+ opts.on("--max-pages COUNT", Integer, "Cap starting page requests") { |value| options[:max_pages] = value }
89
+ opts.on("--max-edges COUNT", Integer, "Cap stored link occurrences") { |value| options[:max_edges] = value }
90
+ opts.on("--follow-limit COUNT", Integer, "Maximum additional link-discovered pages") { |value| options[:follow_limit] = value }
91
+ opts.on("--follow-depth COUNT", Integer, "Deepest newly discovered page to fetch") { |value| options[:follow_depth] = value }
92
+ opts.on("--format FORMAT", %w[json csv dot text], "Output format (default json)") { |value| output[:format] = value }
93
+ opts.on("--table TABLE", %w[nodes occurrences pairs expected_edges issues], "CSV table (default occurrences)") { |value| output[:table] = value }
94
+ opts.on("--view VIEW", %w[all contextual], "Link view (default all)") { |value| output[:view] = value }
95
+ opts.on("--cluster NAME", "Show links involving this topic cluster") { |value| output[:cluster] = value }
96
+ opts.on("--priority", "Show links involving priority pages") { output[:priority] = true }
97
+ opts.on("-h", "--help", "Show link-map options") do
98
+ @out.puts(opts)
99
+ return 0
100
+ end
101
+ end
102
+ parser.parse!(@argv)
103
+ raise ConfigurationError, "Unexpected link map arguments" unless @argv.empty?
104
+
105
+ options[:manifest] = read_link_map_json(manifest_path) if manifest_path
106
+ options[:inventory] = read_link_map_inventory(inventory_path) if inventory_path
107
+ task.link_map(**options).write(@out, sitemap_path: options[:sitemap_path] || @configuration.sitemap_path, invocation: @invocation, **output)
108
+ 0
109
+ rescue SystemCallError
110
+ raise ConfigurationError, "Unable to read link map input"
111
+ end
112
+
113
+ def diff_link_maps
114
+ @argv.shift
115
+ raise ConfigurationError, "Usage: crawlscope link-map diff BEFORE.json AFTER.json" unless @argv.size == 2
116
+
117
+ before, after = @argv.map { |path| read_link_map_json(path) }
118
+ @out.puts(JSON.generate(LinkMap::Report.diff(before, after)))
119
+ 0
120
+ end
121
+
122
+ def read_link_map_json(path)
123
+ require "json"
124
+ JSON.parse(File.read(path))
125
+ rescue JSON::ParserError, SystemCallError
126
+ raise ConfigurationError, "Unable to read link map JSON input"
127
+ end
128
+
129
+ def read_link_map_inventory(path)
130
+ return File.readlines(path, chomp: true).map(&:strip).reject(&:empty?) unless File.extname(path).casecmp?(".csv")
131
+
132
+ require "csv"
133
+ csv = CSV.read(path, headers: true, encoding: "bom|utf-8")
134
+ header = csv.headers.find { |name| %w[url page pages].include?(name.to_s.strip.downcase) || name.to_s.strip.casecmp?("top pages") }
135
+ raise ConfigurationError, "Link map inventory CSV needs a URL, Page, or Top pages header" unless header
136
+
137
+ csv[header].compact.map(&:strip).reject(&:empty?)
138
+ rescue CSV::MalformedCSVError
139
+ raise ConfigurationError, "Unable to read link map inventory CSV"
140
+ end
141
+
66
142
  def run_ldjson
67
143
  options = {
68
144
  debug: env_enabled?("DEBUG"),
@@ -127,6 +203,7 @@ module Crawlscope
127
203
 
128
204
  def run_validate
129
205
  options = {
206
+ link_map: ENV["LINK_MAP"] != "0",
130
207
  url: normalized_string(ENV["URL"]),
131
208
  rule_names: normalized_string(ENV["RULES"]),
132
209
  sitemap_path: normalized_string(ENV["SITEMAP"])
@@ -154,6 +231,10 @@ module Crawlscope
154
231
  options[:rule_names] = value
155
232
  end
156
233
 
234
+ opts.on("--[no-]link-map", "Show the link map from validation pages (default on)") do |value|
235
+ options[:link_map] = value
236
+ end
237
+
157
238
  opts.on("--renderer NAME", "Use http or browser rendering") do |value|
158
239
  configure_renderer(value.to_sym)
159
240
  end
@@ -179,7 +260,7 @@ module Crawlscope
179
260
  parser.parse!(@argv)
180
261
  @configuration.fetch_executor = :threaded if @configuration.renderer == :browser && !fetch_executor_configured
181
262
 
182
- result = task.validate(
263
+ result = task(link_map: options[:link_map]).validate(
183
264
  base_url: options[:url],
184
265
  sitemap_path: options[:sitemap_path],
185
266
  rule_names: options[:rule_names]
@@ -262,8 +343,8 @@ module Crawlscope
262
343
  [normalized_string(@configuration.base_url) || "http://localhost:3000"]
263
344
  end
264
345
 
265
- def task
266
- @task ||= Run.new(configuration: @configuration, reporter: Reporter.new(io: @out))
346
+ def task(link_map: true)
347
+ @task ||= Run.new(configuration: @configuration, reporter: Reporter.new(io: @out, link_map: link_map, invocation: @invocation))
267
348
  end
268
349
  end
269
350
  end
@@ -9,12 +9,14 @@ module Crawlscope
9
9
  class Http
10
10
  MAX_REDIRECTS = 5
11
11
  USER_AGENT = "Mozilla/5.0 (compatible; Crawlscope/1.0)"
12
+ BodyLimitExceeded = Class.new(Error)
12
13
 
13
- def initialize(base_url:, timeout_seconds:, adapter: nil, profile_token: nil)
14
+ def initialize(base_url:, timeout_seconds:, adapter: nil, profile_token: nil, follow_redirects: true)
14
15
  @base_url = base_url
15
16
  @timeout_seconds = timeout_seconds
16
17
  @adapter = adapter
17
18
  @profile_token = profile_token
19
+ @follow_redirects = follow_redirects
18
20
  @connections_by_thread = Concurrent::Map.new
19
21
  end
20
22
 
@@ -26,9 +28,18 @@ module Crawlscope
26
28
  @connections_by_thread.clear
27
29
  end
28
30
 
29
- def fetch(url)
31
+ def fetch(url, max_body_bytes: nil, parse_html: true)
32
+ streamed_body = +"".b if max_body_bytes
30
33
  response = connection.get(url) do |request|
31
34
  request.headers["User-Agent"] = USER_AGENT
35
+ if max_body_bytes
36
+ request.options.on_data = lambda do |chunk, size, _env|
37
+ raise BodyLimitExceeded, "Response exceeded its byte limit" if size > max_body_bytes
38
+
39
+ streamed_body.clear if size == chunk.bytesize
40
+ streamed_body << chunk
41
+ end
42
+ end
32
43
  RequestHeaders.add_profile_token(
33
44
  request.headers,
34
45
  url: url,
@@ -40,9 +51,9 @@ module Crawlscope
40
51
  final_url = response.env.url.to_s
41
52
  final_url = url if final_url.empty?
42
53
  headers = response.headers.to_h
43
- body = response.body.to_s
44
- doc = if response.status == 200 && html_response?(headers)
45
- Nokogiri::HTML(body)
54
+ body = streamed_body || response.body.to_s
55
+ doc = if parse_html && response.status == 200 && html_response?(headers)
56
+ Nokogiri::HTML(body, nil, streamed_body ? charset(headers) : nil)
46
57
  end
47
58
 
48
59
  Page.new(
@@ -55,7 +66,7 @@ module Crawlscope
55
66
  body: body,
56
67
  doc: doc
57
68
  )
58
- rescue Faraday::Error, SocketError, SystemCallError, Timeout::Error => error
69
+ rescue Faraday::Error, SocketError, SystemCallError, Timeout::Error, BodyLimitExceeded => error
59
70
  Page.new(
60
71
  url: url,
61
72
  normalized_url: Url.normalize(url, base_url: @base_url),
@@ -74,11 +85,13 @@ module Crawlscope
74
85
  def connection
75
86
  @connections_by_thread.compute_if_absent(Thread.current.object_id) do
76
87
  Faraday.new do |faraday|
77
- faraday.response(
78
- :follow_redirects,
79
- limit: MAX_REDIRECTS,
80
- callback: RequestHeaders.method(:strip_profile_token_on_cross_origin_redirect)
81
- )
88
+ if @follow_redirects
89
+ faraday.response(
90
+ :follow_redirects,
91
+ limit: MAX_REDIRECTS,
92
+ callback: RequestHeaders.method(:strip_profile_token_on_cross_origin_redirect)
93
+ )
94
+ end
82
95
  faraday.options.timeout = @timeout_seconds
83
96
  faraday.options.open_timeout = @timeout_seconds
84
97
  faraday.adapter @adapter if @adapter
@@ -87,8 +100,19 @@ module Crawlscope
87
100
  end
88
101
 
89
102
  def html_response?(headers)
90
- content_type = headers["content-type"] || headers.find { |key, _value| key.to_s.casecmp("content-type").zero? }&.last.to_s
91
- content_type.empty? || content_type.include?("text/html")
103
+ type = content_type(headers)
104
+ type.empty? || type.include?("text/html")
105
+ end
106
+
107
+ def charset(headers)
108
+ label = content_type(headers)[/;\s*charset\s*=\s*["']?([\w.-]+)/i, 1]
109
+ Encoding.find(label).name if label
110
+ rescue ArgumentError
111
+ nil
112
+ end
113
+
114
+ def content_type(headers)
115
+ headers["content-type"] || headers.find { |key, _value| key.to_s.casecmp("content-type").zero? }&.last.to_s
92
116
  end
93
117
  end
94
118
  end