@bigbinary/neeto-molecules 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.
Files changed (45) hide show
  1. package/README.md +36 -0
  2. package/dist/BrowserSupport.cjs.js +1468 -0
  3. package/dist/BrowserSupport.js +1462 -0
  4. package/dist/Columns.cjs.js +183 -0
  5. package/dist/Columns.js +177 -0
  6. package/dist/CustomDomain.cjs.js +758 -0
  7. package/dist/CustomDomain.js +732 -0
  8. package/dist/DateRangeFilter.cjs.js +214 -0
  9. package/dist/DateRangeFilter.js +207 -0
  10. package/dist/EmailPreview.cjs.js +32409 -0
  11. package/dist/EmailPreview.js +32383 -0
  12. package/dist/ErrorPage.cjs.js +135 -0
  13. package/dist/ErrorPage.js +111 -0
  14. package/dist/IpRestriction.cjs.js +3578 -0
  15. package/dist/IpRestriction.js +3552 -0
  16. package/dist/KeyboardShortcuts.cjs.js +2212 -0
  17. package/dist/KeyboardShortcuts.js +2205 -0
  18. package/dist/LoginPage.cjs.js +598 -0
  19. package/dist/LoginPage.js +573 -0
  20. package/dist/NeetoWidget.cjs.js +86969 -0
  21. package/dist/NeetoWidget.js +86943 -0
  22. package/dist/PublishBlock.cjs.js +188 -0
  23. package/dist/PublishBlock.js +182 -0
  24. package/dist/Schedule.cjs.js +949 -0
  25. package/dist/Schedule.js +918 -0
  26. package/dist/ShareViaLink.cjs.js +1247 -0
  27. package/dist/ShareViaLink.js +1241 -0
  28. package/dist/Sidebar.cjs.js +222 -0
  29. package/dist/Sidebar.js +195 -0
  30. package/package.json +149 -0
  31. package/src/translations/en.json +244 -0
  32. package/types/BrowserSupport.d.ts +20 -0
  33. package/types/Columns.d.ts +22 -0
  34. package/types/CustomDomain.d.ts +7 -0
  35. package/types/DateRangeFilter.d.ts +17 -0
  36. package/types/EmailPreview.d.ts +11 -0
  37. package/types/ErrorPage.d.ts +8 -0
  38. package/types/IpRestriction.d.ts +5 -0
  39. package/types/KeyboardShortcuts.d.ts +21 -0
  40. package/types/LoginPage.d.ts +12 -0
  41. package/types/NeetoWidget.d.ts +17 -0
  42. package/types/PublishBlock.d.ts +20 -0
  43. package/types/Schedule.d.ts +15 -0
  44. package/types/ShareViaLink.d.ts +17 -0
  45. package/types/Sidebar.d.ts +28 -0
