semantic-versions 1.0.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: 3e8202ecd584e7bb3ecb45fda43186b0c42d42bcbcdfe840f3121866c4c8ce31
4
+ data.tar.gz: 4ee9870fc43f9228aa41f445f793b906e37e1af8035f5602e9827e703b42468a
5
+ SHA512:
6
+ metadata.gz: ada3640c4e46c4fafadd2c91a92bf534b05639d1e2e609f0b74a0ce1850840232c5157b1b43c9d8361090fb0136d18f3d0750204777d9e3e3a181f964de1c7aa
7
+ data.tar.gz: be9934ce2d5e76fa67c7d276ca42e18baed16a60b45e5bb8404b25f6197aa9e1e966d360c7641390c37ee69ca87554681a6420228692460882a35fac5b52a084
data/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or Derivative
95
+ Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and do
117
+ not modify the License. You may add Your own attribution notices
118
+ within Derivative Works that You distribute, alongside or as an
119
+ addendum to the NOTICE text from the Work, provided that such
120
+ additional attribution notices cannot be construed as modifying
121
+ the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions for
125
+ use, reproduction, or distribution of Your modifications, or for any
126
+ such Derivative Works as a whole, provided Your use, reproduction,
127
+ and distribution of the Work otherwise complies with the conditions
128
+ stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or agreed
144
+ to in writing, Licensor provides the Work (and each Contributor
145
+ provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES
146
+ OR CONDITIONS OF ANY KIND, either express or implied, including,
147
+ without limitation, any warranties or conditions of TITLE,
148
+ NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR
149
+ PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor has
163
+ been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing the
166
+ Work or Derivative Works thereof, You may choose to offer, and charge
167
+ a fee for, acceptance of support, warranty, indemnity, or other
168
+ liability obligations and/or rights consistent with this License.
169
+ However, in accepting such obligations, You may act only on Your own
170
+ behalf and on Your sole responsibility, not on behalf of any other
171
+ Contributor, and only if You agree to indemnify, defend, and hold
172
+ each Contributor harmless for any liability incurred by, or claims
173
+ asserted against, such Contributor by reason of your accepting any
174
+ such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 vlt technologies, inc. and Semantic Versions contributors
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
data/README.md ADDED
@@ -0,0 +1,112 @@
1
+ # semantic-versions
2
+
3
+ The Ruby implementation of [**Semantic Versions**](https://semver.xyz): parse,
4
+ validate, compare and range-match version numbers, with builds that participate
5
+ in precedence.
6
+
7
+ It is a port of the JavaScript reference implementation
8
+ ([`semantic-versions`](https://www.npmjs.com/package/semantic-versions) on npm)
9
+ and behaves identically: both pass the same
10
+ [conformance suite](https://github.com/vltpkg/semantic-versions/tree/main/conformance),
11
+ and they agree on every version, range and resolution in the benchmark corpus.
12
+ Plain Ruby 3.1+, no dependencies.
13
+
14
+ ## Install
15
+
16
+ ```sh
17
+ gem install semantic-versions
18
+ ```
19
+
20
+ ## Usage
21
+
22
+ ```ruby
23
+ require "semantic_versions"
24
+ SV = SemanticVersions
25
+
26
+ v = SV.parse("1.2.3-beta.4+build.7")
27
+ [v.major, v.minor, v.patch, v.pre, v.build] # => [1, 2, 3, "beta.4", "build.7"]
28
+
29
+ # Builds participate in precedence: a build ranks above its plain release.
30
+ SV.parse("1.0.0") < SV.parse("1.0.0+build.1") # => true
31
+
32
+ SV.satisfies?("1.4.0", "^1.2.3") # => true
33
+ SV.satisfies?("1.0.0-rc.1", "^1.0.0-rc") # => true: pre-release channel
34
+ SV.satisfies?("1.0.0-beta", "^1.0.0-rc") # => false: a different channel
35
+ SV.satisfies?("1.4.2+win.x64", "^1.0.0+win") # => true: build channel
36
+ SV.valid_range("~>1.2") # => ">=1.2.0 <1.3.0-0"
37
+
38
+ # Contexts scope a version or range to an identity. Ranges work with case/when.
39
+ case SV.parse("npm:react@18.2.0")
40
+ when SV::Range.new("npm:react@^18") then "React 18"
41
+ end # => "React 18"
42
+
43
+ SV.max_satisfying(%w[1.0.0 1.9.0 2.0.0], "^1") # => "1.9.0"
44
+ SV.valid("v1.2.3") # => nil: no coercion
45
+ ```
46
+
47
+ `parse` raises `SemanticVersions::InvalidVersion` and `Range.new` raises
48
+ `SemanticVersions::InvalidRange` (both `ArgumentError`s).
49
+
50
+ ## How this differs from `semantic_range` and `Gem::Version`
51
+
52
+ - **Builds participate in precedence** (`1.0.0 < 1.0.0+build`), and a build on a
53
+ comparator is a [channel filter](https://semver.xyz/spec/#build-channels).
54
+ - **Pre-releases are range-driven**: a pre-release on a comparator is a
55
+ [prefix channel](https://semver.xyz/spec/#pre-release-channels) scoped to its
56
+ tuple; `X.Y.Z-*` and `*-*` opt in explicitly.
57
+ - **Contexts**: `npm:react@18.2.0`, `npm:@babel/core@^7`.
58
+ - **No coercion**: `v1.2.3` and `1.2` are errors.
59
+ - **npm-style ranges**, not RubyGems' `~> 1.2, >= 1.2.3` requirement syntax (though `~>` is supported as a tilde range).
60
+
61
+ ## Performance and conformance
62
+
63
+ Compared with [`semantic_range`](https://github.com/librariesio/semantic_range) and RubyGems' `Gem::Version` on real versions and dependency ranges from the npm registry. Method and raw
64
+ results: [`benchmarks/`](https://github.com/vltpkg/semantic-versions/tree/main/benchmarks).
65
+ All implementations: [semver.xyz/libraries](https://semver.xyz/libraries/).
66
+
67
+ <!-- benchmarks:start -->
68
+ <!-- Generated by benchmarks/report.mjs from benchmarks/results/. Do not edit by hand. -->
69
+
70
+ ### Speed
71
+
72
+ | Operation | `semantic-versions@1.0.0` | `semantic_range@3.1.1` | `Gem::Version@3.5.22` | semantic-versions vs semantic_range |
73
+ | --- | ---: | ---: | ---: | --- |
74
+ | Parse a version | **1.15 µs** | 1.79 µs | 1.00 µs | **1.6× faster** |
75
+ | Sort versions | **2.12 µs** | 18.9 µs | 3.67 µs | **8.9× faster** |
76
+ | Parse a range | **5.92 µs** | 23.8 µs | — | **4.0× faster** |
77
+ | range.test(version) | **314 ns** | 6.15 µs | — | **20× faster** |
78
+ | Resolve a range | **54.4 µs** | 885.3 µs | — | **16× faster** |
79
+
80
+ <sub>Median time per operation (lower is better) on 5,398 published versions and 1,996 dependency ranges from the npm registry. ruby 3.3.6 · Intel(R) Xeon(R) Processor @ 2.30GHz · linux x86_64 · 2026-11-19. `Gem::Version`: Parsing is timed without Gem::Version.new's per-string cache, and Gem::Version defers splitting into segments until the first comparison (part of its sort time). RubyGems' own requirement syntax (~> 1.2, comma-separated comparators, no ^, || or x-ranges) and lenient versions (1.2 is accepted), so it is compared on versions only.</sub>
81
+
82
+ ### Conformance
83
+
84
+ | Semantic Versions feature | `semantic-versions` | `semantic_range` | `Gem::Version` |
85
+ | --- | :---: | :---: | :---: |
86
+ | Version grammar <br><sub>Valid and invalid versions per the BNF</sub> | ✓ 81/81 | ◐ 80/81 | ◐ 37/81 |
87
+ | No coercion <br><sub>Rejects `v1.2.3`, `=1.2.3`, `1.2.3pre`, …</sub> | ✓ 11/11 | ◐ 10/11 | ◐ 9/11 |
88
+ | Precedence <br><sub>Major, minor, patch and pre-release ordering</sub> | ✓ 32/32 | ✓ 32/32 | ◐ 24/32 |
89
+ | Build precedence <br><sub>A build ranks above its release: `1.0.0 < 1.0.0+b`</sub> | ✓ 10/10 | ◐ 1/10 | ◐ 1/10 |
90
+ | Ranges <br><sub>Comparators, `\|\|`, x-ranges, `~`, `^`, hyphen ranges</sub> | ✓ 199/199 | ◐ 174/199 | ◐ 104/172 |
91
+ | Approximate ranges <br><sub>The pessimistic operator `~>`</sub> | ✓ 17/17 | ◐ 13/17 | ◐ 12/13 |
92
+ | Pre-release channels <br><sub>`^1.0.0-rc` admits `rc.*`, never `beta`</sub> | ✓ 44/44 | ◐ 33/44 | ◐ 32/44 |
93
+ | Pre-release wildcards <br><sub>`X.Y.Z-*` and `*-*` opt in explicitly</sub> | ✓ 14/14 | ◐ 2/14 | ◐ 2/13 |
94
+ | Build channels <br><sub>`^1.0.0+win` admits `+win.*` builds only</sub> | ✓ 24/24 | ◐ 12/24 | ◐ 12/22 |
95
+ | Contexts <br><sub>`npm:react@18.2.0`, `npm:react@^18`</sub> | ✓ 15/15 | ◐ 3/15 | ◐ 3/15 |
96
+ | **All cases** | **447/447** | **360/447** | **236/413** |
97
+
98
+ <sub>Cases from the shared conformance suite in [`conformance/`](https://github.com/vltpkg/semantic-versions/tree/main/conformance), drawn from the specification. ✓ all pass · ◐ some pass · ✗ none pass.</sub>
99
+
100
+ <!-- benchmarks:end -->
101
+
102
+ ## Develop
103
+
104
+ ```sh
105
+ bundle install
106
+ bundle exec rake test # conformance suite
107
+ bundle exec rake bench # benchmarks
108
+ ```
109
+
110
+ ## License
111
+
112
+ Apache-2.0. The specification is at [semver.xyz](https://semver.xyz/spec/).
@@ -0,0 +1 @@
1
+ require_relative "semantic_versions"
@@ -0,0 +1,7 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Kept in its own file so the gemspec can read it without loading the library,
4
+ # which needs Ruby 3.1 (builds then work on any Ruby, including macOS's).
5
+ module SemanticVersions
6
+ VERSION = "1.0.0"
7
+ end
@@ -0,0 +1,575 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Parse, compare and match versions per the Semantic Versions specification
4
+ # (https://semver.xyz). A port of the JavaScript reference implementation
5
+ # (semantic-versions on npm), checked against the same conformance suite.
6
+ require_relative "semantic_versions/version"
7
+
8
+ module SemanticVersions
9
+ MAX_LENGTH = 256
10
+ MAX_SAFE_INTEGER = 9_007_199_254_740_991
11
+
12
+ class Error < ArgumentError; end
13
+ class InvalidVersion < Error; end
14
+ class InvalidRange < Error; end
15
+
16
+ NUM = "(?:0|[1-9][0-9]*)"
17
+ PRE_ID = "(?:0|[1-9][0-9]*|[0-9]*[A-Za-z-][0-9A-Za-z-]*)"
18
+ BUILD_ID = "[0-9A-Za-z-]+"
19
+ PRE = "#{PRE_ID}(?:\\.#{PRE_ID})*"
20
+ BUILD = "#{BUILD_ID}(?:\\.#{BUILD_ID})*"
21
+ VERSION_RE = /\A(#{NUM})\.(#{NUM})\.(#{NUM})(?:-(#{PRE}))?(?:\+(#{BUILD}))?\z/
22
+ PLAIN_RE = /\A#{NUM}\.#{NUM}\.#{NUM}\z/
23
+ PRE_RE = /\A#{PRE}\z/
24
+ BUILD_RE = /\A#{BUILD}\z/
25
+ XR = "(?:[xX*]|0|[1-9][0-9]*)"
26
+ PARTIAL_RE = /\A(#{XR})(?:\.(#{XR})(?:\.(#{XR})(?:-([^+]*))?(?:\+(.*))?)?)?\z/m
27
+ TUPLE_PRE_RE = /\A(<=|>=|\^|~|<|>|=)?(#{NUM})\.(#{NUM})\.(#{NUM})-\*\z/
28
+ private_constant :NUM, :PRE_ID, :BUILD_ID, :PRE, :BUILD, :VERSION_RE, :PLAIN_RE, :PRE_RE, :BUILD_RE,
29
+ :XR, :PARTIAL_RE, :TUPLE_PRE_RE
30
+
31
+ # A release ranks above its pre-releases; a build ranks above its release.
32
+ RELEASE = [1, [].freeze].freeze
33
+ NO_BUILD = [0, [].freeze].freeze
34
+ private_constant :RELEASE, :NO_BUILD
35
+
36
+ module Util # :nodoc:
37
+ module_function
38
+
39
+ def safe?(n)
40
+ n.length <= 16 && n.to_i <= MAX_SAFE_INTEGER
41
+ end
42
+
43
+ # The JavaScript reference requires numeric pre-release identifiers to be
44
+ # below MAX_SAFE_INTEGER.
45
+ def pre_safe?(pre)
46
+ pre.split(".").none? { |i| i.length >= 16 && i.match?(/\A\d+\z/) && i.to_i >= MAX_SAFE_INTEGER }
47
+ end
48
+
49
+ # Numeric identifiers sort numerically and below alphanumeric ones.
50
+ def ids_key(ids)
51
+ ids.split(".").map { |i| i.match?(/\A\d+\z/) ? [0, i.to_i] : [1, i] }
52
+ end
53
+
54
+ # Identifier-wise prefix: "rc" begins "rc.1" but not "rc1".
55
+ def starts_with?(ids, prefix)
56
+ prefix.empty? || ids == prefix || ids.start_with?("#{prefix}.")
57
+ end
58
+ end
59
+ private_constant :Util
60
+
61
+ # Split an optional context off a reference: "npm:react@1.2.3" →
62
+ # ["npm:react", "1.2.3"]. The context ends at the last "@" of the first
63
+ # whitespace-delimited token; an "@" at position 0 means there is none.
64
+ def self.split_reference(value)
65
+ return [nil, value] unless value.include?("@")
66
+
67
+ i = value =~ /\s/
68
+ head, tail = i ? [value[0...i], value[i..]] : [value, ""]
69
+ at = head.rindex("@")
70
+ at&.positive? ? [head[0...at], head[(at + 1)..] + tail] : [nil, value]
71
+ end
72
+
73
+ # A parsed Semantic Version, optionally scoped to a context.
74
+ #
75
+ # Ordering follows the specification: pre-releases rank below their release
76
+ # and builds rank above it (1.0.0-rc < 1.0.0 < 1.0.0+build). The context
77
+ # never participates in precedence or equality.
78
+ class Version
79
+ include Comparable
80
+
81
+ # The precedence key: [major, minor, patch, pre-release key, build key].
82
+ attr_reader :key
83
+ attr_reader :pre, :build, :context
84
+
85
+ def initialize(major, minor, patch, pre = "", build = "", context = nil)
86
+ # Few instance variables keep the object small (major, minor and patch
87
+ # live in the key).
88
+ @key = [major, minor, patch,
89
+ pre.empty? ? RELEASE : [0, Util.ids_key(pre)],
90
+ build.empty? ? NO_BUILD : [1, Util.ids_key(build)]]
91
+ @pre = pre
92
+ @build = build
93
+ @context = context
94
+ end
95
+
96
+ def major
97
+ @key[0]
98
+ end
99
+
100
+ def minor
101
+ @key[1]
102
+ end
103
+
104
+ def patch
105
+ @key[2]
106
+ end
107
+
108
+ # Parse a version, optionally context-qualified ("npm:react@1.2.3").
109
+ # There is no coercion: "v1.2.3" and "1.2" raise InvalidVersion.
110
+ def self.parse(value)
111
+ raise InvalidVersion, "version is longer than #{MAX_LENGTH} characters" if value.length > MAX_LENGTH
112
+
113
+ # Fast path: most versions are a bare major.minor.patch.
114
+ if value.length < 16 && PLAIN_RE.match?(value)
115
+ major, minor, patch = value.split(".")
116
+ return new(major.to_i, minor.to_i, patch.to_i)
117
+ end
118
+
119
+ context = nil
120
+ m = VERSION_RE.match(value)
121
+ if m.nil?
122
+ context, rest = SemanticVersions.split_reference(value)
123
+ m = VERSION_RE.match(rest.strip)
124
+ raise InvalidVersion, "invalid version: #{value.inspect}" if m.nil?
125
+ end
126
+ major, minor, patch, pre, build = m.captures
127
+ if value.length >= 16
128
+ raise InvalidVersion, "version component too large: #{value.inspect}" unless
129
+ Util.safe?(major) && Util.safe?(minor) && Util.safe?(patch)
130
+ raise InvalidVersion, "pre-release identifier too large: #{value.inspect}" if pre && !Util.pre_safe?(pre)
131
+ end
132
+ new(major.to_i, minor.to_i, patch.to_i, pre || "", build || "", context)
133
+ end
134
+
135
+ def prerelease?
136
+ !@pre.empty?
137
+ end
138
+
139
+ def without_build
140
+ Version.new(@key[0], @key[1], @key[2], @pre, "", @context)
141
+ end
142
+
143
+ # The context-qualified form, "context@version", or the bare version.
144
+ def reference
145
+ @context ? "#{@context}@#{self}" : to_s
146
+ end
147
+
148
+ def <=>(other)
149
+ other.is_a?(Version) ? @key <=> other.key : nil
150
+ end
151
+
152
+ def eql?(other)
153
+ other.is_a?(Version) && @key == other.key
154
+ end
155
+
156
+ def hash
157
+ @key.hash
158
+ end
159
+
160
+ def to_s
161
+ s = +"#{@key[0]}.#{@key[1]}.#{@key[2]}"
162
+ s << "-" << @pre unless @pre.empty?
163
+ s << "+" << @build unless @build.empty?
164
+ s
165
+ end
166
+
167
+ def inspect
168
+ "#<SemanticVersions::Version #{reference}>"
169
+ end
170
+ end
171
+
172
+ # A primitive comparator: an operator and a bound, or "any". A build on the
173
+ # bound is a build channel (a prefix filter on the candidate's build); a
174
+ # pre-release on it declares a pre-release channel for its tuple.
175
+ class Comparator
176
+ attr_reader :op, :version
177
+
178
+ def initialize(op, version)
179
+ @op = op
180
+ @version = version
181
+ @bound = version&.key&.first(4)
182
+ @channel = version&.build
183
+ end
184
+
185
+ # ">=0.0.0" bounds nothing: it is the "any" comparator.
186
+ def self.make(op, version)
187
+ if op == ">=" && version.major.zero? && version.minor.zero? && version.patch.zero? &&
188
+ version.pre.empty? && version.build.empty?
189
+ return ANY
190
+ end
191
+
192
+ new(op, version)
193
+ end
194
+
195
+ def any?
196
+ @version.nil?
197
+ end
198
+
199
+ def null?
200
+ v = @version
201
+ !v.nil? && @op == "<" && v.major.zero? && v.minor.zero? && v.patch.zero? && v.pre == "0" && v.build.empty?
202
+ end
203
+
204
+ def test(version)
205
+ return true if @bound.nil?
206
+
207
+ k = version.key
208
+ b = @bound
209
+ c = k[0] <=> b[0]
210
+ c = k[1] <=> b[1] if c.zero?
211
+ c = k[2] <=> b[2] if c.zero?
212
+ c = k[3] <=> b[3] if c.zero?
213
+ ok = case @op
214
+ when "<" then c.negative?
215
+ when ">=" then c >= 0
216
+ when "<=" then c <= 0
217
+ when ">" then c.positive?
218
+ else c.zero?
219
+ end
220
+ ok && (@channel.empty? || Util.starts_with?(version.build, @channel))
221
+ end
222
+
223
+ def same?(other)
224
+ return false unless @op == other.op
225
+
226
+ a = @version
227
+ b = other.version
228
+ return a.nil? && b.nil? if a.nil? || b.nil?
229
+
230
+ a.major == b.major && a.minor == b.minor && a.patch == b.patch && a.pre == b.pre && a.build == b.build
231
+ end
232
+
233
+ def to_s
234
+ @version.nil? ? "" : "#{@op}#{@version}"
235
+ end
236
+
237
+ ANY = new("", nil)
238
+ end
239
+
240
+ ANY = Comparator::ANY
241
+ private_constant :ANY
242
+
243
+ # A parsed range: comparator sets joined by "||", optionally scoped to a
244
+ # context ("npm:react@^18"). Advanced syntax (hyphen, x-ranges, ~, ~>, ^,
245
+ # -*, *-*) desugars to primitive comparators exactly as in the spec.
246
+ class Range
247
+ Partial = Struct.new(:major, :minor, :patch, :pre, :build) # :nodoc:
248
+ ComparatorSet = Struct.new(:comparators, :universal_pre, :any_pre) do # :nodoc:
249
+ def test(v)
250
+ return false unless comparators.all? { |c| c.test(v) }
251
+ return true if v.pre.empty? || universal_pre
252
+ return true if any_pre.include?([v.major, v.minor, v.patch])
253
+
254
+ # A pre-release is admitted only by a comparator that declares a
255
+ # channel on the same tuple whose identifiers it begins with.
256
+ comparators.any? do |c|
257
+ b = c.version
258
+ b && !b.pre.empty? && b.major == v.major && b.minor == v.minor && b.patch == v.patch &&
259
+ Util.starts_with?(v.pre, b.pre)
260
+ end
261
+ end
262
+ end
263
+ private_constant :Partial, :ComparatorSet
264
+
265
+ OPERATORS = %w[< <= > >= = ~ ~> ^].freeze
266
+ PREFIXES = [">=", "<=", ">", "<", "="].freeze
267
+ private_constant :OPERATORS, :PREFIXES
268
+
269
+ attr_reader :raw, :context
270
+
271
+ def initialize(value)
272
+ raise InvalidRange, "range is longer than #{MAX_LENGTH} characters" if value.length > MAX_LENGTH
273
+
274
+ @raw = value
275
+ @context, body = SemanticVersions.split_reference(value)
276
+ # "".split returns [], but an empty range is one set that matches all.
277
+ parts = body.empty? ? [body] : body.split("||", -1)
278
+ sets = parts.map { |part| parse_set(part.strip) }
279
+ if sets.length > 1
280
+ # Drop sets that can match nothing (unless that is all there is), and
281
+ # collapse to "any" if any set matches everything.
282
+ first = sets.first
283
+ sets = sets.reject { |s| s.comparators.first&.null? }
284
+ if sets.empty?
285
+ sets = [first]
286
+ elsif sets.length > 1
287
+ universal = sets.find { |s| s.comparators.length == 1 && s.comparators[0].any? }
288
+ sets = [universal] if universal
289
+ end
290
+ end
291
+ @sets = sets
292
+ end
293
+
294
+ def self.parse(value)
295
+ new(value)
296
+ end
297
+
298
+ def comparator_sets
299
+ @sets.map { |s| s.comparators.dup }
300
+ end
301
+
302
+ # True if version satisfies the range. A context-scoped range only admits
303
+ # versions of the same context.
304
+ def test(version)
305
+ return false if @context && version.context != @context
306
+
307
+ @sets.any? { |s| s.test(version) }
308
+ end
309
+ alias satisfied_by? test
310
+ alias include? test
311
+ alias === test
312
+
313
+ def to_s
314
+ @sets.map { |s| s.comparators.reject(&:any?).join(" ") }.join("||")
315
+ end
316
+
317
+ def inspect
318
+ "#<SemanticVersions::Range #{@raw.inspect}>"
319
+ end
320
+
321
+ private
322
+
323
+ def invalid!
324
+ raise InvalidRange, "invalid range: #{@raw.inspect}"
325
+ end
326
+
327
+ def xr(s)
328
+ return nil if s.nil? || s == "x" || s == "X" || s == "*"
329
+
330
+ invalid! unless Util.safe?(s)
331
+ s.to_i
332
+ end
333
+
334
+ def partial(s)
335
+ m = PARTIAL_RE.match(s) || invalid!
336
+ major, minor, patch, pre, build = m.captures
337
+ invalid! if pre && (!PRE_RE.match?(pre) || !Util.pre_safe?(pre))
338
+ invalid! if build && !BUILD_RE.match?(build)
339
+ Partial.new(xr(major), xr(minor), xr(patch), pre || "", build || "")
340
+ end
341
+
342
+ def v(major, minor, patch, pre = "")
343
+ Version.new(major, minor, patch, pre)
344
+ end
345
+
346
+ def cmp(op, version)
347
+ Comparator.make(op, version)
348
+ end
349
+
350
+ def with_channel(comps, channel)
351
+ return comps if channel.empty?
352
+
353
+ comps.map do |c|
354
+ if c.any?
355
+ # A channel turns ">=0.0.0" back into a real bound.
356
+ Comparator.new(">=", Version.new(0, 0, 0, "", channel))
357
+ else
358
+ b = c.version
359
+ Comparator.new(c.op, Version.new(b.major, b.minor, b.patch, b.pre, channel))
360
+ end
361
+ end
362
+ end
363
+
364
+ def tilde(p)
365
+ return [ANY] if p.major.nil?
366
+
367
+ m = p.major
368
+ mi = p.minor || 0
369
+ out = if p.minor.nil?
370
+ [cmp(">=", v(m, 0, 0)), cmp("<", v(m + 1, 0, 0, "0"))]
371
+ elsif p.patch.nil?
372
+ [cmp(">=", v(m, mi, 0)), cmp("<", v(m, mi + 1, 0, "0"))]
373
+ else
374
+ [cmp(">=", v(m, mi, p.patch, p.pre)), cmp("<", v(m, mi + 1, 0, "0"))]
375
+ end
376
+ with_channel(out, p.build)
377
+ end
378
+
379
+ def caret(p)
380
+ return [ANY] if p.major.nil?
381
+
382
+ m = p.major
383
+ mi = p.minor || 0
384
+ pa = p.patch || 0
385
+ out = if p.minor.nil?
386
+ [cmp(">=", v(m, 0, 0)), cmp("<", v(m + 1, 0, 0, "0"))]
387
+ elsif p.patch.nil?
388
+ upper = m.zero? ? v(0, mi + 1, 0, "0") : v(m + 1, 0, 0, "0")
389
+ [cmp(">=", v(m, mi, 0)), cmp("<", upper)]
390
+ else
391
+ upper = if m.zero?
392
+ mi.zero? ? v(0, 0, pa + 1, "0") : v(0, mi + 1, 0, "0")
393
+ else
394
+ v(m + 1, 0, 0, "0")
395
+ end
396
+ [cmp(">=", v(m, mi, pa, p.pre)), cmp("<", upper)]
397
+ end
398
+ with_channel(out, p.build)
399
+ end
400
+
401
+ def xrange(op, p)
402
+ xm = p.major.nil? || p.minor.nil?
403
+ any_x = xm || p.patch.nil?
404
+ return [%w[> <].include?(op) ? cmp("<", v(0, 0, 0, "0")) : ANY] if p.major.nil?
405
+
406
+ m = p.major
407
+ mi = xm ? 0 : p.minor
408
+ if any_x && op != ""
409
+ return [case op
410
+ when ">" then cmp(">=", xm ? v(m + 1, 0, 0) : v(m, mi + 1, 0))
411
+ when "<=" then cmp("<", xm ? v(m + 1, 0, 0, "0") : v(m, mi + 1, 0, "0"))
412
+ when "<" then cmp("<", v(m, mi, 0, "0"))
413
+ else cmp(op, v(m, mi, 0))
414
+ end]
415
+ end
416
+ return [cmp(">=", v(m, 0, 0)), cmp("<", v(m + 1, 0, 0, "0"))] if xm
417
+ return [cmp(">=", v(m, mi, 0)), cmp("<", v(m, mi + 1, 0, "0"))] if p.patch.nil?
418
+
419
+ [cmp(op, Version.new(m, mi, p.patch, p.pre, p.build))]
420
+ end
421
+
422
+ def hyphen(a, b)
423
+ out = []
424
+ unless a.major.nil?
425
+ lower = if a.minor.nil? then v(a.major, 0, 0)
426
+ elsif a.patch.nil? then v(a.major, a.minor, 0)
427
+ else v(a.major, a.minor, a.patch, a.pre)
428
+ end
429
+ out << cmp(">=", lower)
430
+ end
431
+ unless b.major.nil?
432
+ out << if b.minor.nil? then cmp("<", v(b.major + 1, 0, 0, "0"))
433
+ elsif b.patch.nil? then cmp("<", v(b.major, b.minor + 1, 0, "0"))
434
+ else cmp("<=", v(b.major, b.minor, b.patch, b.pre))
435
+ end
436
+ end
437
+ out.empty? ? [ANY] : out
438
+ end
439
+
440
+ def comparator_token(tok)
441
+ return [ANY] if tok.empty? || tok == "*"
442
+ return caret(partial(tok[1..])) if tok.start_with?("^")
443
+ return tilde(partial(tok.start_with?("~>") ? tok[2..] : tok[1..])) if tok.start_with?("~")
444
+
445
+ PREFIXES.each do |op|
446
+ return xrange(op == "=" ? "" : op, partial(tok[op.length..])) if tok.start_with?(op)
447
+ end
448
+ xrange("", partial(tok))
449
+ end
450
+
451
+ def parse_set(s)
452
+ universal_pre = false
453
+ any_pre = []
454
+ tokens = s.split.map do |tok|
455
+ if tok == "*-*"
456
+ universal_pre = true
457
+ ">=0.0.0-0"
458
+ elsif tok.end_with?("-*") && (m = TUPLE_PRE_RE.match(tok))
459
+ op, a, b, c = m.captures
460
+ any_pre << [a.to_i, b.to_i, c.to_i]
461
+ "#{op}#{a}.#{b}.#{c}-0"
462
+ else
463
+ tok
464
+ end
465
+ end
466
+
467
+ comps = []
468
+ if tokens.length == 3 && tokens[1] == "-"
469
+ comps = hyphen(partial(tokens[0]), partial(tokens[2]))
470
+ else
471
+ i = 0
472
+ while i < tokens.length
473
+ # ">= 1.2.3", "~ 1.2": an operator separated from its version.
474
+ if OPERATORS.include?(tokens[i]) && i + 1 < tokens.length
475
+ comps.concat(comparator_token(tokens[i] + tokens[i + 1]))
476
+ i += 2
477
+ else
478
+ comps.concat(comparator_token(tokens[i]))
479
+ i += 1
480
+ end
481
+ end
482
+ comps = [ANY] if comps.empty?
483
+ end
484
+
485
+ # A comparator that can match nothing makes the whole set match nothing.
486
+ null = comps.find(&:null?)
487
+ return ComparatorSet.new([null], universal_pre, any_pre) if null
488
+
489
+ unique = []
490
+ comps.each { |c| unique << c unless unique.any? { |u| u.same?(c) } }
491
+ unique = unique.reject(&:any?) if unique.length > 1
492
+ ComparatorSet.new(unique, universal_pre, any_pre)
493
+ end
494
+ end
495
+
496
+ module_function
497
+
498
+ # Parse a version; raises InvalidVersion.
499
+ def parse(version)
500
+ Version.parse(version)
501
+ end
502
+
503
+ # The normalized version, or nil if it is not a version.
504
+ def valid(version)
505
+ Version.parse(version).to_s
506
+ rescue Error
507
+ nil
508
+ end
509
+
510
+ # The desugared range ("*" when it matches everything), or nil.
511
+ def valid_range(range)
512
+ out = Range.new(range).to_s
513
+ out.empty? ? "*" : out
514
+ rescue Error
515
+ nil
516
+ end
517
+
518
+ # -1, 0 or 1 by precedence (builds rank above their release).
519
+ def compare(a, b)
520
+ Version.parse(a) <=> Version.parse(b)
521
+ end
522
+
523
+ def satisfies?(version, range)
524
+ # Mirrors the JavaScript reference: an identical string trivially matches.
525
+ return !valid(version).nil? if version == range
526
+
527
+ Range.new(range).test(Version.parse(version))
528
+ rescue Error
529
+ false
530
+ end
531
+
532
+ # The highest version in versions that satisfies range, or nil.
533
+ def max_satisfying(versions, range)
534
+ pick(versions, range) { |a, b| (a <=> b).positive? }
535
+ end
536
+
537
+ # The lowest version in versions that satisfies range, or nil.
538
+ def min_satisfying(versions, range)
539
+ pick(versions, range) { |a, b| (a <=> b).negative? }
540
+ end
541
+
542
+ # Versions sorted ascending by precedence (stable).
543
+ def sort(versions)
544
+ versions.each_with_index.sort_by { |s, i| [Version.parse(s).key, i] }.map(&:first)
545
+ end
546
+
547
+ # Versions sorted descending by precedence (stable).
548
+ def rsort(versions)
549
+ sort(versions.reverse).reverse
550
+ end
551
+
552
+ def pick(versions, range)
553
+ r = begin
554
+ Range.new(range)
555
+ rescue Error
556
+ return nil
557
+ end
558
+ best = best_key = nil
559
+ versions.each do |s|
560
+ v = begin
561
+ Version.parse(s)
562
+ rescue Error
563
+ next
564
+ end
565
+ next unless r.test(v)
566
+
567
+ if best.nil? || yield(v.key, best_key)
568
+ best = s
569
+ best_key = v.key
570
+ end
571
+ end
572
+ best
573
+ end
574
+ private_class_method :pick
575
+ end
metadata ADDED
@@ -0,0 +1,52 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: semantic-versions
3
+ version: !ruby/object:Gem::Version
4
+ version: 1.0.0
5
+ platform: ruby
6
+ authors:
7
+ - vlt technology inc.
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2026-11-19 00:00:00.000000000 Z
12
+ dependencies: []
13
+ description: 'A port of the semantic-versions reference implementation: strict parsing,
14
+ build precedence, pre-release and build channels, contexts and npm-style ranges.'
15
+ email:
16
+ executables: []
17
+ extensions: []
18
+ extra_rdoc_files: []
19
+ files:
20
+ - LICENSE
21
+ - README.md
22
+ - lib/semantic-versions.rb
23
+ - lib/semantic_versions.rb
24
+ - lib/semantic_versions/version.rb
25
+ homepage: https://semver.xyz/libraries/#ruby
26
+ licenses:
27
+ - Apache-2.0
28
+ metadata:
29
+ source_code_uri: https://github.com/vltpkg/semantic-versions/tree/main/ports/ruby
30
+ documentation_uri: https://semver.xyz/spec/
31
+ rubygems_mfa_required: 'true'
32
+ post_install_message:
33
+ rdoc_options: []
34
+ require_paths:
35
+ - lib
36
+ required_ruby_version: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - ">="
39
+ - !ruby/object:Gem::Version
40
+ version: '3.1'
41
+ required_rubygems_version: !ruby/object:Gem::Requirement
42
+ requirements:
43
+ - - ">="
44
+ - !ruby/object:Gem::Version
45
+ version: '0'
46
+ requirements: []
47
+ rubygems_version: 3.0.3.1
48
+ signing_key:
49
+ specification_version: 4
50
+ summary: Parse, compare and match versions per the Semantic Versions specification
51
+ (semver.xyz)
52
+ test_files: []