@se-oss/ip-address 1.1.0 → 1.1.2

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/dist/index.cjs CHANGED
@@ -59,7 +59,15 @@ var IPV6_COMPRESSED_7 = `(?:${IPV6_SEGMENT}:){1,2}(?::${IPV6_SEGMENT}){1,5}`;
59
59
  var IPV6_COMPRESSED_8 = `${IPV6_SEGMENT}:(?::${IPV6_SEGMENT}){1,6}`;
60
60
  var IPV6_COMPRESSED_9 = `::(?:${IPV6_SEGMENT}:){0,5}${IPV6_SEGMENT}`;
61
61
  var IPV6_COMPRESSED_10 = "::";
62
- var IPV6_IPV4_MAPPED = `(?:(?:${IPV6_SEGMENT}:){6}|::(?:${IPV6_SEGMENT}:){0,5}|(?:${IPV6_SEGMENT}:){0,5}::(?:${IPV6_SEGMENT}:){0,5})${IPV4_ADDRESS_PATTERN}`;
62
+ var IPV6_IPV4_MAPPED = [
63
+ `(?:${IPV6_SEGMENT}:){6}`,
64
+ `::(?:${IPV6_SEGMENT}:){0,5}`,
65
+ `(?:${IPV6_SEGMENT}:){1}:(?:${IPV6_SEGMENT}:){0,4}`,
66
+ `(?:${IPV6_SEGMENT}:){2}:(?:${IPV6_SEGMENT}:){0,3}`,
67
+ `(?:${IPV6_SEGMENT}:){3}:(?:${IPV6_SEGMENT}:){0,2}`,
68
+ `(?:${IPV6_SEGMENT}:){4}:(?:${IPV6_SEGMENT}:){0,1}`,
69
+ `(?:${IPV6_SEGMENT}:){5}:`
70
+ ].map((prefix) => `${prefix}${IPV4_ADDRESS_PATTERN}`).join("|");
63
71
  var IPV6_COMBINED = [
64
72
  IPV6_STANDARD,
65
73
  IPV6_COMPRESSED_1,
@@ -86,19 +94,19 @@ var InvalidIPAddressError = class extends Error {
86
94
 
87
95
  // src/utils.ts
88
96
  function fastIpVersion(probablyIp) {
89
- if (probablyIp.includes(".")) {
90
- return 4;
91
- }
92
97
  if (probablyIp.includes(":")) {
93
98
  return 6;
94
99
  }
100
+ if (probablyIp.includes(".")) {
101
+ return 4;
102
+ }
95
103
  throw new InvalidIPAddressError(`Invalid IP address: ${probablyIp}`);
96
104
  }
97
105
  function ipv4ToBigInt(ip) {
98
- const parts = ip.split(".");
99
- if (parts.length !== 4 || parts.some((part) => !/^\d+$/.test(part) || Number(part) > 255)) {
106
+ if (!IPV4_ADDRESS_REGEX.test(ip)) {
100
107
  throw new InvalidIPAddressError(`Invalid IPv4 address: ${ip}`);
101
108
  }
109
+ const parts = ip.split(".");
102
110
  return parts.reduce((acc, octet) => acc << 8n | BigInt(parseInt(octet, 10)), 0n);
103
111
  }
104
112
  function expandIPv6Shorthand(parts) {
@@ -110,26 +118,28 @@ function expandIPv6Shorthand(parts) {
110
118
  return parts;
111
119
  }
112
120
  function ipv6ToBigInt(ip) {
113
- if (ip.includes("%")) {
114
- ip = /(.+)%(.+)/.exec(ip)[1];
115
- }
116
- const ipv4MappedMatch = /^(::ffff:)(?:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}))$/.exec(ip);
117
- if (ipv4MappedMatch) {
118
- const ipv4Part = ipv4MappedMatch[2];
119
- const ipv4BigInt = ipv4ToBigInt(ipv4Part);
120
- return 0x00000000000000000000ffffn << 32n | ipv4BigInt;
121
- }
122
- let parts = ip.split(":");
123
- parts = expandIPv6Shorthand(parts);
124
- if (parts.length !== 8 || parts.some((part) => !/^[0-9a-fA-F]*$/.test(part) || part.length > 4)) {
121
+ const percentIndex = ip.indexOf("%");
122
+ if (percentIndex !== -1) {
123
+ if (percentIndex === 0 || percentIndex === ip.length - 1) {
124
+ throw new InvalidIPAddressError(`Invalid IPv6 address: ${ip}`);
125
+ }
126
+ ip = ip.slice(0, percentIndex);
127
+ }
128
+ if (!IPV6_VALIDATION_REGEX.test(ip)) {
125
129
  throw new InvalidIPAddressError(`Invalid IPv6 address: ${ip}`);
126
130
  }
131
+ if (ip.includes(".")) {
132
+ const lastColon = ip.lastIndexOf(":");
133
+ const prefix = ip.slice(0, lastColon + 1);
134
+ const ipv4BigInt = ipv4ToBigInt(ip.slice(lastColon + 1));
135
+ const high = (ipv4BigInt >> 16n & 0xffffn).toString(16);
136
+ const low = (ipv4BigInt & 0xffffn).toString(16);
137
+ ip = `${prefix}${high}:${low}`;
138
+ }
139
+ const parts = expandIPv6Shorthand(ip.split(":"));
127
140
  let number = 0n;
128
- let exp = 0n;
129
- const r = parts.map((part) => part === "" ? 0n : BigInt(Number.parseInt(part, 16))).reverse();
130
- for (const n of r) {
131
- number += n * 2n ** exp;
132
- exp += 16n;
141
+ for (const part of parts) {
142
+ number = number << 16n | (part === "" ? 0n : BigInt(Number.parseInt(part, 16)));
133
143
  }
134
144
  return number;
135
145
  }
@@ -144,7 +154,7 @@ function bigIntToIp(number, version, compress = true) {
144
154
  if (version === 4) {
145
155
  return `${number >> 24n & 0xffn}.${number >> 16n & 0xffn}.${number >> 8n & 0xffn}.${number & 0xffn}`;
146
156
  }
147
- if (number >> 32n === 0xffffn) {
157
+ if (compress && number >> 32n === 0xffffn) {
148
158
  const ipv4Part = number & 0xffffffffn;
149
159
  const ipv4String = bigIntToIp(ipv4Part, 4);
150
160
  return `::ffff:${ipv4String}`;
@@ -160,27 +170,33 @@ function bigIntToIp(number, version, compress = true) {
160
170
  return to16.map((part) => part.padStart(4, "0")).join(":");
161
171
  }
162
172
  function compressIPv6(parts) {
163
- let longest = null;
164
- let current = null;
165
- for (let i = 0, len = parts.length; i < len; i++) {
166
- const part = parts[i];
167
- if (part === "0") {
168
- current ??= /* @__PURE__ */ new Set();
169
- current.add(i);
170
- } else if (current) {
171
- if (!longest || current.size > longest.size) {
172
- longest = current;
173
+ let bestStart = -1;
174
+ let bestLen = 0;
175
+ let curStart = -1;
176
+ let curLen = 0;
177
+ for (let i = 0; i < parts.length; i++) {
178
+ if (parts[i] === "0") {
179
+ if (curStart === -1) {
180
+ curStart = i;
181
+ curLen = 1;
182
+ } else {
183
+ curLen++;
184
+ }
185
+ if (curLen > bestLen) {
186
+ bestStart = curStart;
187
+ bestLen = curLen;
173
188
  }
174
- current = null;
189
+ } else {
190
+ curStart = -1;
191
+ curLen = 0;
175
192
  }
176
193
  }
177
- if (!longest && current || current && longest && current.size > longest.size) {
178
- longest = current;
194
+ if (bestLen < 2) {
195
+ return parts.join(":");
179
196
  }
180
- for (const index of longest || []) {
181
- parts[index] = ":";
182
- }
183
- return parts.filter(Boolean).join(":").replace(/:{2,}/, "::");
197
+ const before = parts.slice(0, bestStart).join(":");
198
+ const after = parts.slice(bestStart + bestLen).join(":");
199
+ return `${before}::${after}`;
184
200
  }
185
201
 
186
202
  // src/ipv6.ts
@@ -720,24 +736,29 @@ var CIDR = class {
720
736
  */
721
737
  constructor(cidr) {
722
738
  const parts = cidr.split("/");
739
+ if (parts.length > 2) {
740
+ throw new InvalidIPAddressError(`Invalid CIDR: ${cidr}`);
741
+ }
723
742
  const addressPart = parts[0];
724
743
  let prefixPart = parts[1];
725
744
  let address;
726
745
  let version;
727
- if (addressPart.includes(".")) {
746
+ if (addressPart.includes(":")) {
747
+ address = new IPv6(addressPart);
748
+ version = 6;
749
+ } else if (addressPart.includes(".")) {
728
750
  address = new IPv4(addressPart);
729
751
  version = 4;
730
752
  } else {
731
- address = new IPv6(addressPart);
732
- version = 6;
753
+ throw new InvalidIPAddressError(`Invalid IP address: ${addressPart}`);
733
754
  }
734
755
  if (prefixPart === void 0) {
735
756
  prefixPart = String(BITS[version]);
736
757
  }
737
- const prefix = parseInt(prefixPart, 10);
738
- if (isNaN(prefix)) {
758
+ if (!/^\d+$/.test(prefixPart)) {
739
759
  throw new InvalidIPAddressError(`Invalid prefix: ${prefixPart}`);
740
760
  }
761
+ const prefix = Number(prefixPart);
741
762
  if (prefix < 0 || prefix > BITS[version]) {
742
763
  throw new InvalidIPAddressError(`Prefix out of range for IPv${version}: ${prefix}`);
743
764
  }
@@ -864,12 +885,12 @@ var CIDR = class {
864
885
 
865
886
  // src/index.ts
866
887
  function parseIP(address) {
867
- if (address.includes(".")) {
868
- return new IPv4(address);
869
- }
870
888
  if (address.includes(":")) {
871
889
  return new IPv6(address);
872
890
  }
891
+ if (address.includes(".")) {
892
+ return new IPv4(address);
893
+ }
873
894
  throw new InvalidIPAddressError(`Invalid IP address: ${address}`);
874
895
  }
875
896
  function parseCIDR(cidr) {
@@ -0,0 +1,513 @@
1
+ /**
2
+ * Represents a single IPv6 address, providing methods for validation,
3
+ * classification, and manipulation.
4
+ *
5
+ * @example
6
+ * const ip = new IPv6('2001:db8::1');
7
+ * console.log(ip.address); // "2001:db8::1"
8
+ * console.log(ip.isLinkLocal()); // false
9
+ */
10
+ declare class IPv6 {
11
+ #private;
12
+ /**
13
+ * @param address An IPv6 address string (e.g., "2001:db8::1").
14
+ * @throws {InvalidIPAddressError} If the address is not a valid IPv6 address.
15
+ */
16
+ constructor(address: string);
17
+ /**
18
+ * Creates an IPv6 instance from a BigInt.
19
+ * @param value The BigInt representation of an IPv6 address.
20
+ * @returns A new IPv6 instance.
21
+ *
22
+ * @example
23
+ * const ip = IPv6.fromBigInt(1n);
24
+ * console.log(ip.address); // "::1"
25
+ */
26
+ static fromBigInt(value: bigint): IPv6;
27
+ /**
28
+ * Creates an IPv6 instance from an array of 16 bytes.
29
+ * @param bytes An array of 16 numbers (0-255).
30
+ * @returns A new IPv6 instance.
31
+ * @throws {InvalidIPAddressError} If the byte array is not 16 bytes long.
32
+ *
33
+ * @example
34
+ * const bytes = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1];
35
+ * const ip = IPv6.fromBytes(bytes);
36
+ * console.log(ip.address); // "::1"
37
+ */
38
+ static fromBytes(bytes: number[]): IPv6;
39
+ /**
40
+ * Checks if a string is a valid IPv6 address.
41
+ * @param address The string to validate.
42
+ * @returns True if the string is a valid IPv6 address.
43
+ *
44
+ * @example
45
+ * IPv6.isValid('2001:db8::1'); // true
46
+ * IPv6.isValid('2001:db8::g'); // false
47
+ */
48
+ static isValid(address: string): boolean;
49
+ /**
50
+ * The IP version number.
51
+ * @returns {6}
52
+ */
53
+ get version(): 6;
54
+ /**
55
+ * The compressed, canonical IPv6 address string.
56
+ * @returns {string}
57
+ */
58
+ get address(): string;
59
+ /**
60
+ * The fully expanded IPv6 address string.
61
+ * @returns {string}
62
+ */
63
+ get expandedAddress(): string;
64
+ /**
65
+ * Converts the IP address to its BigInt representation.
66
+ * @returns {bigint}
67
+ */
68
+ toBigInt(): bigint;
69
+ /**
70
+ * Converts the IP address to an array of 16 bytes.
71
+ * @returns {number[]}
72
+ */
73
+ toBytes(): number[];
74
+ /**
75
+ * Returns the string representation of the IP address.
76
+ * @returns {string}
77
+ */
78
+ toString(): string;
79
+ /**
80
+ * Returns the string representation for JSON serialization.
81
+ * @returns {string}
82
+ */
83
+ toJSON(): string;
84
+ /**
85
+ * Converts an IPv4-mapped address to an IPv4 instance, otherwise returns null.
86
+ * @returns {IPv4 | null}
87
+ */
88
+ toIPv4(): IPv4 | null;
89
+ /**
90
+ * Returns the reverse DNS (ARPA) name for the IP address.
91
+ * @returns {string}
92
+ *
93
+ * @example
94
+ * const ip = new IPv6('2001:db8::1');
95
+ * console.log(ip.toArpa()); // "1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.8.b.d.0.1.0.0.2.ip6.arpa"
96
+ */
97
+ toArpa(): string;
98
+ /**
99
+ * Checks if the address is the unspecified address (::).
100
+ * @returns {boolean}
101
+ */
102
+ isUnspecified(): boolean;
103
+ /**
104
+ * Checks if the address is the loopback address (::1).
105
+ * @returns {boolean}
106
+ */
107
+ isLoopback(): boolean;
108
+ /**
109
+ * Checks if the address is a multicast address (ff00::/8).
110
+ * @returns {boolean}
111
+ */
112
+ isMulticast(): boolean;
113
+ /**
114
+ * Checks if the address is a link-local address (fe80::/10).
115
+ * @returns {boolean}
116
+ */
117
+ isLinkLocal(): boolean;
118
+ /**
119
+ * Checks if the address is a unique local address (fc00::/7).
120
+ * @returns {boolean}
121
+ */
122
+ isUniqueLocal(): boolean;
123
+ /**
124
+ * Checks if the address is an IPv4-mapped address (::ffff:0:0/96).
125
+ * @returns {boolean}
126
+ */
127
+ isIPv4Mapped(): boolean;
128
+ /**
129
+ * Checks if the address is reserved by IANA. This includes ranges for
130
+ * documentation, benchmarking, and other special purposes.
131
+ * @returns {boolean}
132
+ */
133
+ isReserved(): boolean;
134
+ /**
135
+ * Checks if the address is a global unicast address.
136
+ * @returns {boolean}
137
+ */
138
+ isGlobalUnicast(): boolean;
139
+ /**
140
+ * Checks for exact equality between this and another IPv6 address.
141
+ * @param other The other IPv6 address to compare with.
142
+ * @returns {boolean}
143
+ */
144
+ equals(other: IPv6 | string): boolean;
145
+ /**
146
+ * Compares this IP address with another.
147
+ * @param other The other IPv6 address to compare with.
148
+ * @returns `-1` if this address is less than the other, `0` if they are equal, `1` if it is greater.
149
+ */
150
+ compare(other: IPv6 | string): -1 | 0 | 1;
151
+ /**
152
+ * Performs a bitwise AND operation with another IPv6 address.
153
+ * @param other The other IPv6 address.
154
+ * @returns A new IPv6 instance with the result of the AND operation.
155
+ */
156
+ and(other: IPv6 | string): IPv6;
157
+ /**
158
+ * Performs a bitwise OR operation with another IPv6 address.
159
+ * @param other The other IPv6 address.
160
+ * @returns A new IPv6 instance with the result of the OR operation.
161
+ */
162
+ or(other: IPv6 | string): IPv6;
163
+ /**
164
+ * Performs a bitwise NOT operation on the address.
165
+ * @returns A new IPv6 instance with the result of the NOT operation.
166
+ */
167
+ not(): IPv6;
168
+ /**
169
+ * Returns the next IP address.
170
+ * @param [count=1n] The number of addresses to increment by.
171
+ * @returns {IPv6}
172
+ */
173
+ next(count?: bigint): IPv6;
174
+ /**
175
+ * Returns the previous IP address.
176
+ * @param [count=1n] The number of addresses to decrement by.
177
+ * @returns {IPv6}
178
+ */
179
+ previous(count?: bigint): IPv6;
180
+ }
181
+
182
+ /**
183
+ * Represents a single IPv4 address, providing methods for validation,
184
+ * classification, and manipulation.
185
+ *
186
+ * @example
187
+ * const ip = new IPv4('192.168.1.1');
188
+ * console.log(ip.address); // "192.168.1.1"
189
+ * console.log(ip.isPrivate()); // true
190
+ */
191
+ declare class IPv4 {
192
+ #private;
193
+ /**
194
+ * @param address An IPv4 address string (e.g., "192.168.1.1").
195
+ * @throws {InvalidIPAddressError} If the address is not a valid IPv4 address.
196
+ */
197
+ constructor(address: string);
198
+ /**
199
+ * Creates an IPv4 instance from a BigInt.
200
+ * @param value The BigInt representation of an IPv4 address.
201
+ * @returns A new IPv4 instance.
202
+ *
203
+ * @example
204
+ * const ip = IPv4.fromBigInt(3232235777n);
205
+ * console.log(ip.address); // "192.168.1.1"
206
+ */
207
+ static fromBigInt(value: bigint): IPv4;
208
+ /**
209
+ * Creates an IPv4 instance from an array of 4 bytes.
210
+ * @param bytes An array of 4 numbers (0-255).
211
+ * @returns A new IPv4 instance.
212
+ *
213
+ * @example
214
+ * const ip = IPv4.fromBytes([192, 168, 1, 1]);
215
+ * console.log(ip.address); // "192.168.1.1"
216
+ */
217
+ static fromBytes(bytes: [number, number, number, number]): IPv4;
218
+ /**
219
+ * Checks if a string is a valid IPv4 address.
220
+ * @param address The string to validate.
221
+ * @returns True if the string is a valid IPv4 address.
222
+ *
223
+ * @example
224
+ * IPv4.isValid('1.2.3.4'); // true
225
+ * IPv4.isValid('1.2.3.256'); // false
226
+ */
227
+ static isValid(address: string): boolean;
228
+ /**
229
+ * The IP version number.
230
+ * @returns {4}
231
+ */
232
+ get version(): 4;
233
+ /**
234
+ * The IP address as a string.
235
+ * @returns {string}
236
+ */
237
+ get address(): string;
238
+ /**
239
+ * Converts the IP address to its BigInt representation.
240
+ * @returns {bigint}
241
+ */
242
+ toBigInt(): bigint;
243
+ /**
244
+ * Converts the IP address to an array of 4 bytes.
245
+ * @returns {[number, number, number, number]}
246
+ */
247
+ toBytes(): [number, number, number, number];
248
+ /**
249
+ * Returns the string representation of the IP address.
250
+ * @returns {string}
251
+ */
252
+ toString(): string;
253
+ /**
254
+ * Returns the string representation for JSON serialization.
255
+ * @returns {string}
256
+ */
257
+ toJSON(): string;
258
+ /**
259
+ * Converts the IPv4 address to an IPv4-mapped IPv6 address.
260
+ * @returns {IPv6} An IPv6 instance representing the mapped address.
261
+ *
262
+ * @example
263
+ * const ipv4 = new IPv4('192.0.2.1');
264
+ * const ipv6 = ipv4.toIPv4Mapped();
265
+ * console.log(ipv6.address); // "::ffff:192.0.2.1"
266
+ */
267
+ toIPv4Mapped(): IPv6;
268
+ /**
269
+ * Returns the reverse DNS (ARPA) name for the IP address.
270
+ * @returns {string}
271
+ *
272
+ * @example
273
+ * const ip = new IPv4('192.168.1.1');
274
+ * console.log(ip.toArpa()); // "1.1.168.192.in-addr.arpa"
275
+ */
276
+ toArpa(): string;
277
+ /**
278
+ * Checks if the address is in a private range (RFC 1918).
279
+ * @returns {boolean}
280
+ */
281
+ isPrivate(): boolean;
282
+ /**
283
+ * Checks if the address is a loopback address (127.0.0.0/8).
284
+ * @returns {boolean}
285
+ */
286
+ isLoopback(): boolean;
287
+ /**
288
+ * Checks if the address is a multicast address (224.0.0.0/4).
289
+ * @returns {boolean}
290
+ */
291
+ isMulticast(): boolean;
292
+ /**
293
+ * Checks if the address is a link-local address (169.254.0.0/16).
294
+ * @returns {boolean}
295
+ */
296
+ isLinkLocal(): boolean;
297
+ /**
298
+ * Checks if the address is the unspecified address (0.0.0.0).
299
+ * @returns {boolean}
300
+ */
301
+ isUnspecified(): boolean;
302
+ /**
303
+ * Checks if the address is the limited broadcast address (255.255.255.255).
304
+ * Note: This does not check for subnet-directed broadcasts.
305
+ * @returns {boolean}
306
+ */
307
+ isBroadcast(): boolean;
308
+ /**
309
+ * Checks if the address is reserved by IANA. This includes ranges for
310
+ * private use, loopback, multicast, and other special purposes.
311
+ * @returns {boolean}
312
+ */
313
+ isReserved(): boolean;
314
+ /**
315
+ * Checks if the address is a global unicast address (i.e., a public IP).
316
+ * @returns {boolean}
317
+ */
318
+ isGlobalUnicast(): boolean;
319
+ /**
320
+ * Checks for exact equality between this and another IPv4 address.
321
+ * @param other The other IPv4 address to compare with.
322
+ * @returns {boolean}
323
+ */
324
+ equals(other: IPv4 | string): boolean;
325
+ /**
326
+ * Compares this IP address with another.
327
+ * @param other The other IPv4 address to compare with.
328
+ * @returns `-1` if this address is less than the other, `0` if they are equal, `1` if it is greater.
329
+ */
330
+ compare(other: IPv4 | string): -1 | 0 | 1;
331
+ /**
332
+ * Performs a bitwise AND operation with another IPv4 address.
333
+ * @param other The other IPv4 address.
334
+ * @returns A new IPv4 instance with the result of the AND operation.
335
+ */
336
+ and(other: IPv4 | string): IPv4;
337
+ /**
338
+ * Performs a bitwise OR operation with another IPv4 address.
339
+ * @param other The other IPv4 address.
340
+ * @returns A new IPv4 instance with the result of the OR operation.
341
+ */
342
+ or(other: IPv4 | string): IPv4;
343
+ /**
344
+ * Performs a bitwise NOT operation on the address.
345
+ * @returns A new IPv4 instance with the result of the NOT operation.
346
+ */
347
+ not(): IPv4;
348
+ /**
349
+ * Returns the next IP address.
350
+ * @param [count=1n] The number of addresses to increment by.
351
+ * @returns {IPv4}
352
+ */
353
+ next(count?: bigint): IPv4;
354
+ /**
355
+ * Returns the previous IP address.
356
+ * @param [count=1n] The number of addresses to decrement by.
357
+ * @returns {IPv4}
358
+ */
359
+ previous(count?: bigint): IPv4;
360
+ }
361
+
362
+ /**
363
+ * Represents the version of an IP address.
364
+ * - `4` for IPv4
365
+ * - `6` for IPv6
366
+ */
367
+ type IPVersion = 4 | 6;
368
+ /**
369
+ * Represents an IP address, which can be either an IPv4 or an IPv6 address.
370
+ */
371
+ type IP = IPv4 | IPv6;
372
+
373
+ /**
374
+ * Represents a CIDR block, which includes an IP address and a prefix length.
375
+ *
376
+ * @example
377
+ * const cidr = new CIDR('192.168.1.0/24');
378
+ * console.log(cidr.network.address); // "192.168.1.0"
379
+ * console.log(cidr.broadcast.address); // "192.168.1.255"
380
+ * console.log(cidr.contains('192.168.1.50')); // true
381
+ */
382
+ declare class CIDR<T extends IP> {
383
+ #private;
384
+ /**
385
+ * @param cidr A CIDR string (e.g., "192.168.1.0/24" or "2001:db8::/32").
386
+ * @throws {InvalidIPAddressError} If the CIDR string is invalid.
387
+ */
388
+ constructor(cidr: string);
389
+ /**
390
+ * The IP address portion of the CIDR.
391
+ * @returns {T}
392
+ */
393
+ get address(): T;
394
+ /**
395
+ * The prefix length of the CIDR.
396
+ * @returns {number}
397
+ */
398
+ get prefix(): number;
399
+ /**
400
+ * The IP version.
401
+ * @returns {IPVersion}
402
+ */
403
+ get version(): IPVersion;
404
+ /**
405
+ * The netmask for the CIDR block.
406
+ * @returns {T}
407
+ */
408
+ get netmask(): T;
409
+ /**
410
+ * The network address of the CIDR block.
411
+ * @returns {T}
412
+ */
413
+ get network(): T;
414
+ /**
415
+ * The broadcast address for the CIDR block.
416
+ * @returns {T}
417
+ */
418
+ get broadcast(): T;
419
+ /**
420
+ * The first usable IP address in the CIDR block.
421
+ * For IPv4 /31 and /32, this is the network address.
422
+ * For IPv6, this is the network address (Subnet-Router anycast).
423
+ * @returns {T}
424
+ */
425
+ get first(): T;
426
+ /**
427
+ * The last usable IP address in the CIDR block.
428
+ * For IPv4 /31 and /32, this is the broadcast address.
429
+ * For IPv6, this is the highest address in the range.
430
+ * @returns {T}
431
+ */
432
+ get last(): T;
433
+ /**
434
+ * Checks if a given IP address is contained within this CIDR block.
435
+ * @param ip The IP address to check.
436
+ * @returns {boolean}
437
+ */
438
+ contains(ip: T | string): boolean;
439
+ /**
440
+ * Returns the string representation of the CIDR.
441
+ * @returns {string}
442
+ */
443
+ toString(): string;
444
+ /**
445
+ * Returns the string representation for JSON serialization.
446
+ * @returns {string}
447
+ */
448
+ toJSON(): string;
449
+ }
450
+
451
+ /**
452
+ * Quickly determines the IP version from a string.
453
+ * @param probablyIp The IP address string.
454
+ * @returns The IP version (4 or 6).
455
+ * @throws {InvalidIPAddressError} If the string is not recognizable as an IP address.
456
+ */
457
+ declare function fastIpVersion(probablyIp: string): IPVersion;
458
+ /**
459
+ * Converts an IP address string to its BigInt representation.
460
+ *
461
+ * @param ip The IP address string to convert.
462
+ * @param version The IP version (4 or 6). If not provided, it will be detected automatically.
463
+ * @returns The BigInt representation of the IP address.
464
+ * @throws {InvalidIPAddressError} If the IP address is invalid.
465
+ */
466
+ declare function ipToBigInt(ip: string, version?: IPVersion): bigint;
467
+ /**
468
+ * Converts a BigInt to its IP address string representation.
469
+ *
470
+ * @param number The BigInt to convert.
471
+ * @param version The IP version (4 or 6).
472
+ * @param compress Whether to compress the IPv6 address (e.g., remove leading zeros and use `::`).
473
+ * @returns The IP address string.
474
+ */
475
+ declare function bigIntToIp(number: bigint, version: IPVersion, compress?: boolean): string;
476
+
477
+ declare class InvalidIPAddressError extends Error {
478
+ constructor(message: string);
479
+ }
480
+
481
+ /**
482
+ * A factory function that parses an IP address string and returns
483
+ * an instance of the appropriate class (IPv4 or IPv6).
484
+ *
485
+ * @param address The IP address string.
486
+ * @returns An instance of IPv4 or IPv6.
487
+ * @throws {InvalidIPAddressError} if the address is not a valid v4 or v6 address.
488
+ */
489
+ declare function parseIP(address: string): IP;
490
+ /**
491
+ * A factory function that parses a CIDR string and returns
492
+ * an instance of the CIDR class.
493
+ *
494
+ * @param cidr The CIDR string.
495
+ * @returns An instance of CIDR.
496
+ * @throws {InvalidIPAddressError} if the cidr is not a valid v4 or v6 cidr.
497
+ */
498
+ declare function parseCIDR(cidr: string): CIDR<IP>;
499
+ /**
500
+ * Safely checks if a value is a string representing a valid IPv4 or IPv6 address.
501
+ *
502
+ * @param maybeIP The value to check.
503
+ * @returns {boolean} True if the value is a valid IP address string.
504
+ *
505
+ * @example
506
+ * isValidIP('192.168.1.1'); // true
507
+ * isValidIP('2001:db8::1'); // true
508
+ * isValidIP('not an ip'); // false
509
+ * isValidIP(null); // false
510
+ */
511
+ declare function isValidIP(maybeIP: unknown): boolean;
512
+
513
+ export { CIDR, type IP, type IPVersion, IPv4, IPv6, InvalidIPAddressError, bigIntToIp, fastIpVersion, ipToBigInt, isValidIP, parseCIDR, parseIP };
package/dist/index.js CHANGED
@@ -24,7 +24,15 @@ var IPV6_COMPRESSED_7 = `(?:${IPV6_SEGMENT}:){1,2}(?::${IPV6_SEGMENT}){1,5}`;
24
24
  var IPV6_COMPRESSED_8 = `${IPV6_SEGMENT}:(?::${IPV6_SEGMENT}){1,6}`;
25
25
  var IPV6_COMPRESSED_9 = `::(?:${IPV6_SEGMENT}:){0,5}${IPV6_SEGMENT}`;
26
26
  var IPV6_COMPRESSED_10 = "::";
27
- var IPV6_IPV4_MAPPED = `(?:(?:${IPV6_SEGMENT}:){6}|::(?:${IPV6_SEGMENT}:){0,5}|(?:${IPV6_SEGMENT}:){0,5}::(?:${IPV6_SEGMENT}:){0,5})${IPV4_ADDRESS_PATTERN}`;
27
+ var IPV6_IPV4_MAPPED = [
28
+ `(?:${IPV6_SEGMENT}:){6}`,
29
+ `::(?:${IPV6_SEGMENT}:){0,5}`,
30
+ `(?:${IPV6_SEGMENT}:){1}:(?:${IPV6_SEGMENT}:){0,4}`,
31
+ `(?:${IPV6_SEGMENT}:){2}:(?:${IPV6_SEGMENT}:){0,3}`,
32
+ `(?:${IPV6_SEGMENT}:){3}:(?:${IPV6_SEGMENT}:){0,2}`,
33
+ `(?:${IPV6_SEGMENT}:){4}:(?:${IPV6_SEGMENT}:){0,1}`,
34
+ `(?:${IPV6_SEGMENT}:){5}:`
35
+ ].map((prefix) => `${prefix}${IPV4_ADDRESS_PATTERN}`).join("|");
28
36
  var IPV6_COMBINED = [
29
37
  IPV6_STANDARD,
30
38
  IPV6_COMPRESSED_1,
@@ -51,19 +59,19 @@ var InvalidIPAddressError = class extends Error {
51
59
 
52
60
  // src/utils.ts
53
61
  function fastIpVersion(probablyIp) {
54
- if (probablyIp.includes(".")) {
55
- return 4;
56
- }
57
62
  if (probablyIp.includes(":")) {
58
63
  return 6;
59
64
  }
65
+ if (probablyIp.includes(".")) {
66
+ return 4;
67
+ }
60
68
  throw new InvalidIPAddressError(`Invalid IP address: ${probablyIp}`);
61
69
  }
62
70
  function ipv4ToBigInt(ip) {
63
- const parts = ip.split(".");
64
- if (parts.length !== 4 || parts.some((part) => !/^\d+$/.test(part) || Number(part) > 255)) {
71
+ if (!IPV4_ADDRESS_REGEX.test(ip)) {
65
72
  throw new InvalidIPAddressError(`Invalid IPv4 address: ${ip}`);
66
73
  }
74
+ const parts = ip.split(".");
67
75
  return parts.reduce((acc, octet) => acc << 8n | BigInt(parseInt(octet, 10)), 0n);
68
76
  }
69
77
  function expandIPv6Shorthand(parts) {
@@ -75,26 +83,28 @@ function expandIPv6Shorthand(parts) {
75
83
  return parts;
76
84
  }
77
85
  function ipv6ToBigInt(ip) {
78
- if (ip.includes("%")) {
79
- ip = /(.+)%(.+)/.exec(ip)[1];
80
- }
81
- const ipv4MappedMatch = /^(::ffff:)(?:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}))$/.exec(ip);
82
- if (ipv4MappedMatch) {
83
- const ipv4Part = ipv4MappedMatch[2];
84
- const ipv4BigInt = ipv4ToBigInt(ipv4Part);
85
- return 0x00000000000000000000ffffn << 32n | ipv4BigInt;
86
- }
87
- let parts = ip.split(":");
88
- parts = expandIPv6Shorthand(parts);
89
- if (parts.length !== 8 || parts.some((part) => !/^[0-9a-fA-F]*$/.test(part) || part.length > 4)) {
86
+ const percentIndex = ip.indexOf("%");
87
+ if (percentIndex !== -1) {
88
+ if (percentIndex === 0 || percentIndex === ip.length - 1) {
89
+ throw new InvalidIPAddressError(`Invalid IPv6 address: ${ip}`);
90
+ }
91
+ ip = ip.slice(0, percentIndex);
92
+ }
93
+ if (!IPV6_VALIDATION_REGEX.test(ip)) {
90
94
  throw new InvalidIPAddressError(`Invalid IPv6 address: ${ip}`);
91
95
  }
96
+ if (ip.includes(".")) {
97
+ const lastColon = ip.lastIndexOf(":");
98
+ const prefix = ip.slice(0, lastColon + 1);
99
+ const ipv4BigInt = ipv4ToBigInt(ip.slice(lastColon + 1));
100
+ const high = (ipv4BigInt >> 16n & 0xffffn).toString(16);
101
+ const low = (ipv4BigInt & 0xffffn).toString(16);
102
+ ip = `${prefix}${high}:${low}`;
103
+ }
104
+ const parts = expandIPv6Shorthand(ip.split(":"));
92
105
  let number = 0n;
93
- let exp = 0n;
94
- const r = parts.map((part) => part === "" ? 0n : BigInt(Number.parseInt(part, 16))).reverse();
95
- for (const n of r) {
96
- number += n * 2n ** exp;
97
- exp += 16n;
106
+ for (const part of parts) {
107
+ number = number << 16n | (part === "" ? 0n : BigInt(Number.parseInt(part, 16)));
98
108
  }
99
109
  return number;
100
110
  }
@@ -109,7 +119,7 @@ function bigIntToIp(number, version, compress = true) {
109
119
  if (version === 4) {
110
120
  return `${number >> 24n & 0xffn}.${number >> 16n & 0xffn}.${number >> 8n & 0xffn}.${number & 0xffn}`;
111
121
  }
112
- if (number >> 32n === 0xffffn) {
122
+ if (compress && number >> 32n === 0xffffn) {
113
123
  const ipv4Part = number & 0xffffffffn;
114
124
  const ipv4String = bigIntToIp(ipv4Part, 4);
115
125
  return `::ffff:${ipv4String}`;
@@ -125,27 +135,33 @@ function bigIntToIp(number, version, compress = true) {
125
135
  return to16.map((part) => part.padStart(4, "0")).join(":");
126
136
  }
127
137
  function compressIPv6(parts) {
128
- let longest = null;
129
- let current = null;
130
- for (let i = 0, len = parts.length; i < len; i++) {
131
- const part = parts[i];
132
- if (part === "0") {
133
- current ??= /* @__PURE__ */ new Set();
134
- current.add(i);
135
- } else if (current) {
136
- if (!longest || current.size > longest.size) {
137
- longest = current;
138
+ let bestStart = -1;
139
+ let bestLen = 0;
140
+ let curStart = -1;
141
+ let curLen = 0;
142
+ for (let i = 0; i < parts.length; i++) {
143
+ if (parts[i] === "0") {
144
+ if (curStart === -1) {
145
+ curStart = i;
146
+ curLen = 1;
147
+ } else {
148
+ curLen++;
149
+ }
150
+ if (curLen > bestLen) {
151
+ bestStart = curStart;
152
+ bestLen = curLen;
138
153
  }
139
- current = null;
154
+ } else {
155
+ curStart = -1;
156
+ curLen = 0;
140
157
  }
141
158
  }
142
- if (!longest && current || current && longest && current.size > longest.size) {
143
- longest = current;
159
+ if (bestLen < 2) {
160
+ return parts.join(":");
144
161
  }
145
- for (const index of longest || []) {
146
- parts[index] = ":";
147
- }
148
- return parts.filter(Boolean).join(":").replace(/:{2,}/, "::");
162
+ const before = parts.slice(0, bestStart).join(":");
163
+ const after = parts.slice(bestStart + bestLen).join(":");
164
+ return `${before}::${after}`;
149
165
  }
150
166
 
151
167
  // src/ipv6.ts
@@ -685,24 +701,29 @@ var CIDR = class {
685
701
  */
686
702
  constructor(cidr) {
687
703
  const parts = cidr.split("/");
704
+ if (parts.length > 2) {
705
+ throw new InvalidIPAddressError(`Invalid CIDR: ${cidr}`);
706
+ }
688
707
  const addressPart = parts[0];
689
708
  let prefixPart = parts[1];
690
709
  let address;
691
710
  let version;
692
- if (addressPart.includes(".")) {
711
+ if (addressPart.includes(":")) {
712
+ address = new IPv6(addressPart);
713
+ version = 6;
714
+ } else if (addressPart.includes(".")) {
693
715
  address = new IPv4(addressPart);
694
716
  version = 4;
695
717
  } else {
696
- address = new IPv6(addressPart);
697
- version = 6;
718
+ throw new InvalidIPAddressError(`Invalid IP address: ${addressPart}`);
698
719
  }
699
720
  if (prefixPart === void 0) {
700
721
  prefixPart = String(BITS[version]);
701
722
  }
702
- const prefix = parseInt(prefixPart, 10);
703
- if (isNaN(prefix)) {
723
+ if (!/^\d+$/.test(prefixPart)) {
704
724
  throw new InvalidIPAddressError(`Invalid prefix: ${prefixPart}`);
705
725
  }
726
+ const prefix = Number(prefixPart);
706
727
  if (prefix < 0 || prefix > BITS[version]) {
707
728
  throw new InvalidIPAddressError(`Prefix out of range for IPv${version}: ${prefix}`);
708
729
  }
@@ -829,12 +850,12 @@ var CIDR = class {
829
850
 
830
851
  // src/index.ts
831
852
  function parseIP(address) {
832
- if (address.includes(".")) {
833
- return new IPv4(address);
834
- }
835
853
  if (address.includes(":")) {
836
854
  return new IPv6(address);
837
855
  }
856
+ if (address.includes(".")) {
857
+ return new IPv4(address);
858
+ }
838
859
  throw new InvalidIPAddressError(`Invalid IP address: ${address}`);
839
860
  }
840
861
  function parseCIDR(cidr) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@se-oss/ip-address",
3
- "version": "1.1.0",
3
+ "version": "1.1.2",
4
4
  "description": "A modern, immutable, and zero-dependency library for working with IPv4 and IPv6 addresses in JavaScript and TypeScript.",
5
5
  "keywords": [
6
6
  "ip",
@@ -22,42 +22,47 @@
22
22
  "type": "module",
23
23
  "exports": {
24
24
  ".": {
25
- "import": "./dist/index.js",
26
- "default": "./dist/index.cjs"
25
+ "import": {
26
+ "types": "./dist/index.d.ts",
27
+ "default": "./dist/index.js"
28
+ },
29
+ "require": {
30
+ "types": "./dist/index.d.cts",
31
+ "default": "./dist/index.cjs"
32
+ }
27
33
  }
28
34
  },
29
- "main": "dist/index.js",
35
+ "main": "dist/index.cjs",
36
+ "module": "dist/index.js",
30
37
  "types": "dist/index.d.ts",
31
38
  "files": [
32
- "dist/**",
33
- "!**/*.d.cts"
39
+ "dist/**"
34
40
  ],
41
+ "prettier": "@shahrad/prettier-config",
42
+ "devDependencies": {
43
+ "@changesets/cli": "^2.31.1",
44
+ "@shahrad/eslint-config": "^1.1.0",
45
+ "@shahrad/prettier-config": "^1.2.2",
46
+ "@shahrad/tsconfig": "^1.3.0",
47
+ "@types/node": "^26.1.2",
48
+ "eslint": "^10.8.0",
49
+ "globals": "^16.5.0",
50
+ "prettier": "^3.9.6",
51
+ "tsup": "^8.5.1",
52
+ "typescript": "^6.0.3",
53
+ "vitest": "^3.2.7"
54
+ },
35
55
  "scripts": {
36
56
  "bench": "vitest bench --run",
37
- "build": "pnpm typecheck && tsup",
57
+ "build": "tsup",
58
+ "ci:publish": "changeset publish",
38
59
  "clean": "git clean -dfx node_modules dist .tsbuildinfo",
39
60
  "dev": "tsup --watch",
40
61
  "format": "prettier --write .",
41
62
  "format:check": "prettier --check .",
42
63
  "lint": "pnpm typecheck && eslint .",
43
64
  "lint:fix": "eslint --fix .",
44
- "prepublishOnly": "pnpm build && pnpm lint && pnpm format:check && pnpm test",
45
65
  "test": "vitest --run",
46
66
  "typecheck": "tsc --noEmit"
47
- },
48
- "prettier": "@shahrad/prettier-config",
49
- "devDependencies": {
50
- "@shahrad/eslint-config": "^1.0.1",
51
- "@shahrad/prettier-config": "^1.2.2",
52
- "@shahrad/tsconfig": "^1.2.0",
53
- "@types/node": "^24.7.0",
54
- "eslint": "^9.37.0",
55
- "globals": "^16.4.0",
56
- "prettier": "^3.6.2",
57
- "tsup": "^8.5.0",
58
- "tsx": "^4.20.6",
59
- "typescript": "^5.9.3",
60
- "vitest": "^3.2.4"
61
- },
62
- "packageManager": "pnpm@10.15.0"
63
- }
67
+ }
68
+ }