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