mybase 1.2.2 → 2.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 (194) hide show
  1. package/dist/funcs/Geoip2Paths.js.map +1 -0
  2. package/dist/funcs/MaxRuntimeHours.js.map +1 -0
  3. package/dist/funcs/asJSON.js.map +1 -0
  4. package/dist/funcs/deepCopy.js.map +1 -0
  5. package/dist/funcs/ensureFolder.js.map +1 -0
  6. package/dist/funcs/fileCacheIsValid.js.map +1 -0
  7. package/dist/funcs/getMysql1.js.map +1 -0
  8. package/dist/funcs/getMysql2.js.map +1 -0
  9. package/dist/funcs/getWeekNumber.js.map +1 -0
  10. package/dist/funcs/hash_sha512.js.map +1 -0
  11. package/dist/funcs/initMysql2Pool.js.map +1 -0
  12. package/dist/funcs/int2ip.js.map +1 -0
  13. package/dist/funcs/ip2int.js.map +1 -0
  14. package/dist/funcs/isLANIp.d.ts +2 -0
  15. package/{ts → dist}/funcs/isLANIp.js +6 -6
  16. package/dist/funcs/isLANIp.js.map +1 -0
  17. package/dist/funcs/isLocal.js.map +1 -0
  18. package/dist/funcs/isLoopbackIP.d.ts +2 -0
  19. package/{ts → dist}/funcs/isLoopbackIP.js +3 -3
  20. package/dist/funcs/isLoopbackIP.js.map +1 -0
  21. package/dist/funcs/knexConnection.js.map +1 -0
  22. package/dist/funcs/promiseTimeout.js.map +1 -0
  23. package/dist/funcs/randomIP.js.map +1 -0
  24. package/dist/funcs/randomIP6.js.map +1 -0
  25. package/dist/funcs/randomString.js.map +1 -0
  26. package/dist/funcs/randomTCPPort.js.map +1 -0
  27. package/dist/funcs/randomUTFString.js.map +1 -0
  28. package/dist/funcs/utcnow.js.map +1 -0
  29. package/dist/funcs/validEmail.js.map +1 -0
  30. package/dist/funcs/validIp.js.map +1 -0
  31. package/dist/funcs/vaultFill.js.map +1 -0
  32. package/dist/funcs/vaultRead.js.map +1 -0
  33. package/dist/funcs/wait.js.map +1 -0
  34. package/dist/global.js.map +1 -0
  35. package/dist/index.d.ts +38 -0
  36. package/{ts → dist}/index.js +35 -27
  37. package/dist/index.js.map +1 -0
  38. package/dist/ip6addr.d.ts +69 -0
  39. package/dist/ip6addr.js +752 -0
  40. package/dist/ip6addr.js.map +1 -0
  41. package/dist/models/DateIterator.js.map +1 -0
  42. package/{ts → dist}/models/IPAddress.d.ts +2 -1
  43. package/{ts → dist}/models/IPAddress.js +11 -12
  44. package/dist/models/IPAddress.js.map +1 -0
  45. package/dist/models/Interfaces.js.map +1 -0
  46. package/dist/models/OTPGenerator.js.map +1 -0
  47. package/dist/models/Timespan.js.map +1 -0
  48. package/dist/models/Unixtime.js.map +1 -0
  49. package/{mybase.d.ts → dist/mybase.d.ts} +1 -20
  50. package/{mybase.js → dist/mybase.js} +1 -56
  51. package/dist/mybase.js.map +1 -0
  52. package/{ts → dist}/types.d.ts +10 -0
  53. package/dist/types.js.map +1 -0
  54. package/package.json +22 -9
  55. package/ip6addr.d.ts +0 -61
  56. package/jest/isLANIp.test.js +0 -36
  57. package/jest/isLoopbackIP.test.js +0 -31
  58. package/jest.config.js +0 -13
  59. package/mybase.test.ts +0 -647
  60. package/mybase.ts +0 -397
  61. package/ts/funcs/Geoip2Paths.test.ts +0 -11
  62. package/ts/funcs/Geoip2Paths.ts +0 -28
  63. package/ts/funcs/MaxRuntimeHours.ts +0 -7
  64. package/ts/funcs/asJSON.test.js +0 -72
  65. package/ts/funcs/asJSON.ts +0 -9
  66. package/ts/funcs/deepCopy.test.ts +0 -108
  67. package/ts/funcs/deepCopy.ts +0 -34
  68. package/ts/funcs/ensureFolder.test.ts +0 -79
  69. package/ts/funcs/ensureFolder.ts +0 -21
  70. package/ts/funcs/fileCacheIsValid.ts +0 -13
  71. package/ts/funcs/getMysql1.ts +0 -41
  72. package/ts/funcs/getMysql2.ts +0 -42
  73. package/ts/funcs/getWeekNumber.test.ts +0 -9
  74. package/ts/funcs/getWeekNumber.ts +0 -31
  75. package/ts/funcs/hash_sha512.ts +0 -6
  76. package/ts/funcs/initMysql2Pool.ts +0 -11
  77. package/ts/funcs/int2ip.test.js +0 -33
  78. package/ts/funcs/int2ip.ts +0 -9
  79. package/ts/funcs/ip2int.test.js +0 -30
  80. package/ts/funcs/ip2int.ts +0 -10
  81. package/ts/funcs/isLANIp.d.ts +0 -2
  82. package/ts/funcs/isLANIp.test.ts +0 -58
  83. package/ts/funcs/isLANIp.ts +0 -34
  84. package/ts/funcs/isLocal.test.ts +0 -16
  85. package/ts/funcs/isLocal.ts +0 -5
  86. package/ts/funcs/isLoopbackIP.d.ts +0 -2
  87. package/ts/funcs/isLoopbackIP.test.ts +0 -72
  88. package/ts/funcs/isLoopbackIP.ts +0 -30
  89. package/ts/funcs/knexConnection.ts +0 -42
  90. package/ts/funcs/promiseTimeout.test.js +0 -104
  91. package/ts/funcs/promiseTimeout.ts +0 -19
  92. package/ts/funcs/randomIP.test.ts +0 -16
  93. package/ts/funcs/randomIP.ts +0 -10
  94. package/ts/funcs/randomIP6.test.js +0 -18
  95. package/ts/funcs/randomIP6.ts +0 -12
  96. package/ts/funcs/randomString.test.ts +0 -15
  97. package/ts/funcs/randomString.ts +0 -5
  98. package/ts/funcs/randomTCPPort.test.ts +0 -62
  99. package/ts/funcs/randomTCPPort.ts +0 -58
  100. package/ts/funcs/randomUTFString.test.ts +0 -44
  101. package/ts/funcs/randomUTFString.ts +0 -33
  102. package/ts/funcs/utcnow.ts +0 -5
  103. package/ts/funcs/validEmail.test.js +0 -31
  104. package/ts/funcs/validEmail.ts +0 -11
  105. package/ts/funcs/validIp.test.ts +0 -33
  106. package/ts/funcs/validIp.ts +0 -5
  107. package/ts/funcs/vaultFill.ts +0 -89
  108. package/ts/funcs/vaultRead.ts +0 -50
  109. package/ts/funcs/wait.ts +0 -7
  110. package/ts/global.ts +0 -10
  111. package/ts/index.d.ts +0 -35
  112. package/ts/index.test.ts +0 -7
  113. package/ts/index.ts +0 -39
  114. package/ts/models/DateIterator.test.ts +0 -149
  115. package/ts/models/DateIterator.ts +0 -80
  116. package/ts/models/IPAddress.test.ts +0 -393
  117. package/ts/models/IPAddress.ts +0 -272
  118. package/ts/models/Interfaces.ts +0 -58
  119. package/ts/models/OTPGenerator.test.ts +0 -42
  120. package/ts/models/OTPGenerator.ts +0 -43
  121. package/ts/models/Timespan.ts +0 -80
  122. package/ts/models/Unixtime.test.ts +0 -168
  123. package/ts/models/Unixtime.ts +0 -208
  124. package/ts/types.ts +0 -42
  125. package/tsconfig.jest.json +0 -11
  126. package/tsconfig.json +0 -37
  127. package/types/third-party.d.ts +0 -21
  128. /package/{ts → dist}/funcs/Geoip2Paths.d.ts +0 -0
  129. /package/{ts → dist}/funcs/Geoip2Paths.js +0 -0
  130. /package/{ts → dist}/funcs/MaxRuntimeHours.d.ts +0 -0
  131. /package/{ts → dist}/funcs/MaxRuntimeHours.js +0 -0
  132. /package/{ts → dist}/funcs/asJSON.d.ts +0 -0
  133. /package/{ts → dist}/funcs/asJSON.js +0 -0
  134. /package/{ts → dist}/funcs/deepCopy.d.ts +0 -0
  135. /package/{ts → dist}/funcs/deepCopy.js +0 -0
  136. /package/{ts → dist}/funcs/ensureFolder.d.ts +0 -0
  137. /package/{ts → dist}/funcs/ensureFolder.js +0 -0
  138. /package/{ts → dist}/funcs/fileCacheIsValid.d.ts +0 -0
  139. /package/{ts → dist}/funcs/fileCacheIsValid.js +0 -0
  140. /package/{ts → dist}/funcs/getMysql1.d.ts +0 -0
  141. /package/{ts → dist}/funcs/getMysql1.js +0 -0
  142. /package/{ts → dist}/funcs/getMysql2.d.ts +0 -0
  143. /package/{ts → dist}/funcs/getMysql2.js +0 -0
  144. /package/{ts → dist}/funcs/getWeekNumber.d.ts +0 -0
  145. /package/{ts → dist}/funcs/getWeekNumber.js +0 -0
  146. /package/{ts → dist}/funcs/hash_sha512.d.ts +0 -0
  147. /package/{ts → dist}/funcs/hash_sha512.js +0 -0
  148. /package/{ts → dist}/funcs/initMysql2Pool.d.ts +0 -0
  149. /package/{ts → dist}/funcs/initMysql2Pool.js +0 -0
  150. /package/{ts → dist}/funcs/int2ip.d.ts +0 -0
  151. /package/{ts → dist}/funcs/int2ip.js +0 -0
  152. /package/{ts → dist}/funcs/ip2int.d.ts +0 -0
  153. /package/{ts → dist}/funcs/ip2int.js +0 -0
  154. /package/{ts → dist}/funcs/isLocal.d.ts +0 -0
  155. /package/{ts → dist}/funcs/isLocal.js +0 -0
  156. /package/{ts → dist}/funcs/knexConnection.d.ts +0 -0
  157. /package/{ts → dist}/funcs/knexConnection.js +0 -0
  158. /package/{ts → dist}/funcs/promiseTimeout.d.ts +0 -0
  159. /package/{ts → dist}/funcs/promiseTimeout.js +0 -0
  160. /package/{ts → dist}/funcs/randomIP.d.ts +0 -0
  161. /package/{ts → dist}/funcs/randomIP.js +0 -0
  162. /package/{ts → dist}/funcs/randomIP6.d.ts +0 -0
  163. /package/{ts → dist}/funcs/randomIP6.js +0 -0
  164. /package/{ts → dist}/funcs/randomString.d.ts +0 -0
  165. /package/{ts → dist}/funcs/randomString.js +0 -0
  166. /package/{ts → dist}/funcs/randomTCPPort.d.ts +0 -0
  167. /package/{ts → dist}/funcs/randomTCPPort.js +0 -0
  168. /package/{ts → dist}/funcs/randomUTFString.d.ts +0 -0
  169. /package/{ts → dist}/funcs/randomUTFString.js +0 -0
  170. /package/{ts → dist}/funcs/utcnow.d.ts +0 -0
  171. /package/{ts → dist}/funcs/utcnow.js +0 -0
  172. /package/{ts → dist}/funcs/validEmail.d.ts +0 -0
  173. /package/{ts → dist}/funcs/validEmail.js +0 -0
  174. /package/{ts → dist}/funcs/validIp.d.ts +0 -0
  175. /package/{ts → dist}/funcs/validIp.js +0 -0
  176. /package/{ts → dist}/funcs/vaultFill.d.ts +0 -0
  177. /package/{ts → dist}/funcs/vaultFill.js +0 -0
  178. /package/{ts → dist}/funcs/vaultRead.d.ts +0 -0
  179. /package/{ts → dist}/funcs/vaultRead.js +0 -0
  180. /package/{ts → dist}/funcs/wait.d.ts +0 -0
  181. /package/{ts → dist}/funcs/wait.js +0 -0
  182. /package/{ts → dist}/global.d.ts +0 -0
  183. /package/{ts → dist}/global.js +0 -0
  184. /package/{ts → dist}/models/DateIterator.d.ts +0 -0
  185. /package/{ts → dist}/models/DateIterator.js +0 -0
  186. /package/{ts → dist}/models/Interfaces.d.ts +0 -0
  187. /package/{ts → dist}/models/Interfaces.js +0 -0
  188. /package/{ts → dist}/models/OTPGenerator.d.ts +0 -0
  189. /package/{ts → dist}/models/OTPGenerator.js +0 -0
  190. /package/{ts → dist}/models/Timespan.d.ts +0 -0
  191. /package/{ts → dist}/models/Timespan.js +0 -0
  192. /package/{ts → dist}/models/Unixtime.d.ts +0 -0
  193. /package/{ts → dist}/models/Unixtime.js +0 -0
  194. /package/{ts → dist}/types.js +0 -0
