url_extract 0.1.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 ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: a7f4c3905e79eaad75e82c76fb1ca193d3badfbff09e43b5d768dc548742d138
4
+ data.tar.gz: 553127a23ec1cd59622a353ce7f7dbc4d736a8610443f6db2eae8fa8d8020c20
5
+ SHA512:
6
+ metadata.gz: f3d51171a76be54b832fc6686d332ed832afe57a65b58ebde73a9718064df32f625e3cab6d24521771cc9b983a6f7f98596766a566d297e8456581972853a2df
7
+ data.tar.gz: 2ea3b375e191f959236163aac1a83e0778537a442a4628c3c59e920ef13f39fa047610b5c296d0c5c0680129f90419d034f4a5f27758205904187d24258eb378
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2026 Andrey
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,202 @@
1
+ # UrlExtract
2
+
3
+ Find and extract URLs from plain text:
4
+
5
+ - Trims punctuation
6
+ - Reads non-ASCII URLs, such as `https://ru.wikipedia.org/wiki/Привет`
7
+ - Keeps only paired brackets
8
+ - Gives the position of each URL
9
+ - Reads localhost and IP URLs
10
+ - Thread-safe and Ractor-ready
11
+ - Linear time, no dependencies
12
+
13
+ ## Usage
14
+
15
+ ```ruby
16
+ UrlExtract.scan("See https://example.com/x").map(&:url)
17
+ # => ["https://example.com/x"]
18
+ ```
19
+
20
+ `UrlExtract.scan` returns an enumerable of the matches, so each `Enumerable` method works:
21
+ `each`, `map`, `first(3)`, `to_a`, `count`, `all?` and the others. It reads the text only as far as it needs:
22
+ `first(3)` stops at the third URL.
23
+
24
+ `UrlExtract.(text)` is short for `UrlExtract.scan(text)`:
25
+
26
+ ```ruby
27
+ UrlExtract.("See https://example.com/x, https://example.org/y and https://example.net/z").first(2).map(&:url)
28
+ # => ["https://example.com/x", "https://example.org/y"]
29
+ ```
30
+
31
+ ```ruby
32
+ UrlExtract.scan("See https://example.com/x").each do |match|
33
+ match.url # => "https://example.com/x"
34
+ match.range # => 4...25
35
+ match.text # => "See https://example.com/x"
36
+ end
37
+ ```
38
+
39
+ To replace URLs, always use `reverse_each`. A replacement changes the length of the text and moves each match
40
+ after it; from the last match to the first, each range still points at its URL:
41
+
42
+ ```ruby
43
+ text = "See https://example.com/x and https://example.org/y"
44
+ UrlExtract.scan(text).reverse_each do |match|
45
+ text[match.range] = %(<a href="#{match.url}">#{match.url}</a>)
46
+ end
47
+ puts text
48
+ # See <a href="https://example.com/x">https://example.com/x</a> and <a href="https://example.org/y">https://example.org/y</a>
49
+ ```
50
+
51
+ ## Options
52
+
53
+ The defaults are a great start: try them first, and change an option only when a text needs it.
54
+
55
+ ```ruby
56
+ default_options = {
57
+ prefixes: %w[https:// http://], # what starts a URL
58
+ max_bytesize: 8000, # the largest URL, in bytes
59
+ trim: %w[? ! . , : ; * _ ~], # the strings to remove from the end of a URL
60
+ trim_html_entities: true, # remove an HTML entity from the end of a URL
61
+ trim_brackets: true, # remove a bracket with no partner from the end of a URL
62
+ on_encoding_error: :warn # a text not readable as UTF-8 gives no match, and a warning
63
+ }
64
+
65
+ UrlExtract.scan(text)
66
+
67
+ # same as
68
+ UrlExtract.scan(text, **default_options)
69
+ ```
70
+
71
+ Each option, with examples:
72
+
73
+ ```ruby
74
+ # :prefixes - what starts a URL; www. and localhost: only at the start of a word
75
+ text = "See www.example.com, localhost:3000/x and https://example.com/x"
76
+ UrlExtract.scan(text).map(&:url)
77
+ # => ["https://example.com/x"]
78
+
79
+ UrlExtract.scan(text, prefixes: %w[https:// http:// www. localhost:]).map(&:url)
80
+ # => ["www.example.com", "localhost:3000/x", "https://example.com/x"]
81
+
82
+ # :max_bytesize - the largest URL, in bytes; a longer URL gives no match, and nil sets no limit
83
+ UrlExtract.scan("https://example.com/x https://example.com/very/long/path", max_bytesize: 25).map(&:url)
84
+ # => ["https://example.com/x"]
85
+
86
+ UrlExtract.scan("https://example.com/x https://example.com/very/long/path", max_bytesize: nil).map(&:url)
87
+ # => ["https://example.com/x", "https://example.com/very/long/path"]
88
+
89
+ # :trim - the strings to remove from the end of a URL
90
+ UrlExtract.scan("See https://example.com/x.", trim: []).map(&:url)
91
+ # => ["https://example.com/x."]
92
+
93
+ UrlExtract.scan("See https://example.com/x...", trim: %w[...]).map(&:url)
94
+ # => ["https://example.com/x"]
95
+
96
+ # :trim_html_entities - false keeps an HTML entity at the end of a URL
97
+ UrlExtract.scan("&quot;https://example.com/x&quot;", trim_html_entities: false).map(&:url)
98
+ # => ["https://example.com/x&quot;"]
99
+
100
+ # :trim_brackets - false keeps a bracket with no partner at the end of a URL
101
+ UrlExtract.scan("(https://example.com/x)", trim_brackets: false).map(&:url)
102
+ # => ["https://example.com/x)"]
103
+
104
+ # :on_encoding_error - a text not readable as UTF-8 gives no match; :warn also warns
105
+ UrlExtract.scan("https://example.com/\xFF").to_a
106
+ # => []
107
+
108
+ UrlExtract.scan("https://example.com/\xFF", on_encoding_error: :skip).to_a
109
+ # => []
110
+
111
+ UrlExtract.scan("https://example.com/\xFF", on_encoding_error: :raise)
112
+ # raises UrlExtract::EncodingError
113
+ ```
114
+
115
+ ## Raised errors
116
+
117
+ A text that can not be read as UTF-8 gives no match, and a warning:
118
+
119
+ ```ruby
120
+ UrlExtract.scan("https://example.com/\xFF").to_a
121
+ # => []
122
+ # warning: url_extract: Invalid text: can not be read as UTF-8 (encoding UTF-8, index 20)
123
+ # [hint] Provide a valid UTF-8 string
124
+ ```
125
+
126
+ To get an error instead, set `on_encoding_error: :raise`:
127
+
128
+ ```ruby
129
+ UrlExtract.scan("https://example.com/\xFF", on_encoding_error: :raise)
130
+ # UrlExtract::EncodingError: Invalid text: can not be read as UTF-8 (encoding UTF-8, index 20)
131
+ # [hint] Provide a valid UTF-8 string
132
+ ```
133
+
134
+ ## Corner cases
135
+
136
+ ```ruby
137
+ # Punctuation after a URL
138
+ UrlExtract.scan("Is it https://example.com/x?!").map(&:url)
139
+ # => ["https://example.com/x"]
140
+
141
+ # Brackets around a URL, and the URL's own brackets
142
+ UrlExtract.scan("(See https://en.wikipedia.org/wiki/Ruby_(programming_language))").map(&:url)
143
+ # => ["https://en.wikipedia.org/wiki/Ruby_(programming_language)"]
144
+
145
+ # An HTML entity around a URL
146
+ UrlExtract.scan("&quot;https://example.com/x&quot;").map(&:url)
147
+ # => ["https://example.com/x"]
148
+
149
+ # A character reference in a URL, as in an HTML attribute
150
+ UrlExtract.scan('<a href="https://example.com/x?a=1&amp;b=2">').map(&:url)
151
+ # => ["https://example.com/x?a=1&amp;b=2"]
152
+
153
+ # Non-ASCII characters
154
+ UrlExtract.scan("https://ru.wikipedia.org/wiki/Привет").map(&:url)
155
+ # => ["https://ru.wikipedia.org/wiki/Привет"]
156
+
157
+ # A space that is not ASCII ends a URL
158
+ UrlExtract.scan("https://example.com/x\u00A0y").map(&:url)
159
+ # => ["https://example.com/x"]
160
+
161
+ # An IP address or localhost as the host
162
+ UrlExtract.scan("Open http://127.0.0.1:8080/x, http://[::1]:3000/ or http://localhost:3000").map(&:url)
163
+ # => ["http://127.0.0.1:8080/x", "http://[::1]:3000/", "http://localhost:3000"]
164
+
165
+ # A scheme in capital letters
166
+ UrlExtract.scan("HTTPS://EXAMPLE.COM/x").map(&:url)
167
+ # => ["HTTPS://EXAMPLE.COM/x"]
168
+
169
+ # A URL in a URL is one URL
170
+ UrlExtract.scan("https://example.com/x?u=https://example.org/y").map(&:url)
171
+ # => ["https://example.com/x?u=https://example.org/y"]
172
+
173
+ # www. at the start of a word only
174
+ UrlExtract.scan("www.example.com xwww.example.org", prefixes: %w[www.]).map(&:url)
175
+ # => ["www.example.com"]
176
+
177
+ # Each URL at each place, with repeats
178
+ UrlExtract.scan("https://example.com/x and https://example.com/x").map(&:url)
179
+ # => ["https://example.com/x", "https://example.com/x"]
180
+
181
+ # The first URLs only: reads the text up to the second
182
+ UrlExtract.scan("https://example.com https://example.org https://example.net").first(2).map(&:url)
183
+ # => ["https://example.com", "https://example.org"]
184
+
185
+ # A text in another encoding: the range in that text
186
+ UrlExtract.scan("Привет https://example.com/путь".encode(Encoding::Windows_1251)).first.range
187
+ # => 7...31
188
+ ```
189
+
190
+ ## Security
191
+
192
+ The gem finds URLs and does not check where they lead. Before your server fetches a URL from untrusted
193
+ user-generated text, protect it from [SSRF](https://owasp.org/www-community/attacks/Server_Side_Request_Forgery):
194
+ a URL can lead to `localhost`, a private network, or a cloud metadata address.
195
+
196
+ ## Development
197
+
198
+ Run `bin/setup` to install the dependencies, and `bundle exec rake` to run the specs and Standard.
199
+
200
+ ## License
201
+
202
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
data/VERSION ADDED
@@ -0,0 +1 @@
1
+ 0.1.0
@@ -0,0 +1,6 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Loads the reading of a text in an encoding other than UTF-8 ahead. `UrlExtract.new` loads it
4
+ # when it first gets such a text. `UrlExtract::Input::Encodings` describes it.
5
+ require_relative "../url_extract"
6
+ require_relative "input/encodings"
@@ -0,0 +1,31 @@
1
+ # frozen_string_literal: true
2
+
3
+ class UrlExtract
4
+ module Input # :nodoc: all
5
+ # Does what `on_encoding_error` says for a text that the extractor can not read:
6
+ # `:raise` raises the error, `:warn` warns at the line of the caller, and `:skip` says nothing.
7
+ class EncodingErrorPolicy # :nodoc: all
8
+ # The start of the path of each file of the gem. A warning names the first line outside them: the caller's.
9
+ SOURCE_PATH = File.expand_path("..", __dir__).freeze
10
+
11
+ class << self
12
+ def apply(error, policy)
13
+ case policy
14
+ when :raise then raise error
15
+ when :warn then warn_at_caller(error)
16
+ end
17
+ end
18
+
19
+ private
20
+
21
+ # The caller's line, in the form of Ruby's warnings. `uplevel:` counts no C frame, such as `Class#new`,
22
+ # so it can not take an index of `caller_locations`.
23
+ def warn_at_caller(error)
24
+ locations = caller_locations
25
+ caller = locations.find { |location| !location.path.start_with?(SOURCE_PATH) } || locations.last
26
+ warn("#{caller.path}:#{caller.lineno}: warning: url_extract: #{error.message}")
27
+ end
28
+ end
29
+ end
30
+ end
31
+ end
@@ -0,0 +1,60 @@
1
+ # frozen_string_literal: true
2
+
3
+ class UrlExtract
4
+ module Input # :nodoc: all
5
+ # Reads a text in an encoding other than UTF-8, such as Windows-1251, Shift_JIS, GB18030 or UTF-16LE.
6
+ # `Reader` loads this file when it gets such a text, so a program that reads UTF-8 only
7
+ # does not load it. `require "url_extract/encodings"` loads it ahead.
8
+ #
9
+ # The reader reads a UTF-8 copy of the text, and gives each URL in the encoding of the text.
10
+ # Ruby converts each character of such an encoding to one UTF-8 character, so the index of a URL in the copy
11
+ # is its index in the text, and the range of a match is the place of the URL in the text.
12
+ # The copy costs one conversion of the text for each extractor, and its memory.
13
+ #
14
+ # It can not read:
15
+ # - a string of bytes (`ASCII-8BIT`) that are not ASCII: its bytes are no characters
16
+ # - a dummy encoding, such as ISO-2022-JP or UTF-16 with a byte order mark: Ruby counts its bytes, not its
17
+ # characters, so an index in the copy is no index in the text
18
+ # - an encoding that Ruby can not convert to UTF-8, such as EUC-TW, or a character with no Unicode form
19
+ module Encodings # :nodoc: all
20
+ class << self
21
+ # The error names the character at fault: the first byte that is not ASCII in a string of bytes,
22
+ # or the first character with no Unicode form. A dummy encoding, and an encoding with no converter,
23
+ # are at fault as a whole.
24
+ def utf8_copy(text)
25
+ encoding = text.encoding
26
+ if encoding == Encoding::BINARY
27
+ Validations::Text.fail_unreadable(text, text.each_char.find_index { |byte| !byte.ascii_only? })
28
+ end
29
+ Validations::Text.fail_unreadable(text) if encoding.dummy?
30
+
31
+ text.encode(Encoding::UTF_8).freeze
32
+ rescue Encoding::ConverterNotFoundError
33
+ Validations::Text.fail_unreadable(text)
34
+ rescue Encoding::UndefinedConversionError => error
35
+ index = text.each_char.find_index { |character| character == error.error_char }
36
+ Validations::Text.fail_unreadable(text, index)
37
+ end
38
+ end
39
+
40
+ # The methods of `Reader` for a text in another encoding. A text in UTF-8 goes to the methods
41
+ # of the class.
42
+ module ReaderMethods
43
+ def each_url
44
+ return super if @scanned_text.equal?(@text)
45
+
46
+ encoding = @text.encoding
47
+ super { |url, index| yield url.encode(encoding), index }
48
+ end
49
+
50
+ private
51
+
52
+ def scanned_text(text)
53
+ Validations::Text.utf8?(text) ? super : Encodings.utf8_copy(text)
54
+ end
55
+ end
56
+ end
57
+
58
+ Reader.prepend(Encodings::ReaderMethods)
59
+ end
60
+ end
@@ -0,0 +1,61 @@
1
+ # frozen_string_literal: true
2
+
3
+ class UrlExtract
4
+ module Input # :nodoc: all
5
+ # Reads the text of an extractor, and gives each URL in it, with its index in characters.
6
+ #
7
+ # It keeps a frozen copy of the text, so a change of the text during the scan or after it
8
+ # does not change what a match holds. A frozen text needs no copy.
9
+ # A text in an encoding other than UTF-8 loads `Input::Encodings`, which changes `scanned_text`
10
+ # and `each_url` of the class, for each reader after it.
11
+ # A text that the extractor can not read gives no URL, and `EncodingErrorPolicy` says what else it does.
12
+ class Reader # :nodoc: all
13
+ # The frozen text, or nil for a text that the extractor can not read.
14
+ attr_reader :text
15
+
16
+ def initialize(text, rules)
17
+ @rules = rules
18
+ @text, @scanned_text = read(text)
19
+ end
20
+
21
+ # Gives each URL of the scanned text, and its index in characters.
22
+ # The scan gives byte indexes. In a text of ASCII characters, they are the indexes in characters.
23
+ # In another text, counting the characters between two URLs keeps the time linear.
24
+ def each_url
25
+ text = @scanned_text
26
+ return unless text
27
+
28
+ ascii = text.ascii_only?
29
+ character_index = 0
30
+ byte_index = 0
31
+
32
+ Scanner.new(text, @rules).each_url do |url, url_byte_index|
33
+ gap_size = url_byte_index - byte_index
34
+ character_index += ascii ? gap_size : text.byteslice(byte_index, gap_size).length
35
+ byte_index = url_byte_index
36
+
37
+ yield url, character_index
38
+ end
39
+ end
40
+
41
+ private
42
+
43
+ # Returns the text and the text that the scan reads, or nil and nil for a text that the extractor
44
+ # can not read.
45
+ def read(text)
46
+ Validations::Text.check(text)
47
+ text = text.frozen? ? text : text.dup.freeze
48
+ require_relative "encodings" unless Validations::Text.utf8?(text)
49
+ [text, scanned_text(text)]
50
+ rescue UrlExtract::EncodingError => error
51
+ EncodingErrorPolicy.apply(error, @rules.on_encoding_error)
52
+ [nil, nil]
53
+ end
54
+
55
+ # The text that the scan reads: the text itself, in UTF-8 or of ASCII characters only.
56
+ def scanned_text(text)
57
+ text
58
+ end
59
+ end
60
+ end
61
+ end
@@ -0,0 +1,79 @@
1
+ # frozen_string_literal: true
2
+
3
+ class UrlExtract
4
+ # A URL that the extractor found in a text:
5
+ #
6
+ # ```ruby
7
+ # UrlExtract.scan("See https://example.com/x").first # => #<UrlExtract::Match url="https://example.com/x" range=4...25>
8
+ # ```
9
+ class Match
10
+ # Returns the URL as the text writes it. In HTML it can hold a character reference, such as `&amp;`:
11
+ #
12
+ # ```ruby
13
+ # UrlExtract.scan("See https://example.com/x").first.url # => "https://example.com/x"
14
+ # UrlExtract.scan(%(<a href="https://example.com/x?a=1&amp;b=2">)).first.url # => "https://example.com/x?a=1&amp;b=2"
15
+ # ```
16
+ attr_reader :url
17
+
18
+ # Returns the place of the URL in the text, in characters:
19
+ #
20
+ # ```ruby
21
+ # match = UrlExtract.scan("See https://example.com/x").first
22
+ # match.range # => 4...25
23
+ # match.text[match.range] # => "https://example.com/x"
24
+ # ```
25
+ #
26
+ # To replace the URLs of a text, go from the last match to the first: a replacement changes the length
27
+ # of the text, and moves each URL after it:
28
+ #
29
+ # ```ruby
30
+ # text = "See https://example.com/x and https://example.org/y"
31
+ # UrlExtract.scan(text).reverse_each { |match| text[match.range] = "<FILTERED>" }
32
+ # text # => "See <FILTERED> and <FILTERED>"
33
+ # ```
34
+ attr_reader :range
35
+
36
+ # Returns a frozen copy of the text, as it was when the extractor read it. The matches of one text share it:
37
+ #
38
+ # ```ruby
39
+ # text = +"See https://example.com/x"
40
+ # match = UrlExtract.scan(text).first
41
+ # text << " More."
42
+ # match.text # => "See https://example.com/x"
43
+ # match.text.frozen? # => true
44
+ # ```
45
+ attr_reader :text
46
+
47
+ # The extractor makes each match, from the index of the URL in the text.
48
+ def initialize(url, index, text)
49
+ @url = url
50
+ @range = index...(index + url.length)
51
+ @text = text
52
+ end
53
+
54
+ # call-seq:
55
+ # to_s -> string
56
+ #
57
+ # Returns the URL:
58
+ #
59
+ # ```ruby
60
+ # match = UrlExtract.scan("See https://example.com/x").first
61
+ # "Link: #{match}" # => "Link: https://example.com/x"
62
+ # ```
63
+ def to_s
64
+ url
65
+ end
66
+
67
+ # call-seq:
68
+ # inspect -> string
69
+ #
70
+ # Returns a string that shows the URL and the range, and not the text, which can be large:
71
+ #
72
+ # ```ruby
73
+ # UrlExtract.scan("See https://example.com/x").first # => #<UrlExtract::Match url="https://example.com/x" range=4...25>
74
+ # ```
75
+ def inspect
76
+ "#<#{self.class} url=#{url.inspect} range=#{range.inspect}>"
77
+ end
78
+ end
79
+ end
@@ -0,0 +1,57 @@
1
+ # frozen_string_literal: true
2
+
3
+ class UrlExtract
4
+ # The rules of an extractor, built from its options:
5
+ # - prefix_regexp: the regexp of each prefix, or nil when no prefix can start a URL
6
+ # - max_bytesize: the largest size of a URL, in bytes, or infinity
7
+ # - trim: the `Trimming::Trim` of the trim options
8
+ # - on_encoding_error: what a text that the extractor can not read does
9
+ #
10
+ # The rules are frozen, as each part of them, so threads and Ractors can share them.
11
+ Rules = Data.define(:prefix_regexp, :max_bytesize, :trim, :on_encoding_error)
12
+
13
+ class Rules # :nodoc: all
14
+ class << self
15
+ # Returns the rules for the options. The rules of the default options are built one time, when the file loads.
16
+ # Other options build their rules for each extractor: the build compiles a regexp, which costs
17
+ # a few microseconds, about the scan of a short text. The class keeps no other rules, so it has no state
18
+ # that threads or Ractors share.
19
+ def from(options)
20
+ return DEFAULT if options.empty?
21
+
22
+ Validations::Options.check(options)
23
+ build(**DEFAULTS, **options)
24
+ end
25
+
26
+ # Each option is present.
27
+ def build(**options)
28
+ new(
29
+ prefix_regexp: prefix_regexp(options[:prefixes]),
30
+ max_bytesize: options[:max_bytesize] || Float::INFINITY,
31
+ trim: Trimming::Trim.new(**options.slice(:trim, :trim_html_entities, :trim_brackets)),
32
+ on_encoding_error: options[:on_encoding_error]
33
+ )
34
+ end
35
+
36
+ private
37
+
38
+ # Returns the regexp of each prefix, or nil when there is no prefix.
39
+ def prefix_regexp(prefixes)
40
+ sources = prefixes.map { |prefix| prefix_source(prefix) }
41
+
42
+ Regexp.new(sources.join("|"), Regexp::IGNORECASE).freeze if sources.any?
43
+ end
44
+
45
+ # The source of the regexp of one prefix. A prefix with `://` starts a URL at each place.
46
+ # Another prefix, such as `www.`, starts a URL only at the start of a word, before a letter or a digit.
47
+ def prefix_source(prefix)
48
+ escaped_prefix = Regexp.escape(prefix)
49
+
50
+ prefix.end_with?("://") ? escaped_prefix : "(?<![[:alnum:]])#{escaped_prefix}(?=[a-z0-9])"
51
+ end
52
+ end
53
+
54
+ # The rules of the default options. Built here, as `Trimming` loads before this file.
55
+ DEFAULT = build(**DEFAULTS)
56
+ end
57
+ end
@@ -0,0 +1,59 @@
1
+ # frozen_string_literal: true
2
+
3
+ class UrlExtract
4
+ # Reads the text from its start to its end, and gives each URL to the block, with its byte index.
5
+ #
6
+ # The time is linear in the length of the text: the scan reads the characters after a prefix one time.
7
+ # It works with byte indexes, and makes one string for each URL: the URL.
8
+ class Scanner # :nodoc: all
9
+ # The characters that RFC 3986 allows in a URL, as the content of a regexp character class:
10
+ # - unreserved: letters, digits and `-._~` (https://www.rfc-editor.org/rfc/rfc3986#section-2.3)
11
+ # - reserved: `:/?#[]@` and `!$&'()*+,;=` (https://www.rfc-editor.org/rfc/rfc3986#section-2.2)
12
+ # - `%`, which starts a percent-encoded byte (https://www.rfc-editor.org/rfc/rfc3986#section-2.1)
13
+ # The whole grammar is in https://www.rfc-editor.org/rfc/rfc3986#appendix-A
14
+ RFC3986_CHARACTERS = "A-Za-z0-9\\-._~:/?#\\[\\]@!$&'()*+,;=%"
15
+
16
+ # The characters of a URL: the characters of RFC 3986, and each character that is not ASCII and not a space.
17
+ # The URL Standard of browsers allows these: https://url.spec.whatwg.org/#url-code-points
18
+ CHARACTERS = /(?:[#{RFC3986_CHARACTERS}]|[[^\x00-\x7F]&&[^[:space:]]])*/
19
+
20
+ # The characters of a URL in a text of ASCII characters only. Such a text gets this shorter regexp,
21
+ # which finds the same URLs there.
22
+ ASCII_CHARACTERS = /[#{RFC3986_CHARACTERS}]*/
23
+
24
+ def initialize(text, rules)
25
+ @scanner = StringScanner.new(text)
26
+ @rules = rules
27
+ @characters = text.ascii_only? ? ASCII_CHARACTERS : CHARACTERS
28
+ end
29
+
30
+ def each_url(&)
31
+ prefix_regexp = @rules.prefix_regexp
32
+ return unless prefix_regexp
33
+
34
+ scan_url(&) while @scanner.skip_until(prefix_regexp)
35
+ end
36
+
37
+ private
38
+
39
+ def scan_url
40
+ prefix_finish = @scanner.pos
41
+ byte_index = prefix_finish - @scanner.matched_size
42
+ rest_size = @scanner.match?(@characters)
43
+ text = @scanner.string
44
+ finish = @rules.trim.call(text, byte_index, prefix_finish + rest_size)
45
+ size = finish - byte_index
46
+ return skip_rest(rest_size) if (finish <= prefix_finish) || (size > @rules.max_bytesize)
47
+
48
+ @scanner.pos = finish
49
+ yield(text.byteslice(byte_index, size), byte_index)
50
+ end
51
+
52
+ # The trim removed each character after the prefix, or the URL is longer than the limit, so no URL is there.
53
+ # The scan goes on after these characters. Reading them again for each prefix in them takes a time
54
+ # that grows with the square of their count.
55
+ def skip_rest(rest_size)
56
+ @scanner.pos += rest_size
57
+ end
58
+ end
59
+ end
@@ -0,0 +1,62 @@
1
+ # frozen_string_literal: true
2
+
3
+ class UrlExtract
4
+ module Trimming # :nodoc: all
5
+ # Returns the count of the bytes of the HTML entity that ends a URL, or 0 when no entity ends it.
6
+ # The URL is the bytes of the text from `start` to `finish`.
7
+ #
8
+ # An entity is `&`, a name and `;`. The name is a letter and 1 to 30 letters or digits, as in `&quot;`,
9
+ # or `#` and 1 to 8 letters or digits, as in `&#39;` and `&#x27;`.
10
+ # The names of HTML are in https://html.spec.whatwg.org/multipage/named-characters.html
11
+ #
12
+ # It reads the bytes from the end of the URL, and makes no object.
13
+ class EndingEntitySize # :nodoc: all
14
+ SEMICOLON = ";".ord
15
+ AMPERSAND = "&".ord
16
+ NUMBER_SIGN = "#".ord
17
+ MAX_NAME_SIZE = 31
18
+ MAX_NUMBER_SIZE = 8
19
+ LETTER_BYTES = Array.new(256) { |byte| byte.chr.match?(/[a-z]/i) }.freeze
20
+ NAME_BYTES = Array.new(256) { |byte| byte.chr.match?(/[a-z0-9]/i) }.freeze
21
+
22
+ class << self
23
+ def call(text, start, finish)
24
+ semicolon_index = finish - 1
25
+ return 0 if text.getbyte(semicolon_index) != SEMICOLON
26
+
27
+ name_start = name_start(text, start, semicolon_index)
28
+ entity_start = entity_start(text, start, name_start, semicolon_index - name_start)
29
+
30
+ entity_start ? finish - entity_start : 0
31
+ end
32
+
33
+ private
34
+
35
+ # Returns the index of the first of the letters and digits before the `;`.
36
+ # It reads one byte more than the longest name, so a longer name is no name.
37
+ def name_start(text, start, name_finish)
38
+ first = [start, name_finish - MAX_NAME_SIZE - 1].max
39
+ index = name_finish
40
+ index -= 1 while (index > first) && NAME_BYTES[text.getbyte(index - 1)]
41
+ index
42
+ end
43
+
44
+ # Returns the index of the `&` of the entity, or nil when the name is no name of an entity.
45
+ def entity_start(text, start, name_start, name_size)
46
+ index = name_start - 1
47
+ return if index < start
48
+
49
+ case text.getbyte(index)
50
+ when AMPERSAND then index if name_size.between?(2, MAX_NAME_SIZE) && LETTER_BYTES[text.getbyte(name_start)]
51
+ when NUMBER_SIGN then number_start(text, start, index - 1) if name_size.between?(1, MAX_NUMBER_SIZE)
52
+ end
53
+ end
54
+
55
+ # Returns the index of the `&` before the `#`, or nil.
56
+ def number_start(text, start, index)
57
+ index if (index >= start) && (text.getbyte(index) == AMPERSAND)
58
+ end
59
+ end
60
+ end
61
+ end
62
+ end