@@ -0,0 +1,3552 @@
1
+ import React, { useState } from 'react';
2
+ import { Button as Button$1, Typography, Alert, Spinner, Switch } from '@bigbinary/neetoui';
3
+ import { useTranslation } from 'react-i18next';
4
+ import { Check, Close, Delete, Edit, Plus } from '@bigbinary/neeto-icons';
5
+ import { Form, Input, Button } from '@bigbinary/neetoui/formik';
6
+ import { useQuery, useQueryClient, useMutation } from 'react-query';
7
+ import axios from 'axios';
8
+ import { t } from 'i18next';
9
+ import { isNil } from 'ramda';
10
+ import * as yup from 'yup';
11
+
12
+ function _arrayWithHoles(arr) {
13
+ if (Array.isArray(arr)) return arr;
14
+ }
15
+
16
+ function _iterableToArrayLimit(arr, i) {
17
+ var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"];
18
+ if (null != _i) {
19
+ var _s,
20
+ _e,
21
+ _x,
22
+ _r,
23
+ _arr = [],
24
+ _n = !0,
25
+ _d = !1;
26
+ try {
27
+ if (_x = (_i = _i.call(arr)).next, 0 === i) {
28
+ if (Object(_i) !== _i) return;
29
+ _n = !1;
30
+ } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0);
31
+ } catch (err) {
32
+ _d = !0, _e = err;
33
+ } finally {
34
+ try {
35
+ if (!_n && null != _i["return"] && (_r = _i["return"](), Object(_r) !== _r)) return;
36
+ } finally {
37
+ if (_d) throw _e;
38
+ }
39
+ }
40
+ return _arr;
41
+ }
42
+ }
43
+
44
+ function _arrayLikeToArray(arr, len) {
45
+ if (len == null || len > arr.length) len = arr.length;
46
+ for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
47
+ return arr2;
48
+ }
49
+
50
+ function _unsupportedIterableToArray(o, minLen) {
51
+ if (!o) return;
52
+ if (typeof o === "string") return _arrayLikeToArray(o, minLen);
53
+ var n = Object.prototype.toString.call(o).slice(8, -1);
54
+ if (n === "Object" && o.constructor) n = o.constructor.name;
55
+ if (n === "Map" || n === "Set") return Array.from(o);
56
+ if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
57
+ }
58
+
59
+ function _nonIterableRest() {
60
+ throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
61
+ }
62
+
63
+ function _slicedToArray(arr, i) {
64
+ return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest();
65
+ }
66
+
67
+ var IP_RESTRICTIONS_ENGINE_BASE_URL = "ip_restrictions/api/v1";
68
+ var INITIAL_VALUES = {
69
+ ipStart: "",
70
+ ipEnd: ""
71
+ };
72
+ var QUERY_KEYS = {
73
+ IP_RESTRICTION: "IP_RESTRICTION",
74
+ ALLOWED_IP_RANGES: "ALLOWED_IP_RANGES",
75
+ CURRENT_IP: "CURRENT_IP"
76
+ };
77
+
78
+ var allowedIpRangesUrl = "".concat(IP_RESTRICTIONS_ENGINE_BASE_URL, "/allowed_ips");
79
+ var fetch = function fetch() {
80
+ return axios.get(allowedIpRangesUrl);
81
+ };
82
+ var create = function create(payload) {
83
+ return axios.post(allowedIpRangesUrl, {
84
+ allowedIpRange: payload
85
+ });
86
+ };
87
+ var destroy = function destroy(id) {
88
+ return axios["delete"]("".concat(allowedIpRangesUrl, "/").concat(id));
89
+ };
90
+ var update$1 = function update(_ref) {
91
+ var id = _ref.id,
92
+ payload = _ref.payload;
93
+ return axios.patch("".concat(allowedIpRangesUrl, "/").concat(id), {
94
+ allowedIpRange: payload
95
+ });
96
+ };
97
+ var allowedIpRangesApi = {
98
+ fetch: fetch,
99
+ create: create,
100
+ destroy: destroy,
101
+ update: update$1
102
+ };
103
+
104
+ var ALLOWED_IP_RANGES = QUERY_KEYS.ALLOWED_IP_RANGES;
105
+ var useFetchAllowedIpRanges = function useFetchAllowedIpRanges() {
106
+ return useQuery([ALLOWED_IP_RANGES], function () {
107
+ return allowedIpRangesApi.fetch();
108
+ });
109
+ };
110
+ var useCreateAllowedIpRanges = function useCreateAllowedIpRanges() {
111
+ var queryClient = useQueryClient();
112
+ return useMutation(allowedIpRangesApi.create, {
113
+ onSuccess: function onSuccess() {
114
+ return queryClient.invalidateQueries(ALLOWED_IP_RANGES);
115
+ }
116
+ });
117
+ };
118
+ var useDestroyAllowedIpRanges = function useDestroyAllowedIpRanges() {
119
+ var queryClient = useQueryClient();
120
+ return useMutation(allowedIpRangesApi.destroy, {
121
+ onSuccess: function onSuccess() {
122
+ queryClient.invalidateQueries(ALLOWED_IP_RANGES);
123
+ }
124
+ });
125
+ };
126
+ var useUpdateAllowedIpRanges = function useUpdateAllowedIpRanges() {
127
+ var queryClient = useQueryClient();
128
+ return useMutation(allowedIpRangesApi.update, {
129
+ onSuccess: function onSuccess() {
130
+ queryClient.invalidateQueries(ALLOWED_IP_RANGES);
131
+ }
132
+ });
133
+ };
134
+
135
+ var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
136
+
137
+ var ipNum = {};
138
+
139
+ var BinaryUtils = {};
140
+
141
+ (function (exports) {
142
+ Object.defineProperty(exports, "__esModule", { value: true });
143
+ exports.matchingBitCount = exports.intLog2 = exports.cidrPrefixToMaskBinaryString = exports.leftPadWithZeroBit = exports.dottedDecimalNotationToBinaryString = exports.parseBinaryStringToBigInt = exports.decimalNumberToOctetString = exports.numberToBinaryString = void 0;
144
+ /**
145
+ * Converts a decimal number to binary string
146
+ *
147
+ * @param num number to parse
148
+ * @returns {string} the binary string representation of number
149
+ */
150
+ exports.numberToBinaryString = (num) => {
151
+ return num.toString(2);
152
+ };
153
+ /**
154
+ * Converts a decimal number to binary octet (8 bit) string. If needed the octet will be padded with zeros
155
+ * to make it up to 8 bits
156
+ *
157
+ * @param {number} num to convert to octet string
158
+ * @returns {string} the octet string representation of given number
159
+ */
160
+ exports.decimalNumberToOctetString = (num) => {
161
+ let binaryString = exports.numberToBinaryString(num);
162
+ let length = binaryString.length;
163
+ if (length > 8) {
164
+ throw new Error("Given decimal in binary contains digits greater than an octet");
165
+ }
166
+ return exports.leftPadWithZeroBit(binaryString, 8);
167
+ };
168
+ /**
169
+ * Parses number in binary to number in BigInt
170
+ *
171
+ * @param num binary number in string to parse
172
+ * @returns {number} binary number in BigInt
173
+ */
174
+ exports.parseBinaryStringToBigInt = (num) => {
175
+ return BigInt(`0b${num}`);
176
+ };
177
+ /**
178
+ * Given an IPv4 number in dot-decimal notated string, e.g 192.168.0.1 converts it to
179
+ * binary string, e.g. '11000000101010000000000000000001'
180
+ *
181
+ * @param dottedDecimal IPv4 string in dot-decimal notation
182
+ * @returns {string} the binary value of the given ipv4 number in string
183
+ */
184
+ exports.dottedDecimalNotationToBinaryString = (dottedDecimal) => {
185
+ let stringOctets = dottedDecimal.split(".");
186
+ return stringOctets.reduce((binaryAsString, octet) => {
187
+ return binaryAsString.concat(exports.decimalNumberToOctetString(parseInt(octet)));
188
+ }, '');
189
+ };
190
+ /**
191
+ * Given a binary string, adds a number of zero to the left until string is as long as the given string length
192
+ * @param {string} binaryString the string to pad
193
+ * @param {number} finalStringLength the final length of string after padding
194
+ * @returns {string}
195
+ */
196
+ exports.leftPadWithZeroBit = (binaryString, finalStringLength) => {
197
+ if (binaryString.length > finalStringLength) {
198
+ throw new Error(`Given string is already longer than given final length after padding: ${finalStringLength}`);
199
+ }
200
+ return "0".repeat(finalStringLength - binaryString.length).concat(binaryString);
201
+ };
202
+ /**
203
+ * Given the prefix portion of a cidr notation and the type of IP number, returns the mask in binary string
204
+ *
205
+ * @param {number} cidrPrefix the prefix part of a cidr notation
206
+ * @param {IPNumType.IPv4 | IPNumType.IPv6} ipType the type of the ip number in the range the cidr represents
207
+ */
208
+ exports.cidrPrefixToMaskBinaryString = (cidrPrefix, ipType) => {
209
+ let cidrUpperValue;
210
+ if (ipType == "IPv4" /* IPv4 */) {
211
+ cidrUpperValue = 32;
212
+ }
213
+ else {
214
+ cidrUpperValue = 128;
215
+ }
216
+ if (cidrPrefix > cidrUpperValue)
217
+ throw Error(`Value is greater than ${cidrUpperValue}`);
218
+ let onBits = '1'.repeat(cidrPrefix);
219
+ let offBits = '0'.repeat(cidrUpperValue - cidrPrefix);
220
+ return `${onBits}${offBits}`;
221
+ };
222
+ /**
223
+ * Calculates the log, to base 2 of given number.
224
+ *
225
+ * @throws Error if number cannot be converted to log base 2
226
+ * @param givenNumber the number to calculate log base 2
227
+ * @return the log base 2 of given number
228
+ */
229
+ exports.intLog2 = (givenNumber) => {
230
+ let result = 0;
231
+ while (givenNumber % 2n === 0n) {
232
+ if (givenNumber === 2n) {
233
+ result++;
234
+ break;
235
+ }
236
+ givenNumber = givenNumber >> 1n;
237
+ if (givenNumber % 2n !== 0n) {
238
+ result = 0;
239
+ break;
240
+ }
241
+ result++;
242
+ }
243
+ if (result == 0) {
244
+ throw new Error(`The value of log2 for ${givenNumber.toString()} is not an integer`);
245
+ }
246
+ return result;
247
+ };
248
+ /**
249
+ * Starting from the most significant bit (from left) returns the number of first bits from both string that are equal
250
+ * @param firstBinaryString first binary string
251
+ * @param secondBinaryString second binary string
252
+ */
253
+ exports.matchingBitCount = (firstBinaryString, secondBinaryString) => {
254
+ let longerString;
255
+ let otherString;
256
+ if (firstBinaryString.length >= secondBinaryString.length) {
257
+ longerString = firstBinaryString;
258
+ otherString = secondBinaryString;
259
+ }
260
+ else {
261
+ longerString = secondBinaryString;
262
+ otherString = firstBinaryString;
263
+ }
264
+ let count = 0;
265
+ for (; count < longerString.length; count++) {
266
+ if (longerString.charAt(count) === otherString.charAt(count)) {
267
+ continue;
268
+ }
269
+ break;
270
+ }
271
+ return count;
272
+ };
273
+
274
+ } (BinaryUtils));
275
+
276
+ var Hexadecatet$1 = {};
277
+
278
+ var Validator = {};
279
+
280
+ var IPv6Utils = {};
281
+
282
+ var hasRequiredIPv6Utils;
283
+
284
+ function requireIPv6Utils () {
285
+ if (hasRequiredIPv6Utils) return IPv6Utils;
286
+ hasRequiredIPv6Utils = 1;
287
+ Object.defineProperty(IPv6Utils, "__esModule", { value: true });
288
+ IPv6Utils.collapseIPv6Number = IPv6Utils.expandIPv6Number = void 0;
289
+ const BinaryUtils_1 = BinaryUtils;
290
+ const Validator_1 = requireValidator();
291
+ let extractPrefix = (ipv6String) => {
292
+ return ipv6String.includes("/") ? `/${ipv6String.split("/")[1]}` : "";
293
+ };
294
+ /**
295
+ * Expands an IPv6 number in abbreviated format into its full form
296
+ *
297
+ * {@see https://en.wikipedia.org/wiki/IPv6_address#Representation} for more on the representation of IPv6 addresses
298
+ *
299
+ * @param {string} ipv6String the abbreviated IPv6 address to expand
300
+ * @returns {string} the expanded IPv6 address
301
+ */
302
+ IPv6Utils.expandIPv6Number = (ipv6String) => {
303
+ let expandWithZero = (hexadecimalArray) => {
304
+ let paddedArray = hexadecimalArray.map((hexadecimal) => {
305
+ return BinaryUtils_1.leftPadWithZeroBit(hexadecimal, 4);
306
+ });
307
+ return paddedArray.join(":");
308
+ };
309
+ let expandDoubleColon = (gapCount) => {
310
+ let pads = [];
311
+ for (let count = 0; count < gapCount; count++) {
312
+ pads.push("0000");
313
+ }
314
+ return pads.join(":");
315
+ };
316
+ if (/(:){3,}/.test(ipv6String))
317
+ throw "given IPv6 contains consecutive : more than two";
318
+ const prefix = extractPrefix(ipv6String);
319
+ if (ipv6String.includes("/")) {
320
+ ipv6String = ipv6String.split("/")[0];
321
+ }
322
+ let isValid = Validator_1.Validator.IPV6_PATTERN.test(ipv6String);
323
+ if (!isValid) {
324
+ throw Error(Validator_1.Validator.invalidIPv6PatternMessage);
325
+ }
326
+ if (ipv6String.includes("::")) {
327
+ let split = ipv6String.split("::");
328
+ let leftPortion = split[0];
329
+ let rightPortion = split[1];
330
+ let leftPortionSplit = leftPortion.split(":").filter(hexadecimal => { return hexadecimal !== ""; });
331
+ let rightPortionSplit = rightPortion.split(":").filter(hexadecimal => { return hexadecimal !== ""; });
332
+ let doublePortion = expandDoubleColon(8 - (leftPortionSplit.length + rightPortionSplit.length));
333
+ let leftString = expandWithZero(leftPortionSplit);
334
+ if (leftString !== "") {
335
+ leftString += ":";
336
+ }
337
+ let rightString = expandWithZero(rightPortionSplit);
338
+ if (rightString !== "") {
339
+ rightString = ":" + rightString;
340
+ }
341
+ return `${leftString}${doublePortion}${rightString}${prefix}`;
342
+ }
343
+ else {
344
+ return `${expandWithZero(ipv6String.split(":"))}${prefix}`;
345
+ }
346
+ };
347
+ /**
348
+ * Collapses an IPv6 number in full format into its abbreviated form
349
+ *
350
+ * {@see https://en.wikipedia.org/wiki/IPv6_address#Representation} for more on the representation of IPv6 addresses
351
+ *
352
+ * @param {string} ipv6String the full form IPv6 number to collapse
353
+ * @returns {string} the collapsed IPv6 number
354
+ */
355
+ IPv6Utils.collapseIPv6Number = (ipv6String) => {
356
+ const prefix = extractPrefix(ipv6String);
357
+ if (ipv6String.includes("/")) {
358
+ ipv6String = ipv6String.split("/")[0];
359
+ }
360
+ let isValid = Validator_1.Validator.IPV6_PATTERN.test(ipv6String);
361
+ if (!isValid) {
362
+ throw Error(Validator_1.Validator.invalidIPv6PatternMessage);
363
+ }
364
+ let hexadecimals = ipv6String.split(":");
365
+ let hexadecimalsWithoutLeadingZeros = hexadecimals.map((hexidecimal) => {
366
+ let withoutLeadingZero = hexidecimal.replace(/^0+/, '');
367
+ if (withoutLeadingZero !== '') {
368
+ return withoutLeadingZero;
369
+ }
370
+ else {
371
+ return "0";
372
+ }
373
+ });
374
+ let contracted = hexadecimalsWithoutLeadingZeros.join(":").replace(/((^0)?(:0){2,}|(^0)(:0){1,})/, ':');
375
+ if (contracted.slice(-1) === ":") {
376
+ return `${contracted}:${prefix}`;
377
+ }
378
+ contracted = contracted.replace(":0:", "::");
379
+ return `${contracted}${prefix}`;
380
+ };
381
+
382
+ return IPv6Utils;
383
+ }
384
+
385
+ var HexadecimalUtils = {};
386
+
387
+ var hasRequiredHexadecimalUtils;
388
+
389
+ function requireHexadecimalUtils () {
390
+ if (hasRequiredHexadecimalUtils) return HexadecimalUtils;
391
+ hasRequiredHexadecimalUtils = 1;
392
+ (function (exports) {
393
+ Object.defineProperty(exports, "__esModule", { value: true });
394
+ exports.hexadectetNotationToBinaryString = exports.binaryStringToHexadecimalString = exports.colonHexadecimalNotationToBinaryString = exports.hexadecimalStringToHexadecatetString = exports.hexadecimalStringToBinaryString = exports.bigIntToHexadecimalString = void 0;
395
+ const IPv6Utils_1 = requireIPv6Utils();
396
+ const BinaryUtils_1 = BinaryUtils;
397
+ /**
398
+ * Converts a given bigint number to a hexadecimal string
399
+ * @param num the bigint number
400
+ * @returns {string} the hexadeciaml string
401
+ */
402
+ exports.bigIntToHexadecimalString = (num) => {
403
+ return num.toString(16);
404
+ };
405
+ /**
406
+ * Converts a number in hexadecimal (base 16) to binary string
407
+ * @param {string} hexadecimalString the number in base 16
408
+ * @returns {string} the number converted to base 2
409
+ */
410
+ exports.hexadecimalStringToBinaryString = (hexadecimalString) => {
411
+ let inDecimal = BigInt(`0x${hexadecimalString}`);
412
+ return inDecimal.toString(2);
413
+ };
414
+ /**
415
+ * Converts a number in hexadecimal (base 16) to binary hexadecatet string.
416
+ * This means the bits in the output cannot be more than 16
417
+ *
418
+ * @param hexadecimalString {string} the number converted to binary hexadecatet string
419
+ */
420
+ exports.hexadecimalStringToHexadecatetString = (hexadecimalString) => {
421
+ let binaryString = exports.hexadecimalStringToBinaryString(hexadecimalString);
422
+ let length = binaryString.length;
423
+ if (length > 16) {
424
+ throw new Error("Given decimal in binary contains digits greater than an Hexadecatet");
425
+ }
426
+ return BinaryUtils_1.leftPadWithZeroBit(binaryString, 16);
427
+ };
428
+ /**
429
+ * Given an IPv6 number in hexadecimal notated string, e.g 2001:0db8:0000:0000:0000:0000:0000:0000 converts it to
430
+ * binary string
431
+ *
432
+ * @param hexadecimalString IPv6 string
433
+ * @returns {string} the binary value of the given ipv6 number in string
434
+ */
435
+ exports.colonHexadecimalNotationToBinaryString = (hexadecimalString) => {
436
+ let expandedIPv6 = IPv6Utils_1.expandIPv6Number(hexadecimalString);
437
+ let stringHexadecimal = expandedIPv6.split(":");
438
+ return stringHexadecimal.reduce((binaryAsString, hexidecimal) => {
439
+ return binaryAsString.concat(exports.hexadecimalStringToHexadecatetString(hexidecimal));
440
+ }, '');
441
+ };
442
+ /**
443
+ * Converts number in binary string to hexadecimal string
444
+ * @param {string} num in binary string
445
+ * @returns {string} num in hexadecimal string
446
+ */
447
+ exports.binaryStringToHexadecimalString = (num) => {
448
+ // first convert to binary string to decimal (big Integer)
449
+ let inDecimal = BigInt(`0b${num}`);
450
+ return inDecimal.toString(16);
451
+ };
452
+ /**
453
+ * Converts a given IPv6 number expressed in the hexadecimal string notation into a 16 bit binary number in string
454
+ * @param {string} hexadectetString the IPv6 number
455
+ * @returns {string} the IPv6 number converted to binary string
456
+ */
457
+ exports.hexadectetNotationToBinaryString = (hexadectetString) => {
458
+ let expand = IPv6Utils_1.expandIPv6Number(hexadectetString);
459
+ let hexadecimals = expand.split(":");
460
+ return hexadecimals.reduce((hexadecimalAsString, hexavalue) => {
461
+ return hexadecimalAsString.concat(BinaryUtils_1.leftPadWithZeroBit(exports.hexadecimalStringToBinaryString(hexavalue), 16));
462
+ }, '');
463
+ };
464
+
465
+ } (HexadecimalUtils));
466
+ return HexadecimalUtils;
467
+ }
468
+
469
+ var hasRequiredValidator;
470
+
471
+ function requireValidator () {
472
+ if (hasRequiredValidator) return Validator;
473
+ hasRequiredValidator = 1;
474
+ Object.defineProperty(Validator, "__esModule", { value: true });
475
+ Validator.Validator = void 0;
476
+ const BinaryUtils_1 = BinaryUtils;
477
+ const BinaryUtils_2 = BinaryUtils;
478
+ const IPv6Utils_1 = requireIPv6Utils();
479
+ const HexadecimalUtils_1 = requireHexadecimalUtils();
480
+ const HexadecimalUtils_2 = requireHexadecimalUtils();
481
+ class Validator$1 {
482
+ /**
483
+ * Checks if given ipNumber is in between the given lower and upper bound
484
+ *
485
+ * @param ipNumber ipNumber to check
486
+ * @param lowerBound lower bound
487
+ * @param upperBound upper bound
488
+ * @returns {boolean} true if ipNumber is between lower and upper bound
489
+ */
490
+ static isWithinRange(ipNumber, lowerBound, upperBound) {
491
+ return ipNumber >= lowerBound && ipNumber <= upperBound;
492
+ }
493
+ /**
494
+ * Checks if the number given is within the value considered valid for an ASN number
495
+ *
496
+ * @param asnNumber the asn number to validate
497
+ * @returns {[boolean , string]} first value is true if valid ASN, false otherwise. Second value contains
498
+ * "valid" or an error message when value is invalid
499
+ */
500
+ static isValidAsnNumber(asnNumber) {
501
+ let isValid = this.isWithinRange(asnNumber, 0n, this.THIRTY_TWO_BIT_SIZE);
502
+ return [isValid, isValid ? [] : [Validator$1.invalidAsnRangeMessage]];
503
+ }
504
+ /**
505
+ * Checks if the given ASN number is a 16bit ASN number
506
+ *
507
+ * @param {bigint} asnNumber to check if 16bit or not
508
+ * @returns {[boolean , string]} first value is true if valid 16bit ASN, false otherwise. Second value contains
509
+ * "valid" or an error message when value is invalid
510
+ */
511
+ static isValid16BitAsnNumber(asnNumber) {
512
+ let isValid = Validator$1.isWithinRange(asnNumber, 0n, Validator$1.SIXTEEN_BIT_SIZE);
513
+ return [isValid, isValid ? [] : [Validator$1.invalid16BitAsnRangeMessage]];
514
+ }
515
+ /**
516
+ * Checks if the number given is within the value considered valid for an IPv4 number
517
+ *
518
+ * @param ipv4Number the asn number to validate
519
+ * @returns {[boolean , string]} first value is true if valid IPv4 number, false otherwise. Second value contains
520
+ * "valid" or an error message when value is invalid
521
+ */
522
+ static isValidIPv4Number(ipv4Number) {
523
+ ipv4Number = typeof ipv4Number === "bigint" ? ipv4Number : BigInt(ipv4Number);
524
+ let isValid = this.isWithinRange(ipv4Number, 0n, this.THIRTY_TWO_BIT_SIZE);
525
+ return isValid ? [isValid, []] : [isValid, [Validator$1.invalidIPv4NumberMessage]];
526
+ }
527
+ /**
528
+ * Checks if the number given is within the value considered valid for an IPv6 number
529
+ *
530
+ * @param ipv6Number the asn number to validate
531
+ * @returns {[boolean , string]} first value is true if valid IPv6 number, false otherwise. Second value contains
532
+ * "valid" or an error message when value is invalid
533
+ */
534
+ static isValidIPv6Number(ipv6Number) {
535
+ let isValid = this.isWithinRange(ipv6Number, 0n, this.ONE_HUNDRED_AND_TWENTY_EIGHT_BIT_SIZE);
536
+ return isValid ? [isValid, []] : [isValid, [Validator$1.invalidIPv6NumberMessage]];
537
+ }
538
+ /**
539
+ * Checks if the number given is valid for an IPv4 octet
540
+ *
541
+ * @param octetNumber the octet value
542
+ * @returns {boolean} true if valid octet, false otherwise
543
+ */
544
+ static isValidIPv4Octet(octetNumber) {
545
+ let withinRange = this.isWithinRange(octetNumber, 0n, this.EIGHT_BIT_SIZE);
546
+ return [withinRange, withinRange ? [] : [Validator$1.invalidOctetRangeMessage]];
547
+ }
548
+ /**
549
+ * Checks if the number given is valid for an IPv6 hexadecatet
550
+ *
551
+ * @param {bigint} hexadecatetNum the hexadecatet value
552
+ * @returns {[boolean , string]} first value is true if valid hexadecatet, false otherwise. Second value contains
553
+ * "valid" or an error message when value is invalid
554
+ */
555
+ static isValidIPv6Hexadecatet(hexadecatetNum) {
556
+ let isValid = this.isWithinRange(hexadecatetNum, 0n, this.SIXTEEN_BIT_SIZE);
557
+ return isValid ? [isValid, []] : [isValid, [Validator$1.invalidHexadecatetMessage]];
558
+ }
559
+ /**
560
+ * Checks if given string is a valid IPv4 value.
561
+ *
562
+ * @param {string} ipv4String the IPv4 string to validate
563
+ * @returns {[boolean , string]} result of validation, first value represents if is valid IPv4, second value
564
+ * contains error message if invalid IPv4
565
+ */
566
+ static isValidIPv4String(ipv4String) {
567
+ let rawOctets = ipv4String.split(".");
568
+ if (rawOctets.length != 4 || rawOctets.includes('')) {
569
+ return [false, [Validator$1.invalidOctetCountMessage]];
570
+ }
571
+ let isValid = rawOctets.every(octet => {
572
+ return Validator$1.isNumeric(octet) ? Validator$1.isValidIPv4Octet(BigInt(octet))[0] : false;
573
+ });
574
+ if (!isValid) {
575
+ return [false, [Validator$1.invalidOctetRangeMessage]];
576
+ }
577
+ isValid = Validator$1.IPV4_PATTERN.test(ipv4String);
578
+ return [isValid, isValid ? [] : [Validator$1.invalidIPv4PatternMessage]];
579
+ }
580
+ /**
581
+ * Checks if given string is a valid IPv6 value.
582
+ *
583
+ * @param {string} ipv6String the IPv6 string to validate
584
+ * @returns {[boolean , string]} result of validation, first value represents if is valid IPv6, second value
585
+ * contains error message if invalid IPv6
586
+ */
587
+ static isValidIPv6String(ipv6String) {
588
+ try {
589
+ let hexadecimals = IPv6Utils_1.expandIPv6Number(ipv6String).split(":");
590
+ if (hexadecimals.length != 8) {
591
+ return [false, [Validator$1.invalidHexadecatetCountMessage]];
592
+ }
593
+ let isValid = hexadecimals.every(hexadecimal => {
594
+ return Validator$1.isHexadecatet(hexadecimal) ?
595
+ Validator$1.isValidIPv6Hexadecatet(BigInt(`0x${hexadecimal}`))[0] : false;
596
+ });
597
+ if (!isValid) {
598
+ return [false, [Validator$1.invalidHexadecatetMessage]];
599
+ }
600
+ isValid = Validator$1.IPV6_PATTERN.test(ipv6String);
601
+ return [isValid, isValid ? [] : [Validator$1.invalidIPv6PatternMessage]];
602
+ }
603
+ catch (error) {
604
+ return [false, [error]];
605
+ }
606
+ }
607
+ /**
608
+ * Checks if given value is a valid prefix value
609
+ *
610
+ * @param prefixValue value to check
611
+ * @param ipNumType The type of IP number
612
+ * @returns {(boolean|string)[]} a tuple representing if valid or not and corresponding message
613
+ */
614
+ static isValidPrefixValue(prefixValue, ipNumType) {
615
+ if ("IPv4" /* IPv4 */ === ipNumType) {
616
+ let withinRange = Validator$1.isWithinRange(BigInt(prefixValue), 0n, 32n);
617
+ return [withinRange, withinRange ? [] : [Validator$1.invalidPrefixValueMessage]];
618
+ }
619
+ if ("IPv6" /* IPv6 */ === ipNumType) {
620
+ let withinRange = Validator$1.isWithinRange(BigInt(prefixValue), 0n, 128n);
621
+ return [withinRange, withinRange ? [] : [Validator$1.invalidPrefixValueMessage]];
622
+ }
623
+ return [false, [Validator$1.invalidInetNumType]];
624
+ }
625
+ /**
626
+ * Checks if given string is a valid IPv4 mask
627
+ *
628
+ * @param {string} ipv4MaskString the given IPv4 mask string
629
+ * @returns {[boolean , string]} first value is true if valid IPv4 mask string, false otherwise. Second value
630
+ * contains "valid" or an error message when value is invalid
631
+ */
632
+ static isValidIPv4Mask(ipv4MaskString) {
633
+ let ipv4InBinary = BinaryUtils_1.dottedDecimalNotationToBinaryString(ipv4MaskString);
634
+ let isValid = Validator$1.IPV4_CONTIGUOUS_MASK_BIT_PATTERN.test(ipv4InBinary);
635
+ return isValid ? [isValid, []] : [isValid, [Validator$1.invalidMaskMessage]];
636
+ }
637
+ /**
638
+ * Checks if given string is a valid IPv6 mask
639
+ *
640
+ * @param {string} ipv6MaskString the given IPv6 mask string
641
+ * @returns {[boolean , string]} first value is true if valid IPv6 mask string, false otherwise. Second value
642
+ * contains "valid" or an error message when value is invalid
643
+ */
644
+ static isValidIPv6Mask(ipv6MaskString) {
645
+ let ipv6InBinary = HexadecimalUtils_2.hexadectetNotationToBinaryString(ipv6MaskString);
646
+ let isValid = Validator$1.IPV6_CONTIGUOUS_MASK_BIT_PATTERN.test(ipv6InBinary);
647
+ return isValid ? [isValid, []] : [isValid, [Validator$1.invalidMaskMessage]];
648
+ }
649
+ /**
650
+ * Checks if the given string is a valid IPv4 range in Cidr notation
651
+ *
652
+ * @param {string} ipv4RangeAsCidrString the IPv4 range in Cidr notation
653
+ *
654
+ * @returns {[boolean , string[]]} first value is true if valid IPv4 range in Cidr notation, false otherwise. Second
655
+ * value contains "valid" or an error message when value is invalid
656
+ */
657
+ static isValidIPv4CidrNotation(ipv4RangeAsCidrString) {
658
+ let cidrComponents = ipv4RangeAsCidrString.split("/");
659
+ if (cidrComponents.length !== 2 || (cidrComponents[0].length === 0 || cidrComponents[1].length === 0)) {
660
+ return [false, [Validator$1.invalidIPv4CidrNotationMessage]];
661
+ }
662
+ let ip = cidrComponents[0];
663
+ let range = cidrComponents[1];
664
+ if (isNaN(Number(range))) {
665
+ return [false, [Validator$1.invalidIPv4CidrNotationMessage]];
666
+ }
667
+ let [validIpv4, invalidIpv4Message] = Validator$1.isValidIPv4String(ip);
668
+ let [validPrefix, invalidPrefixMessage] = Validator$1.isValidPrefixValue(BigInt(range), "IPv4" /* IPv4 */);
669
+ let isValid = validIpv4 && validPrefix;
670
+ let invalidMessage = invalidIpv4Message.concat(invalidPrefixMessage);
671
+ return isValid ? [isValid, []] : [isValid, invalidMessage];
672
+ }
673
+ /**
674
+ * Checks if the given string is a valid IPv4 range in Cidr notation, with the ip number in the cidr notation
675
+ * being the start of the range
676
+ *
677
+ * @param {string} ipv4CidrNotation the IPv4 range in Cidr notation
678
+ *
679
+ * * @returns {[boolean , string[]]} first value is true if valid Cidr notation, false otherwise. Second
680
+ * value contains [] or an array of error message when invalid
681
+ */
682
+ static isValidIPv4CidrRange(ipv4CidrNotation) {
683
+ return Validator$1.isValidCidrRange(ipv4CidrNotation, Validator$1.isValidIPv4CidrNotation, BinaryUtils_1.dottedDecimalNotationToBinaryString, (value) => BinaryUtils_2.cidrPrefixToMaskBinaryString(value, "IPv4" /* IPv4 */));
684
+ }
685
+ /**
686
+ * Checks if the given string is a valid IPv6 range in Cidr notation, with the ip number in the cidr notation
687
+ * being the start of the range
688
+ *
689
+ * @param {string} ipv6CidrNotation the IPv6 range in Cidr notation
690
+ *
691
+ * * @returns {[boolean , string[]]} first value is true if valid Cidr notation, false otherwise. Second
692
+ * value contains [] or an array of error message when invalid
693
+ */
694
+ static isValidIPv6CidrRange(ipv6CidrNotation) {
695
+ return Validator$1.isValidCidrRange(ipv6CidrNotation, Validator$1.isValidIPv6CidrNotation, HexadecimalUtils_1.colonHexadecimalNotationToBinaryString, (value) => BinaryUtils_2.cidrPrefixToMaskBinaryString(value, "IPv6" /* IPv6 */));
696
+ }
697
+ static isValidCidrRange(rangeString, cidrNotationValidator, toBinaryStringConverter, prefixFactory) {
698
+ let validationResult = cidrNotationValidator(rangeString);
699
+ if (!validationResult[0]) {
700
+ return validationResult;
701
+ }
702
+ let cidrComponents = rangeString.split("/");
703
+ let ip = cidrComponents[0];
704
+ let range = cidrComponents[1];
705
+ let ipNumber = BigInt(`0b${toBinaryStringConverter(ip)}`);
706
+ let mask = BigInt(`0b${prefixFactory(parseInt(range))}`);
707
+ let isValid = (ipNumber & (mask)) === (ipNumber);
708
+ return isValid ? [isValid, []] : [isValid, [Validator$1.InvalidIPCidrRangeMessage]];
709
+ }
710
+ static isValidIPv4RangeString(ipv4RangeString) {
711
+ let firstLastValidator = (firstIP, lastIP) => BigInt(`0b${BinaryUtils_1.dottedDecimalNotationToBinaryString(firstIP)}`)
712
+ >= BigInt(`0b${BinaryUtils_1.dottedDecimalNotationToBinaryString(lastIP)}`);
713
+ return this.isValidRange(ipv4RangeString, Validator$1.isValidIPv4String, firstLastValidator);
714
+ }
715
+ static isValidIPv6RangeString(ipv6RangeString) {
716
+ let firstLastValidator = (firstIP, lastIP) => BigInt(`0b${HexadecimalUtils_2.hexadectetNotationToBinaryString(firstIP)}`)
717
+ >= BigInt(`0b${HexadecimalUtils_2.hexadectetNotationToBinaryString(lastIP)}`);
718
+ return this.isValidRange(ipv6RangeString, Validator$1.isValidIPv6String, firstLastValidator);
719
+ }
720
+ static isValidRange(rangeString, validator, firstLastValidator) {
721
+ let rangeComponents = rangeString.split("-").map(component => component.trim());
722
+ if (rangeComponents.length !== 2 || (rangeComponents[0].length === 0 || rangeComponents[1].length === 0)) {
723
+ return [false, [Validator$1.invalidRangeNotationMessage]];
724
+ }
725
+ let firstIP = rangeComponents[0];
726
+ let lastIP = rangeComponents[1];
727
+ let [validFirstIP, invalidFirstIPMessage] = validator(firstIP);
728
+ let [validLastIP, invalidLastIPMessage] = validator(lastIP);
729
+ let isValid = validFirstIP && validLastIP;
730
+ if (isValid && firstLastValidator(firstIP, lastIP)) {
731
+ return [false, [Validator$1.invalidRangeFirstNotGreaterThanLastMessage]];
732
+ }
733
+ let invalidMessage = invalidFirstIPMessage.concat(invalidLastIPMessage);
734
+ return isValid ? [isValid, []] : [isValid, invalidMessage];
735
+ }
736
+ /**
737
+ * Checks if the given string is a valid IPv6 range in Cidr notation
738
+ *
739
+ * @param {string} ipv6RangeAsCidrString the IPv6 range in Cidr notation
740
+ *
741
+ * @returns {[boolean , string]} first value is true if valid IPv6 range in Cidr notation, false otherwise.
742
+ * Second value contains "valid" or an error message when value is invalid
743
+ */
744
+ // TODO change to be like isValidIPv4CidrNotation where validation is done on the component of the cidr notation
745
+ // instead of a single regex check
746
+ static isValidIPv6CidrNotation(ipv6RangeAsCidrString) {
747
+ let isValid = Validator$1.IPV6_RANGE_PATTERN.test(ipv6RangeAsCidrString);
748
+ return isValid ? [isValid, []] : [isValid, [Validator$1.invalidIPv6CidrNotationString]];
749
+ }
750
+ /**
751
+ * Checks if the given string is a binary string. That is contains only contiguous 1s and 0s
752
+ *
753
+ * @param {string} binaryString the binary string
754
+ * @returns {(boolean|string)[]} a tuple representing if valid or not and corresponding message
755
+ */
756
+ static isValidBinaryString(binaryString) {
757
+ if (/^([10])+$/.test(binaryString)) {
758
+ return [true, []];
759
+ }
760
+ else {
761
+ return [false, [Validator$1.invalidBinaryStringErrorMessage]];
762
+ }
763
+ }
764
+ static isNumeric(value) {
765
+ return /^(\d+)$/.test(value);
766
+ }
767
+ static isHexadecatet(value) {
768
+ return /^[0-9A-Fa-f]{4}$/.test(value);
769
+ }
770
+ }
771
+ Validator.Validator = Validator$1;
772
+ Validator$1.IPV4_PATTERN = new RegExp(/^(0?[0-9]?[0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.(0?[0-9]?[0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.(0?[0-9]?[0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.(0?[0-9]?[0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])$/);
773
+ // source: https://community.helpsystems.com/forums/intermapper/miscellaneous-topics/5acc4fcf-fa83-e511-80cf-0050568460e4
774
+ Validator$1.IPV6_PATTERN = new RegExp(/^\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?\s*$/);
775
+ Validator$1.IPV4_RANGE_PATTERN = new RegExp(/^(0?[0-9]?[0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.(0?[0-9]?[0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.(0?[0-9]?[0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.(0?[0-9]?[0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(\/)([1-9]|[1-2][0-9]|3[0-2])$/);
776
+ Validator$1.IPV6_RANGE_PATTERN = new RegExp(/^s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3}))|:)))(%.+)?s*(\/([0-9]|[1-9][0-9]|1[0-1][0-9]|12[0-8]))?$/);
777
+ Validator$1.IPV4_CONTIGUOUS_MASK_BIT_PATTERN = new RegExp(/^(1){0,32}(0){0,32}$/);
778
+ Validator$1.IPV6_CONTIGUOUS_MASK_BIT_PATTERN = new RegExp(/^(1){0,128}(0){0,128}$/);
779
+ Validator$1.EIGHT_BIT_SIZE = BigInt(`0b${"1".repeat(8)}`);
780
+ Validator$1.SIXTEEN_BIT_SIZE = BigInt(`0b${"1".repeat(16)}`);
781
+ Validator$1.THIRTY_TWO_BIT_SIZE = BigInt(`0b${"1".repeat(32)}`);
782
+ Validator$1.ONE_HUNDRED_AND_TWENTY_EIGHT_BIT_SIZE = BigInt(`0b${"1".repeat(128)}`);
783
+ Validator$1.IPV4_SIZE = BigInt("4294967296");
784
+ Validator$1.IPV6_SIZE = BigInt("340282366920938463463374607431768211456");
785
+ Validator$1.invalidAsnRangeMessage = "ASN number given less than zero or is greater than 32bit";
786
+ Validator$1.invalid16BitAsnRangeMessage = "ASN number given less than zero or is greater than 16bit";
787
+ Validator$1.invalidIPv4NumberMessage = "IPv4 number given less than zero or is greater than 32bit";
788
+ Validator$1.invalidIPv6NumberMessage = "IPv6 number given less than zero or is greater than 128bit";
789
+ Validator$1.invalidOctetRangeMessage = "Value given contains an invalid Octet; Value is less than zero or is greater than 8bit";
790
+ Validator$1.invalidHexadecatetMessage = "The value given is less than zero or is greater than 16bit";
791
+ Validator$1.invalidOctetCountMessage = "An IP4 number cannot have less or greater than 4 octets";
792
+ Validator$1.invalidHexadecatetCountMessage = "An IP6 number must have exactly 8 hexadecatet";
793
+ Validator$1.invalidMaskMessage = "The Mask is invalid";
794
+ Validator$1.invalidPrefixValueMessage = "A Prefix value cannot be less than 0 or greater than 32";
795
+ Validator$1.invalidIPv4CidrNotationMessage = "Cidr notation should be in the form [ip number]/[range]";
796
+ Validator$1.InvalidIPCidrRangeMessage = "Given IP number portion must is not the start of the range";
797
+ Validator$1.invalidRangeNotationMessage = "Range notation should be in the form [first ip]-[last ip]";
798
+ Validator$1.invalidRangeFirstNotGreaterThanLastMessage = "First IP in [first ip]-[last ip] must be less than Last IP";
799
+ Validator$1.invalidIPv6CidrNotationString = "A Cidr notation string should contain an IPv6 number and prefix";
800
+ Validator$1.takeOutOfRangeSizeMessage = "$count is greater than $size, the size of the range";
801
+ Validator$1.cannotSplitSingleRangeErrorMessage = "Cannot split an IP range with a single IP number";
802
+ Validator$1.invalidInetNumType = "Given ipNumType must be either InetNumType.IPv4 or InetNumType.IPv6";
803
+ Validator$1.invalidBinaryStringErrorMessage = "Binary string should contain only contiguous 1s and 0s";
804
+ Validator$1.invalidIPRangeSizeMessage = "Given size is zero or greater than maximum size of $iptype";
805
+ Validator$1.invalidIPRangeSizeForCidrMessage = "Given size can't be created via cidr prefix";
806
+ Validator$1.invalidIPv4PatternMessage = "Given IPv4 is not confirm to a valid IPv6 address";
807
+ Validator$1.invalidIPv6PatternMessage = "Given IPv6 is not confirm to a valid IPv6 address";
808
+
809
+ return Validator;
810
+ }
811
+
812
+ Object.defineProperty(Hexadecatet$1, "__esModule", { value: true });
813
+ Hexadecatet$1.Hexadecatet = void 0;
814
+ const Validator_1$4 = requireValidator();
815
+ /**
816
+ * A representation of a 4-digit hexadecimal number.
817
+ *
818
+ * It consists of four (base 16) number. ie FFFF
819
+ *
820
+ * It is used to represents the components of an IPv6 address
821
+ */
822
+ class Hexadecatet {
823
+ /**
824
+ * Constructor for creating an instance of {@link Hexadecatet}
825
+ *
826
+ * @param {string | number} givenValue a string or numeric value. If given value is a string then it should be a
827
+ * four (base 16) number representation of a 16bit value. If it is a number, then it should be a decimal number
828
+ * representation of a 16 bit value
829
+ */
830
+ constructor(givenValue) {
831
+ let hexadecatetValue;
832
+ if (typeof givenValue === 'string') {
833
+ hexadecatetValue = parseInt(givenValue, 16);
834
+ }
835
+ else {
836
+ hexadecatetValue = parseInt(String(givenValue), 16);
837
+ }
838
+ let [isValid, message] = Validator_1$4.Validator.isValidIPv6Hexadecatet(BigInt(hexadecatetValue));
839
+ if (!isValid) {
840
+ throw Error(message.filter(msg => { return msg !== ''; }).toString());
841
+ }
842
+ this.value = hexadecatetValue;
843
+ }
844
+ /**
845
+ * A convenience method for constructing an instance of {@link Hexadecatet} from a four (base 16) number
846
+ * representation of a 16bit value.
847
+ *
848
+ * @param {string} rawValue the four (base 16) number
849
+ * @returns {Hexadecatet} an instance of {@link Hexadecatet}
850
+ */
851
+ static fromString(rawValue) {
852
+ return new Hexadecatet(rawValue);
853
+ }
854
+ ;
855
+ /**
856
+ * A convenience method for constructing an instance of {@link Hexadecatet} from a decimal number representation
857
+ * of a 16 bit value
858
+ *
859
+ * @param {number} rawValue decimal number representation of a 16 bit value
860
+ * @returns {Hexadecatet} an instance of {@link Hexadecatet}
861
+ */
862
+ static fromNumber(rawValue) {
863
+ return new Hexadecatet(rawValue);
864
+ }
865
+ ;
866
+ /**
867
+ * Returns the numeric value in base 10 (ie decimal)
868
+ *
869
+ * @returns {number} the numeric value in base 10 (ie decimal)
870
+ */
871
+ getValue() {
872
+ return this.value;
873
+ }
874
+ /**
875
+ * Returns the string representation of the base 16 representation of the value
876
+ * @returns {string} the string representation of the base 16 representation of the value
877
+ */
878
+ // TODO pad with a zero if digit is less than 4
879
+ toString() {
880
+ return this.value.toString(16);
881
+ }
882
+ }
883
+ Hexadecatet$1.Hexadecatet = Hexadecatet;
884
+
885
+ var IPNumber = {};
886
+
887
+ var Octet$1 = {};
888
+
889
+ Object.defineProperty(Octet$1, "__esModule", { value: true });
890
+ Octet$1.Octet = void 0;
891
+ const Validator_1$3 = requireValidator();
892
+ /**
893
+ * A binary representation of a 8 bit value.
894
+ *
895
+ * {@see https://en.wikipedia.org/wiki/Octet_(computing)} for more information on Octets
896
+ *
897
+ * An octet is used in the textual representation of an {@link IPv4} number, where the IP number value is divided
898
+ * into 4 octets
899
+ */
900
+ class Octet {
901
+ /**
902
+ * Constructor for creating an instance of an Octet.
903
+ *
904
+ * The constructor parameter given could either be a string or number.
905
+ *
906
+ * If a string, it is the string representation of the numeric value of the octet
907
+ * If a number, it is the numeric representation of the value of the octet
908
+ *
909
+ * @param {string | number} givenValue value of the octet to be created.
910
+ */
911
+ constructor(givenValue) {
912
+ let octetValue;
913
+ if (typeof givenValue === 'string') {
914
+ octetValue = parseInt(givenValue);
915
+ }
916
+ else {
917
+ octetValue = givenValue;
918
+ }
919
+ let [isValid, message] = Validator_1$3.Validator.isValidIPv4Octet(BigInt(octetValue));
920
+ if (!isValid) {
921
+ throw Error(message.filter(msg => { return msg !== ''; }).toString());
922
+ }
923
+ this.value = octetValue;
924
+ }
925
+ /**
926
+ * Convenience method for creating an Octet out of a string value representing the value of the octet
927
+ *
928
+ * @param {string} rawValue the octet value in string
929
+ * @returns {Octet} the Octet instance
930
+ */
931
+ static fromString(rawValue) {
932
+ return new Octet(rawValue);
933
+ }
934
+ ;
935
+ /**
936
+ * Convenience method for creating an Octet out of a numeric value representing the value of the octet
937
+ *
938
+ * @param {number} rawValue the octet value in number
939
+ * @returns {Octet} the Octet instance
940
+ */
941
+ static fromNumber(rawValue) {
942
+ return new Octet(rawValue);
943
+ }
944
+ ;
945
+ /**
946
+ * Method to get the numeric value of the octet
947
+ *
948
+ * @returns {number} the numeric value of the octet
949
+ */
950
+ getValue() {
951
+ return this.value;
952
+ }
953
+ /**
954
+ * Returns a decimal representation of the value of the octet in string
955
+ *
956
+ * @returns {string} a decimal representation of the value of the octet in string
957
+ */
958
+ toString() {
959
+ return this.value.toString(10);
960
+ }
961
+ }
962
+ Octet$1.Octet = Octet;
963
+
964
+ Object.defineProperty(IPNumber, "__esModule", { value: true });
965
+ IPNumber.isIPv4 = IPNumber.IPv6Mask = IPNumber.IPv4Mask = IPNumber.IPv6 = IPNumber.Asn = IPNumber.IPv4 = IPNumber.AbstractIPNum = void 0;
966
+ const Octet_1 = Octet$1;
967
+ const Validator_1$2 = requireValidator();
968
+ const BinaryUtils_1$2 = BinaryUtils;
969
+ const BinaryUtils_2 = BinaryUtils;
970
+ const BinaryUtils_3 = BinaryUtils;
971
+ const BinaryUtils_4 = BinaryUtils;
972
+ const Hexadecatet_1$1 = Hexadecatet$1;
973
+ const HexadecimalUtils_1$1 = requireHexadecimalUtils();
974
+ const IPv6Utils_1 = requireIPv6Utils();
975
+ const HexadecimalUtils_2 = requireHexadecimalUtils();
976
+ /**
977
+ * Provides the implementation of functionality that are common
978
+ * to {@link IPv4}, {@link IPv6}, {@link IPv4Mask} and {@link IPv6Mask}
979
+ */
980
+ class AbstractIPNum {
981
+ /**
982
+ * Gets the numeric value of an IP number as {@link BigInt}
983
+ *
984
+ * @returns bigInt the numeric value of an IP number.
985
+ */
986
+ getValue() {
987
+ return this.value;
988
+ }
989
+ /**
990
+ * Gets the binary string representation of an IP number.
991
+ *
992
+ * @returns {string} the string binary representation.
993
+ */
994
+ toBinaryString() {
995
+ return BinaryUtils_3.leftPadWithZeroBit(this.value.toString(2), this.bitSize);
996
+ }
997
+ /**
998
+ * Checks if an IP number has a value greater than the present value
999
+ * @returns {boolean} true, if there is a value greater than the present value. Returns false otherwise.
1000
+ */
1001
+ hasNext() {
1002
+ return this.value < this.maximumBitSize;
1003
+ }
1004
+ /**
1005
+ * Checks if an IP number has a value lesser than the present value
1006
+ * @returns {boolean} true, if there is a value lesser than the present value. Returns false otherwise.
1007
+ */
1008
+ hasPrevious() {
1009
+ return this.value > 0n;
1010
+ }
1011
+ /**
1012
+ * Checks if the given IP number, is equals to the current IP number
1013
+ *
1014
+ * @param {AbstractIPNum} anotherIPNum the other IP number to compare with
1015
+ * @returns {boolean} true if the given IP number is equals
1016
+ */
1017
+ isEquals(anotherIPNum) {
1018
+ return this.value === anotherIPNum.value;
1019
+ }
1020
+ /**
1021
+ * Checks if the given IP number is lesser than this current IP number
1022
+ *
1023
+ * @param {AbstractIPNum} anotherIPNum the other IP number to compare with
1024
+ * @returns {boolean} true if the given IP number is less than this current one. False otherwise.
1025
+ */
1026
+ isLessThan(anotherIPNum) {
1027
+ return this.value < anotherIPNum.value;
1028
+ }
1029
+ /**
1030
+ * Checks if the given IP number is greater than this current IP number
1031
+ *
1032
+ * @param {AbstractIPNum} anotherIPNum the other IP number to compare with
1033
+ * @returns {boolean} true if the given IP number is greater than this current one. False otherwise.
1034
+ */
1035
+ isGreaterThan(anotherIPNum) {
1036
+ return this.value > anotherIPNum.value;
1037
+ }
1038
+ /**
1039
+ * Checks if the given IP number is less than or equals to this current IP number
1040
+ *
1041
+ * @param {AbstractIPNum} anotherIPNum the other IP number to compare with
1042
+ * @returns {boolean} true if the given IP number is less than or equals to this current one. False otherwise.
1043
+ */
1044
+ isLessThanOrEquals(anotherIPNum) {
1045
+ return this.value <= anotherIPNum.value;
1046
+ }
1047
+ /**
1048
+ * Checks if the given IP number is greater than or equals to this current IP number
1049
+ *
1050
+ * @param {AbstractIPNum} anotherIPNum the other IP number to compare with
1051
+ * @returns {boolean} {boolean} true if the given IP number is greater than or equals to this current one. False
1052
+ * otherwise.
1053
+ */
1054
+ isGreaterThanOrEquals(anotherIPNum) {
1055
+ return this.value >= anotherIPNum.value;
1056
+ }
1057
+ }
1058
+ IPNumber.AbstractIPNum = AbstractIPNum;
1059
+ /**
1060
+ * Represents an IPv4 number. A 32 bit number that is used to uniquely identify a device that is part of a computer
1061
+ * network that uses the internet protocol for communication.
1062
+ *
1063
+ * @see https://en.wikipedia.org/wiki/IPv4
1064
+ * @see https://www.rfc-editor.org/info/rfc791
1065
+ */
1066
+ class IPv4 extends AbstractIPNum {
1067
+ /**
1068
+ * Constructor for an IPv4 number.
1069
+ *
1070
+ * @param {string | bigint} ipValue value to construct an IPv4 from. The given value can either be
1071
+ * numeric or string. If a string is given then it needs to be in dot-decimal notation
1072
+ */
1073
+ constructor(ipValue) {
1074
+ super();
1075
+ /**
1076
+ * The number of bits needed to represents the value of the IPv4 number
1077
+ */
1078
+ this.bitSize = 32;
1079
+ /**
1080
+ * The maximum bit size (i.e. binary value) of the IPv4 number in BigInt
1081
+ */
1082
+ this.maximumBitSize = Validator_1$2.Validator.THIRTY_TWO_BIT_SIZE;
1083
+ /**
1084
+ * The type of IP number. Value is one of the values of the {@link IPNumType} enum
1085
+ * @type {IPNumType} the type of IP number
1086
+ */
1087
+ this.type = "IPv4" /* IPv4 */;
1088
+ /**
1089
+ * An array of {@link Octet}'s
1090
+ *
1091
+ * @type {Array} the octets that makes up the IPv4 number
1092
+ */
1093
+ this.octets = [];
1094
+ /**
1095
+ * The string character used to separate the individual octets when the IPv4 is rendered as strings
1096
+ *
1097
+ * @type {string} The string character used to separate the individual octets when rendered as strings
1098
+ */
1099
+ this.separator = ".";
1100
+ if (typeof ipValue === "string") {
1101
+ let [value, octets] = this.constructFromDecimalDottedString(ipValue);
1102
+ this.value = value;
1103
+ this.octets = octets;
1104
+ }
1105
+ else {
1106
+ let [value, octets] = this.constructFromBigIntValue(ipValue);
1107
+ this.value = value;
1108
+ this.octets = octets;
1109
+ }
1110
+ }
1111
+ /**
1112
+ * A convenience method for creating an {@link IPv4} by providing the decimal value of the IP number in BigInt
1113
+ *
1114
+ * @param {bigint} bigIntValue the decimal value of the IP number in BigInt
1115
+ * @returns {IPv4} the IPv4 instance
1116
+ */
1117
+ static fromNumber(bigIntValue) {
1118
+ return new IPv4(bigIntValue);
1119
+ }
1120
+ /**
1121
+ * A convenience method for creating an {@link IPv4} by providing the IP number in dot-decimal notation. E.g
1122
+ * "10.1.1.10"
1123
+ *
1124
+ * {@see https://en.wikipedia.org/wiki/Dot-decimal_notation} for more information on dot-decimal notation.
1125
+ *
1126
+ * @param {string} ipString the IP number in dot-decimal notation
1127
+ * @returns {IPv4} the IPv4 instance
1128
+ */
1129
+ static fromDecimalDottedString(ipString) {
1130
+ return new IPv4(ipString);
1131
+ }
1132
+ /**
1133
+ * Alias for IPv4.fromDecimalDottedString.
1134
+ *
1135
+ * @param {string} ipString the IP number in dot-decimal notation
1136
+ * @returns {IPv4} the IPv4 instance
1137
+ */
1138
+ static fromString(ipString) {
1139
+ return IPv4.fromDecimalDottedString(ipString);
1140
+ }
1141
+ /**
1142
+ * A convenience method for creating an {@link IPv4} from binary string
1143
+ *
1144
+ * @param {string} ipBinaryString the binary string representing the IPv4 number to be created
1145
+ * @returns {IPv4} the IPv4 instance
1146
+ */
1147
+ static fromBinaryString(ipBinaryString) {
1148
+ let validationResult = Validator_1$2.Validator.isValidBinaryString(ipBinaryString);
1149
+ if (validationResult[0]) {
1150
+ return new IPv4(BinaryUtils_2.parseBinaryStringToBigInt(ipBinaryString));
1151
+ }
1152
+ else {
1153
+ throw Error(validationResult[1].join(','));
1154
+ }
1155
+ }
1156
+ /**
1157
+ * A string representation of the IPv4 number. The string representation is in dot-decimal notation
1158
+ *
1159
+ * @returns {string} The string representation in dot-decimal notation
1160
+ */
1161
+ toString() {
1162
+ return this.octets.map((value) => { return value.toString(); }).join(this.separator);
1163
+ }
1164
+ /**
1165
+ * Gets the individual {@link Octet} that makes up the IPv4 number
1166
+ *
1167
+ * @returns {Array<Octet>} The individual {@link Octet} that makes up the IPv4 number
1168
+ */
1169
+ getOctets() {
1170
+ return this.octets;
1171
+ }
1172
+ /**
1173
+ * Returns the next IPv4 number
1174
+ *
1175
+ * @returns {IPv4} the next IPv4 number
1176
+ */
1177
+ nextIPNumber() {
1178
+ return IPv4.fromNumber(this.getValue() + 1n);
1179
+ }
1180
+ /**
1181
+ * Returns the previous IPv4 number
1182
+ *
1183
+ * @returns {IPv4} the previous IPv4 number
1184
+ */
1185
+ previousIPNumber() {
1186
+ return IPv4.fromNumber(this.getValue() - 1n);
1187
+ }
1188
+ /**
1189
+ * Returns this IPv4 number as a IPv4-Mapped IPv6 Address
1190
+ *
1191
+ * The IPv4-Mapped IPv6 Address allows an IPv4 number to be embedded within an IPv6 number
1192
+ *
1193
+ * {@see https://tools.ietf.org/html/rfc4291#section-2.5.5} for more information on the IPv4-Mapped IPv6 Address
1194
+ *
1195
+ * @returns {IPv6} an IPv6 number with the IPv4 embedded within it
1196
+ */
1197
+ toIPv4MappedIPv6() {
1198
+ let binary = '1'.repeat(16) + this.toBinaryString();
1199
+ return IPv6.fromBinaryString(binary);
1200
+ }
1201
+ constructFromDecimalDottedString(ipString) {
1202
+ let octets;
1203
+ let value;
1204
+ let [isValid, message] = Validator_1$2.Validator.isValidIPv4String(ipString);
1205
+ if (!isValid) {
1206
+ throw new Error(message.filter(msg => { return msg !== ''; }).toString());
1207
+ }
1208
+ let stringOctets = ipString.split(".");
1209
+ octets = stringOctets.map((rawOctet) => {
1210
+ return Octet_1.Octet.fromString(rawOctet);
1211
+ });
1212
+ value = BigInt(`0b${BinaryUtils_1$2.dottedDecimalNotationToBinaryString(ipString)}`);
1213
+ return [value, octets];
1214
+ }
1215
+ constructFromBigIntValue(ipv4Number) {
1216
+ let [isValid, message] = Validator_1$2.Validator.isValidIPv4Number(ipv4Number);
1217
+ if (!isValid) {
1218
+ throw new Error(message.filter(msg => { return msg !== ''; }).toString());
1219
+ }
1220
+ let binaryString = BinaryUtils_4.numberToBinaryString(ipv4Number);
1221
+ ipv4Number = typeof ipv4Number === "bigint" ? ipv4Number : BigInt(ipv4Number);
1222
+ return [ipv4Number, this.binaryStringToDecimalOctets(binaryString)];
1223
+ }
1224
+ binaryStringToDecimalOctets(ipv4BinaryString) {
1225
+ if (ipv4BinaryString.length < 32) {
1226
+ ipv4BinaryString = BinaryUtils_3.leftPadWithZeroBit(ipv4BinaryString, 32);
1227
+ }
1228
+ let octets = ipv4BinaryString.match(/.{1,8}/g);
1229
+ return octets.map((octet) => {
1230
+ return Octet_1.Octet.fromString(BinaryUtils_2.parseBinaryStringToBigInt(octet).toString());
1231
+ });
1232
+ }
1233
+ }
1234
+ IPNumber.IPv4 = IPv4;
1235
+ /**
1236
+ * Represents an Autonomous System Number. Which is a number that is used to identify
1237
+ * a group of IP addresses with a common, clearly defined routing policy.
1238
+ *
1239
+ * @see https://en.wikipedia.org/wiki/Autonomous_system_(Internet)
1240
+ * @see https://tools.ietf.org/html/rfc5396
1241
+ */
1242
+ class Asn extends AbstractIPNum {
1243
+ /**
1244
+ * Constructor for an instance of {@link ASN}
1245
+ *
1246
+ * @param {string | number} rawValue value to construct an ASN from. The given value can either be numeric or
1247
+ * string. If in string then it can be in asplain, asdot or asdot+ string representation format
1248
+ */
1249
+ constructor(rawValue) {
1250
+ super();
1251
+ /**
1252
+ * The number of bits needed to represents the value of the ASN number
1253
+ */
1254
+ this.bitSize = 32;
1255
+ /**
1256
+ * The maximum bit size (i.e. binary value) of the ASN number in BigInt
1257
+ */
1258
+ this.maximumBitSize = Validator_1$2.Validator.THIRTY_TWO_BIT_SIZE;
1259
+ this.type = "ASN" /* ASN */;
1260
+ if (typeof rawValue === 'string') {
1261
+ if (Asn.startWithASPrefix(rawValue)) {
1262
+ this.value = BigInt(parseInt(rawValue.substring(2)));
1263
+ }
1264
+ else if (rawValue.indexOf(".") != -1) {
1265
+ this.value = BigInt(this.parseFromDotNotation(rawValue));
1266
+ }
1267
+ else {
1268
+ this.value = BigInt(parseInt(rawValue));
1269
+ }
1270
+ }
1271
+ else {
1272
+ let valueAsBigInt = BigInt(rawValue);
1273
+ let [isValid, message] = Validator_1$2.Validator.isValidAsnNumber(valueAsBigInt);
1274
+ if (!isValid) {
1275
+ throw Error(message.filter(msg => { return msg !== ''; }).toString());
1276
+ }
1277
+ this.value = valueAsBigInt;
1278
+ }
1279
+ }
1280
+ /**
1281
+ * A convenience method for creating an instance of {@link Asn} from a string
1282
+ *
1283
+ * The given string can be in asplain, asdot or asdot+ representation format.
1284
+ * {@see https://tools.ietf.org/html/rfc5396} for more information on
1285
+ * the different ASN string representation
1286
+ *
1287
+ * @param {string} rawValue the asn string. In either asplain, asdot or asdot+ format
1288
+ * @returns {Asn} the constructed ASN instance
1289
+ */
1290
+ static fromString(rawValue) {
1291
+ return new Asn(rawValue);
1292
+ }
1293
+ ;
1294
+ /**
1295
+ * A convenience method for creating an instance of {@link Asn} from a numeric value
1296
+ *
1297
+ * @param {number} rawValue the asn numeric value
1298
+ * @returns {Asn} the constructed ASN instance
1299
+ */
1300
+ static fromNumber(rawValue) {
1301
+ return new Asn(rawValue);
1302
+ }
1303
+ ;
1304
+ /**
1305
+ * A convenience method for creating an instance of {@link Asn} from a binary string
1306
+ *
1307
+ * @param {string} binaryString to create an ASN instance from
1308
+ * @returns {Asn} the constructed ASN instance
1309
+ */
1310
+ static fromBinaryString(binaryString) {
1311
+ let validationResult = Validator_1$2.Validator.isValidBinaryString(binaryString);
1312
+ if (validationResult[0]) {
1313
+ return new Asn(parseInt(binaryString, 2));
1314
+ }
1315
+ else {
1316
+ throw Error(validationResult[1].join(','));
1317
+ }
1318
+ }
1319
+ /**
1320
+ * A string representation where the asn value is prefixed by "ASN". For example "AS65526"
1321
+ *
1322
+ * @returns {string} A string representation where the asn value is prefixed by "ASN"
1323
+ */
1324
+ toString() {
1325
+ let stringValue = this.value.toString();
1326
+ return `${Asn.AS_PREFIX}${stringValue}`;
1327
+ }
1328
+ /**
1329
+ * A string representation where the ASN numeric value of is represented as a string. For example "65526"
1330
+ *
1331
+ * @returns {string} A string representation where the ASN numeric value of is represented as a string
1332
+ */
1333
+ toASPlain() {
1334
+ return this.value.toString();
1335
+ }
1336
+ /**
1337
+ * A string representation where the ASN value is represented using the asplain notation if the ASN value is
1338
+ * less than 65536 and uses asdot+ notation when the value is greater than 65536.
1339
+ *
1340
+ * For example 65526 will be represented as "65526" while 65546 will be represented as "1.10"
1341
+ *
1342
+ *
1343
+ * @returns {string} A string representation of the ASN in either asplain or asdot+ notation depending on
1344
+ * whether the numeric value of the ASN number is greater than 65526 or not.
1345
+ */
1346
+ toASDot() {
1347
+ if (this.value.valueOf() >= 65536n) {
1348
+ return this.toASDotPlus();
1349
+ }
1350
+ return this.toASPlain();
1351
+ }
1352
+ /**
1353
+ * A string representation where the ASN value is represented using the asdot+ notation
1354
+ *
1355
+ * @returns {string} A string representation where the ASN value is represented using the asdot+ notation
1356
+ *
1357
+ */
1358
+ toASDotPlus() {
1359
+ let high = this.value.valueOf() / 65535n;
1360
+ let low = (this.value.valueOf() % 65535n) - high;
1361
+ return `${high}.${low}`;
1362
+ }
1363
+ /**
1364
+ * Converts the ASN value to binary numbers represented with strings
1365
+ *
1366
+ * @returns {string} a binary string representation of the value of the ASN number
1367
+ */
1368
+ toBinaryString() {
1369
+ return BinaryUtils_4.numberToBinaryString(this.value);
1370
+ }
1371
+ /**
1372
+ * Checks if the ASN value is 16bit
1373
+ *
1374
+ * @returns {boolean} true if the ASN is a 16bit value. False otherwise.
1375
+ */
1376
+ is16Bit() {
1377
+ let [valid16BitAsnNumber,] = Validator_1$2.Validator.isValid16BitAsnNumber(this.value);
1378
+ return valid16BitAsnNumber;
1379
+ }
1380
+ /**
1381
+ * Checks if the ASN value is 32bit
1382
+ *
1383
+ * @returns {boolean} true if the ASN is a 32bit value. False otherwise.
1384
+ */
1385
+ is32Bit() {
1386
+ return !this.is16Bit();
1387
+ }
1388
+ /**
1389
+ * Returns the next ASN number
1390
+ *
1391
+ * @returns {AbstractIPNum} the next ASN number
1392
+ */
1393
+ nextIPNumber() {
1394
+ return new Asn(this.value.valueOf() + 1n);
1395
+ }
1396
+ /**
1397
+ * Returns the previous ASN number
1398
+ *
1399
+ * @returns {AbstractIPNum} the previous ASN number
1400
+ */
1401
+ previousIPNumber() {
1402
+ return new Asn(this.value.valueOf() - 1n);
1403
+ }
1404
+ static startWithASPrefix(word) {
1405
+ return word.indexOf(Asn.AS_PREFIX) === 0;
1406
+ }
1407
+ parseFromDotNotation(rawValue) {
1408
+ let values = rawValue.split(".");
1409
+ let high = parseInt(values[0]);
1410
+ let low = parseInt(values[1]);
1411
+ return (high * 65535) + (low + high);
1412
+ }
1413
+ }
1414
+ IPNumber.Asn = Asn;
1415
+ Asn.AS_PREFIX = "AS";
1416
+ /**
1417
+ * Represents an IPv6 number. A 128 bit number that is used to uniquely identify a device that is part of a computer
1418
+ * network that uses the internet protocol for communication.
1419
+ *
1420
+ * @see https://en.wikipedia.org/wiki/IPv6
1421
+ * @see https://www.rfc-editor.org/info/rfc8200
1422
+ */
1423
+ class IPv6 extends AbstractIPNum {
1424
+ /**
1425
+ * Constructor for an IPv6 number.
1426
+ *
1427
+ * @param {string | bigint} ipValue value to construct an IPv6 from. The given value can either be
1428
+ * numeric or string. If a string is given then it needs to be in hexadecatet string notation
1429
+ */
1430
+ constructor(ipValue) {
1431
+ super();
1432
+ /**
1433
+ * The number of bits needed to represents the value of the IPv6 number
1434
+ */
1435
+ this.bitSize = 128;
1436
+ /**
1437
+ * The maximum bit size (i.e. binary value) of the IPv6 number in BigInt
1438
+ */
1439
+ this.maximumBitSize = Validator_1$2.Validator.ONE_HUNDRED_AND_TWENTY_EIGHT_BIT_SIZE;
1440
+ /**
1441
+ * The type of IP number. Value is one of the values of the {@link IPNumType} enum
1442
+ * @type {IPNumType} the type of IP number
1443
+ */
1444
+ this.type = "IPv6" /* IPv6 */;
1445
+ /**
1446
+ * An array of {@link Hexadecatet}'s
1447
+ *
1448
+ * @type {Array} the hexadecatet that makes up the IPv6 number
1449
+ */
1450
+ this.hexadecatet = [];
1451
+ /**
1452
+ * The string character used to separate the individual hexadecatet when the IPv6 is rendered as strings
1453
+ *
1454
+ * @type {string} The string character used to separate the individual hexadecatet when rendered as strings
1455
+ */
1456
+ this.separator = ":";
1457
+ if (typeof ipValue === "string") {
1458
+ let expandedIPv6 = IPv6Utils_1.expandIPv6Number(ipValue);
1459
+ let [value, hexadecatet] = this.constructFromHexadecimalDottedString(expandedIPv6);
1460
+ this.value = value;
1461
+ this.hexadecatet = hexadecatet;
1462
+ }
1463
+ else {
1464
+ let [value, hexadecatet] = this.constructFromBigIntValue(ipValue);
1465
+ this.value = value;
1466
+ this.hexadecatet = hexadecatet;
1467
+ }
1468
+ }
1469
+ /**
1470
+ * A convenience method for creating an {@link IPv6} by providing the decimal value of the IP number in BigInt
1471
+ *
1472
+ * @param {bigint} bigIntValue the decimal value of the IP number in BigInt
1473
+ * @returns {IPv6} the IPv6 instance
1474
+ */
1475
+ static fromBigInt(bigIntValue) {
1476
+ return new IPv6(bigIntValue);
1477
+ }
1478
+ /**
1479
+ * A convenience method for creating an {@link IPv6} by providing the IP number in hexadecatet notation. E.g
1480
+ * "2001:800:0:0:0:0:0:2002"
1481
+ *
1482
+ * {@see https://en.wikipedia.org/wiki/IPv6_address#Representation} for more information on hexadecatet notation.
1483
+ *
1484
+ * @param {string} ipString the IP number in hexadecatet
1485
+ * @returns {IPv6} the IPv6 instance
1486
+ */
1487
+ static fromHexadecatet(ipString) {
1488
+ return new IPv6(ipString);
1489
+ }
1490
+ /**
1491
+ * Alias for IPv6.fromHexadecimalString
1492
+ *
1493
+ * @param {string} ipString the IP number in hexadecatet
1494
+ * @returns {IPv6} the IPv6 instance
1495
+ */
1496
+ static fromString(ipString) {
1497
+ return IPv6.fromHexadecatet(ipString);
1498
+ }
1499
+ /**
1500
+ * A convenience method for creating an {@link IPv6} from binary string
1501
+ *
1502
+ * @param {string} ipBinaryString the binary string representing the IPv6 number to be created
1503
+ * @returns {IPv6} the IPv6 instance
1504
+ */
1505
+ static fromBinaryString(ipBinaryString) {
1506
+ let validationResult = Validator_1$2.Validator.isValidBinaryString(ipBinaryString);
1507
+ if (validationResult[0]) {
1508
+ let paddedBinaryString = BinaryUtils_3.leftPadWithZeroBit(ipBinaryString, 128);
1509
+ return new IPv6(BinaryUtils_2.parseBinaryStringToBigInt(paddedBinaryString));
1510
+ }
1511
+ else {
1512
+ throw Error(validationResult[1].join(','));
1513
+ }
1514
+ }
1515
+ /**
1516
+ * A convenience method for creating an IPv4-Compatible {@link IPv6} Address from an instance of {@link IPv4}
1517
+ *
1518
+ * @param {IPv4} ipv4 to create an IPv4-Compatible {@link IPv6} Address
1519
+ * @returns {IPv6} the IPv4-Compatible {@link IPv6} Address
1520
+ */
1521
+ static fromIPv4(ipv4) {
1522
+ return ipv4.toIPv4MappedIPv6();
1523
+ }
1524
+ /**
1525
+ * A convenience method for creating an IPv4-Compatible {@link IPv6} Address from a IPv4 represented in
1526
+ * dot-decimal notation i.e. 127.0.0.1
1527
+ *
1528
+ * @param {IPv4} ip4DotDecimalString string represented in a dot decimal string
1529
+ * @returns {IPv6} the IPv4-Compatible {@link IPv6} Address
1530
+ */
1531
+ static fromIPv4DotDecimalString(ip4DotDecimalString) {
1532
+ return new IPv4(ip4DotDecimalString).toIPv4MappedIPv6();
1533
+ }
1534
+ /**
1535
+ * A string representation of the IPv6 number.
1536
+ *
1537
+ * @returns {string} The string representation of IPv6
1538
+ */
1539
+ toString() {
1540
+ let ipv6String = this.hexadecatet.map((value) => { return value.toString(); }).join(":");
1541
+ if (this.hexadecatet.length < 8) {
1542
+ return "::" + ipv6String;
1543
+ }
1544
+ else {
1545
+ return ipv6String;
1546
+ }
1547
+ }
1548
+ /**
1549
+ * Gets the individual {@link Hexadecatet} that makes up the IPv6 number
1550
+ *
1551
+ * @returns {Array<Hexadecatet>} The individual {@link Hexadecatet} that makes up the IPv6 number
1552
+ */
1553
+ //TODO maybe rename to something like getSegments? so it can be same with getOctet
1554
+ getHexadecatet() {
1555
+ return this.hexadecatet;
1556
+ }
1557
+ /**
1558
+ * Returns the next IPv6 number
1559
+ *
1560
+ * @returns {IPv6} the next IPv6 number
1561
+ */
1562
+ nextIPNumber() {
1563
+ return IPv6.fromBigInt(this.getValue() + 1n);
1564
+ }
1565
+ /**
1566
+ * Returns the previous IPv6 number
1567
+ *
1568
+ * @returns {IPv6} the previous IPv6 number
1569
+ */
1570
+ previousIPNumber() {
1571
+ return IPv6.fromBigInt(this.getValue() - 1n);
1572
+ }
1573
+ constructFromBigIntValue(ipv6Number) {
1574
+ let [isValid, message] = Validator_1$2.Validator.isValidIPv6Number(ipv6Number);
1575
+ if (!isValid) {
1576
+ throw new Error(message.filter(msg => { return msg !== ''; }).toString());
1577
+ }
1578
+ let binaryString = BinaryUtils_4.numberToBinaryString(ipv6Number);
1579
+ return [ipv6Number, this.binaryStringToHexadecatets(binaryString)];
1580
+ }
1581
+ constructFromHexadecimalDottedString(expandedIPv6) {
1582
+ let [isValid, message] = Validator_1$2.Validator.isValidIPv6String(expandedIPv6);
1583
+ if (!isValid) {
1584
+ throw new Error(message.filter(msg => { return msg !== ''; }).toString());
1585
+ }
1586
+ let stringHexadecimals = expandedIPv6.split(":");
1587
+ let hexadecatet = stringHexadecimals.map((stringHexadecatet) => {
1588
+ return Hexadecatet_1$1.Hexadecatet.fromString(stringHexadecatet);
1589
+ });
1590
+ let value = BigInt(`0b${HexadecimalUtils_2.hexadectetNotationToBinaryString(expandedIPv6)}`);
1591
+ return [value, hexadecatet];
1592
+ }
1593
+ binaryStringToHexadecatets(binaryString) {
1594
+ let hexadecimalString = HexadecimalUtils_1$1.binaryStringToHexadecimalString(binaryString);
1595
+ while (hexadecimalString.length % 4 != 0) {
1596
+ hexadecimalString = '0' + hexadecimalString;
1597
+ }
1598
+ let hexadecimalStrings = hexadecimalString.match(/.{1,4}/g);
1599
+ return hexadecimalStrings.map((stringHexadecatet) => {
1600
+ return Hexadecatet_1$1.Hexadecatet.fromString(stringHexadecatet);
1601
+ });
1602
+ }
1603
+ }
1604
+ IPNumber.IPv6 = IPv6;
1605
+ /**
1606
+ * The IPv4Mask can be seen as a specialized IPv4 number where, in a 32 bit number, starting from the left, you
1607
+ * have continuous bits turned on (with 1 value) followed by bits turned off (with 0 value). In networking, it is used
1608
+ * to demarcate which bits are used to identify a network, and the ones that are used to identify hosts on the network
1609
+ */
1610
+ class IPv4Mask extends IPv4 {
1611
+ /**
1612
+ * Constructor for creating an instance of IPv4Mask.
1613
+ * The passed strings need to be a valid IPv4 mask number in dot-decimal notation.
1614
+ *
1615
+ * @param {string} ipString The passed string in dot-decimal notation
1616
+ */
1617
+ constructor(ipString) {
1618
+ super(ipString);
1619
+ /**
1620
+ * An array of {@link Octet}'s
1621
+ *
1622
+ * @type {Array} the octets that makes up the IPv4Mask
1623
+ */
1624
+ this.octets = [];
1625
+ let isValid;
1626
+ let message;
1627
+ [isValid, message] = Validator_1$2.Validator.isValidIPv4Mask(ipString);
1628
+ if (!isValid) {
1629
+ throw new Error(message.filter(msg => { return msg !== ''; }).toString());
1630
+ }
1631
+ let stringOctets = ipString.split(".");
1632
+ this.octets = stringOctets.map((rawOctet) => {
1633
+ return Octet_1.Octet.fromString(rawOctet);
1634
+ });
1635
+ let binaryString = BinaryUtils_1$2.dottedDecimalNotationToBinaryString(ipString);
1636
+ this.prefix = (binaryString.match(/1/g) || []).length;
1637
+ this.value = BigInt(`0b${binaryString}`);
1638
+ }
1639
+ /**
1640
+ * A convenience method for creating an instance of IPv4Mask. The passed strings need to be a valid IPv4
1641
+ * number in dot-decimal notation.
1642
+ *
1643
+ * @param {string} rawValue The passed string in dot-decimal notation
1644
+ * @returns {IPv4Mask} the instance of IPv4Mask
1645
+ */
1646
+ static fromDecimalDottedString(rawValue) {
1647
+ return new IPv4Mask(rawValue);
1648
+ }
1649
+ ;
1650
+ }
1651
+ IPNumber.IPv4Mask = IPv4Mask;
1652
+ /**
1653
+ * The IPv6Mask can be seen as a specialized IPv4 number where, in a 128 bit number, starting from the left,
1654
+ * you have continuous bits turned on (with 1 value) followed by bits turned off (with 0 value). In networking, it
1655
+ * is used to to demarcate which bits are used to identify a network, and the ones that are used to identify hosts
1656
+ * on the network
1657
+ */
1658
+ class IPv6Mask extends IPv6 {
1659
+ /**
1660
+ * Constructor for creating an instance of IPv6Mask.
1661
+ * The passed strings need to be a valid IPv6 mask number in dot-decimal notation
1662
+ *
1663
+ * @param {string} ipString The passed IPv6 string
1664
+ */
1665
+ constructor(ipString) {
1666
+ super(ipString);
1667
+ /**
1668
+ * An array of {@link Hexadecatet}'s
1669
+ *
1670
+ * @type {Array} the hexadecatet that makes up the IPv6 number
1671
+ */
1672
+ this.hexadecatet = [];
1673
+ let isValid;
1674
+ let message;
1675
+ [isValid, message] = Validator_1$2.Validator.isValidIPv6Mask(ipString);
1676
+ if (!isValid) {
1677
+ throw new Error(message.filter(msg => { return msg !== ''; }).toString());
1678
+ }
1679
+ let stringHexadecimals = ipString.split(":");
1680
+ this.hexadecatet = stringHexadecimals.map((stringHexadecatet) => {
1681
+ return Hexadecatet_1$1.Hexadecatet.fromString(stringHexadecatet);
1682
+ });
1683
+ let binaryString = HexadecimalUtils_2.hexadectetNotationToBinaryString(ipString);
1684
+ this.prefix = (binaryString.match(/1/g) || []).length;
1685
+ this.value = BigInt(`0b${binaryString}`);
1686
+ this.value = BigInt(`0b${HexadecimalUtils_2.hexadectetNotationToBinaryString(ipString)}`);
1687
+ }
1688
+ /**
1689
+ * A convenience method for creating an instance of IPv6Mask.
1690
+ * The passed strings need to be a valid IPv4 mask number in dot-decimal notation.
1691
+ *
1692
+ * @param {string} rawValue The passed string in textual notation
1693
+ * @returns {IPv6Mask} the instance of IPv6Mask
1694
+ */
1695
+ static fromHexadecatet(rawValue) {
1696
+ return new IPv6Mask(rawValue);
1697
+ }
1698
+ ;
1699
+ }
1700
+ IPNumber.IPv6Mask = IPv6Mask;
1701
+ /**
1702
+ * Check is the given IP number is an {@link IPv4} or not
1703
+ * @param ip the IP number to check if it is IPv4.
1704
+ */
1705
+ function isIPv4(ip) {
1706
+ return ip.bitSize === 32;
1707
+ }
1708
+ IPNumber.isIPv4 = isIPv4;
1709
+
1710
+ var IPNumType = {};
1711
+
1712
+ Object.defineProperty(IPNumType, "__esModule", { value: true });
1713
+
1714
+ var IPPool = {};
1715
+
1716
+ var IPRange = {};
1717
+
1718
+ var Prefix = {};
1719
+
1720
+ Object.defineProperty(Prefix, "__esModule", { value: true });
1721
+ Prefix.isIPv4Prefix = Prefix.IPv6Prefix = Prefix.IPv4Prefix = void 0;
1722
+ const Validator_1$1 = requireValidator();
1723
+ const IPNumber_1$1 = IPNumber;
1724
+ const BinaryUtils_1$1 = BinaryUtils;
1725
+ const HexadecimalUtils_1 = requireHexadecimalUtils();
1726
+ const Hexadecatet_1 = Hexadecatet$1;
1727
+ /**
1728
+ * Represents the prefix portion in the CIDR notation for representing IP ranges
1729
+ *
1730
+ * The IPv4 prefix portion represents the mask. It is the number of continuous bits turned on (with value 1)
1731
+ * counting from the left side of an 8 bit value.
1732
+ *
1733
+ * {@see https://en.wikipedia.org/wiki/Classless_Inter-Domain_Routing} for more information on CIDR
1734
+ */
1735
+ class IPv4Prefix {
1736
+ /**
1737
+ * Constructor for an instance of IPv4 prefix from a decimal number
1738
+ *
1739
+ * @param {number} rawValue the decimal value to construct the IPv4 prefix from.
1740
+ * @returns {IPv4Prefix} the instance of an IPv4 prefix
1741
+ */
1742
+ constructor(rawValue) {
1743
+ this.type = "IPv4";
1744
+ this.bitValue = 32n;
1745
+ let isValid;
1746
+ let message;
1747
+ [isValid, message] = Validator_1$1.Validator.isValidPrefixValue(rawValue, "IPv4" /* IPv4 */);
1748
+ if (!isValid) {
1749
+ throw new Error(message.filter(msg => { return msg !== ''; }).toString());
1750
+ }
1751
+ this.value = rawValue;
1752
+ }
1753
+ /**
1754
+ * Convenience method for constructing an instance of IPv4 prefix from a decimal number
1755
+ *
1756
+ * @param {number} rawValue the decimal value to construct the IPv4 prefix from.
1757
+ * @returns {IPv4Prefix} the instance of an IPv4 prefix
1758
+ */
1759
+ static fromNumber(rawValue) {
1760
+ return new IPv4Prefix(rawValue);
1761
+ }
1762
+ ;
1763
+ static fromRangeSize(rangeSize) {
1764
+ let prefixNumber = rangeSize === (1n) ? 32 : 32 - rangeSizeToPrefix(rangeSize, Validator_1$1.Validator.IPV4_SIZE);
1765
+ return IPv4Prefix.fromNumber(BigInt(prefixNumber));
1766
+ }
1767
+ ;
1768
+ /**
1769
+ * Gets the decimal value of the IPv4 prefix
1770
+ *
1771
+ * @returns {number} the decimal value of the IPv4 prefix
1772
+ */
1773
+ getValue() {
1774
+ return this.value;
1775
+ }
1776
+ /**
1777
+ * Gets the decimal value of the IPv4 prefix as string
1778
+ * @returns {string} The decimal value of the IPv4 prefix as string
1779
+ */
1780
+ toString() {
1781
+ return this.value.toString();
1782
+ }
1783
+ /**
1784
+ * Converts the IPv4 prefix to a {@link IPv4Mask}
1785
+ *
1786
+ * The IPv4 mask is the representation of the prefix in the dot-decimal notation
1787
+ *
1788
+ * @returns {IPv4Mask} the mask representation of the prefix
1789
+ */
1790
+ toMask() {
1791
+ let onBits = '1'.repeat(Number(this.value));
1792
+ let offBits = '0'.repeat(Number(32n - this.value));
1793
+ return IPNumber_1$1.IPv4Mask.fromDecimalDottedString(this.toDecimalNotation(`${onBits}${offBits}`));
1794
+ }
1795
+ /**
1796
+ * Returns the size (number of IP numbers) of range of this prefix
1797
+ *
1798
+ * @return {bigint} the size (number of IP numbers) of range of this prefix
1799
+ */
1800
+ toRangeSize() {
1801
+ /**
1802
+ * Using bitwise shift operation this will be
1803
+ * 1 << (this.bitValue - this.getValue())
1804
+ * Since left shift a number by x is equivalent to multiplying the number by the power x raised to 2
1805
+ * 2 << 4 = 2 * (2 raised to 4)
1806
+ */
1807
+ return 1n << (this.bitValue - this.getValue());
1808
+ }
1809
+ /**
1810
+ * Returns a prefix for when this prefix is merged
1811
+ * with another prefix of the same size
1812
+ */
1813
+ merge() {
1814
+ return new IPv4Prefix(this.value - 1n);
1815
+ }
1816
+ /**
1817
+ * Returns a prefix for when this prefix is split
1818
+ * into two equal halves
1819
+ */
1820
+ split() {
1821
+ return new IPv4Prefix(this.value + 1n);
1822
+ }
1823
+ toDecimalNotation(bits) {
1824
+ return `${BinaryUtils_1$1.parseBinaryStringToBigInt(bits.substr(0, 8))}.${BinaryUtils_1$1.parseBinaryStringToBigInt(bits.substr(8, 8))}.${BinaryUtils_1$1.parseBinaryStringToBigInt(bits.substr(16, 8))}.${BinaryUtils_1$1.parseBinaryStringToBigInt(bits.substr(24, 8))}`;
1825
+ }
1826
+ }
1827
+ Prefix.IPv4Prefix = IPv4Prefix;
1828
+ /**
1829
+ * Represents the prefix portion in the CIDR notation for representing IP ranges
1830
+ *
1831
+ * The IPv6 prefix portion represents the mask. It is the number of continuous bits turned on (with value 1)
1832
+ * counting from the left side of an 128 bit value.
1833
+ *
1834
+ * {@see https://en.wikipedia.org/wiki/Classless_Inter-Domain_Routing} for more information on CIDR
1835
+ */
1836
+ class IPv6Prefix {
1837
+ /**
1838
+ * Constructor for an instance of IPv6 prefix from a decimal number
1839
+ *
1840
+ * @param {number} rawValue the decimal value to construct the IPv6 prefix from.
1841
+ * @returns {IPv4Prefix} the instance of an IPv6 prefix
1842
+ */
1843
+ constructor(rawValue) {
1844
+ this.type = "IPv6";
1845
+ this.bitValue = 128n;
1846
+ let isValid;
1847
+ let message;
1848
+ [isValid, message] = Validator_1$1.Validator.isValidPrefixValue(rawValue, "IPv6" /* IPv6 */);
1849
+ if (!isValid) {
1850
+ throw new Error(message.filter(msg => { return msg !== ''; }).toString());
1851
+ }
1852
+ this.value = rawValue;
1853
+ }
1854
+ /**
1855
+ * Convenience method for constructing an instance of IPv46 prefix from a decimal number
1856
+ *
1857
+ * @param {number} rawValue the decimal value to construct the IPv6 prefix from.
1858
+ * @returns {IPv4Prefix} the instance of an IPv6 prefix
1859
+ */
1860
+ static fromNumber(rawValue) {
1861
+ return new IPv6Prefix(rawValue);
1862
+ }
1863
+ ;
1864
+ static fromRangeSize(rangeSize) {
1865
+ let prefixNumber = rangeSize === (1n) ? 128 : 128 - rangeSizeToPrefix(rangeSize, Validator_1$1.Validator.IPV6_SIZE);
1866
+ return IPv6Prefix.fromNumber(BigInt(prefixNumber));
1867
+ }
1868
+ /**
1869
+ * Gets the decimal value of the IPv6 prefix
1870
+ *
1871
+ * @returns {number} the decimal value of the IPv6 prefix
1872
+ */
1873
+ getValue() {
1874
+ return this.value;
1875
+ }
1876
+ /**
1877
+ * Gets the decimal value of the IPv4 prefix as string
1878
+ * @returns {string} he decimal value of the IPv4 prefix as string
1879
+ */
1880
+ toString() {
1881
+ return this.value.toString();
1882
+ }
1883
+ /**
1884
+ * Converts the IPv6 prefix to a {@link IPv6Mask}
1885
+ *
1886
+ * The IPv6 mask is the representation of the prefix in 8 groups of 16 bit values represented in hexadecimal
1887
+ *
1888
+ * @returns {IPv6Mask} the mask representation of the prefix
1889
+ */
1890
+ toMask() {
1891
+ let onBits = '1'.repeat(Number(this.value));
1892
+ let offBits = '0'.repeat(128 - Number(this.value));
1893
+ return IPNumber_1$1.IPv6Mask.fromHexadecatet(this.toHexadecatetNotation(`${onBits}${offBits}`));
1894
+ }
1895
+ /**
1896
+ * Returns the size (number of IP numbers) of range of this prefix
1897
+ *
1898
+ * @return {bigint} the size (number of IP numbers) of range of this prefix
1899
+ */
1900
+ toRangeSize() {
1901
+ /**
1902
+ * Using bitwise shift operation this will be
1903
+ * 1 << (this.bitValue - this.getValue())
1904
+ * Since left shift a number by x is equivalent to multiplying the number by the power x raised to 2
1905
+ * 2 << 4 = 2 * (2 raised to 4)
1906
+ */
1907
+ return 1n << (this.bitValue - this.getValue());
1908
+ }
1909
+ /**
1910
+ * Returns a prefix for when this prefix is merged
1911
+ * with another prefix of the same size
1912
+ */
1913
+ merge() {
1914
+ return new IPv6Prefix(this.value - 1n);
1915
+ }
1916
+ /**
1917
+ * Returns a prefix for when this prefix is split
1918
+ * into two equal halves
1919
+ */
1920
+ split() {
1921
+ return new IPv6Prefix(this.value + 1n);
1922
+ }
1923
+ toHexadecatetNotation(bits) {
1924
+ let binaryStrings = bits.match(/.{1,16}/g);
1925
+ let hexadecimalStrings = binaryStrings.map((binaryString) => {
1926
+ return Hexadecatet_1.Hexadecatet.fromString(HexadecimalUtils_1.binaryStringToHexadecimalString(binaryString));
1927
+ });
1928
+ return hexadecimalStrings.map((value) => { return value.toString(); }).join(":");
1929
+ }
1930
+ }
1931
+ Prefix.IPv6Prefix = IPv6Prefix;
1932
+ function rangeSizeToPrefix(rangeSize, rangeMaxSize) {
1933
+ let ipType = rangeMaxSize > (Validator_1$1.Validator.IPV4_SIZE) ? "IPv6" : "IPv4";
1934
+ if (rangeSize > (rangeMaxSize) || rangeSize === (0n)) {
1935
+ throw new Error(Validator_1$1.Validator.invalidIPRangeSizeMessage.replace("$iptype", ipType));
1936
+ }
1937
+ try {
1938
+ return BinaryUtils_1$1.intLog2(rangeSize);
1939
+ }
1940
+ catch (e) {
1941
+ throw new Error(Validator_1$1.Validator.invalidIPRangeSizeForCidrMessage);
1942
+ }
1943
+ }
1944
+ /**
1945
+ * Check is the given Prefix is an {@link IPv4Prefix} or not
1946
+ * @param prefix the IP prefix to check if it is IPv4Prefix.
1947
+ */
1948
+ function isIPv4Prefix(prefix) {
1949
+ return prefix.type === "IPv4";
1950
+ }
1951
+ Prefix.isIPv4Prefix = isIPv4Prefix;
1952
+
1953
+ Object.defineProperty(IPRange, "__esModule", { value: true });
1954
+ IPRange.isIPv4CidrRange = IPRange.IPv6CidrRange = IPRange.IPv4CidrRange = IPRange.AbstractIPRange = IPRange.RangedSet = void 0;
1955
+ const IPNumber_1 = IPNumber;
1956
+ const Prefix_1$1 = Prefix;
1957
+ const BinaryUtils_1 = BinaryUtils;
1958
+ const Validator_1 = requireValidator();
1959
+ /**
1960
+ * Represents a continuous segment of either IPv4 or IPv6 numbers
1961
+ * without adhering to classless inter-domain routing scheme
1962
+ * for allocating IP addresses.
1963
+ */
1964
+ class RangedSet {
1965
+ /**
1966
+ * Constructor for an instance of {@link RangedSet} from an
1967
+ * instance of either {@link IPv4CidrRange} or {@link IPv6CidrRange}
1968
+ *
1969
+ * Throws an exception if first IP number is not less than given last IP number
1970
+ *
1971
+ * @param first the first IP number of the range
1972
+ * @param last the last IP number of the range
1973
+ */
1974
+ constructor(first, last) {
1975
+ this.first = first;
1976
+ this.last = last;
1977
+ if (first.isGreaterThan(last)) {
1978
+ throw new Error(`${first.toString()} should be lower than ${last.toString()}`);
1979
+ }
1980
+ this.currentValue = first;
1981
+ this.bitValue = BigInt(first.bitSize);
1982
+ }
1983
+ /**
1984
+ * Convenience method for constructing an instance of {@link RangedSet} from a
1985
+ * single IP number.
1986
+ *
1987
+ * @param ip The IP number, either IPv4 or IPv6 to construct the range from.
1988
+ */
1989
+ static fromSingleIP(ip) {
1990
+ return new RangedSet(ip, ip);
1991
+ }
1992
+ /**
1993
+ * Convenience method for constructing an instance of {@link RangedSet} from an
1994
+ * instance of either {@link IPv4CidrRange} or {@link IPv6CidrRange}
1995
+ *
1996
+ * @param cidrRange an instance of {@link RangedSet}
1997
+ */
1998
+ static fromCidrRange(cidrRange) {
1999
+ return new RangedSet(cidrRange.getFirst(), cidrRange.getLast());
2000
+ }
2001
+ /**
2002
+ * Convenience method for constructing an instance of {@link RangedSet} from
2003
+ * a range string in the form of firstIp-lastIp
2004
+ *
2005
+ * @param rangeString string in the form of firstIp-lastIp
2006
+ */
2007
+ static fromRangeString(rangeString) {
2008
+ let ips = rangeString.split("-").map(ip => ip.trim());
2009
+ if (ips.length !== 2) {
2010
+ throw new Error("Argument should be in the format firstip-lastip");
2011
+ }
2012
+ let [firstIPString, lastIPString] = ips;
2013
+ let [isValidFirstIPv4,] = Validator_1.Validator.isValidIPv4String(firstIPString);
2014
+ let [isValidSecondIPv4,] = Validator_1.Validator.isValidIPv4String(lastIPString);
2015
+ let [isValidFirstIPv6,] = Validator_1.Validator.isValidIPv6String(firstIPString);
2016
+ let [isValidLastIPv6,] = Validator_1.Validator.isValidIPv6String(lastIPString);
2017
+ if (isValidFirstIPv4 && isValidSecondIPv4) {
2018
+ return new RangedSet(IPNumber_1.IPv4.fromDecimalDottedString(firstIPString), IPNumber_1.IPv4.fromDecimalDottedString(lastIPString));
2019
+ }
2020
+ else if (isValidFirstIPv6 && isValidLastIPv6) {
2021
+ return new RangedSet(IPNumber_1.IPv6.fromHexadecatet(firstIPString), IPNumber_1.IPv6.fromHexadecatet(lastIPString));
2022
+ }
2023
+ else {
2024
+ throw new Error("First IP and Last IP should be valid and same type");
2025
+ }
2026
+ }
2027
+ /**
2028
+ * Returns the first IP number in the range
2029
+ */
2030
+ getFirst() {
2031
+ return this.first;
2032
+ }
2033
+ /**
2034
+ * Returns the last IP number in the range
2035
+ */
2036
+ getLast() {
2037
+ return this.last;
2038
+ }
2039
+ /**
2040
+ * Returns the size, which is the number of IP numbers in the range.
2041
+ */
2042
+ getSize() {
2043
+ return this.last.getValue() - (this.first.getValue()) + 1n;
2044
+ }
2045
+ /**
2046
+ * Converts to a string representation of the range in the form of:
2047
+ * <first-ip>-<last-ip>
2048
+ */
2049
+ toRangeString() {
2050
+ return `${this.getFirst()}-${this.getLast()}`;
2051
+ }
2052
+ /**
2053
+ * Checks if this range is inside another range.
2054
+ *
2055
+ * @param otherRange the other range to check if this range is inside of.
2056
+ */
2057
+ inside(otherRange) {
2058
+ return otherRange.contains(this);
2059
+ }
2060
+ /**
2061
+ * Checks if this range contains the given other range.
2062
+ *
2063
+ * @param otherRange the other range to check if this range contains
2064
+ */
2065
+ contains(otherRange) {
2066
+ let thisFirst = this.getFirst();
2067
+ let thisLast = this.getLast();
2068
+ let otherFirst = otherRange.getFirst();
2069
+ let otherLast = otherRange.getLast();
2070
+ return (thisFirst.isLessThanOrEquals(otherFirst) && thisLast.isGreaterThanOrEquals(otherLast));
2071
+ }
2072
+ /**
2073
+ * Check if this range is equal to the given other range.
2074
+ *
2075
+ * @param otherRange the other range to check if equal to this range.
2076
+ */
2077
+ isEquals(otherRange) {
2078
+ return this.getFirst().isEquals(otherRange.getFirst())
2079
+ && this.getLast().isEquals(otherRange.getLast());
2080
+ }
2081
+ ;
2082
+ /**
2083
+ * Check if this range is less than the given range.
2084
+ *
2085
+ * @param otherRange the other range to check if less than.
2086
+ */
2087
+ isLessThan(otherRange) {
2088
+ if (this.isEquals(otherRange)) {
2089
+ return false;
2090
+ }
2091
+ else {
2092
+ if (this.getFirst().isEquals(otherRange.getFirst())) {
2093
+ return this.getSize() < (otherRange.getSize());
2094
+ }
2095
+ return this.getFirst().isLessThan(otherRange.getFirst());
2096
+ }
2097
+ }
2098
+ /**
2099
+ * Check if this range is greater than the given range.
2100
+ *
2101
+ * @param otherRange the other range to check if greater than.
2102
+ */
2103
+ isGreaterThan(otherRange) {
2104
+ if (this.isEquals(otherRange)) {
2105
+ return false;
2106
+ }
2107
+ else {
2108
+ if (this.getFirst().isEquals(otherRange.getFirst())) {
2109
+ return this.getSize() > (otherRange.getSize());
2110
+ }
2111
+ return this.getFirst().isGreaterThan(otherRange.getFirst());
2112
+ }
2113
+ }
2114
+ /**
2115
+ * Checks of this range overlaps with a given other range.
2116
+ *
2117
+ * This means it checks if part of a range is part of another range without
2118
+ * being totally contained in the other range. Hence Equal or ranges contained inside one
2119
+ * another are not considered as overlapping.
2120
+ *
2121
+ * @param otherRange the other range to check if it overlaps with this range.
2122
+ */
2123
+ isOverlapping(otherRange) {
2124
+ let thisFirst = this.getFirst();
2125
+ let thisLast = this.getLast();
2126
+ let otherFirst = otherRange.getFirst();
2127
+ let otherLast = otherRange.getLast();
2128
+ return (thisLast.isGreaterThan(otherFirst) && thisLast.isLessThanOrEquals(otherLast) && thisFirst.isLessThan(otherFirst)
2129
+ ||
2130
+ otherLast.isGreaterThan(thisFirst) && otherLast.isLessThanOrEquals(thisLast) && otherFirst.isLessThan(thisFirst));
2131
+ }
2132
+ /**
2133
+ * Check if this range can be converted to a CIDR range.
2134
+ */
2135
+ isCidrAble() {
2136
+ if (this.getSize() === 1n) {
2137
+ return true;
2138
+ }
2139
+ try {
2140
+ let prefix = BinaryUtils_1.intLog2(this.getSize());
2141
+ let netmask = BinaryUtils_1.parseBinaryStringToBigInt(BinaryUtils_1.cidrPrefixToMaskBinaryString(prefix, IPNumber_1.isIPv4(this.currentValue) ? "IPv4" /* IPv4 */ : "IPv6" /* IPv6 */));
2142
+ return (this.first.getValue()) === (netmask & (this.first.getValue()));
2143
+ }
2144
+ catch (e) {
2145
+ return false;
2146
+ }
2147
+ }
2148
+ /**
2149
+ * Converts an instance of range to an instance of CIDR range
2150
+ */
2151
+ toCidrRange() {
2152
+ if (IPNumber_1.isIPv4(this.currentValue)) {
2153
+ return this.toIPv4CidrRange();
2154
+ }
2155
+ else {
2156
+ return this.toIPv6CidrRange();
2157
+ }
2158
+ }
2159
+ ;
2160
+ /**
2161
+ * Checks if this range is consecutive with another range.
2162
+ *
2163
+ * This means if the two ranges can be placed side by side, without any gap. Hence Equal
2164
+ * or ranges contained inside one another, or overlapping ranges are not considered as consecutive.
2165
+ *
2166
+ * @param otherRange the other range to check if this range is consecutive to.
2167
+ */
2168
+ isConsecutive(otherRange) {
2169
+ let thisFirst = this.getFirst();
2170
+ let thisLast = this.getLast();
2171
+ let otherFirst = otherRange.getFirst();
2172
+ let otherLast = otherRange.getLast();
2173
+ return (thisLast.hasNext() && thisLast.nextIPNumber().isEquals(otherFirst)
2174
+ ||
2175
+ otherLast.hasNext() && otherLast.nextIPNumber().isEquals(thisFirst));
2176
+ }
2177
+ /**
2178
+ * Creates a range that is a union of this range and the given other range.
2179
+ *
2180
+ * @param otherRange the other range to combine with this range
2181
+ */
2182
+ union(otherRange) {
2183
+ if (this.isEquals(otherRange)) {
2184
+ return new RangedSet(otherRange.getFirst(), otherRange.getLast());
2185
+ }
2186
+ if (this.isOverlapping(otherRange)) {
2187
+ if (this.getFirst().isLessThan(otherRange.getFirst())) {
2188
+ return new RangedSet(this.getFirst(), otherRange.getLast());
2189
+ }
2190
+ else {
2191
+ return new RangedSet(otherRange.getFirst(), this.getLast());
2192
+ }
2193
+ }
2194
+ if (this.contains(otherRange)) {
2195
+ return new RangedSet(this.getFirst(), this.getLast());
2196
+ }
2197
+ else if (otherRange.contains(this)) {
2198
+ return new RangedSet(otherRange.getFirst(), otherRange.getLast());
2199
+ }
2200
+ throw new Error("Ranges do not overlap nor are equal");
2201
+ }
2202
+ /**
2203
+ * Prepends given range with this range.
2204
+ * The last IP in the given range should be adjacent to the first IP in this range
2205
+ *
2206
+ * @param otherRange the other range to prepend
2207
+ */
2208
+ prepend(otherRange) {
2209
+ if (otherRange.getLast().nextIPNumber().isEquals(this.getFirst())) {
2210
+ return new RangedSet(otherRange.getFirst(), this.getLast());
2211
+ }
2212
+ else {
2213
+ throw new Error("Range to prepend must be adjacent");
2214
+ }
2215
+ }
2216
+ /**
2217
+ * Appends given range with this range.
2218
+ * The last IP in this range should be adjacent to the first IP in range to append
2219
+ *
2220
+ * @param otherRange the other range to append
2221
+ */
2222
+ append(otherRange) {
2223
+ if (this.getLast().nextIPNumber().isEquals(otherRange.getFirst())) {
2224
+ return new RangedSet(this.getFirst(), otherRange.getLast());
2225
+ }
2226
+ else {
2227
+ throw new Error("Range to append must be adjacent");
2228
+ }
2229
+ }
2230
+ subtract(otherRange) {
2231
+ if (!this.isOverlapping(otherRange)) {
2232
+ throw new Error("Cannot subtract ranges that are not overlapping");
2233
+ }
2234
+ if (!this.isLessThan(otherRange)) {
2235
+ throw new Error("Cannot subtract a larger range from this range");
2236
+ }
2237
+ return new RangedSet(this.getFirst(), otherRange.getLast());
2238
+ }
2239
+ /**
2240
+ * Returns a sub range of a given size from this range.
2241
+ *
2242
+ * @param offset offset from this range where the subrange should begin
2243
+ * @param size the size of the range
2244
+ */
2245
+ takeSubRange(offset, size) {
2246
+ if (offset + (size) > (this.getSize())) {
2247
+ throw new RangeError("Requested range is greater than what can be taken");
2248
+ }
2249
+ if (size === (0n)) {
2250
+ throw new Error("Sub range cannot be zero");
2251
+ }
2252
+ let valueOfFirstIp = this.getFirst().value + (offset);
2253
+ let firstIp = IPNumber_1.isIPv4(this.getFirst()) ?
2254
+ IPNumber_1.IPv4.fromNumber(valueOfFirstIp) : IPNumber_1.IPv6.fromBigInt(valueOfFirstIp);
2255
+ let valueOfLastIp = firstIp.value + (size - 1n);
2256
+ let lastIp = IPNumber_1.isIPv4(firstIp) ? IPNumber_1.IPv4.fromNumber(valueOfLastIp) : IPNumber_1.IPv6.fromBigInt(valueOfLastIp);
2257
+ return new RangedSet(firstIp, lastIp);
2258
+ }
2259
+ /**
2260
+ * Performs a subtraction operation, where the passed range is removed from the original range.
2261
+ *
2262
+ * The return range from the subtraction operation could be a single or multiple ranges
2263
+ *
2264
+ * @param range
2265
+ */
2266
+ difference(range) {
2267
+ if (range.getSize() > (this.getSize())) {
2268
+ throw new Error("Range is greater than range to be subtracted from");
2269
+ }
2270
+ if (!this.contains(range)) {
2271
+ throw new Error("Range to subtract is not contained in this range");
2272
+ }
2273
+ let reminders = [];
2274
+ try {
2275
+ reminders.push(new RangedSet(this.getFirst(), range.getFirst().previousIPNumber()));
2276
+ }
2277
+ catch (e) { }
2278
+ try {
2279
+ reminders.push(new RangedSet(range.getLast().nextIPNumber(), this.getLast()));
2280
+ }
2281
+ catch (e) { }
2282
+ return reminders;
2283
+ }
2284
+ *take(count) {
2285
+ let computed = this.getFirst();
2286
+ let returnCount = count === undefined ? this.getSize().valueOf() : count;
2287
+ while (returnCount > 0) {
2288
+ returnCount--;
2289
+ yield computed;
2290
+ computed = computed.nextIPNumber();
2291
+ }
2292
+ }
2293
+ *[Symbol.iterator]() {
2294
+ yield* this.take();
2295
+ }
2296
+ toIPv4CidrRange() {
2297
+ let candidateRange = new IPv4CidrRange(IPNumber_1.IPv4.fromNumber(this.getFirst().getValue()), Prefix_1$1.IPv4Prefix.fromRangeSize(this.getSize()));
2298
+ if (candidateRange.getFirst().isEquals(this.getFirst())) {
2299
+ return candidateRange;
2300
+ }
2301
+ else {
2302
+ throw new Error("Range cannot be converted to CIDR");
2303
+ }
2304
+ }
2305
+ toIPv6CidrRange() {
2306
+ let candidateRange = new IPv6CidrRange(IPNumber_1.IPv6.fromBigInt(this.getFirst().getValue()), Prefix_1$1.IPv6Prefix.fromRangeSize(this.getSize()));
2307
+ if (candidateRange.getFirst().isEquals(this.getFirst())) {
2308
+ return candidateRange;
2309
+ }
2310
+ else {
2311
+ throw new Error("Range cannot be converted to CIDR");
2312
+ }
2313
+ }
2314
+ }
2315
+ IPRange.RangedSet = RangedSet;
2316
+ /**
2317
+ * Provides the implementation of functionality that are common to {@link IPv4CidrRange} and {@link IPv6CidrRange}
2318
+ */
2319
+ class AbstractIPRange {
2320
+ hasNextRange() {
2321
+ let sizeOfCurrentRange = this.getSize();
2322
+ return ((2n ** this.bitValue) - sizeOfCurrentRange) >= (this.getFirst().getValue() + (sizeOfCurrentRange));
2323
+ }
2324
+ hasPreviousRange() {
2325
+ return this.getSize() <= (this.getFirst().getValue());
2326
+ }
2327
+ toRangeSet() {
2328
+ return new RangedSet(this.getFirst(), this.getLast());
2329
+ }
2330
+ inside(otherRange) {
2331
+ return this.toRangeSet().inside(otherRange.toRangeSet());
2332
+ }
2333
+ contains(otherRange) {
2334
+ return this.toRangeSet().contains(otherRange.toRangeSet());
2335
+ }
2336
+ toRangeString() {
2337
+ return this.toRangeSet().toRangeString();
2338
+ }
2339
+ isOverlapping(otherRange) {
2340
+ return this.toRangeSet().isOverlapping(otherRange.toRangeSet());
2341
+ }
2342
+ isConsecutive(otherRange) {
2343
+ return this.toRangeSet().isConsecutive(otherRange.toRangeSet());
2344
+ }
2345
+ isCidrMergeable(otherRange) {
2346
+ const count = BigInt(BinaryUtils_1.matchingBitCount(this.getFirst().toBinaryString(), otherRange.getFirst().toBinaryString()));
2347
+ if (this.getPrefix().value - count !== 1n) {
2348
+ return false;
2349
+ }
2350
+ return this.isConsecutive(otherRange) && this.getSize() === (otherRange.getSize());
2351
+ }
2352
+ isMergeable(otherRange) {
2353
+ return this.isCidrMergeable(otherRange)
2354
+ || this.contains(otherRange)
2355
+ || this.inside(otherRange);
2356
+ }
2357
+ isEquals(otherRange) {
2358
+ return this.toRangeSet().isEquals(otherRange.toRangeSet());
2359
+ }
2360
+ merge(otherRange) {
2361
+ if (!this.isCidrMergeable(otherRange)) {
2362
+ throw new Error(`Cannot merge. Ranges (${this.toRangeString()},${otherRange.toRangeString()}) are not consecutive and/or of same size`);
2363
+ }
2364
+ return this.newInstance(this.getFirst(), this.getPrefix().merge());
2365
+ }
2366
+ /**
2367
+ * Returns a lazily evaluated representation of the IP range that produces IP numbers by either:
2368
+ *
2369
+ * - iterating over using the for of syntax
2370
+ * - converting to array using spread syntax
2371
+ * - or assigning values to variables using deconstruction
2372
+ *
2373
+ * @param count the number of IP numbers to lazily evaluate.
2374
+ * If none is given, the whole IP range is lazily returned.
2375
+ */
2376
+ *takeStream(count) {
2377
+ return this.toRangeSet().take(count);
2378
+ }
2379
+ *[Symbol.iterator]() {
2380
+ yield* this.toRangeSet();
2381
+ }
2382
+ }
2383
+ IPRange.AbstractIPRange = AbstractIPRange;
2384
+ /**
2385
+ * Represents a continuous segment of IPv4 numbers following the
2386
+ * classless inter-domain routing scheme for allocating IP addresses.
2387
+ *
2388
+ * @see https://en.wikipedia.org/wiki/Classless_Inter-Domain_Routing
2389
+ */
2390
+ class IPv4CidrRange extends AbstractIPRange {
2391
+ /**
2392
+ * Constructor for creating an instance of an IPv4 range.
2393
+ *
2394
+ * The arguments taken by the constructor is inspired by the CIDR notation which basically consists of the IP
2395
+ * number and the prefix.
2396
+ *
2397
+ * @param {IPv4} ipv4 the IP number used to construct the range. By convention this is the first IP number in
2398
+ * the range, but it could also be any IP number within the range
2399
+ * @param {IPv4Prefix} cidrPrefix the prefix which is a representation of the number of bits used to mask the
2400
+ * given IP number in other to create the range
2401
+ */
2402
+ constructor(ipv4, cidrPrefix) {
2403
+ super();
2404
+ this.ipv4 = ipv4;
2405
+ this.cidrPrefix = cidrPrefix;
2406
+ this.bitValue = 32n;
2407
+ }
2408
+ /**
2409
+ * Convenience method for constructing an instance of an IPv4CidrRange from an IP range represented in CIDR notation
2410
+ *
2411
+ * @param {string} rangeIncidrNotation the range of the IPv4 number in CIDR notation
2412
+ * @returns {IPv4CidrRange} the IPv4CidrRange
2413
+ */
2414
+ static fromCidr(rangeIncidrNotation) {
2415
+ let [isValid, errorMessages] = Validator_1.Validator.isValidIPv4CidrNotation(rangeIncidrNotation);
2416
+ if (!isValid) {
2417
+ let messages = errorMessages.filter(message => { return message !== ''; });
2418
+ throw new Error(messages.join(' and '));
2419
+ }
2420
+ let cidrComponents = rangeIncidrNotation.split("/");
2421
+ let ipString = cidrComponents[0];
2422
+ let prefix = BigInt(parseInt(cidrComponents[1]));
2423
+ return new IPv4CidrRange(IPNumber_1.IPv4.fromDecimalDottedString(ipString), Prefix_1$1.IPv4Prefix.fromNumber(prefix));
2424
+ }
2425
+ /**
2426
+ * Gets the size of IPv4 numbers contained within the IPv4 range
2427
+ *
2428
+ * @returns {bigint} the amount of IPv4 numbers in the range
2429
+ */
2430
+ getSize() {
2431
+ return this.cidrPrefix.toRangeSize();
2432
+ }
2433
+ /**
2434
+ * Method that returns the IPv4 range in CIDR (Classless Inter-Domain Routing) notation.
2435
+ *
2436
+ * See {@link https://en.wikipedia.org/wiki/Classless_Inter-Domain_Routing#CIDR_notation} for more information
2437
+ * on the Classless Inter-Domain Routing notation
2438
+ *
2439
+ * @returns {string} the IPv4 range in CIDR (Classless Inter-Domain Routing) notation
2440
+ */
2441
+ toCidrString() {
2442
+ let first = this.ipv4.toString();
2443
+ return `${first.toString()}/${this.cidrPrefix.toString()}`;
2444
+ }
2445
+ /**
2446
+ * Method that returns the IPv4 range in string notation where the first IPv4 number and last IPv4 number are
2447
+ * separated by an hyphen. eg. 192.198.0.0-192.198.0.255
2448
+ *
2449
+ * @returns {string} the range in [first IPv4 number] - [last IPv4 number] format
2450
+ */
2451
+ toRangeString() {
2452
+ return super.toRangeString();
2453
+ }
2454
+ /**
2455
+ * Method that returns the first IPv4 number in the IPv4 range
2456
+ *
2457
+ * @returns {IPv4} the first IPv4 number in the IPv4 range
2458
+ */
2459
+ getFirst() {
2460
+ return IPNumber_1.IPv4.fromNumber(this.ipv4.getValue() & (this.cidrPrefix.toMask().getValue()));
2461
+ }
2462
+ /**
2463
+ * Method that returns the last IPv4 number in the IPv4 range
2464
+ *
2465
+ * @returns {IPv4} the last IPv4 number in the IPv4 range
2466
+ */
2467
+ getLast() {
2468
+ return last(this, this.ipv4);
2469
+ }
2470
+ newInstance(num, prefix) {
2471
+ return new IPv4CidrRange(num, prefix);
2472
+ }
2473
+ getPrefix() {
2474
+ return this.cidrPrefix;
2475
+ }
2476
+ /**
2477
+ * Indicates whether the given IPv4 range is an adjacent range.
2478
+ *
2479
+ * An adjacent range being one where the end of the given range, when incremented by one marks the start of the
2480
+ * other range. Or where the start of the given range, when decreased by one, marks the end of the other range
2481
+ *
2482
+ * @param {IPv4CidrRange} otherRange the other IPv4 range to compare with
2483
+ * @returns {boolean} true if the two IPv4 ranges are consecutive, false otherwise
2484
+ */
2485
+ isConsecutive(otherRange) {
2486
+ return super.isConsecutive(otherRange);
2487
+ }
2488
+ /**
2489
+ * Indicates if the given IPv4 range is a subset.
2490
+ *
2491
+ * By a subset range, it means all the values of the given range are contained by this IPv4 range
2492
+ *
2493
+ * @param {IPv4CidrRange} otherRange the other IPv4 range
2494
+ * @returns {boolean} true if the other Ipv4 range is a subset. False otherwise.
2495
+ */
2496
+ contains(otherRange) {
2497
+ return super.contains(otherRange);
2498
+ }
2499
+ /**
2500
+ * Indicate if the given range is a container range.
2501
+ *
2502
+ * By container range, it means all the IP number in this current range can be found within the given range.
2503
+ *
2504
+ * @param {IPv4CidrRange} otherRange he other IPv4 range
2505
+ * @returns {boolean} true if the other Ipv4 range is a container range. False otherwise.
2506
+ */
2507
+ inside(otherRange) {
2508
+ return super.inside(otherRange);
2509
+ }
2510
+ /**
2511
+ * Checks if two IPv4 ranges overlap
2512
+ * @param {IPv4CidrRange} otherRange the other IPv4 range
2513
+ * @returns {boolean} true if the ranges overlap, false otherwise
2514
+ */
2515
+ isOverlapping(otherRange) {
2516
+ return super.isOverlapping(otherRange);
2517
+ }
2518
+ /**
2519
+ * Method that takes IPv4 number from within an IPv4 range, starting from the first IPv4 number
2520
+ *
2521
+ * @param {bigint} count the amount of IPv4 number to take from the IPv4 range
2522
+ * @returns {Array<IPv4>} an array of IPv4 number, taken from the IPv4 range
2523
+ */
2524
+ take(count) {
2525
+ let ipv4s = [this.getFirst()];
2526
+ let iteratingIPv4 = this.getFirst();
2527
+ if (count > (this.getSize())) {
2528
+ let errMessage = Validator_1.Validator.takeOutOfRangeSizeMessage
2529
+ .replace("$count", count.toString())
2530
+ .replace("$size", this.getSize().toString());
2531
+ throw new Error(errMessage);
2532
+ }
2533
+ for (let counter = 0; counter < count - 1n; counter++) {
2534
+ ipv4s.push(iteratingIPv4.nextIPNumber());
2535
+ iteratingIPv4 = iteratingIPv4.nextIPNumber();
2536
+ }
2537
+ return ipv4s;
2538
+ }
2539
+ /**
2540
+ * Method that splits an IPv4 range into two halves
2541
+ *
2542
+ * @returns {Array<IPv4CidrRange>} An array of two {@link IPv4CidrRange}
2543
+ */
2544
+ split() {
2545
+ let prefixToSplit = this.cidrPrefix.getValue();
2546
+ if (prefixToSplit === 32n) {
2547
+ throw new Error("Cannot split an IP range with a single IP number");
2548
+ }
2549
+ let splitCidr = Prefix_1$1.IPv4Prefix.fromNumber(prefixToSplit + 1n);
2550
+ let firstIPOfFirstRange = this.getFirst();
2551
+ let firstRange = new IPv4CidrRange(firstIPOfFirstRange, splitCidr);
2552
+ let firstIPOfSecondRange = firstRange.getLast().nextIPNumber();
2553
+ let secondRange = new IPv4CidrRange(firstIPOfSecondRange, splitCidr);
2554
+ return [firstRange, secondRange];
2555
+ }
2556
+ /**
2557
+ * Method that split prefix into ranges of the given prefix,
2558
+ * throws an exception if the size of the given prefix is larger than target prefix
2559
+ *
2560
+ * @param prefix the prefix to use to split
2561
+ * @returns {Array<IPv4CidrRange>} An array of two {@link IPv4CidrRange}
2562
+ */
2563
+ splitInto(prefix) {
2564
+ let splitCount = prefix.getValue() - this.cidrPrefix.getValue();
2565
+ if (splitCount < 0) {
2566
+ throw new Error("Prefix to split into is larger than source prefix");
2567
+ }
2568
+ else if (splitCount === 0n) {
2569
+ return [new IPv4CidrRange(this.getFirst(), prefix)];
2570
+ }
2571
+ else if (splitCount === 1n) {
2572
+ return this.split();
2573
+ }
2574
+ else {
2575
+ let results = this.split();
2576
+ while (splitCount > 1) {
2577
+ results = results.flatMap(result => result.split());
2578
+ splitCount = splitCount - 1n;
2579
+ }
2580
+ return results;
2581
+ }
2582
+ }
2583
+ /**
2584
+ * Returns true if there is an adjacent IPv4 cidr range of exactly the same size next to this range
2585
+ */
2586
+ hasNextRange() {
2587
+ return super.hasNextRange();
2588
+ }
2589
+ /**
2590
+ * Returns true if there is an adjacent IPv4 cidr range of exactly the same size previous to this range
2591
+ */
2592
+ hasPreviousRange() {
2593
+ return super.hasPreviousRange();
2594
+ }
2595
+ /**
2596
+ * Return the next IPv6 cidr range, or undefined if no next range
2597
+ */
2598
+ nextRange() {
2599
+ if (this.hasNextRange()) {
2600
+ let sizeOfCurrentRange = this.getSize();
2601
+ let startOfNextRange = this.getFirst().getValue() + (sizeOfCurrentRange);
2602
+ return new IPv4CidrRange(new IPNumber_1.IPv4(startOfNextRange), this.cidrPrefix);
2603
+ }
2604
+ return;
2605
+ }
2606
+ /**
2607
+ * Return the previous IPv6 cidr range, or undefined if no next range
2608
+ */
2609
+ previousRange() {
2610
+ if (this.hasPreviousRange()) {
2611
+ let sizeOfCurrentRange = this.getSize();
2612
+ let startOfPreviousRange = this.getFirst().getValue() - (sizeOfCurrentRange);
2613
+ return new IPv4CidrRange(new IPNumber_1.IPv4(startOfPreviousRange), this.cidrPrefix);
2614
+ }
2615
+ return;
2616
+ }
2617
+ }
2618
+ IPRange.IPv4CidrRange = IPv4CidrRange;
2619
+ /**
2620
+ * Represents a continuous segment of IPv6 number following the
2621
+ * classless inter-domain routing scheme for allocating IP addresses.
2622
+ *
2623
+ * @see https://en.wikipedia.org/wiki/Classless_Inter-Domain_Routing
2624
+ */
2625
+ class IPv6CidrRange extends AbstractIPRange {
2626
+ /**
2627
+ * Constructor for creating an instance of an IPv6 range.
2628
+ *
2629
+ * The arguments taken by the constructor is inspired by the CIDR notation which basically consists of the IP
2630
+ * number and the prefix.
2631
+ *
2632
+ * @param {IPv6} ipv6 the IP number used to construct the range. By convention this is the first IP number in
2633
+ * the range, but it could also be any IP number within the range
2634
+ * @param {IPv6Prefix} cidrPrefix the prefix which is a representation of the number of bits used to mask the
2635
+ * given IPv6 number in other to create the range
2636
+ */
2637
+ constructor(ipv6, cidrPrefix) {
2638
+ super();
2639
+ this.ipv6 = ipv6;
2640
+ this.cidrPrefix = cidrPrefix;
2641
+ this.bitValue = 128n;
2642
+ }
2643
+ /**
2644
+ * Convenience method for constructing an instance of an IPV6Range from an IP range represented in CIDR notation
2645
+ *
2646
+ * @param {string} rangeInCidrNotation the range of the IPv6 number in CIDR notation
2647
+ * @returns {IPv6CidrRange} the IPV6Range
2648
+ */
2649
+ static fromCidr(rangeInCidrNotation) {
2650
+ let [isValid, message] = Validator_1.Validator.isValidIPv6CidrNotation(rangeInCidrNotation);
2651
+ if (!isValid) {
2652
+ throw new Error(message.filter(msg => { return msg !== ''; }).toString());
2653
+ }
2654
+ let cidrComponents = rangeInCidrNotation.split("/");
2655
+ let ipString = cidrComponents[0];
2656
+ let prefix = BigInt(parseInt(cidrComponents[1]));
2657
+ return new IPv6CidrRange(IPNumber_1.IPv6.fromHexadecatet(ipString), Prefix_1$1.IPv6Prefix.fromNumber(prefix));
2658
+ }
2659
+ ;
2660
+ /**
2661
+ * Gets the size of IPv6 numbers contained within the IPv6 range
2662
+ *
2663
+ * @returns {bigint} the amount of IPv6 numbers in the range
2664
+ */
2665
+ getSize() {
2666
+ return this.cidrPrefix.toRangeSize();
2667
+ }
2668
+ /**
2669
+ * Method that returns the IPv6 range in CIDR (Classless Inter-Domain Routing) notation.
2670
+ *
2671
+ * See {@link https://en.wikipedia.org/wiki/Classless_Inter-Domain_Routing#CIDR_notation} for more information
2672
+ * on the Classless Inter-Domain Routing notation
2673
+ *
2674
+ * @returns {string} the IPv6 range in CIDR (Classless Inter-Domain Routing) notation
2675
+ */
2676
+ toCidrString() {
2677
+ let first = this.ipv6.toString();
2678
+ return `${first.toString()}/${this.cidrPrefix.toString()}`;
2679
+ }
2680
+ /**
2681
+ * Method that returns the IPv6 range in string notation where the first IPv6 number and last IPv6 number are
2682
+ * separated by an hyphen. eg. "2001:db8:0:0:0:0:0:0-2001:db8:0:ffff:ffff:ffff:ffff:ffff"
2683
+ *
2684
+ * @returns {string} the range in [first IPv6 number] - [last IPv6 number] format
2685
+ */
2686
+ toRangeString() {
2687
+ return super.toRangeString();
2688
+ }
2689
+ /**
2690
+ * Method that returns the first IPv6 number in the IPv6 range
2691
+ *
2692
+ * @returns {IPv6} the first IPv6 number in the IPv6 range
2693
+ */
2694
+ getFirst() {
2695
+ return IPNumber_1.IPv6.fromBigInt(this.ipv6.getValue() & (this.cidrPrefix.toMask().getValue()));
2696
+ }
2697
+ /**
2698
+ * Method that returns the last IPv6 number in the IPv6 range
2699
+ *
2700
+ * @returns {IPv6} the last IPv6 number in the IPv6 range
2701
+ */
2702
+ getLast() {
2703
+ return last(this, this.ipv6);
2704
+ }
2705
+ newInstance(num, prefix) {
2706
+ return new IPv6CidrRange(num, prefix);
2707
+ }
2708
+ getPrefix() {
2709
+ return this.cidrPrefix;
2710
+ }
2711
+ /**
2712
+ * Indicates whether the given IPv6 range is an adjacent range.
2713
+ *
2714
+ * An adjacent range being one where the end of the given range, when incremented by one marks the start of the
2715
+ * other range. Or where the start of the given range, when decreased by one, marks the end of the other range
2716
+ *
2717
+ * @param {IPv6CidrRange} otherRange the other IPv6 range to compare with
2718
+ * @returns {boolean} true if the two IPv6 ranges are consecutive, false otherwise
2719
+ */
2720
+ isConsecutive(otherRange) {
2721
+ return super.isConsecutive(otherRange);
2722
+ }
2723
+ /**
2724
+ * Indicates if the given IPv6 range is a subset.
2725
+ *
2726
+ * By a subset range, it means all the values of the given range are contained by this IPv6 range
2727
+ *
2728
+ * @param {IPv6CidrRange} otherRange the other IPv6 range
2729
+ * @returns {boolean} true if the other Ipv6 range is a subset. False otherwise.
2730
+ */
2731
+ contains(otherRange) {
2732
+ return super.contains(otherRange);
2733
+ }
2734
+ /**
2735
+ * Indicate if the given range is a container range.
2736
+ *
2737
+ * By container range, it means all the IP number in this current range can be found within the given range.
2738
+ *
2739
+ * @param {IPv6CidrRange} otherRange he other IPv6 range
2740
+ * @returns {boolean} true if the other Ipv6 range is a container range. False otherwise.
2741
+ */
2742
+ inside(otherRange) {
2743
+ return super.inside(otherRange);
2744
+ }
2745
+ /**
2746
+ * Checks if two IPv6 ranges overlap
2747
+ * @param {IPv6CidrRange} otherRange the other IPv6 range
2748
+ * @returns {boolean} true if the ranges overlap, false otherwise
2749
+ */
2750
+ isOverlapping(otherRange) {
2751
+ return super.isOverlapping(otherRange);
2752
+ }
2753
+ /**
2754
+ * Method that takes IPv6 number from within an IPv6 range, starting from the first IPv6 number
2755
+ *
2756
+ * @param {bigint} count the amount of IPv6 number to take from the IPv6 range
2757
+ * @returns {Array<IPv6>} an array of IPv6 number, taken from the IPv6 range
2758
+ */
2759
+ take(count) {
2760
+ let iPv6s = [this.getFirst()];
2761
+ let iteratingIPv6 = this.getFirst();
2762
+ if (count > (this.getSize())) {
2763
+ throw new Error(`${count.toString()} is greater than ${this.getSize().toString()}, the size of the range`);
2764
+ }
2765
+ for (var counter = 0; counter < count - 1n; counter++) {
2766
+ iPv6s.push(iteratingIPv6.nextIPNumber());
2767
+ iteratingIPv6 = iteratingIPv6.nextIPNumber();
2768
+ }
2769
+ return iPv6s;
2770
+ }
2771
+ /**
2772
+ * Method that splits an IPv6 cidr range into two halves
2773
+ *
2774
+ * @returns {Array<IPv6CidrRange>} An array of two {@link IPv6CidrRange}
2775
+ */
2776
+ split() {
2777
+ let prefixToSplit = this.cidrPrefix.getValue();
2778
+ if (prefixToSplit === 128n) {
2779
+ throw new Error("Cannot split an IP range with a single IP number");
2780
+ }
2781
+ let splitCidr = Prefix_1$1.IPv6Prefix.fromNumber(prefixToSplit + 1n);
2782
+ let firstIPOfFirstRange = this.getFirst();
2783
+ let firstRange = new IPv6CidrRange(firstIPOfFirstRange, splitCidr);
2784
+ let firstIPOfSecondRange = firstRange.getLast().nextIPNumber();
2785
+ let secondRange = new IPv6CidrRange(firstIPOfSecondRange, splitCidr);
2786
+ return [firstRange, secondRange];
2787
+ }
2788
+ /**
2789
+ * Method that split prefix into ranges of the given prefix,
2790
+ * throws an exception if the size of the given prefix is larger than target prefix
2791
+ *
2792
+ * @param prefix the prefix to use to split
2793
+ * @returns {Array<IPv6CidrRange>} An array of two {@link IPv6CidrRange}
2794
+ */
2795
+ splitInto(prefix) {
2796
+ let splitCount = prefix.getValue() - this.cidrPrefix.getValue();
2797
+ if (splitCount < 0) {
2798
+ throw new Error("Prefix to split into is larger than source prefix");
2799
+ }
2800
+ else if (splitCount === 0n) {
2801
+ return [new IPv6CidrRange(this.getFirst(), prefix)];
2802
+ }
2803
+ else if (splitCount === 1n) {
2804
+ return this.split();
2805
+ }
2806
+ else {
2807
+ let results = this.split();
2808
+ while (splitCount > 1) {
2809
+ results = results.flatMap(result => result.split());
2810
+ splitCount = splitCount - 1n;
2811
+ }
2812
+ return results;
2813
+ }
2814
+ }
2815
+ /**
2816
+ * Returns true if there is an adjacent IPv6 cidr range of exactly the same size next to this range
2817
+ */
2818
+ hasNextRange() {
2819
+ return super.hasNextRange();
2820
+ }
2821
+ /**
2822
+ * Returns true if there is an adjacent IPv6 cidr range of exactly the same size previous to this range
2823
+ */
2824
+ hasPreviousRange() {
2825
+ return super.hasPreviousRange();
2826
+ }
2827
+ /**
2828
+ * Return the next IPv6 cidr range, or undefined if no next range
2829
+ */
2830
+ nextRange() {
2831
+ if (this.hasNextRange()) {
2832
+ let sizeOfCurrentRange = this.getSize();
2833
+ let startOfNextRange = this.getFirst().getValue() + (sizeOfCurrentRange);
2834
+ return new IPv6CidrRange(new IPNumber_1.IPv6(startOfNextRange), this.cidrPrefix);
2835
+ }
2836
+ return;
2837
+ }
2838
+ /**
2839
+ * Return the previous IPv6 cidr range, or undefined if no next range
2840
+ */
2841
+ previousRange() {
2842
+ if (this.hasPreviousRange()) {
2843
+ let sizeOfCurrentRange = this.getSize();
2844
+ let startOfPreviousRange = this.getFirst().getValue() - sizeOfCurrentRange;
2845
+ return new IPv6CidrRange(new IPNumber_1.IPv6(startOfPreviousRange), this.cidrPrefix);
2846
+ }
2847
+ return;
2848
+ }
2849
+ }
2850
+ IPRange.IPv6CidrRange = IPv6CidrRange;
2851
+ // utility functions shared by both IPv6CidrRange and IPv4CidrRange
2852
+ let last = (range, ip) => {
2853
+ let bitValue = Number(range.bitValue.valueOf());
2854
+ let maskSize = BigInt(`0b${"1".repeat(bitValue)}`);
2855
+ let maskAsBigInteger = range.cidrPrefix.toMask().getValue();
2856
+ let invertedMask = BinaryUtils_1.leftPadWithZeroBit((maskAsBigInteger ^ (maskSize)).toString(2), bitValue);
2857
+ if (isIPv4CidrRange(range)) {
2858
+ return IPNumber_1.IPv4.fromNumber((ip.getValue()) | (BinaryUtils_1.parseBinaryStringToBigInt(invertedMask)));
2859
+ }
2860
+ else {
2861
+ return IPNumber_1.IPv6.fromBigInt((ip.getValue()) | (BinaryUtils_1.parseBinaryStringToBigInt(invertedMask)));
2862
+ }
2863
+ };
2864
+ function isIPv4CidrRange(ip) {
2865
+ return ip.bitValue.valueOf() === 32n;
2866
+ }
2867
+ IPRange.isIPv4CidrRange = isIPv4CidrRange;
2868
+
2869
+ Object.defineProperty(IPPool, "__esModule", { value: true });
2870
+ IPPool.Pool = void 0;
2871
+ const IPRange_1 = IPRange;
2872
+ const Prefix_1 = Prefix;
2873
+ /**
2874
+ * Represents a collection of IP {@link RangedSet}'s
2875
+ */
2876
+ class Pool {
2877
+ /**
2878
+ * Constructor for an IP pool.
2879
+ *
2880
+ * Creates a Pool of IP ranges from supplied {@link RangedSet}'s
2881
+ *
2882
+ * @param ranges the array of IP ranges that would make up the pool.
2883
+ */
2884
+ constructor(ranges) {
2885
+ this.backingSet = new SortedSet();
2886
+ ranges.forEach(range => {
2887
+ this.backingSet.add(range);
2888
+ });
2889
+ }
2890
+ /**
2891
+ * Convenient method for creating an instance from arrays of {@link IPv4} or {@link IPv6}
2892
+ * @param ipNumbers the arrays of {@link IPv4} or {@link IPv6} that will make up the pool.
2893
+ */
2894
+ static fromIP(ipNumbers) {
2895
+ let ranges = ipNumbers.map((ip) => {
2896
+ return IPRange_1.RangedSet.fromSingleIP(ip);
2897
+ });
2898
+ return new Pool(ranges);
2899
+ }
2900
+ /**
2901
+ * Convenient method for creating an instance from arrays of {@link RangedSet}.
2902
+ *
2903
+ * @param ipRanges the arrays of {@link RangedSet}'s that will make up the pool.
2904
+ */
2905
+ // TODO: TSE: This makes it possible to create an instance containing both Range set of IPv4 and IPv6
2906
+ static fromRangeSet(ipRanges) {
2907
+ return new Pool(ipRanges);
2908
+ }
2909
+ /**
2910
+ * Convenient method for creating an instance from arrays of {@link IPv4CidrRange} or {@link IPv6CidrRange}.
2911
+ *
2912
+ * @param cidrRanges the arrays of {@link IPv4CidrRange} or {@link IPv6CidrRange} that will make up the pool.
2913
+ */
2914
+ static fromCidrRanges(cidrRanges) {
2915
+ let cidr = cidrRanges;
2916
+ let rangeSet = cidr.map((range) => {
2917
+ return range.toRangeSet();
2918
+ });
2919
+ return new Pool(rangeSet);
2920
+ }
2921
+ /**
2922
+ * Returns an array of {@link RangedSet}'s that is contained within the pool
2923
+ */
2924
+ getRanges() {
2925
+ return this.backingSet.asArray();
2926
+ }
2927
+ /**
2928
+ * Returns an new {@link Pool} with all the IP ranges aggregated
2929
+ */
2930
+ aggregate() {
2931
+ let sortedRanges = this.backingSet.asArray();
2932
+ let mergedRanges = sortedRanges.reduce((accumulator, currentRange, currentIndex, array) => {
2933
+ if (accumulator.length == 0) {
2934
+ accumulator.push(currentRange);
2935
+ return accumulator;
2936
+ }
2937
+ else {
2938
+ let previous = accumulator.pop();
2939
+ let previousCidrRange = previous.toCidrRange();
2940
+ let currentCidrRange = currentRange.toCidrRange();
2941
+ if (previousCidrRange.isCidrMergeable(currentCidrRange)) {
2942
+ let merged = previousCidrRange.merge(currentCidrRange);
2943
+ accumulator.push(merged.toRangeSet());
2944
+ return accumulator;
2945
+ }
2946
+ else {
2947
+ if (!previous.contains(currentRange)) {
2948
+ accumulator.push(previous);
2949
+ accumulator.push(currentRange);
2950
+ }
2951
+ else {
2952
+ accumulator.push(previous);
2953
+ }
2954
+ return accumulator;
2955
+ }
2956
+ }
2957
+ }, []);
2958
+ let aggregatedPool = Pool.fromRangeSet(mergedRanges);
2959
+ if (aggregatedPool.getRanges().length !== this.getRanges().length) {
2960
+ return aggregatedPool.aggregate();
2961
+ }
2962
+ else {
2963
+ return aggregatedPool;
2964
+ }
2965
+ }
2966
+ /**
2967
+ * Gets a single range of size of the given prefix from pool.
2968
+ * Only returns a range if there is a single range in the pool of same size or greater than given prefix.
2969
+ *
2970
+ * throws exception if the requested range cannot be got from the pool.
2971
+ *
2972
+ * @param prefix prefix range to retrieve
2973
+ * TODO TSE
2974
+ */
2975
+ getCidrRange(prefix) {
2976
+ if (prefix.toRangeSize() > (this.getSize())) {
2977
+ throw new Error(`Not enough IP number in the pool for requested prefix: ${prefix}`);
2978
+ }
2979
+ let selectedCidrRange;
2980
+ let error;
2981
+ loop: for (let range of this.getRanges()) {
2982
+ for (let offset = 0n; offset + (prefix.toRangeSize()) <= (range.getSize()); offset = offset + 1n)
2983
+ try {
2984
+ let selectedRange = range.takeSubRange(offset, prefix.toRangeSize());
2985
+ selectedCidrRange = selectedRange.toCidrRange();
2986
+ let remaining = range.difference(selectedRange);
2987
+ this.removeExact(range);
2988
+ this.add(remaining);
2989
+ break loop;
2990
+ }
2991
+ catch (e) {
2992
+ if (e instanceof RangeError) {
2993
+ continue loop;
2994
+ }
2995
+ error = e;
2996
+ }
2997
+ }
2998
+ if (selectedCidrRange) {
2999
+ return selectedCidrRange;
3000
+ }
3001
+ else {
3002
+ throw (error === undefined ? new Error(`No range big enough in the pool for requested prefix: ${prefix}`) : error);
3003
+ }
3004
+ }
3005
+ /**
3006
+ * Gets a single or multiple ranges that fulfils the given prefix from the pool.
3007
+ *
3008
+ * throws exception if the requested range cannot be got from the pool.
3009
+ *
3010
+ * @param reqprefix prefix range to retrieve
3011
+ */
3012
+ getCidrRanges(reqprefix) {
3013
+ if (reqprefix.toRangeSize() > (this.getSize())) {
3014
+ throw new Error("Prefix greater than pool");
3015
+ }
3016
+ let go = (reqprefix, prefix, accummulated) => {
3017
+ try {
3018
+ let singleCidrRange = this.getCidrRange(prefix);
3019
+ accummulated.push(singleCidrRange);
3020
+ let currentSize = accummulated.reduce((previous, current) => {
3021
+ return previous + (current.getSize());
3022
+ }, 0n);
3023
+ if (reqprefix.toRangeSize() === (currentSize)) {
3024
+ return accummulated;
3025
+ }
3026
+ else {
3027
+ return go(reqprefix, prefix, accummulated);
3028
+ }
3029
+ }
3030
+ catch (e) {
3031
+ let lowerPrefix = Prefix_1.isIPv4Prefix(prefix) ?
3032
+ Prefix_1.IPv4Prefix.fromNumber(prefix.getValue() + 1n) : Prefix_1.IPv6Prefix.fromNumber(prefix.getValue() + 1n);
3033
+ return go(reqprefix, lowerPrefix, accummulated);
3034
+ }
3035
+ };
3036
+ return go(reqprefix, reqprefix, []);
3037
+ }
3038
+ /**
3039
+ * Returns the size of IP numbers in the pool
3040
+ */
3041
+ getSize() {
3042
+ return this
3043
+ .aggregate()
3044
+ .getRanges()
3045
+ .reduce((previous, current) => {
3046
+ return previous + current.getSize();
3047
+ }, 0n);
3048
+ }
3049
+ /**
3050
+ * Empties the pool and fill it with given ranges
3051
+ *
3052
+ * @param ipRanges the range to fill the pool with after emptying
3053
+ */
3054
+ resetWith(ipRanges) {
3055
+ this.backingSet.clear();
3056
+ this.backingSet = this.backingSet.add(ipRanges);
3057
+ }
3058
+ /**
3059
+ * Removes the given range from the pool. It only removes if the exact range exist in the pool.
3060
+ * It is a Noop and returns false, if the given range does not exist in the pool. Returns true otherwise
3061
+ *
3062
+ * @param rangeToRemove range to remove from ppol
3063
+ */
3064
+ removeExact(rangeToRemove) {
3065
+ let updatedSet = this.backingSet.removeExact(rangeToRemove);
3066
+ let isUpdated = !this.backingSet.isEquals(updatedSet);
3067
+ this.backingSet = updatedSet;
3068
+ return isUpdated;
3069
+ }
3070
+ /**
3071
+ * Removes the given range from the pool. If the given range overlaps, then it removes the overlapping portion.
3072
+ * It is a Noop and returns false, if the given range does not exist in the pool. Returns true otherwise
3073
+ *
3074
+ * @param rangeToRemove range to remove from ppol
3075
+ */
3076
+ removeOverlapping(rangeToRemove) {
3077
+ let updatedSet = this.backingSet.removeOverlapping(rangeToRemove);
3078
+ let isUpdated = !this.backingSet.isEquals(updatedSet);
3079
+ this.backingSet = updatedSet;
3080
+ return isUpdated;
3081
+ }
3082
+ /**
3083
+ * Adds the given range to the pool.
3084
+ *
3085
+ * @param range to add to pool.
3086
+ */
3087
+ add(range) {
3088
+ this.backingSet = this.backingSet.add(range);
3089
+ }
3090
+ /**
3091
+ * Removes all ranges from pool
3092
+ */
3093
+ clear() {
3094
+ this.backingSet.clear();
3095
+ }
3096
+ }
3097
+ IPPool.Pool = Pool;
3098
+ class SortedSet {
3099
+ constructor(array) {
3100
+ if (array) {
3101
+ this.backingArray = this.sortArray(array);
3102
+ }
3103
+ else {
3104
+ this.backingArray = new Array();
3105
+ }
3106
+ }
3107
+ sortArray(array) {
3108
+ array.sort((a, b) => {
3109
+ if (a.isLessThan(b)) {
3110
+ return -1;
3111
+ }
3112
+ if (a.isGreaterThan(b)) {
3113
+ return 1;
3114
+ }
3115
+ return 0;
3116
+ });
3117
+ return array;
3118
+ }
3119
+ asArray() {
3120
+ return this.backingArray;
3121
+ }
3122
+ isEquals(other) {
3123
+ if (this.backingArray.length !== other.asArray().length) {
3124
+ return false;
3125
+ }
3126
+ return this.backingArray.every((value, index) => {
3127
+ return value.getSize() === (other.asArray()[index].getSize());
3128
+ });
3129
+ }
3130
+ add(item) {
3131
+ let array = this.backingArray;
3132
+ if ("push" in item) {
3133
+ array = array.concat(item);
3134
+ }
3135
+ else {
3136
+ array.push(item);
3137
+ }
3138
+ return new SortedSet(this.sortArray(array));
3139
+ }
3140
+ removeExact(items) {
3141
+ let filtered = this.backingArray
3142
+ .filter(currentItem => {
3143
+ if ("push" in items) {
3144
+ return items.find(item => item.isEquals(currentItem)) !== undefined;
3145
+ }
3146
+ else {
3147
+ return !items.isEquals(currentItem);
3148
+ }
3149
+ });
3150
+ return new SortedSet(this.sortArray(filtered));
3151
+ }
3152
+ removeOverlapping(items) {
3153
+ let filtered = this.backingArray
3154
+ .flatMap(backingItem => {
3155
+ if ("push" in items) {
3156
+ return items.flatMap(item => {
3157
+ if (backingItem.contains(item)) {
3158
+ return backingItem.difference(item);
3159
+ }
3160
+ else if (backingItem.inside(item)) {
3161
+ return new Array();
3162
+ }
3163
+ else if (backingItem.isOverlapping(item)) {
3164
+ return [backingItem.subtract(item)];
3165
+ }
3166
+ else {
3167
+ return [item];
3168
+ }
3169
+ });
3170
+ }
3171
+ else {
3172
+ try {
3173
+ return backingItem.difference(items);
3174
+ }
3175
+ catch (e) {
3176
+ return backingItem;
3177
+ }
3178
+ }
3179
+ });
3180
+ return new SortedSet(this.sortArray(filtered));
3181
+ }
3182
+ clear() {
3183
+ this.backingArray = [];
3184
+ }
3185
+ }
3186
+
3187
+ (function (exports) {
3188
+ var __createBinding = (commonjsGlobal && commonjsGlobal.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3189
+ if (k2 === undefined) k2 = k;
3190
+ Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
3191
+ }) : (function(o, m, k, k2) {
3192
+ if (k2 === undefined) k2 = k;
3193
+ o[k2] = m[k];
3194
+ }));
3195
+ var __exportStar = (commonjsGlobal && commonjsGlobal.__exportStar) || function(m, exports) {
3196
+ for (var p in m) if (p !== "default" && !exports.hasOwnProperty(p)) __createBinding(exports, m, p);
3197
+ };
3198
+ Object.defineProperty(exports, "__esModule", { value: true });
3199
+ /**
3200
+ * Exposes all the library's modules making them available from the "ip-num" module.
3201
+ * Making it possible to get access to all any of the modules by doing require("ip-num")
3202
+ *
3203
+ * @example
3204
+ * let ipNum = require("ip-num")
3205
+ * ipNum.IPv4CidrRange // gets access to IPv4CidrRange
3206
+ * ipNum.Asn // gets access to Asn
3207
+ */
3208
+ __exportStar(BinaryUtils, exports);
3209
+ __exportStar(Hexadecatet$1, exports);
3210
+ __exportStar(requireHexadecimalUtils(), exports);
3211
+ __exportStar(IPNumber, exports);
3212
+ __exportStar(IPNumType, exports);
3213
+ __exportStar(IPPool, exports);
3214
+ __exportStar(IPRange, exports);
3215
+ __exportStar(requireIPv6Utils(), exports);
3216
+ __exportStar(Octet$1, exports);
3217
+ __exportStar(Prefix, exports);
3218
+ __exportStar(requireValidator(), exports);
3219
+
3220
+ } (ipNum));
3221
+
3222
+ var isValidIPv4Range = function isValidIPv4Range(ipStart, ipEnd) {
3223
+ var ipStartAddr = ipNum.IPv4.fromDecimalDottedString(ipStart);
3224
+ var ipEndAddr = ipNum.IPv4.fromDecimalDottedString(ipEnd);
3225
+ return ipStartAddr.isLessThanOrEquals(ipEndAddr);
3226
+ };
3227
+ var isValidIPv4String = function isValidIPv4String(ip) {
3228
+ if (isNil(ip)) {
3229
+ return false;
3230
+ }
3231
+ var _Validator$isValidIPv = ipNum.Validator.isValidIPv4String(ip),
3232
+ _Validator$isValidIPv2 = _slicedToArray(_Validator$isValidIPv, 1),
3233
+ isValid = _Validator$isValidIPv2[0];
3234
+ return isValid;
3235
+ };
3236
+ yup.addMethod(yup.string, "validIPv4", function (errorMessage) {
3237
+ return this.test("validIpV4", errorMessage, function (value) {
3238
+ if (isNil(value)) {
3239
+ return this;
3240
+ }
3241
+ var _Validator$isValidIPv3 = ipNum.Validator.isValidIPv4String(value),
3242
+ _Validator$isValidIPv4 = _slicedToArray(_Validator$isValidIPv3, 1),
3243
+ isValid = _Validator$isValidIPv4[0];
3244
+ return isValid || this.createError({
3245
+ path: this.path,
3246
+ message: errorMessage
3247
+ });
3248
+ });
3249
+ });
3250
+ var getIpRestrictionValidationSchema = function getIpRestrictionValidationSchema() {
3251
+ return yup.object().shape({
3252
+ ipStart: yup.string().validIPv4(t("neetoMolecules.ipRestriction.validations.invalidIp")).required(),
3253
+ ipEnd: yup.string().validIPv4(t("neetoMolecules.ipRestriction.validations.invalidIp")).when("ipStart", function (ipStart, schema) {
3254
+ return schema.test({
3255
+ test: function test(ipEnd) {
3256
+ return isValidIPv4String(ipEnd) && isValidIPv4String(ipStart) && isValidIPv4Range(ipStart, ipEnd);
3257
+ },
3258
+ message: t("neetoMolecules.ipRestriction.validations.ipEndGreaterThanIpStart")
3259
+ });
3260
+ }).required()
3261
+ });
3262
+ };
3263
+
3264
+ var FormRow = function FormRow(_ref) {
3265
+ var data = _ref.data,
3266
+ isAddNew = _ref.isAddNew,
3267
+ onCollapse = _ref.onCollapse;
3268
+ var _useState = useState(false),
3269
+ _useState2 = _slicedToArray(_useState, 2),
3270
+ isSubmitted = _useState2[0],
3271
+ setIsSubmitted = _useState2[1];
3272
+ var _useCreateAllowedIpRa = useCreateAllowedIpRanges(),
3273
+ createAllowedIpRange = _useCreateAllowedIpRa.mutate;
3274
+ var _useUpdateAllowedIpRa = useUpdateAllowedIpRanges(),
3275
+ updateAllowedIpRange = _useUpdateAllowedIpRa.mutate;
3276
+ var _useTranslation = useTranslation(),
3277
+ t = _useTranslation.t;
3278
+ var handleSubmit = function handleSubmit(values) {
3279
+ if (isAddNew) {
3280
+ createAllowedIpRange(values);
3281
+ } else {
3282
+ updateAllowedIpRange({
3283
+ id: data.id,
3284
+ payload: values
3285
+ });
3286
+ }
3287
+ onCollapse();
3288
+ };
3289
+ return /*#__PURE__*/React.createElement(Form, {
3290
+ formikProps: {
3291
+ initialValues: data,
3292
+ validateOnBlur: isSubmitted,
3293
+ validateOnChange: isSubmitted,
3294
+ validationSchema: getIpRestrictionValidationSchema(),
3295
+ onSubmit: handleSubmit
3296
+ }
3297
+ }, /*#__PURE__*/React.createElement("div", {
3298
+ className: "neeto-ui-bg-white flex w-full flex-row justify-between px-2 py-2"
3299
+ }, /*#__PURE__*/React.createElement(Input, {
3300
+ autoFocus: true,
3301
+ className: "w-5/12 flex-grow px-3 py-2 text-left",
3302
+ name: "ipStart",
3303
+ placeholder: t("neetoMolecules.ipRestriction.ipStart")
3304
+ }), /*#__PURE__*/React.createElement(Input, {
3305
+ className: "w-5/12 flex-grow px-3 py-2 text-left",
3306
+ name: "ipEnd",
3307
+ placeholder: t("neetoMolecules.ipRestriction.ipEnd")
3308
+ }), /*#__PURE__*/React.createElement("div", {
3309
+ className: "w-5/12 flex-grow px-3 py-2 text-center"
3310
+ }, /*#__PURE__*/React.createElement(Button, {
3311
+ icon: Check,
3312
+ style: "text",
3313
+ type: "submit",
3314
+ tooltipProps: {
3315
+ content: "Submit",
3316
+ position: "top"
3317
+ },
3318
+ onClick: function onClick() {
3319
+ return setIsSubmitted(true);
3320
+ }
3321
+ }), /*#__PURE__*/React.createElement(Button$1, {
3322
+ icon: Close,
3323
+ style: "text",
3324
+ type: "reset",
3325
+ tooltipProps: {
3326
+ content: "Cancel",
3327
+ position: "top"
3328
+ },
3329
+ onClick: onCollapse
3330
+ }))));
3331
+ };
3332
+
3333
+ var Row = function Row(_ref) {
3334
+ var data = _ref.data,
3335
+ setEditingRow = _ref.setEditingRow;
3336
+ var _useState = useState(false),
3337
+ _useState2 = _slicedToArray(_useState, 2),
3338
+ isDeleteIpRangeAlertOpen = _useState2[0],
3339
+ setIsDeleteIpRangeAlertOpen = _useState2[1];
3340
+ var _useDestroyAllowedIpR = useDestroyAllowedIpRanges(),
3341
+ destroyAllowedIpRange = _useDestroyAllowedIpR.mutate;
3342
+ var _useTranslation = useTranslation(),
3343
+ t = _useTranslation.t;
3344
+ var handleDelete = function handleDelete() {
3345
+ destroyAllowedIpRange(data.id);
3346
+ setIsDeleteIpRangeAlertOpen(false);
3347
+ };
3348
+ return /*#__PURE__*/React.createElement("div", {
3349
+ className: "flex w-full flex-row justify-between bg-white px-1 py-2"
3350
+ }, /*#__PURE__*/React.createElement(Typography, {
3351
+ className: "w-4/12 flex-grow px-3 py-2 text-left",
3352
+ style: "body2"
3353
+ }, data.ipStart), /*#__PURE__*/React.createElement(Typography, {
3354
+ className: "w-4/12 flex-grow px-3 py-2 text-left",
3355
+ style: "body2"
3356
+ }, data.ipEnd), /*#__PURE__*/React.createElement("div", {
3357
+ className: "w-4/12 flex-grow px-3 py-2 text-center"
3358
+ }, /*#__PURE__*/React.createElement(Button$1, {
3359
+ icon: Delete,
3360
+ style: "text",
3361
+ tooltipProps: {
3362
+ content: "Delete",
3363
+ position: "top"
3364
+ },
3365
+ onClick: function onClick() {
3366
+ return setIsDeleteIpRangeAlertOpen(true);
3367
+ }
3368
+ }), /*#__PURE__*/React.createElement(Alert, {
3369
+ cancelButtonLabel: t("neetoMolecules.common.deleteAlert.no"),
3370
+ isOpen: isDeleteIpRangeAlertOpen,
3371
+ submitButtonLabel: t("neetoMolecules.common.deleteAlert.yes"),
3372
+ message: t("neetoMolecules.ipRestriction.allowedIpRangeConfirmation", data),
3373
+ title: t("neetoMolecules.common.deleteAlert.title", {
3374
+ entity: t("neetoMolecules.ipRestriction.allowedIpRangeTitle")
3375
+ }),
3376
+ onClose: function onClose() {
3377
+ return setIsDeleteIpRangeAlertOpen(false);
3378
+ },
3379
+ onSubmit: handleDelete
3380
+ }), /*#__PURE__*/React.createElement(Button$1, {
3381
+ icon: Edit,
3382
+ style: "text",
3383
+ tooltipProps: {
3384
+ content: "Edit",
3385
+ position: "top"
3386
+ },
3387
+ onClick: function onClick() {
3388
+ return setEditingRow(data.id);
3389
+ }
3390
+ })));
3391
+ };
3392
+
3393
+ var AllowedIpRanges = function AllowedIpRanges() {
3394
+ var _useState = useState(""),
3395
+ _useState2 = _slicedToArray(_useState, 2),
3396
+ editingRow = _useState2[0],
3397
+ setEditingRow = _useState2[1];
3398
+ var _useState3 = useState(false),
3399
+ _useState4 = _slicedToArray(_useState3, 2),
3400
+ showAddNew = _useState4[0],
3401
+ setShowAddNew = _useState4[1];
3402
+ var _useTranslation = useTranslation(),
3403
+ t = _useTranslation.t;
3404
+ var _useFetchAllowedIpRan = useFetchAllowedIpRanges(),
3405
+ allowedIpRanges = _useFetchAllowedIpRan.data;
3406
+ return /*#__PURE__*/React.createElement("div", {
3407
+ className: "space-y-4"
3408
+ }, /*#__PURE__*/React.createElement("div", {
3409
+ className: "flex flex-row items-center"
3410
+ }, /*#__PURE__*/React.createElement(Typography, {
3411
+ style: "h3"
3412
+ }, t("neetoMolecules.ipRestriction.allowedIpRangeTitle")), /*#__PURE__*/React.createElement(Button$1, {
3413
+ className: "ml-2",
3414
+ disabled: showAddNew,
3415
+ icon: Plus,
3416
+ size: "small",
3417
+ tooltipProps: {
3418
+ content: "Add",
3419
+ position: "top"
3420
+ },
3421
+ onClick: function onClick() {
3422
+ return setShowAddNew(true);
3423
+ }
3424
+ })), /*#__PURE__*/React.createElement("div", {
3425
+ className: "neeto-ui-text-gray-500 flex w-full flex-row justify-between"
3426
+ }, /*#__PURE__*/React.createElement(Typography, {
3427
+ className: "w-4/12 flex-grow px-3 py-2 text-left"
3428
+ }, t("neetoMolecules.ipRestriction.ipStart")), /*#__PURE__*/React.createElement(Typography, {
3429
+ className: "w-4/12 flex-grow px-3 py-2 text-left"
3430
+ }, t("neetoMolecules.ipRestriction.ipEnd")), /*#__PURE__*/React.createElement(Typography, {
3431
+ className: "w-4/12 flex-grow px-3 py-2 text-center"
3432
+ }, t("neetoMolecules.ipRestriction.actions"))), /*#__PURE__*/React.createElement("div", {
3433
+ className: "items-between flex w-full flex-col space-y-2"
3434
+ }, showAddNew && /*#__PURE__*/React.createElement(FormRow, {
3435
+ isAddNew: true,
3436
+ data: INITIAL_VALUES,
3437
+ onCollapse: function onCollapse() {
3438
+ return setShowAddNew(false);
3439
+ }
3440
+ }), allowedIpRanges === null || allowedIpRanges === void 0 ? void 0 : allowedIpRanges.map(function (allowedIpRange) {
3441
+ return editingRow === allowedIpRange.id ? /*#__PURE__*/React.createElement(FormRow, {
3442
+ data: allowedIpRange,
3443
+ isAddNew: false,
3444
+ key: allowedIpRange.id,
3445
+ onCollapse: function onCollapse() {
3446
+ return setEditingRow("");
3447
+ }
3448
+ }) : /*#__PURE__*/React.createElement(Row, {
3449
+ data: allowedIpRange,
3450
+ key: allowedIpRange.id,
3451
+ setEditingRow: setEditingRow
3452
+ });
3453
+ })));
3454
+ };
3455
+
3456
+ var show$1 = function show(params) {
3457
+ return axios.get("".concat(IP_RESTRICTIONS_ENGINE_BASE_URL, "/current_ip"), {
3458
+ params: params
3459
+ });
3460
+ };
3461
+ var currentIpApi = {
3462
+ show: show$1
3463
+ };
3464
+
3465
+ var CURRENT_IP = QUERY_KEYS.CURRENT_IP;
3466
+ var useShowCurrentIp = function useShowCurrentIp() {
3467
+ return useQuery([CURRENT_IP], function () {
3468
+ return currentIpApi.show();
3469
+ });
3470
+ };
3471
+
3472
+ var CurrentIp = function CurrentIp() {
3473
+ var _useShowCurrentIp = useShowCurrentIp(),
3474
+ data = _useShowCurrentIp.data,
3475
+ isLoading = _useShowCurrentIp.isLoading;
3476
+ var _useTranslation = useTranslation(),
3477
+ t = _useTranslation.t;
3478
+ return /*#__PURE__*/React.createElement("div", {
3479
+ className: "space-y-1"
3480
+ }, /*#__PURE__*/React.createElement(Typography, null, t("neetoMolecules.ipRestriction.currentIpTitle")), /*#__PURE__*/React.createElement(Typography, {
3481
+ weight: "semibold"
3482
+ }, isLoading ? "..." : data.ip), /*#__PURE__*/React.createElement(Typography, {
3483
+ style: "body2"
3484
+ }, t("neetoMolecules.ipRestriction.currentIpDescription")));
3485
+ };
3486
+
3487
+ var ipRestrictionUrl = "".concat(IP_RESTRICTIONS_ENGINE_BASE_URL, "/ip_restriction");
3488
+ var update = function update(params) {
3489
+ return axios.patch(ipRestrictionUrl, {
3490
+ ipRestriction: params
3491
+ });
3492
+ };
3493
+ var show = function show() {
3494
+ return axios.get(ipRestrictionUrl);
3495
+ };
3496
+ var ipRestrictionApi = {
3497
+ update: update,
3498
+ show: show
3499
+ };
3500
+
3501
+ var IP_RESTRICTION = QUERY_KEYS.IP_RESTRICTION;
3502
+ var useShowIpRestriction = function useShowIpRestriction() {
3503
+ return useQuery([IP_RESTRICTION], function () {
3504
+ return ipRestrictionApi.show();
3505
+ });
3506
+ };
3507
+ var useUpdateIpRestriction = function useUpdateIpRestriction() {
3508
+ var queryClient = useQueryClient();
3509
+ return useMutation(ipRestrictionApi.update, {
3510
+ onSuccess: function onSuccess() {
3511
+ return queryClient.invalidateQueries(IP_RESTRICTION);
3512
+ }
3513
+ });
3514
+ };
3515
+
3516
+ var IpRestriction = function IpRestriction() {
3517
+ var _useShowIpRestriction = useShowIpRestriction(),
3518
+ data = _useShowIpRestriction.data,
3519
+ isFetching = _useShowIpRestriction.isLoading;
3520
+ var _useUpdateIpRestricti = useUpdateIpRestriction(),
3521
+ updateIpRestriction = _useUpdateIpRestricti.mutate,
3522
+ isUpdating = _useUpdateIpRestricti.isLoading;
3523
+ var _useTranslation = useTranslation(),
3524
+ t = _useTranslation.t;
3525
+ var handleSwitchButtonChange = function handleSwitchButtonChange(e) {
3526
+ var payload = {
3527
+ isIpRestrictionEnabled: e.target.checked
3528
+ };
3529
+ updateIpRestriction(payload);
3530
+ };
3531
+ if (isFetching) {
3532
+ return /*#__PURE__*/React.createElement("div", {
3533
+ className: "flex items-center justify-center"
3534
+ }, /*#__PURE__*/React.createElement(Spinner, null));
3535
+ }
3536
+ return /*#__PURE__*/React.createElement("div", {
3537
+ className: "mx-auto mb-4 w-full max-w-3xl space-y-4 rounded-sm border bg-white"
3538
+ }, /*#__PURE__*/React.createElement("div", {
3539
+ className: "space-y-1 p-4"
3540
+ }, /*#__PURE__*/React.createElement(Switch, {
3541
+ checked: data.isIpRestrictionEnabled,
3542
+ disabled: isFetching || isUpdating,
3543
+ label: t("neetoMolecules.ipRestriction.switchLabel"),
3544
+ onChange: handleSwitchButtonChange
3545
+ }), /*#__PURE__*/React.createElement(Typography, {
3546
+ style: "body3"
3547
+ }, t("neetoMolecules.ipRestriction.description"))), data.isIpRestrictionEnabled && /*#__PURE__*/React.createElement("div", {
3548
+ className: "neeto-ui-bg-gray-100 w-full space-y-4 p-4"
3549
+ }, /*#__PURE__*/React.createElement(CurrentIp, null), /*#__PURE__*/React.createElement(AllowedIpRanges, null)));
3550
+ };
3551
+
3552
+ export { IpRestriction as default };