mybase 1.1.34 → 1.1.35

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 (124) hide show
  1. package/jest/isLANIp.test.js +36 -0
  2. package/jest/isLoopbackIP.test.js +31 -0
  3. package/jest.config.js +6 -0
  4. package/package.json +2 -5
  5. package/ts/funcs/Geoip2Paths.d.ts +7 -0
  6. package/ts/funcs/Geoip2Paths.js +26 -0
  7. package/ts/funcs/Geoip2Paths.test.ts +11 -0
  8. package/ts/funcs/Geoip2Paths.ts +26 -0
  9. package/ts/funcs/MaxRuntimeHours.d.ts +1 -0
  10. package/ts/funcs/MaxRuntimeHours.js +11 -0
  11. package/ts/funcs/MaxRuntimeHours.ts +7 -0
  12. package/ts/funcs/asJSON.d.ts +1 -0
  13. package/ts/funcs/asJSON.js +14 -0
  14. package/ts/funcs/asJSON.test.js +72 -0
  15. package/ts/funcs/asJSON.ts +6 -0
  16. package/ts/funcs/ensureFolder.d.ts +3 -0
  17. package/ts/funcs/ensureFolder.js +50 -0
  18. package/ts/funcs/ensureFolder.test.ts +79 -0
  19. package/ts/funcs/ensureFolder.ts +21 -0
  20. package/ts/funcs/fileCacheIsValid.d.ts +1 -0
  21. package/ts/funcs/fileCacheIsValid.js +40 -0
  22. package/ts/funcs/fileCacheIsValid.ts +13 -0
  23. package/ts/funcs/getMysql1.d.ts +8 -0
  24. package/ts/funcs/getMysql1.js +62 -0
  25. package/ts/funcs/getMysql1.ts +41 -0
  26. package/ts/funcs/getMysql2.d.ts +9 -0
  27. package/ts/funcs/getMysql2.js +62 -0
  28. package/ts/funcs/getMysql2.ts +42 -0
  29. package/ts/funcs/getWeekNumber.d.ts +1 -0
  30. package/ts/funcs/getWeekNumber.js +36 -0
  31. package/ts/funcs/getWeekNumber.test.ts +9 -0
  32. package/ts/funcs/getWeekNumber.ts +31 -0
  33. package/ts/funcs/hash_sha512.d.ts +1 -0
  34. package/ts/funcs/hash_sha512.js +11 -0
  35. package/ts/funcs/hash_sha512.ts +7 -0
  36. package/ts/funcs/initMysql2Pool.d.ts +3 -0
  37. package/ts/funcs/initMysql2Pool.js +39 -0
  38. package/ts/funcs/initMysql2Pool.ts +11 -0
  39. package/ts/funcs/int2ip.d.ts +1 -0
  40. package/ts/funcs/int2ip.js +18 -0
  41. package/ts/funcs/int2ip.test.js +33 -0
  42. package/ts/funcs/int2ip.ts +9 -0
  43. package/ts/funcs/ip2int.d.ts +1 -0
  44. package/ts/funcs/ip2int.js +18 -0
  45. package/ts/funcs/ip2int.test.js +30 -0
  46. package/ts/funcs/ip2int.ts +10 -0
  47. package/ts/funcs/isLANIp.d.ts +4 -0
  48. package/ts/funcs/isLANIp.js +47 -0
  49. package/ts/funcs/isLANIp.test.ts +59 -0
  50. package/ts/funcs/isLANIp.ts +37 -0
  51. package/ts/funcs/isLocal.d.ts +1 -0
  52. package/ts/funcs/isLocal.js +12 -0
  53. package/ts/funcs/isLocal.test.ts +16 -0
  54. package/ts/funcs/isLocal.ts +5 -0
  55. package/ts/funcs/isLoopbackIP.d.ts +4 -0
  56. package/ts/funcs/isLoopbackIP.js +42 -0
  57. package/ts/funcs/isLoopbackIP.test.ts +72 -0
  58. package/ts/funcs/isLoopbackIP.ts +32 -0
  59. package/ts/funcs/promiseTimeout.d.ts +1 -0
  60. package/ts/funcs/promiseTimeout.js +19 -0
  61. package/ts/funcs/promiseTimeout.test.js +104 -0
  62. package/ts/funcs/promiseTimeout.ts +19 -0
  63. package/ts/funcs/randomIP.d.ts +1 -0
  64. package/ts/funcs/randomIP.js +11 -0
  65. package/ts/funcs/randomIP.test.ts +16 -0
  66. package/ts/funcs/randomIP.ts +10 -0
  67. package/ts/funcs/randomIP6.d.ts +1 -0
  68. package/ts/funcs/randomIP6.js +17 -0
  69. package/ts/funcs/randomIP6.test.js +18 -0
  70. package/ts/funcs/randomIP6.ts +12 -0
  71. package/ts/funcs/randomString.d.ts +1 -0
  72. package/ts/funcs/randomString.js +8 -0
  73. package/ts/funcs/randomString.test.ts +15 -0
  74. package/ts/funcs/randomString.ts +5 -0
  75. package/ts/funcs/randomTCPPort.d.ts +12 -0
  76. package/ts/funcs/randomTCPPort.js +88 -0
  77. package/ts/funcs/randomTCPPort.test.ts +62 -0
  78. package/ts/funcs/randomTCPPort.ts +58 -0
  79. package/ts/funcs/randomUTFString.d.ts +1 -0
  80. package/ts/funcs/randomUTFString.js +31 -0
  81. package/ts/funcs/randomUTFString.test.ts +44 -0
  82. package/ts/funcs/randomUTFString.ts +33 -0
  83. package/ts/funcs/utcnow.d.ts +2 -0
  84. package/ts/funcs/utcnow.js +8 -0
  85. package/ts/funcs/utcnow.ts +5 -0
  86. package/ts/funcs/validEmail.d.ts +1 -0
  87. package/ts/funcs/validEmail.js +21 -0
  88. package/ts/funcs/validEmail.test.js +31 -0
  89. package/ts/funcs/validEmail.ts +13 -0
  90. package/ts/funcs/validIp.d.ts +1 -0
  91. package/ts/funcs/validIp.js +32 -0
  92. package/ts/funcs/validIp.test.ts +33 -0
  93. package/ts/funcs/validIp.ts +5 -0
  94. package/ts/funcs/vaultFill.d.ts +2 -0
  95. package/ts/funcs/vaultFill.js +86 -0
  96. package/ts/funcs/vaultFill.ts +89 -0
  97. package/ts/funcs/vaultRead.d.ts +2 -0
  98. package/ts/funcs/vaultRead.js +52 -0
  99. package/ts/funcs/vaultRead.ts +45 -0
  100. package/ts/funcs/wait.d.ts +1 -0
  101. package/ts/funcs/wait.js +10 -0
  102. package/ts/funcs/wait.ts +7 -0
  103. package/ts/global.d.ts +1 -0
  104. package/ts/global.js +16 -0
  105. package/ts/global.ts +10 -0
  106. package/ts/index.d.ts +30 -0
  107. package/ts/index.js +48 -0
  108. package/ts/index.test.ts +7 -0
  109. package/ts/index.ts +33 -0
  110. package/ts/models/IPAddress.d.ts +40 -0
  111. package/ts/models/IPAddress.js +254 -0
  112. package/ts/models/IPAddress.test.ts +393 -0
  113. package/ts/models/IPAddress.ts +271 -0
  114. package/ts/models/Timespan.d.ts +18 -0
  115. package/ts/models/Timespan.js +52 -0
  116. package/ts/models/Timespan.ts +63 -0
  117. package/ts/models/Unixtime.d.ts +32 -0
  118. package/ts/models/Unixtime.js +137 -0
  119. package/ts/models/Unixtime.test.ts +102 -0
  120. package/ts/models/Unixtime.ts +164 -0
  121. package/ts/types.d.ts +1 -0
  122. package/ts/types.js +3 -0
  123. package/ts/types.ts +1 -0
  124. package/tsconfig.json +36 -0