@@ -1,104 +0,0 @@
1
- const { promiseTimeout } = require('./promiseTimeout');
2
-
3
- describe('promiseTimeout', () => {
4
-
5
- // Returns a promise that resolves when inputPromise resolves before the timeout.
6
- it('should resolve when inputPromise resolves before the timeout', () => {
7
- // Arrange
8
- const inputPromise = new Promise((resolve) => {
9
- setTimeout(() => {
10
- resolve('Resolved');
11
- }, 100);
12
- });
13
-
14
- // Act
15
- const resultPromise = promiseTimeout(200, inputPromise);
16
-
17
- // Assert
18
- return expect(resultPromise).resolves.toBe('Resolved');
19
- });
20
-
21
- // Returns a promise that rejects with onTimeout when inputPromise rejects after the timeout.
22
- it('should reject with onTimeout when inputPromise rejects after the timeout', () => {
23
- // Arrange
24
- const inputPromise = new Promise((resolve, reject) => {
25
- setTimeout(() => {
26
- reject('Rejected');
27
- }, 200);
28
- });
29
-
30
- // Act
31
- const resultPromise = promiseTimeout(100, inputPromise);
32
-
33
- // Assert
34
- return expect(resultPromise).rejects.toBe('TIMEDOUT');
35
- });
36
-
37
- // Returns a promise that rejects with onTimeout when inputPromise is pending after the timeout.
38
- it('should reject with onTimeout when inputPromise is pending after the timeout', () => {
39
- // Arrange
40
- const inputPromise = new Promise(() => { });
41
-
42
- // Act
43
- const resultPromise = promiseTimeout(100, inputPromise);
44
-
45
- // Assert
46
- return expect(resultPromise).rejects.toBe('TIMEDOUT');
47
- });
48
-
49
- // Returns a promise that resolves with inputPromise value when inputPromise resolves before the timeout.
50
- it('should resolve with inputPromise value when inputPromise resolves before the timeout', () => {
51
- // Arrange
52
- const inputPromise = new Promise((resolve) => {
53
- setTimeout(() => {
54
- resolve('Resolved');
55
- }, 100);
56
- });
57
-
58
- // Act
59
- const resultPromise = promiseTimeout(200, inputPromise);
60
-
61
- // Assert
62
- return expect(resultPromise).resolves.toBe('Resolved');
63
- });
64
-
65
- // Returns a promise that rejects with inputPromise value when inputPromise rejects before the timeout.
66
- it('should reject with inputPromise value when inputPromise rejects before the timeout', () => {
67
- // Arrange
68
- const inputPromise = new Promise((resolve, reject) => {
69
- setTimeout(() => {
70
- reject('Rejected');
71
- }, 100);
72
- });
73
-
74
- // Act
75
- const resultPromise = promiseTimeout(200, inputPromise);
76
-
77
- // Assert
78
- return expect(resultPromise).rejects.toBe('Rejected');
79
- });
80
-
81
- // Returns a promise that rejects with inputPromise value when inputPromise is pending before the timeout.
82
- it('should reject with inputPromise value when inputPromise is pending before the timeout', () => {
83
- // Arrange
84
- const inputPromise = new Promise(() => { });
85
-
86
- // Act
87
- const resultPromise = promiseTimeout(200, inputPromise);
88
-
89
- // Assert
90
- return expect(resultPromise).rejects.toBe('TIMEDOUT');
91
- });
92
-
93
- // Returns a promise that resolves with undefined when inputPromise is undefined.
94
- it('should resolve with undefined when inputPromise is undefined', () => {
95
- // Arrange
96
- const inputPromise = undefined;
97
-
98
- // Act
99
- const resultPromise = promiseTimeout(200, inputPromise);
100
-
101
- // Assert
102
- return expect(resultPromise).resolves.toBe(undefined);
103
- });
104
- });
@@ -1,19 +0,0 @@
1
-
2
-
3
-
4
-
5
- export function promiseTimeout(miliseconds:number, inputPromise:Promise<any>, onTimeout:any='TIMEDOUT') { // ported
6
- // Create a promise that rejects in <miliseconds> milliseconds
7
- let timeout = new Promise((resolve, reject) => {
8
- let stID = setTimeout(() => {
9
- clearTimeout(stID);
10
- reject(onTimeout)
11
- }, miliseconds)
12
- })
13
-
14
- // Returns a race between our timeout and the passed in promise
15
- return Promise.race([
16
- inputPromise,
17
- timeout
18
- ])
19
- }
@@ -1,16 +0,0 @@
1
- import { randomIP } from './randomIP';
2
-
3
- describe('randomIP', () => {
4
- it('should return a valid IP address', () => {
5
- for(let i=0; i<1000; i++) {
6
- const ipAddress = randomIP();
7
- const ipParts = ipAddress.split('.');
8
- expect(ipParts.length).toBe(4);
9
- ipParts.forEach((part) => {
10
- const partInt = parseInt(part);
11
- expect(partInt).toBeGreaterThanOrEqual(0);
12
- expect(partInt).toBeLessThanOrEqual(255);
13
- });
14
- }
15
- });
16
- });
@@ -1,10 +0,0 @@
1
-
2
- export function randomIP() : string {
3
- function int2ip (ipInt: number) {
4
- return ( (ipInt>>>24) +'.' + (ipInt>>16 & 255) +'.' + (ipInt>>8 & 255) +'.' + (ipInt & 255) );
5
- }
6
- return int2ip(Math.random()*Math.pow(2,32))
7
- }
8
-
9
-
10
-
@@ -1,18 +0,0 @@
1
- const ip6 = require('ip6');
2
- const { randomIP6 } = require('./randomIP6');
3
-
4
- describe('randomIP6', () => {
5
- it('should generate a random IPv6 address', () => {
6
- const result = randomIP6();
7
- expect(()=>ip6.normalize(result)).not.toThrow()
8
- expect(()=>ip6.abbreviate(result)).not.toThrow()
9
- });
10
-
11
- it('generate 100 ipv6', () => {
12
- for (let i = 0; i < 100; i++) {
13
- const result = randomIP6();
14
- expect(()=>ip6.normalize(result)).not.toThrow()
15
- expect(()=>ip6.abbreviate(result)).not.toThrow()
16
- }
17
- })
18
- });
@@ -1,12 +0,0 @@
1
- import { randomBytes } from "crypto"
2
- // const ip6 = require('ip6')
3
- //@ts-ignore
4
- import ip6 from 'ip6'
5
-
6
- export function randomIP6() : string {
7
- const bytes = randomBytes(16)
8
- return ip6.abbreviate(ip6.normalize(bytes.toString('hex').match(/.{1,4}/g)?.join(':') || '0000:0000:0000:0000:0000:0000:0000:0000'))
9
- }
10
-
11
-
12
-
@@ -1,15 +0,0 @@
1
- import { randomString } from "./randomString";
2
-
3
- test('randomString', () => {
4
- // Test default length and character set
5
- expect(randomString()).toHaveLength(10);
6
- expect(randomString()).toMatch(/^[A-Za-z0-9]{10}$/);
7
-
8
- // Test custom length and character set
9
- expect(randomString(5, "abc")).toHaveLength(5);
10
- expect(randomString(5, "abc")).toMatch(/^[abc]{5}$/);
11
-
12
- // Test empty character set
13
- expect(randomString(10, "")).toHaveLength(0);
14
- expect(randomString(10, "")).toMatch(/^$/);
15
- });
@@ -1,5 +0,0 @@
1
-
2
-
3
- export function randomString(length = 10, charSet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"): string {
4
- return Array.from({ length }, () => charSet.charAt(Math.floor(Math.random() * charSet.length))).join('');
5
- }
@@ -1,62 +0,0 @@
1
- import { wait } from "./wait";
2
- import { randomTCPPort } from "./randomTCPPort";
3
-
4
-
5
- describe("randomTCPPort", () => {
6
- let fromPort = 15000;
7
- let untilPort = fromPort+1000;
8
- let hostToBind="127.0.0.1"
9
-
10
- beforeEach(() => {
11
- untilPort = fromPort+1000;
12
- })
13
-
14
- test("should return a random port number within the given range", async () => {
15
- const port = await randomTCPPort(1000, fromPort, untilPort, 1000, hostToBind);
16
- expect(port).toBeGreaterThanOrEqual(fromPort);
17
- expect(port).toBeLessThanOrEqual(untilPort);
18
- });
19
-
20
- test("should return false if no available port is found", async () => {
21
- untilPort = fromPort+1;
22
- // listen to the port 15000 and 15001 to simulate that these ports are in use
23
- const server1 = require("net").createServer();
24
- const server2 = require("net").createServer();
25
- server1.listen(fromPort, hostToBind);
26
- server2.listen(untilPort, hostToBind);
27
- // try to find a port within the range
28
- const port = await randomTCPPort(1000, fromPort, untilPort, 1000, hostToBind);
29
- expect(port).toBe(false);
30
- server1.close();
31
- server2.close();
32
- await wait(1/100)
33
- const port2 = await randomTCPPort(1000, fromPort, untilPort, 1000, hostToBind);
34
- expect(port2===fromPort || port2===untilPort).toBe(true);
35
- });
36
-
37
- test("should handle errors when trying to listen to a port", async () => {
38
- const port = await randomTCPPort(1000, fromPort, untilPort, 1000, "invalid-host");
39
- expect(port).toBe(false);
40
- })
41
-
42
- test("should return false if the given port range is invalid", async () => {
43
- const port = await randomTCPPort(1000, untilPort, fromPort, 1000, hostToBind);
44
- expect(port).toBe(false);
45
- });
46
-
47
- test("should return false if the given port range is invalid", async () => {
48
- const port = await randomTCPPort(1000, -1, untilPort, 1000, hostToBind);
49
- expect(port).toBe(false);
50
- });
51
-
52
- test("should return false if the given port range is invalid", async () => {
53
- const port = await randomTCPPort(1000, fromPort, -1, 1000, hostToBind);
54
- expect(port).toBe(false);
55
- });
56
-
57
- test("should return false if the given port range is invalid", async () => {
58
- const port = await randomTCPPort(1000, fromPort, 65536, 1000, hostToBind);
59
- expect(port).toBe(false);
60
- });
61
-
62
- })
@@ -1,58 +0,0 @@
1
- import * as net from 'net'
2
-
3
- /**
4
- * This function returns a random port number that is not in use and we should validate this port number by trying to listen to it and releasing
5
- * this port number immediately
6
- * This function should be used for testing purposes only
7
- * This function is not suitable for production use
8
- * @param timeout the timeout for each port check
9
- * @param fromPort the first port number to check defaults to 1025
10
- * @param untilPort the last port number to check defaults to 65534
11
- * @param tries the number of tries to find a port number
12
- * @param host the host to bind to
13
- */
14
- export async function randomTCPPort(timeout: number = 1000, fromPort: number = 1025, untilPort: number = 65534, tries = 1000, host = '127.0.0.1'): Promise<number | false> {
15
- return new Promise(async function (resolve, reject) {
16
- // check if the given port range is valid
17
- if (fromPort > untilPort) return resolve(false)
18
- // check if the given port range is valid
19
- if (fromPort < 0 || untilPort < 0) return resolve(false)
20
- // check if the given port range is valid
21
- if (fromPort > 65535 || untilPort > 65535) return resolve(false)
22
-
23
- // this function shall return a random port number that is not in use and we should validate this port number by trying to listen to it and releasing
24
- // this port number immediately
25
- // this function should be used for testing purposes only
26
- // this function is not suitable for production use
27
- while(true && tries > 0) {
28
- tries--
29
- let port = Math.floor(Math.random() * (untilPort - fromPort + 1) + fromPort)
30
- let server = net.createServer()
31
- let checkPort = new Promise((resolveInner, reject) => {
32
- server.on('error', (err) => {
33
- // any error should raise problem
34
- resolveInner(false)
35
- })
36
- server.on('listening', () => {
37
- resolveInner(true)
38
- })
39
- })
40
- server.listen(port, host)
41
- let result = await checkPort
42
- if (result) {
43
- let to = setTimeout(() => {
44
- return resolve(port)
45
- },1000)
46
- server.on('close', () => {
47
- clearTimeout(to)
48
- return resolve(port)
49
- })
50
- server.close()
51
- return
52
- } else server.close()
53
- }
54
- if (tries===0)
55
- return resolve(false)
56
- })
57
-
58
- }
@@ -1,44 +0,0 @@
1
- import { randomUTFString } from './randomUTFString';
2
-
3
- describe('randomUTFString', () => {
4
- const asciiCharacters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
5
- let extendedCharset =
6
- 'àáâãäåæçèéêëìíîïðñòóôõöøùúûüýÿ' + // Accented Latin characters
7
- 'ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩαβγδεζηθικλμνξοπρσςτυφχψω' + // Greek
8
- 'אבגדהוזחטיךכלםמןנסעפצקרשת' + // Hebrew
9
- //Arabic
10
- 'ا ب ت ث ج ح خ د ذ ر ز س ش ص ض ط ظ ع غ ف ق ك ل م ن ه و ي' +
11
- // Persian
12
- 'آ ا ب پ ت ث ج چ ح خ د ذ ر ز ژ س ش ص ض ط ظ ع غ ف ق ک گ ل م ن و ه ی' +
13
- // Turkish
14
- 'a b c ç d e f g ğ h ı i j k l m n o ö p r s ş t u ü v y z' +
15
- 'A B C Ç D E F G Ğ H I İ J K L M N O Ö P R S Ş T U Ü V Y Z' +
16
- // More Emojis
17
- '🙂🤔😍😂👍🚀❤️🎉' +
18
- 'абвгдежзийклмнопрстуфхцчшщъыьэюя' + // Cyrillic (Russian, etc.)
19
- '日本語中文한국어' + // Japanese, Chinese, Korean characters
20
- '🙂🤔😍😂👍🚀❤️🎉' // Emojis
21
- it('should generate a random string within the specified length range', () => {
22
- const minLength = 5;
23
- const maxLength = 10;
24
- const result = randomUTFString(minLength, maxLength);
25
- expect(result.length).toBeGreaterThanOrEqual(minLength);
26
- expect(result.length).toBeLessThanOrEqual(maxLength+1); // utf8 characters can be 1-4 bytes long
27
- });
28
-
29
- it('should include ASCII characters by default', () => {
30
- const result = randomUTFString(500, 400);
31
-
32
- expect(result).toMatch(new RegExp(`[${asciiCharacters}]`));
33
- });
34
-
35
- it('should exclude ASCII characters when includeAscii is set to false', () => {
36
- const result = randomUTFString(500, 1000, false);
37
- expect(result).not.toMatch(new RegExp(`[${asciiCharacters}]`));
38
- });
39
-
40
- it('should include extended characters when includeAscii is set to true', () => {
41
- const result = randomUTFString(500, 1000, true);
42
- expect(result).toMatch(new RegExp(`[${extendedCharset}]`));
43
- });
44
- });
@@ -1,33 +0,0 @@
1
-
2
-
3
-
4
- export function randomUTFString(minLength: number, maxLength: number, includeAscii:boolean=true): string {
5
- // Extended characters set including various languages and symbols
6
- let characters =
7
- 'àáâãäåæçèéêëìíîïðñòóôõöøùúûüýÿ' + // Accented Latin characters
8
- 'ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩαβγδεζηθικλμνξοπρσςτυφχψω' + // Greek
9
- 'אבגדהוזחטיךכלםמןנסעפצקרשת' + // Hebrew
10
- //Arabic
11
- 'ا ب ت ث ج ح خ د ذ ر ز س ش ص ض ط ظ ع غ ف ق ك ل م ن ه و ي' +
12
- // Persian
13
- 'آ ا ب پ ت ث ج چ ح خ د ذ ر ز ژ س ش ص ض ط ظ ع غ ف ق ک گ ل م ن و ه ی' +
14
- // Turkish
15
- 'ğıöşü' +
16
- 'ĞİÖŞÜ ' +
17
- // More Emojis
18
- '🙂🤔😍😂👍🚀❤️🎉' +
19
- 'бвгдежзийклмнопрстуфхцчшщъыьэюя' + // Cyrillic (Russian, etc.)
20
- '日本語中文한국어' + // Japanese, Chinese, Korean characters
21
- '🙂🤔😍😂👍🚀❤️🎉' // Emojis
22
-
23
- if (includeAscii) characters += 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
24
-
25
- const charactersLength = Array.from(characters).length
26
- const length = Math.floor(Math.random() * (maxLength - minLength + 1)) + minLength
27
- let result = ''
28
-
29
- for (let i = 0; i < length; i++)
30
- result += Array.from(characters)[Math.floor(Math.random() * charactersLength)]
31
-
32
- return result
33
- }
@@ -1,5 +0,0 @@
1
- import { UnixtimeShort } from '../types'
2
-
3
- export function utcnow() : UnixtimeShort {
4
- return Math.floor(Date.now() / 1000)
5
- }
@@ -1,31 +0,0 @@
1
- const { validEmail } = require('./validEmail')
2
-
3
- // since we use validator, we do not need to test it further
4
- // detailed tests with millions of emails are in tests/ folder which is .gitignored
5
-
6
- describe('validEmail', () => {
7
- test('should return true for a valid email', () => {
8
- const email = 'test@example.com'
9
- expect(validEmail(email)).toBe(true)
10
- })
11
-
12
- test('should return false for an invalid email', () => {
13
- const email = 'invalidemail'
14
- expect(validEmail(email)).toBe(false)
15
- })
16
-
17
- test('should return false for an empty email', () => {
18
- const email = ''
19
- expect(validEmail(email)).toBe(false)
20
- })
21
-
22
- test('should return false for a null email', () => {
23
- const email = null
24
- expect(validEmail(email)).toBe(false)
25
- })
26
-
27
- test('should return false for a non-string email', () => {
28
- const email = 12345
29
- expect(validEmail(email)).toBe(false)
30
- })
31
- })
@@ -1,11 +0,0 @@
1
- import validator from 'validator'
2
-
3
- export function validEmail(email: unknown): boolean {
4
- if (typeof email==='string')
5
- return validator.isEmail(email) // validator needs a string
6
- return false
7
- // giving up old style, was not reliable
8
- // taken from https://www.w3resource.com/javascript/form/email-validation.php
9
- // strange looking emails might be indeed valid
10
- // check https://www.w3resource.com/javascript/form/example-javascript-form-validation-email-REC-2822.html
11
- }
@@ -1,33 +0,0 @@
1
- import { validIp } from './validIp';
2
-
3
- describe('validIp', () => {
4
- it('should return true for a valid IP address', () => {
5
- const ipAddress = '192.168.0.1';
6
- const result = validIp(ipAddress);
7
- expect(result).toBe(4);
8
- });
9
-
10
- it('should return false for an invalid IP address', () => {
11
- const ipAddress = '256.0.0.1';
12
- const result = validIp(ipAddress);
13
- expect(result).toBe(0);
14
- });
15
-
16
- it('should support IPv6', () => {
17
- const ipAddress = '2001:0db8:85a3:0000:0000:8a2e:0370:7334';
18
- const result = validIp(ipAddress);
19
- expect(result).toBe(6);
20
- })
21
-
22
- it('invalid IPv6', () => {
23
- const ipAddress = '2001:0db8:85a3:0000:0000:8a2e:0370:7334:0000';
24
- const result = validIp(ipAddress);
25
- expect(result).toBe(0);
26
- })
27
-
28
- it('should support IPv6 shorthand', () => {
29
- const ipAddress = '2001:db8:85a3::8a2e:370:7334';
30
- const result = validIp(ipAddress);
31
- expect(result).toBe(6);
32
- })
33
- })
@@ -1,5 +0,0 @@
1
- import * as net from 'net'
2
-
3
- export function validIp(IPAddress: string): number {
4
- return net.isIP(IPAddress)
5
- }
@@ -1,89 +0,0 @@
1
- import { debug } from "debug"
2
- import nodeVault from "node-vault";
3
- import { vaultRead } from "./vaultRead";
4
- const dbg = debug('mybase')
5
-
6
- export function vaultFill(vaultInstance: nodeVault.client, inputObject: any, ignoreError = false, keepCache = true) {
7
- // v2.1
8
- // fills all strings with ^vault@/secret/... with proper vault values
9
- // if you call it again, it does reload the configuration
10
- // v2.2
11
- // supports keepCache - if vault fails, we will keep previous values instead of filling with false
12
- return new Promise(async function (resolve, reject) {
13
- let vaultKeys = Array<string>()
14
- let vaultResults: any = {}
15
- findVaultKeyMappings(inputObject, vaultKeys)
16
-
17
- // read these keys from vault
18
- for (let idx in vaultKeys) {
19
- const val = vaultKeys[idx]
20
- if (typeof val !== "string") continue
21
-
22
- try {
23
- let got = await vaultRead(vaultInstance, vaultKeys[idx])
24
- got['__vaultkey'] = val
25
- got['__vaultfilled'] = Date.now()
26
- vaultResults[val]=got
27
- }
28
- catch (err) {
29
-
30
- dbg(`Could not read vaultKey '${val}'`, err)
31
- if (!ignoreError) vaultResults[val]=false
32
- }
33
- }
34
-
35
- fillVaultKeyMappings(inputObject, vaultResults, keepCache)
36
-
37
- resolve(true)
38
- })
39
- }
40
-
41
-
42
- function findVaultKeyMappings(config: any, keys = Array<string>()) {
43
- for (var i in config) {
44
- if (config[i] !== null) {
45
- if (typeof config[i] === 'object' && (config[i].constructor.name === 'Array' || config[i].constructor.name === 'Object'))
46
- findVaultKeyMappings(config[i], keys)
47
-
48
- // detect previously read vaultKey
49
- if (i === '__vaultkey') {
50
- if (!keys.includes(vaultKey)) keys.push(config[i])
51
- continue
52
- }
53
- // --
54
- if (typeof config[i] === 'string' && config[i].search(/^vault@/) == 0) {
55
- var splitted = config[i].split(/vault@/)
56
- if (splitted.length == 2) {
57
- var vaultKey = splitted[1]
58
- if (!keys.includes(vaultKey)) keys.push(vaultKey)
59
- }
60
- }
61
- }
62
- }
63
- }
64
-
65
- function fillVaultKeyMappings(config: any, vaultResults:any, keepCache = true) {
66
- for (var i in config) {
67
- if (config[i] !== null) {
68
-
69
- if (config[i] && config[i].constructor.name === 'Object' && config[i].hasOwnProperty('__vaultkey')) {
70
- if (keepCache) {
71
- if (vaultResults[config[i]['__vaultkey']]) config[i] = vaultResults[config[i]['__vaultkey']]
72
- }
73
-
74
- else
75
- config[i] = vaultResults[config[i]['__vaultkey']]
76
- continue
77
- }
78
- if (typeof config[i] === 'object' && (config[i].constructor.name === 'Array' || config[i].constructor.name === 'Object'))
79
- fillVaultKeyMappings(config[i], vaultResults)
80
- if (typeof config[i] === 'string' && config[i].search(/^vault@/) == 0) {
81
- var splitted = config[i].split(/vault@/)
82
- if (splitted.length == 2) {
83
- var vaultKey = splitted[1]
84
- config[i] = vaultResults[vaultKey]
85
- }
86
- }
87
- }
88
- }
89
- }
@@ -1,50 +0,0 @@
1
- import { debug } from "debug"
2
- import chalk from "chalk"
3
- import nodeVault from "node-vault";
4
- import path from "path";
5
- import fs from "fs";
6
- import { readFileSync } from 'fs';
7
- import { fileCacheIsValid } from "./fileCacheIsValid";
8
- import { vault_cache_folder } from "../global";
9
- import { hash_sha512 } from "./hash_sha512";
10
- const dbg = debug('mybase')
11
-
12
- // need to implement it better
13
-
14
- export function vaultRead(vaultInstance: nodeVault.client, vaultKey: string, cache_in_minutes = 10) : Promise<any> {
15
- // v2 - supports caching
16
- return new Promise((resolve, reject) => {
17
- const cacheKeyMaterial = `${vaultInstance.endpoint}/${vaultKey}`
18
- const cacheHash = hash_sha512(cacheKeyMaterial)
19
- if (cacheHash === false) return reject(new Error('vault cache key hash failed'))
20
- let cache_file = path.join(vault_cache_folder, cacheHash)
21
-
22
- if (cache_in_minutes > 0 && fileCacheIsValid(cache_file, cache_in_minutes))
23
- return resolve(JSON.parse(readFileSync(cache_file as string).toString()))
24
-
25
- vaultInstance.read(vaultKey).then((r) => {
26
- if (r.data) {
27
- dbg(`vault ${vaultKey} - success`)
28
- if (cache_in_minutes > 0)
29
- try { fs.writeFileSync(cache_file, JSON.stringify(r.data)); fs.chmodSync(cache_file, 0o600); } catch (_) { }
30
- return resolve(r.data);
31
- }
32
- dbg(`vault ${vaultKey} - failed`)
33
- reject(r);
34
- }).catch(e => {
35
- console.log(e)
36
- dbg(`exception inside vaultRead`, e)
37
- // we will still return latest information from cache
38
- try {
39
- console.log(chalk.bgRed(`returning vault@${vaultKey} from cache due to error`))
40
- if (fs.existsSync(cache_file))
41
- return resolve(JSON.parse(fs.readFileSync(cache_file as string).toString()))
42
- } catch (e2) {
43
- // content of the file is invalid
44
- console.log(e2)
45
- }
46
-
47
- reject(e);
48
- })
49
- })
50
- }
package/ts/funcs/wait.ts DELETED
@@ -1,7 +0,0 @@
1
-
2
-
3
- export function wait(seconds=1) : Promise<void> {
4
- return new Promise((resolve,reject)=>{
5
- setTimeout(resolve,seconds*1000)
6
- })
7
- }
package/ts/global.ts DELETED
@@ -1,10 +0,0 @@
1
- import fs from 'fs'
2
-
3
- export let vault_cache_folder = '/var/tmp/vault-cache'
4
-
5
- try {
6
- if (!fs.existsSync(vault_cache_folder))
7
- fs.mkdirSync(vault_cache_folder)
8
- } catch(e) {
9
- console.log(e)
10
- }