lobzique 0.1.0-x86_64-linux-musl

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.
Files changed (58) hide show
  1. checksums.yaml +7 -0
  2. data/CHANGELOG.md +5 -0
  3. data/LICENSE-NOKOGIRI.md +15 -0
  4. data/LICENSE.txt +21 -0
  5. data/README.md +144 -0
  6. data/ext/lobzique/clippy.toml +15 -0
  7. data/lib/lobzique/3.3/lobzique.so +0 -0
  8. data/lib/lobzique/3.4/lobzique.so +0 -0
  9. data/lib/lobzique/4.0/lobzique.so +0 -0
  10. data/lib/lobzique/action_text.rb +29 -0
  11. data/lib/lobzique/class_resolver.rb +33 -0
  12. data/lib/lobzique/css/selector_cache.rb +36 -0
  13. data/lib/lobzique/css/syntax_error.rb +12 -0
  14. data/lib/lobzique/css/xpath_visitor.rb +60 -0
  15. data/lib/lobzique/css.rb +57 -0
  16. data/lib/lobzique/extension.rb +31 -0
  17. data/lib/lobzique/html.rb +14 -0
  18. data/lib/lobzique/html4/document.rb +235 -0
  19. data/lib/lobzique/html4/document_fragment.rb +75 -0
  20. data/lib/lobzique/html4/encoding_reader.rb +374 -0
  21. data/lib/lobzique/html4.rb +35 -0
  22. data/lib/lobzique/html5/document.rb +106 -0
  23. data/lib/lobzique/html5/document_fragment.rb +113 -0
  24. data/lib/lobzique/html5/node.rb +66 -0
  25. data/lib/lobzique/html5.rb +92 -0
  26. data/lib/lobzique/html5ever.rb +14 -0
  27. data/lib/lobzique/rails_dom_testing.rb +95 -0
  28. data/lib/lobzique/sanitizer/concerns.rb +110 -0
  29. data/lib/lobzique/sanitizer/document.rb +14 -0
  30. data/lib/lobzique/sanitizer/document_fragment.rb +12 -0
  31. data/lib/lobzique/sanitizer/escape_raw_text_in_select.rb +31 -0
  32. data/lib/lobzique/sanitizer/scrubbers.rb +46 -0
  33. data/lib/lobzique/sanitizer.rb +96 -0
  34. data/lib/lobzique/syntax_error.rb +8 -0
  35. data/lib/lobzique/version.rb +6 -0
  36. data/lib/lobzique/xml/attr.rb +23 -0
  37. data/lib/lobzique/xml/cdata.rb +13 -0
  38. data/lib/lobzique/xml/character_data.rb +11 -0
  39. data/lib/lobzique/xml/document.rb +149 -0
  40. data/lib/lobzique/xml/document_fragment.rb +109 -0
  41. data/lib/lobzique/xml/dtd.rb +28 -0
  42. data/lib/lobzique/xml/namespace.rb +19 -0
  43. data/lib/lobzique/xml/node/save_options.rb +52 -0
  44. data/lib/lobzique/xml/node.rb +629 -0
  45. data/lib/lobzique/xml/node_set.rb +329 -0
  46. data/lib/lobzique/xml/parse_options.rb +89 -0
  47. data/lib/lobzique/xml/pp/character_data.rb +22 -0
  48. data/lib/lobzique/xml/pp/node.rb +73 -0
  49. data/lib/lobzique/xml/pp.rb +6 -0
  50. data/lib/lobzique/xml/searchable.rb +123 -0
  51. data/lib/lobzique/xml/syntax_error.rb +77 -0
  52. data/lib/lobzique/xml/text.rb +14 -0
  53. data/lib/lobzique/xml/xpath/syntax_error.rb +20 -0
  54. data/lib/lobzique/xml/xpath.rb +16 -0
  55. data/lib/lobzique/xml/xpath_context.rb +27 -0
  56. data/lib/lobzique/xml.rb +22 -0
  57. data/lib/lobzique.rb +15 -0
  58. metadata +106 -0
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: dc074754042ea4b7627416c290b971be05551924f5c0fdad3bb046adb7b8ad19
4
+ data.tar.gz: 3240bd35df751d4b4b5edd649440c8d94c0938c04cbb062a107dbb336fe4c1a6
5
+ SHA512:
6
+ metadata.gz: 52e901257e934c184860cd58c4ca2dbe8c36d802a0b7f482feee5a003cfa6210e074e0aa978c884755d41aac8f67d64c689cc18a6286c9a8359be6ee3d8a1521
7
+ data.tar.gz: 3e76fac47fb4f90b81d15504ef59aaf953b80599776b04241d612fe9a4bcc44363c51a31d4a201634b894720b6cdf3b759b5e6ec0f38b55e174bfa6d08351f56
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2026-10-25
4
+
5
+ - Initial release
@@ -0,0 +1,15 @@
1
+ The Ruby files under `lib/lobzique/` marked "Adapted from Nokogiri" are
2
+ derived from Nokogiri (https://github.com/sparklemotion/nokogiri), used under
3
+ this license:
4
+
5
+ ---
6
+
7
+ The MIT License
8
+
9
+ Copyright 2008 -- 2023 by Mike Dalessio, Aaron Patterson, Yoko Harada, Akinori MUSHA, John Shahid, Karol Bucek, Sam Ruby, Craig Barnes, Stephen Checkoway, Lars Kanis, Sergio Arbeo, Timothy Elliott, Nobuyoshi Nakada, Charles Nutter, Patrick Mahoney.
10
+
11
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2026 Jury Razumau
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,144 @@
1
+ # lobzique
2
+
3
+ This will be an implementation of a subset of Nokogiri that used by Rails and related libraries with a Rust extension in place of libxml.
4
+
5
+ ## Sanitizing in Rails
6
+
7
+ `Lobzique::Sanitizer` is a rails-html-sanitizer vendor: `sanitize`,
8
+ `strip_tags`, `strip_links` and Action Text parse, scrub and serialize with
9
+ lobzique, so user HTML never reaches libxml2. Its output matches
10
+ `Rails::HTML5::Sanitizer`'s byte for byte, except for one known gap (below).
11
+
12
+ ```ruby
13
+ # config/application.rb, after require "rails/all"
14
+ require "lobzique/sanitizer"
15
+
16
+ config.action_view.sanitizer_vendor = Lobzique::Sanitizer
17
+ config.action_text.sanitizer_vendor = Lobzique::Sanitizer
18
+ ```
19
+
20
+ It needs `loofah` and `rails-html-sanitizer`, which every Rails app already
21
+ has, and raises at `require` on a rails-html-sanitizer outside 1.7.1–1.7.x:
22
+ the vendor is built from that gem's internal modules. Loofah's and Rails'
23
+ scrubbers run unchanged, and so do app scrubbers passed with `scrubber:` or
24
+ set as `ActionText::ContentHelper.scrubber`, with these limits:
25
+
26
+ - A scrubber that checks `is_a?(Nokogiri::XML::Element)` (or another
27
+ Nokogiri class) or builds nodes with `Nokogiri::XML::Text.new` and the like fails on
28
+ lobzique nodes. Build nodes through `node.document` (`create_element`,
29
+ `create_text_node`) or with `node.add_next_sibling("<b>…</b>")`.
30
+ - The vendor is HTML5 only. An app on `load_defaults` below 7.1, whose
31
+ default vendor is `Rails::HTML4::Sanitizer`, sanitizes with an HTML5
32
+ parser after switching.
33
+ - The parser keeps markup inside `<select>`, as the 2025 HTML standard's
34
+ customizable select does; Nokogiri's parser, and browsers without
35
+ customizable select, drop or move it. So output differs from
36
+ `Rails::HTML5` when `select` is in the allowed tags. The text of `style`,
37
+ `xmp`, `iframe`, `noembed`, `noframes` and `plaintext` inside a `select` is
38
+ escaped, as Loofah escapes it on libxml2, so the output is safe with either
39
+ set of rules.
40
+ - Loofah's `text` and `to_text` and its document-level comment removal
41
+ aren't ported; Rails' sanitizers call neither.
42
+
43
+ ## Action Text
44
+
45
+ With the sanitizer vendor above, Action Text still parses stored rich text
46
+ with Nokogiri to find attachments, convert Trix markup and build plain text.
47
+ To parse it with lobzique as well:
48
+
49
+ ```ruby
50
+ # config/application.rb, after require "rails/all"
51
+ require "lobzique/action_text"
52
+ ```
53
+
54
+ `ActionText::Content#fragment.source` and the nodes passed to
55
+ `Fragment#replace` blocks are then lobzique nodes, with the limits listed
56
+ for scrubbers above. Stored content reads the same as on
57
+ `Nokogiri::HTML5`, apart from the `<select>` difference above.
58
+
59
+ ## Tests: assert_dom and parsed_body
60
+
61
+ rails-dom-testing parses HTML for `assert_dom` (`assert_select`),
62
+ `assert_dom_equal`, `css_select`, `response.parsed_body`, and
63
+ `rendered.html` in view tests. To parse it with lobzique:
64
+
65
+ ```ruby
66
+ # test/test_helper.rb, after require "rails/test_help"
67
+ require "lobzique/rails_dom_testing"
68
+ ```
69
+
70
+ Wherever rails-dom-testing would use `Nokogiri::HTML5`, it then uses
71
+ lobzique: on `load_defaults` 7.1 and later, or with
72
+ `config.dom_testing_default_html_version = :html5`. `:html4` stays on
73
+ Nokogiri, and so do XML responses. It raises at `require` on a
74
+ rails-dom-testing outside 2.3.x, because it replaces one of that gem's
75
+ private methods. Limits:
76
+
77
+ - Selected elements, `parsed_body` and `rendered.html` are lobzique
78
+ objects, so a test asserting `Nokogiri::…` classes fails.
79
+ - An invalid selector raises `Lobzique::CSS::SyntaxError`, not
80
+ `Nokogiri::CSS::SyntaxError`.
81
+
82
+ ## Development
83
+
84
+ `bundle exec rake` compiles the extension, runs the tests and lints.
85
+
86
+ Library code goes in `crates/lobzique-core`, which must not depend on Ruby, so the checks below can run it without a Ruby VM. `ext/lobzique` holds only the Ruby bindings.
87
+
88
+ The CI workflow runs these checks on every PR and daily. Locally they need nightly Rust (`rustup toolchain install nightly --component miri,rust-src`) `cargo install cargo-fuzz` and `cargo install cargo-deny`.
89
+
90
+ | Check | Locally | Catches |
91
+ | --- | --- | --- |
92
+ | Miri | `cargo +nightly miri test -p lobzique-core` | undefined behavior in unsafe code, ours or our dependencies' |
93
+ | ASan (Rust) | `RUSTFLAGS=-Zsanitizer=address cargo +nightly test -Zbuild-std --target aarch64-apple-darwin -p lobzique-core` | memory errors in the core crate |
94
+ | ASan (Ruby) | CI only: ASan builds of Ruby exist for Linux x64 only | memory errors in the extension and at the Ruby boundary |
95
+ | GC.stress | `bundle exec rake test:gc_stress` | Ruby objects that Rust holds without the GC knowing |
96
+ | Fuzzing | `cargo +nightly fuzz run <target>` | panics and failed assertions on arbitrary input |
97
+ | cargo-deny | `cargo deny check` | dependencies with RustSec advisories (vulnerable, unmaintained, unsound or yanked), disallowed licenses, duplicate versions, crates from outside crates.io |
98
+ | Fuzzing the Ruby API | `bundle exec rake fuzz:ruby` (Linux, see below) | memory errors in the extension, GC and compaction mistakes, and errors Nokogiri doesn't raise, on fuzzed sequences of Ruby calls |
99
+
100
+ `rake test:gc_stress` and `rake fuzz:ruby` leave a special build in `lib/`; `rake compile` replaces it. `rake test:stress` runs GC.stress on whatever build is in `lib/` (the ASan job's, for one), each test file in its own process, `STRESS_JOBS` at a time.
101
+
102
+ Every entry point that takes untrusted input gets a fuzz target in `fuzz/fuzz_targets/`, plus a `[[bin]]` entry in `fuzz/Cargo.toml`. CI fuzzes each target for 60 seconds on PRs; for a long run, dispatch the Fuzz workflow (`gh workflow run fuzz.yml -f seconds=7200`). A target's libFuzzer dictionary goes in `fuzz/<target>.dict`. CI also passes `-timeout=10 -malloc_limit_mb=512`, so a slow input or a single huge allocation fails. Slowness under the timeout is `html5_scaling`'s job: it repeats its input and fails if the work the core counts under `cfg(fuzzing)` (`lobzique_core::work`) grows faster than linearly in the input times the tree's depth.
103
+
104
+ The Rust targets never reach the bindings or the Ruby layer. `fuzz/ruby/api.rb` does: with [Ruzzy](https://github.com/trailofbits/ruzzy), it runs fuzzed sequences of Ruby calls (editing, copying, searching, scrubbing and serializing nodes, XPath functions that edit the tree, GC and compaction in between) on an extension built with ASan and coverage instrumentation. It fails on a crash, an ASan report or a panic; on an exception that Nokogiri doesn't raise on the same calls from the same tree, apart from the departures in `ARCHITECTURE.md`; and on sanitized output that isn't idempotent or doesn't survive a reparse where Rails::HTML5's does. Nokogiri runs in a child process, only to judge an input; trees it builds differently (as `known.yml` lists) aren't compared from where they differ, and neither are the sanitizer's properties on markup it parses differently, though a sanitizer exception still is. Ruzzy is Linux-only and needs clang with its sanitizer runtimes (`libclang-rt-18-dev` on Ubuntu) and nightly Rust:
105
+
106
+ ```sh
107
+ bundle config set --local with fuzz
108
+ CC=clang CXX=clang++ LDSHARED="clang -shared" LDSHAREDXX="clang++ -shared" \
109
+ MAKE="make --environment-overrides" bundle install
110
+ bundle exec rake fuzz:ruby FUZZOPTS="-max_total_time=600 -fork=4"
111
+ ```
112
+
113
+ Failing inputs go to `fuzz/artifacts/ruby_api/`. To run one again, after `rake fuzz:ruby` has built the extension:
114
+
115
+ ```sh
116
+ LD_PRELOAD=$(ruby -e 'require "ruzzy"; print Ruzzy::ASAN_PATH') ASAN_OPTIONS=detect_leaks=0:use_sigaltstack=0 \
117
+ bundle exec fuzz/ruby/trace.rb fuzz/artifacts/ruby_api/crash-...
118
+ ```
119
+
120
+ CI runs it next to the Rust targets.
121
+
122
+ ### Differential test against Nokogiri::HTML5
123
+
124
+ `script/differential` parses the same inputs with Nokogiri (a development dependency) and with lobzique and compares `to_html` and the tree.
125
+
126
+ | Corpus | Command | When CI runs it |
127
+ | --- | --- | --- |
128
+ | fixtures: WPT, html5lib, DOMPurify and asset inputs from `test/fixtures` | `script/differential` | every push |
129
+ | small hand-written cases in `test/differential/cases.yml` | `script/differential` | every push |
130
+ | a pinned Common Crawl sample (~3,100 pages) | `script/fetch_crawl`, then `script/differential --corpus crawl` | weekly |
131
+
132
+ `--mode sanitize` sends the inputs from the fixtures (DOMPurify, the WPT sanitizer and tree-construction tests, Loofah's sanitizer data, html5lib) or the crawl through `Rails::HTML5`'s sanitizers and through `Lobzique::Sanitizer`, in several configurations. It compares the output, the output sanitized again, and the output parsed and serialized again. Rails::HTML5 itself isn't idempotent on every input, so lobzique has to break these properties exactly where it does; the report counts both. CI runs it next to the parse mode.
133
+
134
+ `--mode action_text` reads the sanitize mode's inputs, and the markup in Action Text's tests, as `ActionText::Content` with Action Text's document classes set to Nokogiri's and then to lobzique's, and compares `to_html`, `to_trix_html` (and what saving it back stores), `to_plain_text`, the attachments, galleries and links. CI runs it next to the other modes.
135
+
136
+ Crawled pages aren't committed: `test/differential/crawl.yml` pins byte ranges of WARC files with their SHA-256, and `script/fetch_crawl` downloads them into `tmp/crawl/`. A difference found on a crawled page becomes a small case in `cases.yml`. Accepted differences go in `test/differential/known.yml` with a reason.
137
+
138
+ ## License
139
+
140
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
141
+
142
+ ## Code of Conduct
143
+
144
+ Everyone interacting in the Lobzique project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/[USERNAME]/lobzique/blob/main/CODE_OF_CONDUCT.md).
@@ -0,0 +1,15 @@
1
+ # Ways to reach Ruby without a handle, which code borrowing an arena must
2
+ # not have (lib.rs). `support` is the one module allowed `protect`.
3
+ disallowed-methods = [
4
+ { path = "magnus::Ruby::get", reason = "take `&Ruby` as an argument instead" },
5
+ { path = "magnus::Ruby::get_with", reason = "take `&Ruby` as an argument instead" },
6
+ { path = "magnus::eval", reason = "use `Ruby::eval`" },
7
+ { path = "magnus::rb_sys::protect", reason = "calls Ruby without a handle; wrap the call in `support`" },
8
+ ]
9
+ disallowed-macros = [
10
+ { path = "magnus::eval", reason = "fetches a handle itself" },
11
+ { path = "magnus::rb_assert", reason = "fetches a handle itself" },
12
+ ]
13
+ disallowed-types = [
14
+ { path = "magnus::value::LazyId", reason = "`Send`, and calls Ruby without a handle" },
15
+ ]
Binary file
Binary file
Binary file
@@ -0,0 +1,29 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Action Text on lobzique (plan.md decision 1, seam mode):
4
+ #
5
+ # require "lobzique/action_text"
6
+ #
7
+ # Action Text memoizes its document classes in instance variables,
8
+ # which is its own seam. Fragment.wrap knows only the fragment class
9
+ # of Nokogiri. Without the patch it would serialize a lobzique fragment
10
+ # and parse it again.
11
+
12
+ require "lobzique"
13
+ require "action_text"
14
+
15
+ module Lobzique
16
+ module ActionText
17
+ module Fragment
18
+ def wrap(fragment_or_html)
19
+ return new(fragment_or_html) if fragment_or_html.is_a?(XML::DocumentFragment)
20
+
21
+ super
22
+ end
23
+ end
24
+ end
25
+ end
26
+
27
+ ActionText.instance_variable_set(:@html_document_class, Lobzique::HTML5::Document)
28
+ ActionText.instance_variable_set(:@html_document_fragment_class, Lobzique::HTML5::DocumentFragment)
29
+ ActionText::Fragment.singleton_class.prepend(Lobzique::ActionText::Fragment)
@@ -0,0 +1,33 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Adapted from Nokogiri 1.19.7, lib/nokogiri/class_resolver.rb (MIT, see LICENSE-NOKOGIRI.md).
4
+
5
+ module Lobzique
6
+ # Finds the class with a given name in the namespace of the receiver's
7
+ # class or of its nearest ancestor class, so a subclass such as
8
+ # `Loofah::HTML5::Document` gets `Loofah::HTML5::DocumentFragment`.
9
+ module ClassResolver
10
+ VALID_NAMESPACES = Set.new(["HTML", "HTML4", "HTML5", "XML", "SAX"])
11
+
12
+ def related_class(class_name)
13
+ klass = nil
14
+ inspecting = self.class
15
+
16
+ while inspecting
17
+ namespace_path = inspecting.name.split("::")[0..-2]
18
+ inspecting = inspecting.superclass
19
+
20
+ next unless VALID_NAMESPACES.include?(namespace_path.last)
21
+
22
+ related_class_name = (namespace_path << class_name).join("::")
23
+ klass = begin
24
+ Object.const_get(related_class_name)
25
+ rescue NameError
26
+ nil
27
+ end
28
+ break if klass
29
+ end
30
+ klass
31
+ end
32
+ end
33
+ end
@@ -0,0 +1,36 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Adapted from Nokogiri 1.19.7, lib/nokogiri/css/selector_cache.rb (MIT, see LICENSE-NOKOGIRI.md).
4
+
5
+ module Lobzique
6
+ module CSS
7
+ module SelectorCache # :nodoc:
8
+ @cache = {}
9
+ @mutex = Mutex.new
10
+
11
+ class << self
12
+ def [](key)
13
+ @mutex.synchronize { @cache[key] }
14
+ end
15
+
16
+ def []=(key, value)
17
+ @mutex.synchronize { @cache[key] = value }
18
+ end
19
+
20
+ def clear_cache(create_new_object = false)
21
+ @mutex.synchronize do
22
+ if create_new_object
23
+ @cache = {}
24
+ else
25
+ @cache.clear
26
+ end
27
+ end
28
+ end
29
+
30
+ def key(selector:, visitor:)
31
+ [selector, visitor.config]
32
+ end
33
+ end
34
+ end
35
+ end
36
+ end
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Adapted from Nokogiri 1.19.7, lib/nokogiri/css/syntax_error.rb (MIT, see LICENSE-NOKOGIRI.md).
4
+
5
+ require_relative "../syntax_error"
6
+
7
+ module Lobzique
8
+ module CSS
9
+ class SyntaxError < Lobzique::SyntaxError
10
+ end
11
+ end
12
+ end
@@ -0,0 +1,60 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Adapted from Nokogiri 1.19.7, lib/nokogiri/css/xpath_visitor.rb (MIT, see LICENSE-NOKOGIRI.md).
4
+
5
+ module Lobzique
6
+ module CSS
7
+ # lobzique: the configuration only. The visit_* methods are in the core
8
+ # (crates/lobzique-core/src/css/write.rs). CSS::Parser#xpath_for runs them
9
+ # with this configuration, so a subclass cannot override them.
10
+ class XPathVisitor
11
+ module BuiltinsConfig
12
+ NEVER = :never
13
+ ALWAYS = :always
14
+ # lobzique: the same as ALWAYS, as in Nokogiri on libxml2.
15
+ OPTIMAL = :optimal
16
+
17
+ VALUES = [NEVER, ALWAYS, OPTIMAL]
18
+ end
19
+
20
+ module DoctypeConfig
21
+ XML = :xml
22
+ HTML4 = :html4
23
+ HTML5 = :html5
24
+
25
+ VALUES = [XML, HTML4, HTML5]
26
+ end
27
+
28
+ attr_reader :builtins
29
+
30
+ attr_reader :doctype
31
+
32
+ attr_reader :prefix
33
+
34
+ attr_reader :namespaces
35
+
36
+ def initialize(
37
+ builtins: BuiltinsConfig::NEVER,
38
+ doctype: DoctypeConfig::XML,
39
+ prefix: XML::XPath::GLOBAL_SEARCH_PREFIX,
40
+ namespaces: nil
41
+ )
42
+ unless BuiltinsConfig::VALUES.include?(builtins)
43
+ raise(ArgumentError, "Invalid values #{builtins.inspect} for builtins: keyword parameter")
44
+ end
45
+ unless DoctypeConfig::VALUES.include?(doctype)
46
+ raise(ArgumentError, "Invalid values #{doctype.inspect} for doctype: keyword parameter")
47
+ end
48
+
49
+ @builtins = builtins
50
+ @doctype = doctype
51
+ @prefix = prefix
52
+ @namespaces = namespaces
53
+ end
54
+
55
+ def config
56
+ {builtins: @builtins, doctype: @doctype, prefix: @prefix, namespaces: @namespaces}
57
+ end
58
+ end
59
+ end
60
+ end
@@ -0,0 +1,57 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Adapted from Nokogiri 1.19.7, lib/nokogiri/css.rb (MIT, see
4
+ # LICENSE-NOKOGIRI.md). Searchable does not use this module: it compiles
5
+ # selectors to CSS::Selector (ARCHITECTURE.md). xpath_for is for callers
6
+ # that want the XPath strings, which the core writes as the visitor of Nokogiri
7
+ # does.
8
+
9
+ module Lobzique
10
+ module CSS
11
+ class << self
12
+ # lobzique: no CSS.parse. It is deprecated and returns CSS::Nodes.
13
+
14
+ def xpath_for(
15
+ selector, options = nil,
16
+ prefix: options&.delete(:prefix),
17
+ visitor: options&.delete(:visitor),
18
+ ns: options&.delete(:ns),
19
+ cache: true
20
+ )
21
+ unless options.nil?
22
+ # lobzique: Nokogiri names itself
23
+ warn("#{self}.xpath_for: Passing options as an explicit hash is deprecated. Use keyword arguments instead. This will become an error in a future release.", uplevel: 1, category: :deprecated)
24
+ end
25
+
26
+ raise(TypeError, "no implicit conversion of #{selector.inspect} to String") unless selector.respond_to?(:to_str)
27
+
28
+ selector = selector.to_str
29
+ raise(CSS::SyntaxError, "empty CSS selector") if selector.empty?
30
+
31
+ if visitor
32
+ raise ArgumentError, "cannot provide both :prefix and :visitor" if prefix
33
+ raise ArgumentError, "cannot provide both :ns and :visitor" if ns
34
+ end
35
+
36
+ visitor ||= begin
37
+ visitor_kw = {}
38
+ visitor_kw[:prefix] = prefix if prefix
39
+ visitor_kw[:namespaces] = ns if ns
40
+
41
+ CSS::XPathVisitor.new(**visitor_kw)
42
+ end
43
+
44
+ if cache
45
+ key = SelectorCache.key(selector: selector, visitor: visitor)
46
+ SelectorCache[key] ||= Parser.new.xpath_for(selector, visitor)
47
+ else
48
+ Parser.new.xpath_for(selector, visitor)
49
+ end
50
+ end
51
+ end
52
+ end
53
+ end
54
+
55
+ require_relative "css/selector_cache"
56
+ require_relative "css/xpath_visitor"
57
+ require_relative "css/syntax_error"
@@ -0,0 +1,31 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Adapted from Nokogiri 1.19.7, lib/nokogiri/extension.rb (MIT, see LICENSE-NOKOGIRI.md).
4
+
5
+ begin
6
+ # A native gem has a binary per Ruby ABI
7
+ RUBY_VERSION =~ /(\d+\.\d+)/
8
+ require_relative "#{Regexp.last_match(1)}/lobzique"
9
+ rescue LoadError => e
10
+ if e.message.include?("GLIBC")
11
+ # lobzique: no installation guide to link to
12
+ warn(<<~EOM)
13
+
14
+ ERROR: It looks like you're trying to use lobzique as a precompiled native gem on a system
15
+ with an unsupported version of glibc.
16
+
17
+ #{e.message}
18
+
19
+ If that's the case, then please install lobzique via the `ruby` platform gem:
20
+ gem install lobzique --platform=ruby
21
+ or:
22
+ bundle config set force_ruby_platform true
23
+
24
+ EOM
25
+ raise e
26
+ end
27
+
28
+ # Not require_relative: the source gem compiles into its extension_dir,
29
+ # which is on $LOAD_PATH but not next to this file.
30
+ require "lobzique/lobzique"
31
+ end
@@ -0,0 +1,14 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Adapted from Nokogiri 1.19.7, lib/nokogiri/html.rb (MIT, see LICENSE-NOKOGIRI.md).
4
+
5
+ require_relative "html4"
6
+
7
+ module Lobzique
8
+ # Alias for Nokogiri::HTML4
9
+ HTML = HTML4
10
+
11
+ # :singleton-method: HTML
12
+ # Parse HTML. Convenience method for Nokogiri::HTML4::Document.parse
13
+ define_singleton_method(:HTML, Lobzique.method(:HTML4))
14
+ end