@@ -0,0 +1,36 @@
1
+ const { isLANIp } = require('./../mybase');
2
+
3
+ test('should return true for private IPv4', () => {
4
+ const ip = '192.168.1.1';
5
+ expect(isLANIp(ip)).toBe(true);
6
+ });
7
+
8
+ test('should return true for private IPv6', () => {
9
+ const ip = 'fd00::';
10
+ expect(isLANIp(ip)).toBe(true);
11
+ });
12
+
13
+ test('should return null for public IPv4', () => {
14
+ const ip = '8.8.8.8';
15
+ expect(isLANIp(ip)).toBe(null);
16
+ });
17
+
18
+ test('should return null for public IPv6', () => {
19
+ const ip = '2001:4860:4860::8888';
20
+ expect(isLANIp(ip)).toBe(null);
21
+ });
22
+
23
+ test('should return false for invalid IP', () => {
24
+ const ip = 'invalid';
25
+ expect(isLANIp(ip)).toBe(false);
26
+ });
27
+
28
+ test('should return false for invalid IP', () => {
29
+ const ip = '1.2.3';
30
+ expect(isLANIp(ip)).toBe(false);
31
+ });
32
+
33
+ test('should return null for non private IPv6', () => {
34
+ const ip = '::2';
35
+ expect(isLANIp(ip)).toBe(null);
36
+ });
@@ -0,0 +1,31 @@
1
+ const { isLoopbackIP } = require('./../mybase') // adjust the path to mybase.js
2
+
3
+ test('should return true for local IPv4', () => {
4
+ const ip = '127.0.0.1'
5
+ expect(isLoopbackIP(ip)).toBe(true)
6
+ })
7
+
8
+ test('should return true for local IPv4', () => {
9
+ const ip = '127.127.127.127'
10
+ expect(isLoopbackIP(ip)).toBe(true)
11
+ })
12
+
13
+ test('should return true for local IPv6', () => {
14
+ const ip = '::1'
15
+ expect(isLoopbackIP(ip)).toBe(true)
16
+ })
17
+
18
+ test('should return null for non-local IPv4', () => {
19
+ const ip = '8.8.8.8'
20
+ expect(isLoopbackIP(ip)).toBe(null)
21
+ })
22
+
23
+ test('should return null for non-local IPv6', () => {
24
+ const ip = '2001:4860:4860::8888'
25
+ expect(isLoopbackIP(ip)).toBe(null)
26
+ })
27
+
28
+ test('should return false for invalid IP', () => {
29
+ const ip = 'invalid'
30
+ expect(isLoopbackIP(ip)).toBe(false)
31
+ })
package/jest.config.js ADDED
@@ -0,0 +1,6 @@
1
+ /** @type {import('ts-jest').JestConfigWithTsJest} */
2
+ module.exports = {
3
+ preset: 'ts-jest',
4
+ testEnvironment: 'node',
5
+ testTimeout: 15000,
6
+ };
package/package.json CHANGED
@@ -1,12 +1,9 @@
1
1
  {
2
2
  "name": "mybase",
3
- "version": "1.1.34",
3
+ "version": "1.1.35",
4
4
  "description": "",
5
5
  "main": "mybase.js",
6
- "files": [
7
- "mybase.js",
8
- "ip6addr.d.ts"
9
- ],
6
+ "types": "./ip6addr.d.ts",
10
7
  "scripts": {
11
8
  "test": "jest --forceExit --verbose"
12
9
  },
@@ -0,0 +1,7 @@
1
+ export type Geoip2Paths = {
2
+ country: string | false;
3
+ city: string | false;
4
+ isp: string | false;
5
+ ct: string | false;
6
+ };
7
+ export declare function Geoip2Paths(): Geoip2Paths;
@@ -0,0 +1,26 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.Geoip2Paths = void 0;
7
+ const fs_1 = __importDefault(require("fs"));
8
+ const path_1 = __importDefault(require("path"));
9
+ function Geoip2Paths() {
10
+ var _a, _b, _c, _d;
11
+ function firstExisting(paths) {
12
+ if (Array.isArray(paths))
13
+ for (let fpath of paths)
14
+ if (fs_1.default.existsSync(fpath))
15
+ return fpath;
16
+ return false;
17
+ }
18
+ return {
19
+ country: firstExisting(['/opt/geoip2/GeoIP2-Country.mmdb', '/usr/local/var/GeoIP/GeoIP2-Country.mmdb', '/var/lib/GeoIP/GeoIP2-Country.mmdb', '/usr/share/GeoIP/GeoIP2-Country.mmdb', path_1.default.join(__dirname, 'assets/GeoIP2-Country.mmdb'), path_1.default.join(((_a = require === null || require === void 0 ? void 0 : require.main) === null || _a === void 0 ? void 0 : _a.path) || __dirname, 'assets/GeoIP2-Country.mmdb')]),
20
+ city: firstExisting(['/opt/geoip2/GeoIP2-City.mmdb', '/usr/local/var/GeoIP/GeoIP2-City.mmdb', '/var/lib/GeoIP/GeoIP2-City.mmdb', '/usr/share/GeoIP/GeoIP2-City.mmdb', path_1.default.join(__dirname, 'assets/GeoIP2-City.mmdb'), path_1.default.join(((_b = require === null || require === void 0 ? void 0 : require.main) === null || _b === void 0 ? void 0 : _b.path) || __dirname, 'assets/GeoIP2-City.mmdb')]),
21
+ isp: firstExisting(['/opt/geoip2/GeoIP2-ISP.mmdb', '/usr/local/var/GeoIP/GeoIP2-ISP.mmdb', '/var/lib/GeoIP/GeoIP2-ISP.mmdb', '/usr/share/GeoIP/GeoIP2-ISP.mmdb', path_1.default.join(__dirname, 'assets/GeoIP2-ISP.mmdb'), path_1.default.join(((_c = require === null || require === void 0 ? void 0 : require.main) === null || _c === void 0 ? void 0 : _c.path) || __dirname, 'assets/GeoIP2-ISP.mmdb')]),
22
+ ct: firstExisting(['/opt/geoip2/GeoIP2-Connection-Type.mmdb', '/usr/local/var/GeoIP/GeoIP2-Connection-Type.mmdb', '/var/lib/GeoIP/GeoIP2-Connection-Type.mmdb', '/usr/share/GeoIP/GeoIP2-Connection-Type.mmdb', path_1.default.join(__dirname, 'assets/GeoIP2-Connection-Type.mmdb'), path_1.default.join(((_d = require === null || require === void 0 ? void 0 : require.main) === null || _d === void 0 ? void 0 : _d.path) || __dirname, 'assets/GeoIP2-Connection-Type.mmdb')]),
23
+ };
24
+ }
25
+ exports.Geoip2Paths = Geoip2Paths;
26
+ //# sourceMappingURL=Geoip2Paths.js.map
@@ -0,0 +1,11 @@
1
+ import { Geoip2Paths } from './Geoip2Paths'
2
+ import * as fs from 'fs'
3
+
4
+ describe('Geoip2Paths', () => {
5
+ it('should return a valid path', () => {
6
+ const paths = Geoip2Paths()
7
+ expect(paths).toHaveProperty('country')
8
+ expect(typeof paths.country).toBe('string')
9
+ expect(fs.existsSync(paths.country as string)).toBe(true)
10
+ })
11
+ })
@@ -0,0 +1,26 @@
1
+ import fs from 'fs'
2
+ import path from 'path'
3
+
4
+ export type Geoip2Paths = {
5
+ country:string|false,
6
+ city:string|false,
7
+ isp:string|false,
8
+ ct:string|false,
9
+ }
10
+
11
+
12
+ export function Geoip2Paths() :Geoip2Paths {
13
+ function firstExisting(paths:Array<string>) : string|false {
14
+ if (Array.isArray(paths))
15
+ for(let fpath of paths)
16
+ if (fs.existsSync(fpath)) return fpath
17
+ return false
18
+ }
19
+
20
+ return {
21
+ country:firstExisting(['/opt/geoip2/GeoIP2-Country.mmdb','/usr/local/var/GeoIP/GeoIP2-Country.mmdb','/var/lib/GeoIP/GeoIP2-Country.mmdb','/usr/share/GeoIP/GeoIP2-Country.mmdb',path.join(__dirname, 'assets/GeoIP2-Country.mmdb'),path.join(require?.main?.path || __dirname, 'assets/GeoIP2-Country.mmdb')]),
22
+ city:firstExisting(['/opt/geoip2/GeoIP2-City.mmdb','/usr/local/var/GeoIP/GeoIP2-City.mmdb','/var/lib/GeoIP/GeoIP2-City.mmdb','/usr/share/GeoIP/GeoIP2-City.mmdb',path.join(__dirname, 'assets/GeoIP2-City.mmdb'),path.join(require?.main?.path || __dirname, 'assets/GeoIP2-City.mmdb')]),
23
+ isp:firstExisting(['/opt/geoip2/GeoIP2-ISP.mmdb','/usr/local/var/GeoIP/GeoIP2-ISP.mmdb','/var/lib/GeoIP/GeoIP2-ISP.mmdb','/usr/share/GeoIP/GeoIP2-ISP.mmdb',path.join(__dirname, 'assets/GeoIP2-ISP.mmdb'),path.join(require?.main?.path || __dirname, 'assets/GeoIP2-ISP.mmdb')]),
24
+ ct:firstExisting(['/opt/geoip2/GeoIP2-Connection-Type.mmdb','/usr/local/var/GeoIP/GeoIP2-Connection-Type.mmdb','/var/lib/GeoIP/GeoIP2-Connection-Type.mmdb','/usr/share/GeoIP/GeoIP2-Connection-Type.mmdb',path.join(__dirname, 'assets/GeoIP2-Connection-Type.mmdb'),path.join(require?.main?.path || __dirname, 'assets/GeoIP2-Connection-Type.mmdb')]),
25
+ }
26
+ }
@@ -0,0 +1 @@
1
+ export declare function MaxRuntimeHours(hours?: number): void;
@@ -0,0 +1,11 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.MaxRuntimeHours = void 0;
4
+ function MaxRuntimeHours(hours = 24) {
5
+ setTimeout(() => {
6
+ console.log(`Max runtime of ${hours} hours reached, exiting`);
7
+ process.exit(0);
8
+ }, hours * 60 * 60 * 1000);
9
+ }
10
+ exports.MaxRuntimeHours = MaxRuntimeHours;
11
+ //# sourceMappingURL=MaxRuntimeHours.js.map
@@ -0,0 +1,7 @@
1
+
2
+ export function MaxRuntimeHours(hours:number=24) {
3
+ setTimeout(() => {
4
+ console.log(`Max runtime of ${hours} hours reached, exiting`)
5
+ process.exit(0)
6
+ }, hours * 60 * 60 * 1000)
7
+ }
@@ -0,0 +1 @@
1
+ export declare function asJSON(inputString: string): any | boolean;
@@ -0,0 +1,14 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.asJSON = void 0;
4
+ function asJSON(inputString) {
5
+ if (!inputString || typeof inputString !== 'string')
6
+ return false;
7
+ try {
8
+ return JSON.parse(inputString);
9
+ }
10
+ catch (_) { }
11
+ return false;
12
+ }
13
+ exports.asJSON = asJSON;
14
+ //# sourceMappingURL=asJSON.js.map
@@ -0,0 +1,72 @@
1
+ const { asJSON } = require('./asJSON')
2
+
3
+ describe('asJSON', () => {
4
+ // Returns parsed JSON object when valid JSON string is passed as input.
5
+ it('should return parsed JSON object when valid JSON string is passed as input', () => {
6
+ const inputString = '{"name": "John", "age": 30}';
7
+ const expectedOutput = { name: "John", age: 30 };
8
+ const result = asJSON(inputString);
9
+ expect(result).toEqual(expectedOutput);
10
+ });
11
+
12
+ // Returns false when empty string is passed as input.
13
+ it('should return false when empty string is passed as input', () => {
14
+ const inputString = "";
15
+ const expectedOutput = false;
16
+ const result = asJSON(inputString);
17
+ expect(result).toEqual(expectedOutput);
18
+ });
19
+
20
+ // Returns false when non-string input is passed.
21
+ it('should return false when non-string input is passed', () => {
22
+ const inputString = 123;
23
+ const expectedOutput = false;
24
+ const result = asJSON(inputString);
25
+ expect(result).toEqual(expectedOutput);
26
+ });
27
+
28
+ // Returns false when null is passed as input.
29
+ it('should return false when null is passed as input', () => {
30
+ const inputString = null;
31
+ const expectedOutput = false;
32
+ const result = asJSON(inputString);
33
+ expect(result).toEqual(expectedOutput);
34
+ });
35
+
36
+ // Returns false when undefined is passed as input.
37
+ it('should return false when undefined is passed as input', () => {
38
+ const inputString = undefined;
39
+ const expectedOutput = false;
40
+ const result = asJSON(inputString);
41
+ expect(result).toEqual(expectedOutput);
42
+ });
43
+
44
+ // Returns false when NaN is passed as input.
45
+ it('should return false when NaN is passed as input', () => {
46
+ const inputString = NaN;
47
+ const expectedOutput = false;
48
+ const result = asJSON(inputString);
49
+ expect(result).toEqual(expectedOutput);
50
+ });
51
+
52
+ // Returns false when invalid JSON string is passed as input.
53
+ it('should return false when invalid JSON string is passed as input', () => {
54
+ const inputString = 'invalid json';
55
+ const result = asJSON(inputString);
56
+ expect(result).toBe(false);
57
+ });
58
+
59
+ // Returns false when Infinity is passed as input.
60
+ it('should return false when Infinity is passed as input', () => {
61
+ const inputString = 'Infinity';
62
+ const result = asJSON(inputString);
63
+ expect(result).toBe(false);
64
+ });
65
+
66
+ // Returns false when input string contains a single quote.
67
+ it('should return false when input string contains a single quote', () => {
68
+ const inputString = "{'name': 'John'}";
69
+ const result = asJSON(inputString);
70
+ expect(result).toBe(false);
71
+ });
72
+ });
@@ -0,0 +1,6 @@
1
+
2
+ export function asJSON(inputString: string): any | boolean {
3
+ if (!inputString || typeof inputString !== 'string') return false
4
+ try { return JSON.parse(inputString) } catch (_) { }
5
+ return false
6
+ }
@@ -0,0 +1,3 @@
1
+ /// <reference types="node" />
2
+ import { MakeDirectoryOptions } from 'fs';
3
+ export declare function ensureFolder(folderPath: string, options?: MakeDirectoryOptions | null): string;
@@ -0,0 +1,50 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ var __importDefault = (this && this.__importDefault) || function (mod) {
26
+ return (mod && mod.__esModule) ? mod : { "default": mod };
27
+ };
28
+ Object.defineProperty(exports, "__esModule", { value: true });
29
+ exports.ensureFolder = void 0;
30
+ const debug_1 = __importDefault(require("debug"));
31
+ const fs = __importStar(require("fs"));
32
+ const dbg = (0, debug_1.default)('_mybase:ensureFolder');
33
+ function ensureFolder(folderPath, options) {
34
+ options = options || {};
35
+ options.recursive = true;
36
+ dbg('ensureFolder()', folderPath);
37
+ if (fs.existsSync(folderPath)) {
38
+ if (!fs.lstatSync(folderPath).isDirectory()) {
39
+ dbg(`${folderPath} exists and is not a folder`);
40
+ throw new Error(`${folderPath} exists and is not a folder`);
41
+ }
42
+ dbg(`${folderPath} exists and is a folder`);
43
+ return folderPath;
44
+ }
45
+ dbg(`creating ${folderPath}`, options);
46
+ fs.mkdirSync(folderPath, options);
47
+ return folderPath;
48
+ }
49
+ exports.ensureFolder = ensureFolder;
50
+ //# sourceMappingURL=ensureFolder.js.map
@@ -0,0 +1,79 @@
1
+ import { ensureFolder } from './ensureFolder'
2
+ import * as fs from 'fs'
3
+ import { wait } from '../index'
4
+
5
+ describe('ensureFolder', () => {
6
+ let folderPath: string
7
+ let filePath: string
8
+
9
+ beforeEach(async () => {
10
+ folderPath = `/tmp/ensureFolder.test.${Date.now()}`
11
+ filePath = `/tmp/ensureFolder.test.${Date.now()}.file`
12
+ await wait(1/1000)
13
+ })
14
+
15
+ it('should create a folder if it does not exist and return the folder path', () => {
16
+ const folder = ensureFolder(folderPath)
17
+ expect(folder).toBe(folderPath)
18
+ expect(fs.existsSync(folderPath)).toBe(true)
19
+ })
20
+
21
+ it('should throw an error if the folder path exists and is not a folder', () => {
22
+ fs.writeFileSync(filePath, 'test')
23
+ expect(() => ensureFolder(filePath)).toThrow('exists and is not a folder')
24
+ })
25
+
26
+ it('creating same folder twice should return the same folder path', () => {
27
+ expect(ensureFolder(folderPath)).toBe(folderPath)
28
+ expect(fs.existsSync(folderPath)).toBe(true)
29
+ expect(ensureFolder(folderPath)).toBe(folderPath)
30
+ })
31
+
32
+ it('we should be able to create recursively a folders and default to recursive mode', () => {
33
+ let sfolder= ensureFolder(`${folderPath}/subfolder/subsubfolder`)
34
+ expect(sfolder).toBe(`${folderPath}/subfolder/subsubfolder`)
35
+ if (sfolder) expect(fs.existsSync(sfolder)).toBe(true)
36
+ // test creating 10 recursive folders
37
+ for(let i=0;i<10;i++) {
38
+ sfolder= `${sfolder}/subsubsubfolder${i}`
39
+ expect(ensureFolder(sfolder)).toBe(sfolder)
40
+ if (sfolder) expect(fs.existsSync(sfolder)).toBe(true)
41
+ }
42
+ })
43
+
44
+ it('we should not be able to disable recursive mode', () => {
45
+ expect(ensureFolder(`${folderPath}/subfolder/subsubfolder`, { recursive: false })).toBe(`${folderPath}/subfolder/subsubfolder`)
46
+ })
47
+
48
+ it('we should be able to create a folder with a custom mode', () => {
49
+ let sfolder= ensureFolder(`${folderPath}/subfolder/subsubfolder`, { mode: 0o700 })
50
+ expect(sfolder).toBe(`${folderPath}/subfolder/subsubfolder`)
51
+ if (sfolder) expect(fs.existsSync(sfolder)).toBe(true)
52
+ expect(fs.statSync(sfolder).mode & 0o777).toBe(0o700);
53
+ })
54
+
55
+ it('try to create a file where we do not have write permissions should throw an error', () => {
56
+ expect(() => ensureFolder('/dev/ensureFolder.test.file')).toThrow()
57
+ })
58
+
59
+ it('should throw an error if folder path is empty', () => {
60
+ expect(() => ensureFolder('')).toThrow();
61
+ });
62
+
63
+ it('should throw an error if folder path is null or undefined or array or object', () => {
64
+ expect(() => ensureFolder(null as unknown as string)).toThrow();
65
+ expect(() => ensureFolder(undefined as unknown as string)).toThrow();
66
+ expect(() => ensureFolder([] as unknown as string)).toThrow();
67
+ expect(() => ensureFolder({} as unknown as string)).toThrow();
68
+ });
69
+
70
+ it('should not change the permissions of an existing folder', () => {
71
+ fs.mkdirSync(folderPath, { mode: 0o755 });
72
+ ensureFolder(folderPath, { mode: 0o700 });
73
+ expect(fs.statSync(folderPath).mode & 0o777).toBe(0o755);
74
+ });
75
+
76
+ it('should throw error for invalid mode value', () => {
77
+
78
+ });
79
+ })
@@ -0,0 +1,21 @@
1
+ import debug from 'debug'
2
+ import * as fs from 'fs';
3
+ import { MakeDirectoryOptions } from 'fs';
4
+ const dbg = debug('_mybase:ensureFolder')
5
+
6
+ export function ensureFolder(folderPath: string, options?: MakeDirectoryOptions | null) : string {
7
+ options = options || {}
8
+ options.recursive = true
9
+ dbg('ensureFolder()', folderPath)
10
+ if (fs.existsSync(folderPath)) {
11
+ if (!fs.lstatSync(folderPath).isDirectory()) {
12
+ dbg(`${folderPath} exists and is not a folder`)
13
+ throw new Error(`${folderPath} exists and is not a folder`);
14
+ }
15
+ dbg(`${folderPath} exists and is a folder`)
16
+ return folderPath
17
+ }
18
+ dbg(`creating ${folderPath}`,options)
19
+ fs.mkdirSync(folderPath, options)
20
+ return folderPath
21
+ }
@@ -0,0 +1 @@
1
+ export declare function fileCacheIsValid(cacheFileName: string, cache_in_minutes?: number): boolean;
@@ -0,0 +1,40 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ Object.defineProperty(exports, "__esModule", { value: true });
26
+ exports.fileCacheIsValid = void 0;
27
+ const fs = __importStar(require("fs"));
28
+ function fileCacheIsValid(cacheFileName, cache_in_minutes = 60) {
29
+ if (fs.existsSync(cacheFileName)) {
30
+ const stat = fs.statSync(cacheFileName);
31
+ const mtime = new Date(stat.mtime).getTime();
32
+ if (Date.now() - mtime < cache_in_minutes * 60 * 1000) {
33
+ // cache is still valid
34
+ return true;
35
+ }
36
+ }
37
+ return false;
38
+ }
39
+ exports.fileCacheIsValid = fileCacheIsValid;
40
+ //# sourceMappingURL=fileCacheIsValid.js.map
@@ -0,0 +1,13 @@
1
+ import * as fs from 'fs'
2
+
3
+ export function fileCacheIsValid(cacheFileName : string, cache_in_minutes = 60) : boolean {
4
+ if (fs.existsSync(cacheFileName)) {
5
+ const stat = fs.statSync(cacheFileName)
6
+ const mtime = new Date(stat.mtime).getTime()
7
+ if (Date.now() - mtime < cache_in_minutes * 60 * 1000) {
8
+ // cache is still valid
9
+ return true
10
+ }
11
+ }
12
+ return false
13
+ }
@@ -0,0 +1,8 @@
1
+ export type Mysql1ServerConfiguration = {
2
+ host: string;
3
+ port: number;
4
+ login: string;
5
+ password: string;
6
+ db: string;
7
+ };
8
+ export declare function getMysql1(config: Mysql1ServerConfiguration, pingInterval?: number): Promise<unknown>;
@@ -0,0 +1,62 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ var __importDefault = (this && this.__importDefault) || function (mod) {
26
+ return (mod && mod.__esModule) ? mod : { "default": mod };
27
+ };
28
+ Object.defineProperty(exports, "__esModule", { value: true });
29
+ exports.getMysql1 = void 0;
30
+ const mysql1 = __importStar(require("mysql"));
31
+ const debug_1 = __importDefault(require("debug"));
32
+ const dbg = (0, debug_1.default)("getMysql1");
33
+ async function getMysql1(config, pingInterval = 0) {
34
+ return new Promise((resolve, reject) => {
35
+ const mysql_client = mysql1.createConnection({
36
+ host: config.host,
37
+ port: config.port ? config.port : 3306,
38
+ user: config.login,
39
+ password: config.password,
40
+ database: config.db
41
+ });
42
+ mysql_client.connect((err, res) => {
43
+ if (err) {
44
+ dbg(`mysql connection has failed to ${config.host}@${config.db}`, err);
45
+ return reject(err);
46
+ }
47
+ dbg(`mysql connection has been established to ${config.host}@${config.db}`);
48
+ // install a pinger every 30 seconds to keep the connection alive
49
+ if (pingInterval > 0)
50
+ setInterval(() => {
51
+ mysql_client.ping(function (err) {
52
+ if (err)
53
+ return console.log(`could not ping mysql ${config.host}@${config.db}`, err.code);
54
+ dbg(`mysql ${config.host}@${config.db} is pinging properly`);
55
+ });
56
+ }, pingInterval);
57
+ resolve(mysql_client);
58
+ });
59
+ });
60
+ }
61
+ exports.getMysql1 = getMysql1;
62
+ //# sourceMappingURL=getMysql1.js.map
@@ -0,0 +1,41 @@
1
+ import * as mysql1 from "mysql"
2
+ import { MysqlError } from "mysql"
3
+ import debug from "debug"
4
+ const dbg = debug("getMysql1")
5
+
6
+ export type Mysql1ServerConfiguration = {
7
+ host: string,
8
+ port: number,
9
+ login: string,
10
+ password: string,
11
+ db: string
12
+ }
13
+
14
+ export async function getMysql1(config: Mysql1ServerConfiguration, pingInterval: number = 0) {
15
+ return new Promise((resolve, reject) => {
16
+ const mysql_client = mysql1.createConnection({
17
+ host: config.host,
18
+ port: config.port ? config.port : 3306,
19
+ user: config.login,
20
+ password: config.password,
21
+ database: config.db
22
+ })
23
+
24
+ mysql_client.connect((err:MysqlError, res) => {
25
+ if (err) {
26
+ dbg(`mysql connection has failed to ${config.host}@${config.db}`, err)
27
+ return reject(err)
28
+ }
29
+ dbg(`mysql connection has been established to ${config.host}@${config.db}`)
30
+ // install a pinger every 30 seconds to keep the connection alive
31
+ if (pingInterval > 0)
32
+ setInterval(() => {
33
+ mysql_client.ping(function (err:MysqlError) {
34
+ if (err) return console.log(`could not ping mysql ${config.host}@${config.db}`, err.code)
35
+ dbg(`mysql ${config.host}@${config.db} is pinging properly`)
36
+ })
37
+ }, pingInterval)
38
+ resolve(mysql_client)
39
+ })
40
+ })
41
+ }
@@ -0,0 +1,9 @@
1
+ import { Connection } from "mysql2";
2
+ export type Mysql2ServerConfiguration = {
3
+ host: string;
4
+ port: number;
5
+ login: string;
6
+ password: string;
7
+ db: string;
8
+ };
9
+ export declare function getMysql2(config: Mysql2ServerConfiguration, pingInterval?: number): Promise<Connection>;