pgchangeling-semver 0.0.0-stage → 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.
package/LICENSE ADDED
@@ -0,0 +1,27 @@
1
+ Copyright (c) 2013, Konstantine Rybnikov
2
+ All rights reserved.
3
+
4
+ Redistribution and use in source and binary forms, with or without modification,
5
+ are permitted provided that the following conditions are met:
6
+
7
+ Redistributions of source code must retain the above copyright notice, this
8
+ list of conditions and the following disclaimer.
9
+
10
+ Redistributions in binary form must reproduce the above copyright notice, this
11
+ list of conditions and the following disclaimer in the documentation and/or
12
+ other materials provided with the distribution.
13
+
14
+ Neither the name of the python-semver org nor the names of its
15
+ contributors may be used to endorse or promote products derived from
16
+ this software without specific prior written permission.
17
+
18
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
19
+ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
20
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
21
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
22
+ ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
23
+ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
24
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
25
+ ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
27
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package/README.md CHANGED
@@ -1,3 +1,34 @@
1
- # Temporary Holding Version
1
+ # pgchangeling-semver
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The module-level functions of the Python package
4
+ [python-semver](https://pypi.org/project/semver/) 3, in TypeScript, giving the answers
5
+ Python gives. It is a port, not the original: it was proved by replaying 24,876 calls
6
+ recorded from python-semver 3 on Python 3.12, and every one matched. It has no runtime
7
+ dependencies, and the library files import no Node built-in modules.
8
+
9
+ ```sh
10
+ npm install pgchangeling-semver
11
+ ```
12
+
13
+ ```ts
14
+ import { compare, match, parse, bumpMinor, finalizeVersion, isValid } from "pgchangeling-semver";
15
+
16
+ compare("1.0.0", "2.0.0"); // -1
17
+ match("2.3.7", ">=2.3.6"); // true
18
+ parse("1.2.3"); // { major: 1n, minor: 2n, patch: 3n, prerelease: null, build: null }
19
+ bumpMinor("1.2.3"); // "1.3.0"
20
+ finalizeVersion("1.2.3-rc.5"); // "1.2.3"
21
+ isValid("1.2.3"); // true
22
+ ```
23
+
24
+ Version numbers are `bigint`, as Python integers have no size limit. Invalid input throws
25
+ a `PyError` whose `pyType` is the name of the exception Python raises (`ValueError` or
26
+ `TypeError`). `call(name, args, kwargs)` calls any ported function by its Python name,
27
+ such as `call("bump_major", ["1.2.3"])`.
28
+
29
+ Needs Node 22 or later, or any runtime with ES2022 and `BigInt`.
30
+
31
+ - Source, tapes and how to replay them: <https://github.com/Pushkal-Gupta/pgchangeling-semver-ts>
32
+ - The port's page, with its match rate: <https://changeling.pgremlin.com/ports/semver-ts>
33
+
34
+ BSD 3-Clause, as python-semver is; see LICENSE.
@@ -0,0 +1,129 @@
1
+ import { type PyValue } from "./py.js";
2
+ export { Version } from "./version.js";
3
+ export { PyFloat, PyError, type PyValue } from "./py.js";
4
+ /** Call a python-semver function by name with Python-shaped arguments. Returns undefined
5
+ * when the name is not one of the ported functions. */
6
+ export declare function call(name: string, args: PyValue[], kwargs?: Record<string, PyValue>): PyValue | undefined;
7
+ export declare const FUNCTIONS: string[];
8
+ /**
9
+ * Compares two semantic versions, matching python-semver's `compare` function.
10
+ *
11
+ * @throws {PyError} With `pyType` `ValueError` for an invalid version, or `TypeError` for a non-string input.
12
+ * @example
13
+ * ```ts
14
+ * compare("1.0.0", "2.0.0"); // -1
15
+ * ```
16
+ */
17
+ export declare const compare: (a: string, b: string) => number;
18
+ /**
19
+ * Parses a semantic version into its components, matching python-semver's `parse` function.
20
+ *
21
+ * @throws {PyError} With `pyType` `ValueError` for an invalid version, or `TypeError` for a non-string input.
22
+ * @example
23
+ * ```ts
24
+ * parse("1.2.3"); // { major: 1n, minor: 2n, patch: 3n, prerelease: null, build: null }
25
+ * ```
26
+ */
27
+ export declare const parse: (v: string) => {
28
+ [key: string]: PyValue;
29
+ };
30
+ /**
31
+ * Tests a semantic version against a comparison expression, matching python-semver's `match` function.
32
+ *
33
+ * @throws {PyError} With `pyType` `ValueError` for an invalid version or expression, or `TypeError` for a non-string input.
34
+ * @example
35
+ * ```ts
36
+ * match("2.3.7", ">=2.3.6"); // true
37
+ * ```
38
+ */
39
+ export declare const match: (v: string, expr: string) => boolean;
40
+ /**
41
+ * Returns the greater version, keeping the first on a tie, matching python-semver's `max_ver` function.
42
+ *
43
+ * @throws {PyError} With `pyType` `ValueError` for an invalid version, or `TypeError` for a non-string input.
44
+ * @example
45
+ * ```ts
46
+ * maxVer("1.2.3", "1.2.4"); // "1.2.4"
47
+ * ```
48
+ */
49
+ export declare const maxVer: (a: string, b: string) => string;
50
+ /**
51
+ * Returns the lesser version, keeping the first on a tie, matching python-semver's `min_ver` function.
52
+ *
53
+ * @throws {PyError} With `pyType` `ValueError` for an invalid version, or `TypeError` for a non-string input.
54
+ * @example
55
+ * ```ts
56
+ * minVer("1.2.3", "1.2.4"); // "1.2.3"
57
+ * ```
58
+ */
59
+ export declare const minVer: (a: string, b: string) => string;
60
+ /**
61
+ * Increments the major component and resets the rest, matching python-semver's `bump_major` function.
62
+ *
63
+ * @throws {PyError} With `pyType` `ValueError` for an invalid version, or `TypeError` for a non-string input.
64
+ * @example
65
+ * ```ts
66
+ * bumpMajor("1.2.3"); // "2.0.0"
67
+ * ```
68
+ */
69
+ export declare const bumpMajor: (v: string) => string;
70
+ /**
71
+ * Increments the minor component and resets later components, matching python-semver's `bump_minor` function.
72
+ *
73
+ * @throws {PyError} With `pyType` `ValueError` for an invalid version, or `TypeError` for a non-string input.
74
+ * @example
75
+ * ```ts
76
+ * bumpMinor("1.2.3"); // "1.3.0"
77
+ * ```
78
+ */
79
+ export declare const bumpMinor: (v: string) => string;
80
+ /**
81
+ * Increments the patch component and removes suffixes, matching python-semver's `bump_patch` function.
82
+ *
83
+ * @throws {PyError} With `pyType` `ValueError` for an invalid version, or `TypeError` for a non-string input.
84
+ * @example
85
+ * ```ts
86
+ * bumpPatch("1.2.3"); // "1.2.4"
87
+ * ```
88
+ */
89
+ export declare const bumpPatch: (v: string) => string;
90
+ /**
91
+ * Increments or adds a prerelease identifier, matching python-semver's `bump_prerelease` function.
92
+ *
93
+ * @throws {PyError} With `pyType` `ValueError` for an invalid version or token, or `TypeError` for a non-string input.
94
+ * @example
95
+ * ```ts
96
+ * bumpPrerelease("1.2.3"); // "1.2.3-rc.1"
97
+ * ```
98
+ */
99
+ export declare const bumpPrerelease: (v: string, token?: string | null) => string;
100
+ /**
101
+ * Increments or adds a build identifier, matching python-semver's `bump_build` function.
102
+ *
103
+ * @throws {PyError} With `pyType` `ValueError` for an invalid version or token, or `TypeError` for a non-string input.
104
+ * @example
105
+ * ```ts
106
+ * bumpBuild("1.2.3"); // "1.2.3+build.1"
107
+ * ```
108
+ */
109
+ export declare const bumpBuild: (v: string, token?: string | null) => string;
110
+ /**
111
+ * Removes prerelease and build suffixes, matching python-semver's `finalize_version` function.
112
+ *
113
+ * @throws {PyError} With `pyType` `ValueError` for an invalid version, or `TypeError` for a non-string input.
114
+ * @example
115
+ * ```ts
116
+ * finalizeVersion("1.2.3-rc.5"); // "1.2.3"
117
+ * ```
118
+ */
119
+ export declare const finalizeVersion: (v: string) => string;
120
+ /**
121
+ * Reports whether a string is a valid semantic version, matching python-semver's `Version.is_valid` function.
122
+ *
123
+ * @throws {PyError} With `pyType` `TypeError` for a non-string input; invalid strings return `false` instead of throwing `ValueError`.
124
+ * @example
125
+ * ```ts
126
+ * isValid("1.2.3"); // true
127
+ * ```
128
+ */
129
+ export declare const isValid: (v: string) => boolean;
package/dist/index.js ADDED
@@ -0,0 +1,197 @@
1
+ // The module-level functions of python-semver 3 (src/semver/_deprecated.py), with the
2
+ // same names, argument handling and results. Each takes Python-shaped values (bigint for
3
+ // int, PyFloat for float) so that every call the original accepts can be expressed.
4
+ import { typeError } from "./py.js";
5
+ import { Version } from "./version.js";
6
+ export { Version } from "./version.js";
7
+ export { PyFloat, PyError } from "./py.js";
8
+ /** Bind positional and keyword arguments the way Python does for a plain signature,
9
+ * optionally collecting extra keywords (`**parts`). */
10
+ function bind(fn, params, args, kwargs, varKw) {
11
+ if (args.length > params.length) {
12
+ throw typeError(`${fn}() takes ${params.length} positional arguments but ${args.length} were given`);
13
+ }
14
+ const out = [...args];
15
+ const rest = {};
16
+ for (const [k, v] of Object.entries(kwargs)) {
17
+ const i = params.findIndex((p) => p.name === k);
18
+ if (i < 0) {
19
+ if (!varKw)
20
+ throw typeError(`${fn}() got an unexpected keyword argument '${k}'`);
21
+ rest[k] = v;
22
+ continue;
23
+ }
24
+ if (i < args.length)
25
+ throw typeError(`${fn}() got multiple values for argument '${k}'`);
26
+ out[i] = v;
27
+ }
28
+ const bound = params.map((p, i) => {
29
+ const v = out[i];
30
+ if (v !== undefined)
31
+ return v;
32
+ if (p.default === undefined)
33
+ throw typeError(`${fn}() missing required argument: '${p.name}'`);
34
+ return p.default;
35
+ });
36
+ return [bound, rest];
37
+ }
38
+ function def(params, impl, varKw = false) {
39
+ return (fn) => (args, kwargs = {}) => {
40
+ const [a, rest] = bind(fn, params, args, kwargs, varKw);
41
+ return impl(a, rest);
42
+ };
43
+ }
44
+ const p = (name, d) => (d === undefined ? { name } : { name, default: d });
45
+ const one = (f) => def([p("version")], ([v]) => String(f(Version.parse(v))));
46
+ const table = {
47
+ compare: def([p("ver1"), p("ver2")], ([a, b]) => BigInt(Version.parse(a).compare(b))),
48
+ parse: def([p("version")], ([v]) => Version.parse(v).toDict()),
49
+ match: def([p("version"), p("match_expr")], ([v, e]) => Version.parse(v).match(e)),
50
+ max_ver: def([p("ver1"), p("ver2")], ([a, b]) => {
51
+ const ka = Version.parse(a);
52
+ const kb = Version.parse(b);
53
+ return String(kb.compare(ka) > 0 ? b : a);
54
+ }),
55
+ min_ver: def([p("ver1"), p("ver2")], ([a, b]) => {
56
+ const ka = Version.parse(a);
57
+ const kb = Version.parse(b);
58
+ return String(kb.compare(ka) < 0 ? b : a);
59
+ }),
60
+ format_version: def([p("major"), p("minor"), p("patch"), p("prerelease", null), p("build", null)], (a) => String(Version.create(a))),
61
+ bump_major: one((v) => v.bumpMajor()),
62
+ bump_minor: one((v) => v.bumpMinor()),
63
+ bump_patch: one((v) => v.bumpPatch()),
64
+ bump_prerelease: def([p("version"), p("token", "rc")], ([v, t]) => String(Version.parse(v).bumpPrerelease(t))),
65
+ bump_build: def([p("version"), p("token", "build")], ([v, t]) => String(Version.parse(v).bumpBuild(t))),
66
+ finalize_version: one((v) => v.finalizeVersion()),
67
+ replace: def([p("version")], ([v], parts) => String(Version.parse(v).replace(parts)), true),
68
+ "Version.is_valid": def([p("version")], ([v]) => Version.isValid(v)),
69
+ };
70
+ /** Call a python-semver function by name with Python-shaped arguments. Returns undefined
71
+ * when the name is not one of the ported functions. */
72
+ export function call(name, args, kwargs = {}) {
73
+ const make = table[name];
74
+ return make === undefined ? undefined : make(name)(args, kwargs);
75
+ }
76
+ export const FUNCTIONS = Object.keys(table);
77
+ // Plain TypeScript entry points for library users.
78
+ /**
79
+ * Compares two semantic versions, matching python-semver's `compare` function.
80
+ *
81
+ * @throws {PyError} With `pyType` `ValueError` for an invalid version, or `TypeError` for a non-string input.
82
+ * @example
83
+ * ```ts
84
+ * compare("1.0.0", "2.0.0"); // -1
85
+ * ```
86
+ */
87
+ export const compare = (a, b) => Version.parse(a).compare(b);
88
+ /**
89
+ * Parses a semantic version into its components, matching python-semver's `parse` function.
90
+ *
91
+ * @throws {PyError} With `pyType` `ValueError` for an invalid version, or `TypeError` for a non-string input.
92
+ * @example
93
+ * ```ts
94
+ * parse("1.2.3"); // { major: 1n, minor: 2n, patch: 3n, prerelease: null, build: null }
95
+ * ```
96
+ */
97
+ export const parse = (v) => Version.parse(v).toDict();
98
+ /**
99
+ * Tests a semantic version against a comparison expression, matching python-semver's `match` function.
100
+ *
101
+ * @throws {PyError} With `pyType` `ValueError` for an invalid version or expression, or `TypeError` for a non-string input.
102
+ * @example
103
+ * ```ts
104
+ * match("2.3.7", ">=2.3.6"); // true
105
+ * ```
106
+ */
107
+ export const match = (v, expr) => Version.parse(v).match(expr);
108
+ /**
109
+ * Returns the greater version, keeping the first on a tie, matching python-semver's `max_ver` function.
110
+ *
111
+ * @throws {PyError} With `pyType` `ValueError` for an invalid version, or `TypeError` for a non-string input.
112
+ * @example
113
+ * ```ts
114
+ * maxVer("1.2.3", "1.2.4"); // "1.2.4"
115
+ * ```
116
+ */
117
+ export const maxVer = (a, b) => (Version.parse(b).compare(Version.parse(a)) > 0 ? b : a);
118
+ /**
119
+ * Returns the lesser version, keeping the first on a tie, matching python-semver's `min_ver` function.
120
+ *
121
+ * @throws {PyError} With `pyType` `ValueError` for an invalid version, or `TypeError` for a non-string input.
122
+ * @example
123
+ * ```ts
124
+ * minVer("1.2.3", "1.2.4"); // "1.2.3"
125
+ * ```
126
+ */
127
+ export const minVer = (a, b) => (Version.parse(b).compare(Version.parse(a)) < 0 ? b : a);
128
+ /**
129
+ * Increments the major component and resets the rest, matching python-semver's `bump_major` function.
130
+ *
131
+ * @throws {PyError} With `pyType` `ValueError` for an invalid version, or `TypeError` for a non-string input.
132
+ * @example
133
+ * ```ts
134
+ * bumpMajor("1.2.3"); // "2.0.0"
135
+ * ```
136
+ */
137
+ export const bumpMajor = (v) => String(Version.parse(v).bumpMajor());
138
+ /**
139
+ * Increments the minor component and resets later components, matching python-semver's `bump_minor` function.
140
+ *
141
+ * @throws {PyError} With `pyType` `ValueError` for an invalid version, or `TypeError` for a non-string input.
142
+ * @example
143
+ * ```ts
144
+ * bumpMinor("1.2.3"); // "1.3.0"
145
+ * ```
146
+ */
147
+ export const bumpMinor = (v) => String(Version.parse(v).bumpMinor());
148
+ /**
149
+ * Increments the patch component and removes suffixes, matching python-semver's `bump_patch` function.
150
+ *
151
+ * @throws {PyError} With `pyType` `ValueError` for an invalid version, or `TypeError` for a non-string input.
152
+ * @example
153
+ * ```ts
154
+ * bumpPatch("1.2.3"); // "1.2.4"
155
+ * ```
156
+ */
157
+ export const bumpPatch = (v) => String(Version.parse(v).bumpPatch());
158
+ /**
159
+ * Increments or adds a prerelease identifier, matching python-semver's `bump_prerelease` function.
160
+ *
161
+ * @throws {PyError} With `pyType` `ValueError` for an invalid version or token, or `TypeError` for a non-string input.
162
+ * @example
163
+ * ```ts
164
+ * bumpPrerelease("1.2.3"); // "1.2.3-rc.1"
165
+ * ```
166
+ */
167
+ export const bumpPrerelease = (v, token = "rc") => String(Version.parse(v).bumpPrerelease(token));
168
+ /**
169
+ * Increments or adds a build identifier, matching python-semver's `bump_build` function.
170
+ *
171
+ * @throws {PyError} With `pyType` `ValueError` for an invalid version or token, or `TypeError` for a non-string input.
172
+ * @example
173
+ * ```ts
174
+ * bumpBuild("1.2.3"); // "1.2.3+build.1"
175
+ * ```
176
+ */
177
+ export const bumpBuild = (v, token = "build") => String(Version.parse(v).bumpBuild(token));
178
+ /**
179
+ * Removes prerelease and build suffixes, matching python-semver's `finalize_version` function.
180
+ *
181
+ * @throws {PyError} With `pyType` `ValueError` for an invalid version, or `TypeError` for a non-string input.
182
+ * @example
183
+ * ```ts
184
+ * finalizeVersion("1.2.3-rc.5"); // "1.2.3"
185
+ * ```
186
+ */
187
+ export const finalizeVersion = (v) => String(Version.parse(v).finalizeVersion());
188
+ /**
189
+ * Reports whether a string is a valid semantic version, matching python-semver's `Version.is_valid` function.
190
+ *
191
+ * @throws {PyError} With `pyType` `TypeError` for a non-string input; invalid strings return `false` instead of throwing `ValueError`.
192
+ * @example
193
+ * ```ts
194
+ * isValid("1.2.3"); // true
195
+ * ```
196
+ */
197
+ export const isValid = (v) => Version.isValid(v);
package/dist/py.d.ts ADDED
@@ -0,0 +1,39 @@
1
+ export declare class PyFloat {
2
+ readonly value: number;
3
+ constructor(value: number);
4
+ }
5
+ export type PyValue = null | boolean | bigint | PyFloat | string | PyValue[] | {
6
+ [key: string]: PyValue;
7
+ };
8
+ export declare class PyError extends Error {
9
+ readonly pyType: "ValueError" | "TypeError" | "OverflowError";
10
+ constructor(pyType: "ValueError" | "TypeError" | "OverflowError", message: string);
11
+ }
12
+ export declare const valueError: (m: string) => PyError;
13
+ export declare const typeError: (m: string) => PyError;
14
+ export declare const isDict: (v: PyValue) => v is {
15
+ [key: string]: PyValue;
16
+ };
17
+ /** Python's `len()` of a str: code points, not UTF-16 units. */
18
+ export declare function pyLen(s: string): number;
19
+ /** Python's ordering of two str values (by code point). */
20
+ export declare function pyStrCmp(a: string, b: string): number;
21
+ /** The decimal value of a character with general category Nd. Every Nd run in Unicode is
22
+ * made of whole 0..9 sequences, so the value is the distance from the start of the run,
23
+ * modulo 10. */
24
+ export declare function decimalValue(ch: string): number;
25
+ export declare const isDecimalChar: (ch: string) => boolean;
26
+ /** Python's `str.isdecimal()`. */
27
+ export declare function isDecimal(s: string): boolean;
28
+ export declare function pyStrip(s: string): string;
29
+ /** Python's `int(s)` for a str, base 10. */
30
+ export declare function intFromStr(s: string): bigint;
31
+ /** Python's `int(x)` for the JSON-shaped values a call can carry. */
32
+ export declare function pyInt(v: PyValue): bigint;
33
+ /** Python's `repr(float)`. */
34
+ export declare function floatRepr(x: number): string;
35
+ export declare function pyRepr(v: PyValue): string;
36
+ /** Python's `str(x)`. */
37
+ export declare function pyStr(v: PyValue): string;
38
+ /** Python's truthiness, for the values used here. */
39
+ export declare function truthy(v: PyValue): boolean;
package/dist/py.js ADDED
@@ -0,0 +1,229 @@
1
+ // The small part of Python's value model that python-semver's public functions rely on:
2
+ // arbitrary-size ints (bigint), floats kept apart from ints, int() and str() of values,
3
+ // code-point lengths and code-point string ordering.
4
+ export class PyFloat {
5
+ value;
6
+ constructor(value) {
7
+ this.value = value;
8
+ }
9
+ }
10
+ export class PyError extends Error {
11
+ pyType;
12
+ constructor(pyType, message) {
13
+ super(message);
14
+ this.pyType = pyType;
15
+ this.name = pyType;
16
+ }
17
+ }
18
+ export const valueError = (m) => new PyError("ValueError", m);
19
+ export const typeError = (m) => new PyError("TypeError", m);
20
+ export const isDict = (v) => typeof v === "object" && v !== null && !Array.isArray(v) && !(v instanceof PyFloat);
21
+ /** Python's `len()` of a str: code points, not UTF-16 units. */
22
+ export function pyLen(s) {
23
+ if (!SURROGATE.test(s))
24
+ return s.length;
25
+ let n = 0;
26
+ for (const _ of s)
27
+ n++;
28
+ return n;
29
+ }
30
+ /** Python's ordering of two str values (by code point). */
31
+ export function pyStrCmp(a, b) {
32
+ if (a === b)
33
+ return 0;
34
+ const ia = a[Symbol.iterator]();
35
+ const ib = b[Symbol.iterator]();
36
+ for (;;) {
37
+ const x = ia.next();
38
+ const y = ib.next();
39
+ if (x.done)
40
+ return y.done ? 0 : -1;
41
+ if (y.done)
42
+ return 1;
43
+ const cx = x.value.codePointAt(0);
44
+ const cy = y.value.codePointAt(0);
45
+ if (cx !== cy)
46
+ return cx < cy ? -1 : 1;
47
+ }
48
+ }
49
+ const ND = /^\p{Nd}$/u;
50
+ const ASCII_DIGITS = /^[0-9]+$/;
51
+ const SURROGATE = /[\uD800-\uDFFF]/;
52
+ /** The decimal value of a character with general category Nd. Every Nd run in Unicode is
53
+ * made of whole 0..9 sequences, so the value is the distance from the start of the run,
54
+ * modulo 10. */
55
+ export function decimalValue(ch) {
56
+ if (ch >= "0" && ch <= "9")
57
+ return ch.charCodeAt(0) - 48;
58
+ let cp = ch.codePointAt(0);
59
+ let k = 0;
60
+ while (ND.test(String.fromCodePoint(cp - 1))) {
61
+ cp--;
62
+ k++;
63
+ }
64
+ return k % 10;
65
+ }
66
+ export const isDecimalChar = (ch) => ND.test(ch);
67
+ /** Python's `str.isdecimal()`. */
68
+ export function isDecimal(s) {
69
+ if (s.length === 0)
70
+ return false;
71
+ if (ASCII_DIGITS.test(s))
72
+ return true;
73
+ for (const ch of s)
74
+ if (!ND.test(ch))
75
+ return false;
76
+ return true;
77
+ }
78
+ // Characters for which Python's str.isspace() is true.
79
+ const PY_SPACE = new Set([
80
+ 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x85, 0xa0, 0x1680,
81
+ 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200a,
82
+ 0x2028, 0x2029, 0x202f, 0x205f, 0x3000,
83
+ ].map((c) => String.fromCodePoint(c)));
84
+ export function pyStrip(s) {
85
+ const chars = [...s];
86
+ let i = 0;
87
+ let j = chars.length;
88
+ while (i < j && PY_SPACE.has(chars[i]))
89
+ i++;
90
+ while (j > i && PY_SPACE.has(chars[j - 1]))
91
+ j--;
92
+ return chars.slice(i, j).join("");
93
+ }
94
+ /** Python's `int(s)` for a str, base 10. */
95
+ export function intFromStr(s) {
96
+ if (ASCII_DIGITS.test(s))
97
+ return BigInt(s);
98
+ const bad = () => valueError(`invalid literal for int() with base 10: '${s}'`);
99
+ const chars = [...pyStrip(s)];
100
+ let i = 0;
101
+ let neg = false;
102
+ if (chars[0] === "+" || chars[0] === "-") {
103
+ neg = chars[0] === "-";
104
+ i = 1;
105
+ }
106
+ if (i >= chars.length)
107
+ throw bad();
108
+ let digits = "";
109
+ let prevDigit = false;
110
+ for (; i < chars.length; i++) {
111
+ const ch = chars[i];
112
+ if (ch === "_") {
113
+ if (!prevDigit)
114
+ throw bad();
115
+ prevDigit = false;
116
+ continue;
117
+ }
118
+ if (!ND.test(ch))
119
+ throw bad();
120
+ digits += String(decimalValue(ch));
121
+ prevDigit = true;
122
+ }
123
+ if (!prevDigit)
124
+ throw bad();
125
+ const n = BigInt(digits);
126
+ return neg ? -n : n;
127
+ }
128
+ /** Python's `int(x)` for the JSON-shaped values a call can carry. */
129
+ export function pyInt(v) {
130
+ if (typeof v === "bigint")
131
+ return v;
132
+ if (typeof v === "boolean")
133
+ return v ? 1n : 0n;
134
+ if (v instanceof PyFloat) {
135
+ if (!Number.isFinite(v.value)) {
136
+ throw Number.isNaN(v.value)
137
+ ? valueError("cannot convert float NaN to integer")
138
+ : new PyError("OverflowError", "cannot convert float infinity to integer");
139
+ }
140
+ return BigInt(Math.trunc(v.value));
141
+ }
142
+ if (typeof v === "string")
143
+ return intFromStr(v);
144
+ if (v === null) {
145
+ throw typeError("int() argument must be a string, a bytes-like object or a real number, not 'NoneType'");
146
+ }
147
+ throw typeError(`int() argument must be a string, a bytes-like object or a real number, not '${Array.isArray(v) ? "list" : "dict"}'`);
148
+ }
149
+ /** Python's `repr(float)`. */
150
+ export function floatRepr(x) {
151
+ if (Number.isNaN(x))
152
+ return "nan";
153
+ if (!Number.isFinite(x))
154
+ return x > 0 ? "inf" : "-inf";
155
+ if (x === 0)
156
+ return Object.is(x, -0) ? "-0.0" : "0.0";
157
+ const sign = x < 0 ? "-" : "";
158
+ const [mant, expStr] = Math.abs(x).toExponential().split("e");
159
+ const digits = mant.replace(".", "");
160
+ const exp = Number(expStr); // value = 0.digits * 10^(exp+1)
161
+ if (exp < -4 || exp >= 16) {
162
+ const m = digits.length > 1 ? `${digits[0]}.${digits.slice(1)}` : digits;
163
+ const e = Math.abs(exp) < 10 ? `0${Math.abs(exp)}` : String(Math.abs(exp));
164
+ return `${sign}${m}e${exp < 0 ? "-" : "+"}${e}`;
165
+ }
166
+ if (exp < 0)
167
+ return `${sign}0.${"0".repeat(-exp - 1)}${digits}`;
168
+ if (digits.length <= exp + 1)
169
+ return `${sign}${digits}${"0".repeat(exp + 1 - digits.length)}.0`;
170
+ return `${sign}${digits.slice(0, exp + 1)}.${digits.slice(exp + 1)}`;
171
+ }
172
+ /** Python's `repr(str)`, enough for values nested in a list or dict. */
173
+ function strRepr(s) {
174
+ const q = s.includes("'") && !s.includes('"') ? '"' : "'";
175
+ let out = q;
176
+ for (const ch of s) {
177
+ const cp = ch.codePointAt(0);
178
+ if (ch === q || ch === "\\")
179
+ out += "\\" + ch;
180
+ else if (ch === "\n")
181
+ out += "\\n";
182
+ else if (ch === "\r")
183
+ out += "\\r";
184
+ else if (ch === "\t")
185
+ out += "\\t";
186
+ else if (cp < 0x20 || cp === 0x7f)
187
+ out += "\\x" + cp.toString(16).padStart(2, "0");
188
+ else
189
+ out += ch;
190
+ }
191
+ return out + q;
192
+ }
193
+ export function pyRepr(v) {
194
+ if (typeof v === "string")
195
+ return strRepr(v);
196
+ return pyStr(v);
197
+ }
198
+ /** Python's `str(x)`. */
199
+ export function pyStr(v) {
200
+ if (v === null)
201
+ return "None";
202
+ if (typeof v === "boolean")
203
+ return v ? "True" : "False";
204
+ if (typeof v === "bigint")
205
+ return v.toString();
206
+ if (v instanceof PyFloat)
207
+ return floatRepr(v.value);
208
+ if (typeof v === "string")
209
+ return v;
210
+ if (Array.isArray(v))
211
+ return `[${v.map(pyRepr).join(", ")}]`;
212
+ return `{${Object.entries(v).map(([k, x]) => `${strRepr(k)}: ${pyRepr(x)}`).join(", ")}}`;
213
+ }
214
+ /** Python's truthiness, for the values used here. */
215
+ export function truthy(v) {
216
+ if (v === null)
217
+ return false;
218
+ if (typeof v === "boolean")
219
+ return v;
220
+ if (typeof v === "bigint")
221
+ return v !== 0n;
222
+ if (v instanceof PyFloat)
223
+ return v.value !== 0;
224
+ if (typeof v === "string")
225
+ return v.length > 0;
226
+ if (Array.isArray(v))
227
+ return v.length > 0;
228
+ return Object.keys(v).length > 0;
229
+ }
@@ -0,0 +1,31 @@
1
+ import { type PyValue } from "./py.js";
2
+ export declare const MAX_LENGTH = 255;
3
+ export declare class Version {
4
+ readonly major: bigint;
5
+ readonly minor: bigint;
6
+ readonly patch: bigint;
7
+ readonly prerelease: string | null;
8
+ readonly build: string | null;
9
+ private constructor();
10
+ /** `Version(*args, **kwargs)` with Python's argument handling and checks. */
11
+ static create(args: PyValue[], kwargs?: Record<string, PyValue>): Version;
12
+ static of(major: bigint, minor?: bigint, patch?: bigint, prerelease?: string | null, build?: string | null): Version;
13
+ static parse(version: PyValue): Version;
14
+ static isValid(version: PyValue): boolean;
15
+ toDict(): {
16
+ [key: string]: PyValue;
17
+ };
18
+ toString(): string;
19
+ bumpMajor(): Version;
20
+ bumpMinor(): Version;
21
+ bumpPatch(): Version;
22
+ static incrementPrerelease(s: string): string;
23
+ static incrementString(s: string): string;
24
+ bumpPrerelease(token?: PyValue): Version;
25
+ bumpBuild(token?: PyValue): Version;
26
+ finalizeVersion(): Version;
27
+ compare(other: PyValue | Version): number;
28
+ match(matchExpr: PyValue): boolean;
29
+ replace(parts: Record<string, PyValue>): Version;
30
+ }
31
+ export declare function typeName(v: PyValue | undefined): string;
@@ -0,0 +1,299 @@
1
+ // A port of python-semver's Version class (src/semver/version.py), limited to what the
2
+ // module-level functions use. Copyright notice of the original: see LICENSE.
3
+ import { PyFloat, intFromStr, isDecimal, decimalValue, isDict, pyInt, pyLen, pyRepr, pyStr, pyStrCmp, typeError, valueError, } from "./py.js";
4
+ export const MAX_LENGTH = 255;
5
+ const NUMERIC_LIMIT = 10n ** BigInt(MAX_LENGTH);
6
+ const LENGTH_ERROR = `Version string exceeds maximum length of ${MAX_LENGTH} characters`;
7
+ const PRE_ID = "0|[1-9][0-9]*|[0-9]*[a-zA-Z-][0-9a-zA-Z-]*";
8
+ const BUILD_ID = "[0-9a-zA-Z-]+";
9
+ const PRERELEASE_IDENTIFIER = new RegExp(`^(?:${PRE_ID})$`);
10
+ const BUILD_IDENTIFIER = new RegExp(`^(?:${BUILD_ID})$`);
11
+ const NUM = "0|[1-9][0-9]*";
12
+ const REGEX = new RegExp(`^(?<major>${NUM})\\.(?<minor>${NUM})\\.(?<patch>${NUM})` +
13
+ `(?:-(?<prerelease>(?:${PRE_ID})(?:\\.(?:${PRE_ID}))*))?` +
14
+ `(?:\\+(?<build>(?:${BUILD_ID})(?:\\.(?:${BUILD_ID}))*))?$`);
15
+ // Python's re without re.ASCII: \d is any Unicode decimal digit.
16
+ const LAST_PRERELEASE = /^(.*\.)?(\p{Nd}+)$/u;
17
+ const LAST_NUMBER = /\p{Nd}+/gu;
18
+ const NAMES = ["major", "minor", "patch", "prerelease", "build"];
19
+ /** Bind Python-style arguments to (major, minor=0, patch=0, prerelease=None, build=None). */
20
+ function bindVersionArgs(args, kwargs) {
21
+ if (args.length > NAMES.length) {
22
+ throw typeError(`Version.__init__() takes from 2 to 6 positional arguments but ${args.length + 1} were given`);
23
+ }
24
+ const out = [...args];
25
+ for (const [k, v] of Object.entries(kwargs)) {
26
+ const i = NAMES.indexOf(k);
27
+ if (i < 0)
28
+ throw typeError(`Version.__init__() got an unexpected keyword argument '${k}'`);
29
+ if (i < args.length)
30
+ throw typeError(`Version.__init__() got multiple values for argument '${k}'`);
31
+ out[i] = v;
32
+ }
33
+ if (out[0] === undefined)
34
+ throw typeError("Version.__init__() missing 1 required positional argument: 'major'");
35
+ const defaults = [null, 0n, 0n, null, null];
36
+ return NAMES.map((_, i) => (out[i] === undefined ? defaults[i] : out[i]));
37
+ }
38
+ function prereleaseKey(identifier) {
39
+ if (!isDecimal(identifier))
40
+ return [1, 0, identifier];
41
+ let digits = "";
42
+ for (const ch of identifier)
43
+ digits += ch < "\u0080" ? ch : String(decimalValue(ch));
44
+ const normalized = digits.replace(/^0+/, "") || "0";
45
+ return [0, normalized.length, normalized];
46
+ }
47
+ function cmpKey(a, b) {
48
+ if (a[0] !== b[0])
49
+ return a[0] < b[0] ? -1 : 1;
50
+ if (a[1] !== b[1])
51
+ return a[1] < b[1] ? -1 : 1;
52
+ return pyStrCmp(a[2], b[2]);
53
+ }
54
+ function natCmp(a, b) {
55
+ const ap = (a || "").split(".").map(prereleaseKey);
56
+ const bp = (b || "").split(".").map(prereleaseKey);
57
+ const n = Math.min(ap.length, bp.length);
58
+ for (let i = 0; i < n; i++) {
59
+ const c = cmpKey(ap[i], bp[i]);
60
+ if (c !== 0)
61
+ return c;
62
+ }
63
+ return ap.length === bp.length ? 0 : ap.length < bp.length ? -1 : 1;
64
+ }
65
+ const cmpBig = (a, b) => (a > b ? 1 : a < b ? -1 : 0);
66
+ function validateIdentifiers(value, pattern, what) {
67
+ for (const identifier of value.split(".")) {
68
+ if (!pattern.test(identifier)) {
69
+ throw valueError(`${pyRepr(value)} is not a valid ${what}. It may only consist of dot-separated identifiers, made of alphanumerics and hyphens.`);
70
+ }
71
+ }
72
+ }
73
+ export class Version {
74
+ major;
75
+ minor;
76
+ patch;
77
+ prerelease;
78
+ build;
79
+ constructor(major, minor, patch, prerelease, build) {
80
+ this.major = major;
81
+ this.minor = minor;
82
+ this.patch = patch;
83
+ this.prerelease = prerelease;
84
+ this.build = build;
85
+ }
86
+ /** `Version(*args, **kwargs)` with Python's argument handling and checks. */
87
+ static create(args, kwargs = {}) {
88
+ const values = bindVersionArgs(args, kwargs);
89
+ for (const value of values) {
90
+ if (typeof value === "string" && pyLen(value) > MAX_LENGTH)
91
+ throw valueError(LENGTH_ERROR);
92
+ const asInt = typeof value === "bigint" ? value : typeof value === "boolean" ? (value ? 1n : 0n) : null;
93
+ if (asInt !== null && (asInt >= NUMERIC_LIMIT || asInt <= -NUMERIC_LIMIT))
94
+ throw valueError(LENGTH_ERROR);
95
+ }
96
+ const parts = [pyInt(values[0]), pyInt(values[1]), pyInt(values[2])];
97
+ parts.forEach((value, i) => {
98
+ if (value < 0n)
99
+ throw valueError(`'${NAMES[i]}' is negative. A version can only be positive.`);
100
+ if (value >= NUMERIC_LIMIT)
101
+ throw valueError(LENGTH_ERROR);
102
+ });
103
+ const prerelease = values[3] === null ? null : pyStr(values[3]);
104
+ const build = values[4] === null ? null : pyStr(values[4]);
105
+ let length = parts.reduce((n, v) => n + v.toString().length, 0) + 2;
106
+ for (const identifier of [prerelease, build]) {
107
+ if (identifier)
108
+ length += pyLen(identifier) + 1;
109
+ }
110
+ if (length > MAX_LENGTH)
111
+ throw valueError(LENGTH_ERROR);
112
+ return new Version(parts[0], parts[1], parts[2], prerelease, build);
113
+ }
114
+ static of(major, minor = 0n, patch = 0n, prerelease = null, build = null) {
115
+ return Version.create([major, minor, patch, prerelease, build]);
116
+ }
117
+ static parse(version) {
118
+ if (typeof version !== "string")
119
+ throw typeError(`not expecting type '${typeName(version)}'`);
120
+ if (pyLen(version) > MAX_LENGTH)
121
+ throw valueError(LENGTH_ERROR);
122
+ const m = REGEX.exec(version);
123
+ if (m === null || m.groups === undefined)
124
+ throw valueError(`${version} is not valid SemVer string`);
125
+ const g = m.groups;
126
+ return Version.create([], {
127
+ major: g["major"],
128
+ minor: g["minor"] || "0",
129
+ patch: g["patch"] || "0",
130
+ prerelease: g["prerelease"] ?? null,
131
+ build: g["build"] ?? null,
132
+ });
133
+ }
134
+ static isValid(version) {
135
+ try {
136
+ Version.parse(version);
137
+ return true;
138
+ }
139
+ catch (e) {
140
+ if (e instanceof Error && e.name === "ValueError")
141
+ return false;
142
+ throw e;
143
+ }
144
+ }
145
+ toDict() {
146
+ return { major: this.major, minor: this.minor, patch: this.patch, prerelease: this.prerelease, build: this.build };
147
+ }
148
+ toString() {
149
+ let s = `${this.major}.${this.minor}.${this.patch}`;
150
+ if (this.prerelease)
151
+ s += `-${this.prerelease}`;
152
+ if (this.build)
153
+ s += `+${this.build}`;
154
+ return s;
155
+ }
156
+ bumpMajor() {
157
+ return Version.of(this.major + 1n);
158
+ }
159
+ bumpMinor() {
160
+ return Version.of(this.major, this.minor + 1n);
161
+ }
162
+ bumpPatch() {
163
+ return Version.of(this.major, this.minor, this.patch + 1n);
164
+ }
165
+ static incrementPrerelease(s) {
166
+ const m = LAST_PRERELEASE.exec(s);
167
+ if (m) {
168
+ const next = (intFromStr(m[2]) + 1n).toString();
169
+ return m[1] ? m[1] + next : next;
170
+ }
171
+ return s + ".0";
172
+ }
173
+ static incrementString(s) {
174
+ let last = null;
175
+ for (const m of s.matchAll(LAST_NUMBER))
176
+ last = m;
177
+ if (last) {
178
+ const next = (intFromStr(last[0]) + 1n).toString();
179
+ const start = last.index;
180
+ const end = start + last[0].length;
181
+ return s.slice(0, Math.max(end - next.length, start)) + next + s.slice(end);
182
+ }
183
+ return s;
184
+ }
185
+ bumpPrerelease(token = "rc") {
186
+ let prerelease;
187
+ if (this.prerelease !== null) {
188
+ prerelease = Version.incrementPrerelease(this.prerelease);
189
+ }
190
+ else if (token === "") {
191
+ prerelease = "1";
192
+ }
193
+ else if (token === null) {
194
+ prerelease = "rc.1";
195
+ }
196
+ else {
197
+ const t = pyStr(token);
198
+ validateIdentifiers(t, PRERELEASE_IDENTIFIER, "prerelease token");
199
+ prerelease = t + ".1";
200
+ }
201
+ return Version.of(this.major, this.minor, this.patch, prerelease);
202
+ }
203
+ bumpBuild(token = "build") {
204
+ let build;
205
+ if (this.build !== null) {
206
+ build = this.build;
207
+ }
208
+ else if (token === "") {
209
+ build = "0";
210
+ }
211
+ else if (token === null) {
212
+ build = "build.0";
213
+ }
214
+ else {
215
+ const t = pyStr(token);
216
+ validateIdentifiers(t, BUILD_IDENTIFIER, "build token");
217
+ build = t + ".0";
218
+ }
219
+ build = Version.incrementString(build);
220
+ if (build === this.build)
221
+ build += ".0";
222
+ return Version.of(this.major, this.minor, this.patch, this.prerelease, build);
223
+ }
224
+ finalizeVersion() {
225
+ return Version.of(this.major, this.minor, this.patch);
226
+ }
227
+ compare(other) {
228
+ let o;
229
+ if (other instanceof Version)
230
+ o = other;
231
+ else if (typeof other === "string")
232
+ o = Version.parse(other);
233
+ else if (other !== null && isDict(other))
234
+ o = Version.create([], other);
235
+ else if (Array.isArray(other))
236
+ o = Version.create(other);
237
+ else
238
+ throw typeError(`Expected str, bytes, dict, tuple, list, or Version instance, but got <class '${typeName(other)}'>`);
239
+ const x = cmpBig(this.major, o.major) || cmpBig(this.minor, o.minor) || cmpBig(this.patch, o.patch);
240
+ if (x)
241
+ return x;
242
+ const rc1 = this.prerelease;
243
+ const rc2 = o.prerelease;
244
+ if (rc1 === rc2)
245
+ return 0;
246
+ if (!rc1)
247
+ return rc2 ? 1 : 0;
248
+ if (!rc2)
249
+ return -1;
250
+ return natCmp(rc1, rc2);
251
+ }
252
+ match(matchExpr) {
253
+ if (typeof matchExpr !== "string") {
254
+ throw typeError(`'${typeName(matchExpr)}' object is not subscriptable`);
255
+ }
256
+ const chars = [...matchExpr];
257
+ let prefix = chars.slice(0, 2).join("");
258
+ let matchVersion;
259
+ if (prefix === ">=" || prefix === "<=" || prefix === "==" || prefix === "!=") {
260
+ matchVersion = chars.slice(2).join("");
261
+ }
262
+ else if (prefix && (chars[0] === ">" || chars[0] === "<")) {
263
+ prefix = chars[0];
264
+ matchVersion = chars.slice(1).join("");
265
+ }
266
+ else if (matchExpr && "0123456789".includes(chars[0])) {
267
+ prefix = "==";
268
+ matchVersion = matchExpr;
269
+ }
270
+ else {
271
+ throw valueError(`match_expr parameter should be in format <op><ver>, You provided: ${pyRepr(matchExpr)}`);
272
+ }
273
+ const c = this.compare(matchVersion);
274
+ switch (prefix) {
275
+ case ">": return c === 1;
276
+ case "<": return c === -1;
277
+ case "==": return c === 0;
278
+ case "!=": return c !== 0;
279
+ case ">=": return c >= 0;
280
+ default: return c <= 0;
281
+ }
282
+ }
283
+ replace(parts) {
284
+ return Version.create([], { ...this.toDict(), ...parts });
285
+ }
286
+ }
287
+ export function typeName(v) {
288
+ if (v === null || v === undefined)
289
+ return "NoneType";
290
+ if (typeof v === "boolean")
291
+ return "bool";
292
+ if (typeof v === "bigint")
293
+ return "int";
294
+ if (v instanceof PyFloat)
295
+ return "float";
296
+ if (typeof v === "string")
297
+ return "str";
298
+ return Array.isArray(v) ? "list" : "dict";
299
+ }
package/package.json CHANGED
@@ -1,6 +1,53 @@
1
1
  {
2
2
  "name": "pgchangeling-semver",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "python-semver's module functions in TypeScript, answering as Python does: a port proved by replaying 24,876 calls recorded from the Python original",
5
+ "keywords": [
6
+ "semver",
7
+ "semantic-versioning",
8
+ "python-semver",
9
+ "port",
10
+ "typescript"
11
+ ],
12
+ "homepage": "https://changeling.pgremlin.com/ports/semver-ts",
13
+ "repository": {
14
+ "type": "git",
15
+ "url": "git+https://github.com/Pushkal-Gupta/pgchangeling-semver-ts.git",
16
+ "directory": "semver-ts"
17
+ },
18
+ "bugs": {
19
+ "url": "https://github.com/Pushkal-Gupta/pgchangeling-semver-ts/issues"
20
+ },
21
+ "license": "BSD-3-Clause",
22
+ "type": "module",
23
+ "main": "dist/index.js",
24
+ "types": "dist/index.d.ts",
25
+ "exports": {
26
+ ".": {
27
+ "types": "./dist/index.d.ts",
28
+ "import": "./dist/index.js"
29
+ },
30
+ "./package.json": "./package.json"
31
+ },
32
+ "files": [
33
+ "dist/index.js",
34
+ "dist/index.d.ts",
35
+ "dist/version.js",
36
+ "dist/version.d.ts",
37
+ "dist/py.js",
38
+ "dist/py.d.ts"
39
+ ],
40
+ "sideEffects": false,
41
+ "scripts": {
42
+ "build": "tsc -p .",
43
+ "test": "tsc -p . && node --test dist/test/*.test.js",
44
+ "prepublishOnly": "npm test"
45
+ },
46
+ "engines": {
47
+ "node": ">=22"
48
+ },
49
+ "devDependencies": {
50
+ "@types/node": "^22.10.0",
51
+ "typescript": "^5.7.0"
52
+ }
53
+ }