mybase 1.1.53 → 1.2.3

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/ip6addr.d.ts +10 -1
  2. package/mybase.d.ts +57 -0
  3. package/mybase.js +401 -684
  4. package/mybase.js.map +1 -0
  5. package/package.json +18 -2
  6. package/ts/funcs/Geoip2Paths.js +7 -5
  7. package/ts/funcs/Geoip2Paths.js.map +1 -0
  8. package/ts/funcs/MaxRuntimeHours.js.map +1 -0
  9. package/ts/funcs/asJSON.d.ts +1 -1
  10. package/ts/funcs/asJSON.js +6 -4
  11. package/ts/funcs/asJSON.js.map +1 -0
  12. package/ts/funcs/deepCopy.js.map +1 -0
  13. package/ts/funcs/ensureFolder.js.map +1 -0
  14. package/ts/funcs/fileCacheIsValid.js.map +1 -0
  15. package/ts/funcs/getMysql1.js.map +1 -0
  16. package/ts/funcs/getMysql2.js.map +1 -0
  17. package/ts/funcs/getWeekNumber.js.map +1 -0
  18. package/ts/funcs/hash_sha512.d.ts +1 -1
  19. package/ts/funcs/hash_sha512.js +4 -4
  20. package/ts/funcs/hash_sha512.js.map +1 -0
  21. package/ts/funcs/initMysql2Pool.js.map +1 -0
  22. package/ts/funcs/int2ip.js.map +1 -0
  23. package/ts/funcs/ip2int.js.map +1 -0
  24. package/ts/funcs/isLANIp.d.ts +2 -3
  25. package/ts/funcs/isLANIp.js +14 -15
  26. package/ts/funcs/isLANIp.js.map +1 -0
  27. package/ts/funcs/isLocal.js.map +1 -0
  28. package/ts/funcs/isLoopbackIP.d.ts +2 -3
  29. package/ts/funcs/isLoopbackIP.js +15 -16
  30. package/ts/funcs/isLoopbackIP.js.map +1 -0
  31. package/ts/funcs/knexConnection.js.map +1 -0
  32. package/ts/funcs/promiseTimeout.js.map +1 -0
  33. package/ts/funcs/randomIP.js.map +1 -0
  34. package/ts/funcs/randomIP6.js.map +1 -0
  35. package/ts/funcs/randomString.js.map +1 -0
  36. package/ts/funcs/randomTCPPort.js.map +1 -0
  37. package/ts/funcs/randomUTFString.js.map +1 -0
  38. package/ts/funcs/utcnow.js.map +1 -0
  39. package/ts/funcs/validEmail.d.ts +1 -1
  40. package/ts/funcs/validEmail.js +0 -3
  41. package/ts/funcs/validEmail.js.map +1 -0
  42. package/ts/funcs/validIp.js.map +1 -0
  43. package/ts/funcs/vaultFill.js +1 -1
  44. package/ts/funcs/vaultFill.js.map +1 -0
  45. package/ts/funcs/vaultRead.js +9 -3
  46. package/ts/funcs/vaultRead.js.map +1 -0
  47. package/ts/funcs/wait.js.map +1 -0
  48. package/ts/global.js.map +1 -0
  49. package/ts/index.js.map +1 -0
  50. package/ts/models/DateIterator.js.map +1 -0
  51. package/ts/models/IPAddress.d.ts +13 -13
  52. package/ts/models/IPAddress.js.map +1 -0
  53. package/ts/models/Interfaces.js.map +1 -0
  54. package/ts/models/OTPGenerator.js.map +1 -0
  55. package/ts/models/Timespan.js.map +1 -0
  56. package/ts/models/Unixtime.js.map +1 -0
  57. package/ts/types.d.ts +35 -0
  58. package/ts/types.js +1 -0
  59. package/ts/types.js.map +1 -0
  60. package/jest/isLANIp.test.js +0 -36
  61. package/jest/isLoopbackIP.test.js +0 -31
  62. package/jest.config.js +0 -7
  63. package/ts/funcs/Geoip2Paths.test.ts +0 -11
  64. package/ts/funcs/Geoip2Paths.ts +0 -26
  65. package/ts/funcs/MaxRuntimeHours.ts +0 -7
  66. package/ts/funcs/asJSON.test.js +0 -72
  67. package/ts/funcs/asJSON.ts +0 -6
  68. package/ts/funcs/deepCopy.test.ts +0 -108
  69. package/ts/funcs/deepCopy.ts +0 -34
  70. package/ts/funcs/ensureFolder.test.ts +0 -79
  71. package/ts/funcs/ensureFolder.ts +0 -21
  72. package/ts/funcs/fileCacheIsValid.ts +0 -13
  73. package/ts/funcs/getMysql1.ts +0 -41
  74. package/ts/funcs/getMysql2.ts +0 -42
  75. package/ts/funcs/getWeekNumber.test.ts +0 -9
  76. package/ts/funcs/getWeekNumber.ts +0 -31
  77. package/ts/funcs/hash_sha512.ts +0 -7
  78. package/ts/funcs/initMysql2Pool.ts +0 -11
  79. package/ts/funcs/int2ip.test.js +0 -33
  80. package/ts/funcs/int2ip.ts +0 -9
  81. package/ts/funcs/ip2int.test.js +0 -30
  82. package/ts/funcs/ip2int.ts +0 -10
  83. package/ts/funcs/isLANIp.test.ts +0 -59
  84. package/ts/funcs/isLANIp.ts +0 -37
  85. package/ts/funcs/isLocal.test.ts +0 -16
  86. package/ts/funcs/isLocal.ts +0 -5
  87. package/ts/funcs/isLoopbackIP.test.ts +0 -72
  88. package/ts/funcs/isLoopbackIP.ts +0 -32
  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 -13
  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 -45
  109. package/ts/funcs/wait.ts +0 -7
  110. package/ts/global.ts +0 -10
  111. package/ts/index.test.ts +0 -7
  112. package/ts/index.ts +0 -39
  113. package/ts/models/DateIterator.test.ts +0 -149
  114. package/ts/models/DateIterator.ts +0 -80
  115. package/ts/models/IPAddress.test.ts +0 -393
  116. package/ts/models/IPAddress.ts +0 -272
  117. package/ts/models/Interfaces.ts +0 -58
  118. package/ts/models/OTPGenerator.test.ts +0 -42
  119. package/ts/models/OTPGenerator.ts +0 -43
  120. package/ts/models/Timespan.ts +0 -80
  121. package/ts/models/Unixtime.test.ts +0 -168
  122. package/ts/models/Unixtime.ts +0 -208
  123. package/ts/types.ts +0 -1
  124. package/tsconfig.json +0 -36
@@ -1,58 +0,0 @@
1
- import { networkInterfaces } from 'os';
2
-
3
- interface NetworkInterfaceInfo {
4
- name: string;
5
- ipv4: string[];
6
- ipv6: string[];
7
- }
8
-
9
-
10
- export class Interfaces {
11
-
12
- static findByName(name: string): NetworkInterfaceInfo | null {
13
- const ifaces = this.getInterfaces()
14
- const iface = ifaces.find(iface => iface.name === name)
15
- return iface || null
16
- }
17
-
18
- static findByNamePrefix(prefix: string): NetworkInterfaceInfo[] {
19
- const ifaces = this.getInterfaces()
20
- return ifaces.filter(iface => iface.name.startsWith(prefix))
21
- }
22
-
23
- static findByIp(ip: string): NetworkInterfaceInfo | null {
24
- const ifaces = this.getInterfaces()
25
- const iface = ifaces.find(iface => iface.ipv4.includes(ip) || iface.ipv6.includes(ip))
26
- return iface || null
27
- }
28
-
29
- static asApiServerConfig(ifaces:string[], port:number): {ip:string,port:number}[] {
30
- const ret: {ip:string,port:number}[] = []
31
- for (const iface of ifaces) {
32
- const i = this.findByName(iface)
33
- if (i) ret.push({ip:i.ipv4[0],port:port})
34
- }
35
- return ret
36
- }
37
-
38
- static getInterfaces(): NetworkInterfaceInfo[] {
39
- const interfaces = networkInterfaces();
40
- const result: NetworkInterfaceInfo[] = [];
41
-
42
- for (const name of Object.keys(interfaces)) {
43
- const networkInterface = interfaces[name];
44
- if (networkInterface) {
45
- const ipv4 = networkInterface.filter(info => info.family === 'IPv4').map(info => info.address);
46
- const ipv6 = networkInterface.filter(info => info.family === 'IPv6').map(info => info.address);
47
-
48
- result.push({
49
- name,
50
- ipv4,
51
- ipv6
52
- });
53
- }
54
- }
55
-
56
- return result;
57
- }
58
- }
@@ -1,42 +0,0 @@
1
- import { OTPGenerator } from './OTPGenerator';
2
- import { wait } from './../funcs/wait';
3
- import { Timespan } from './Timespan';
4
-
5
- const passkey = 'hiowi3rmpewr34';
6
- describe('OTPGenerator', () => {
7
- it('should generate OTP', () => {
8
- const otpGenerator = new OTPGenerator(passkey, 5);
9
- const otp = otpGenerator.generateOTP();
10
- // length should be 5 + 13
11
- expect(otp.length).toBe(18);
12
- // console.log(otp);
13
- })
14
-
15
- it('should generate different OTPs in milliseconds', async () => {
16
- const otpGenerator = new OTPGenerator(passkey, 5);
17
- const otp1 = otpGenerator.generateOTP()
18
- await wait(3/1000);
19
- const otp2 = otpGenerator.generateOTP();
20
- expect(otp1).not.toBe(otp2);
21
- })
22
-
23
- it('should generate different OTPs in milliseconds per password', async () => {
24
- const otpGenerator1 = new OTPGenerator(passkey+'1', 5);
25
- const otpGenerator2 = new OTPGenerator(passkey+'2', 5);
26
- for(let i=0; i<10000; i++) {
27
- const otp1 = otpGenerator1.generateOTP()
28
- const otp2 = otpGenerator2.generateOTP();
29
- expect(otp1).not.toBe(otp2);
30
- }
31
- })
32
-
33
- it('age should be milliseconds since generation', async () => {
34
- const otpGenerator = new OTPGenerator(passkey, 5);
35
- const otp = otpGenerator.generateOTP();
36
- await wait(1/1000);
37
- const age = otpGenerator.age(otp);
38
- expect(age).toBeInstanceOf(Timespan);
39
- expect(age.miliseconds).toBeGreaterThan(0);
40
- expect(age.miliseconds).toBeLessThan(100);
41
- })
42
- });
@@ -1,43 +0,0 @@
1
- import * as crypto from 'crypto';
2
- import { Timespan } from './Timespan';
3
-
4
-
5
- export class OTPGenerator {
6
- constructor(private passkey: string, private length: number = 4) {}
7
-
8
- // Generate OTP with the current timestamp as nonce
9
- public generateOTP(): string {
10
- return this.generateOTPWithNonce(Date.now());
11
- }
12
-
13
- // Validate if the OTP matches by extracting the nonce and regenerating OTP
14
- public validateOTP(otp: string): boolean {
15
- if (!this.isValid(otp)) return false; // Validate plausibility of OTP
16
- const nonce = this.extractNonce(otp);
17
- return otp === this.generateOTPWithNonce(nonce);
18
- }
19
-
20
- // Get the age of the OTP compared to now
21
- public age(otp: string): Timespan {
22
- if (!this.isValid(otp)) throw new Error('Invalid OTP');
23
- const nonce = this.extractNonce(otp);
24
- return new Timespan(Date.now() - nonce)
25
- }
26
-
27
- public generateOTPWithNonce(nonce: number): string { // lets keep it public for testing
28
- const hash = crypto.createHmac('sha256', this.passkey).update(nonce.toString()).digest('hex');
29
- const otp = [...hash.slice(0, this.length)].map(char => String.fromCharCode((parseInt(char, 16) % 26) + 97)).join('');
30
- return `${otp}${nonce.toString(16).padStart(13, '0')}`;
31
- }
32
-
33
- // Private helper to validate plausibility of OTP
34
- private isValid(otp: string): boolean {
35
- return otp.length === this.length + 13;
36
- }
37
-
38
- // Private helper to extract the nonce from the OTP
39
- private extractNonce(otp: string): number {
40
- const nonceHex = otp.slice(-13);
41
- return parseInt(nonceHex, 16);
42
- }
43
- }
@@ -1,80 +0,0 @@
1
- export class Timespan {
2
- constructor(private readonly ms: number){
3
- }
4
-
5
- get miliseconds() : number {
6
- return this.ms
7
- }
8
-
9
- get seconds() : number {
10
- return this.ms / 1000
11
- }
12
-
13
- get minutes() : number {
14
- return this.ms / 1000 / 60
15
- }
16
-
17
- get hours() : number {
18
- return this.ms / 1000 / 60 / 60
19
- }
20
-
21
- get days() : number {
22
- return this.ms / 1000 / 60 / 60 / 24
23
- }
24
-
25
- get weeks() : number {
26
- return this.ms / 1000 / 60 / 60 / 24 / 7
27
- }
28
-
29
- get months() : number {
30
- return this.ms / 1000 / 60 / 60 / 24 / 30
31
- }
32
-
33
- static miliseconds(amount: number): Timespan {
34
- return new Timespan(amount)
35
- }
36
-
37
- static seconds(amount: number): Timespan {
38
- return new Timespan(amount * 1000)
39
- }
40
-
41
- static minutes(mins: number): Timespan {
42
- return new Timespan(mins * 60 * 1000)
43
- }
44
-
45
- static hours(hours: number): Timespan {
46
- return new Timespan(hours * 60 * 60 * 1000)
47
- }
48
-
49
- static days(days: number): Timespan {
50
- return new Timespan(days * 24 * 60 * 60 * 1000)
51
- }
52
-
53
- static weeks(weeks: number): Timespan {
54
- return new Timespan(weeks * 7 * 24 * 60 * 60 * 1000)
55
- }
56
-
57
- static months(months: number): Timespan {
58
- return new Timespan(months * 30 * 24 * 60 * 60 * 1000)
59
- }
60
-
61
- static years(years: number): Timespan {
62
- return new Timespan(years * 365 * 24 * 60 * 60 * 1000)
63
- }
64
-
65
- add(timespan: Timespan): Timespan {
66
- return new Timespan(this.ms + timespan.ms)
67
- }
68
-
69
- subtract(timespan: Timespan): Timespan {
70
- return new Timespan(this.ms - timespan.ms)
71
- }
72
-
73
-
74
- toJSON() {
75
- return {
76
- __type:'Timespan',
77
- value:this.ms
78
- }
79
- }
80
- }
@@ -1,168 +0,0 @@
1
- import { Timespan } from './Timespan';
2
- import { Unixtime } from './Unixtime';
3
-
4
- describe('Unixtime', () => {
5
- it('should create Unixtime object from Date', () => {
6
- const date = new Date();
7
- const unixtime = new Unixtime(date);
8
- expect(unixtime.toDate()).toEqual(date);
9
- });
10
-
11
- it('create invalid date should throw error', () => {
12
- expect(() => new Unixtime('invalid date')).toThrow();
13
- })
14
-
15
- it('should create Unixtime object from string', () => {
16
- const dateString = '2022-01-01T00:00:00Z';
17
- const date = new Date(dateString);
18
- const unixtime = new Unixtime(dateString);
19
- expect(unixtime.toDate()).toEqual(date);
20
- });
21
-
22
- it('should create Unixtime object from number (short form)', () => {
23
- const timestamp = 1640995200; // January 1, 2022 00:00:00 UTC
24
- const date = new Date(timestamp * 1000);
25
- const unixtime = new Unixtime(timestamp);
26
- expect(unixtime.toDate()).toEqual(date);
27
- });
28
-
29
- it('should create Unixtime object from number (long form)', () => {
30
- const timestamp = 1640995200000; // January 1, 2022 00:00:00 UTC
31
- const date = new Date(timestamp);
32
- const unixtime = new Unixtime(timestamp);
33
- expect(unixtime.toDate()).toEqual(date);
34
- });
35
-
36
- it('should convert Unixtime to short Unixtime', () => {
37
- const date = new Date();
38
- const unixtime = new Unixtime(date);
39
- const shortUnixtime = Math.round(date.getTime() / 1000);
40
- expect(unixtime.toShortUnixtime()).toEqual(shortUnixtime);
41
- });
42
-
43
- it('should convert Unixtime to long Unixtime', () => {
44
- const date = new Date();
45
- const unixtime = new Unixtime(date);
46
- expect(unixtime.toLongUnixtime()).toEqual(date.getTime());
47
- });
48
-
49
- it('should convert Unixtime to ISO string', () => {
50
- const date = new Date();
51
- const unixtime = new Unixtime(date);
52
- expect(unixtime.toISOString()).toEqual(date.toISOString());
53
- });
54
-
55
- it('should add miliseconds to Unixtime', () => {
56
- const date = new Date();
57
- const unixtime = new Unixtime(date);
58
- const addedUnixtime = unixtime.addMiliseconds(1000);
59
- expect(addedUnixtime.toDate()).toEqual(new Date(date.getTime() + 1000));
60
- });
61
-
62
- it('should add seconds to Unixtime', () => {
63
- const date = new Date();
64
- const unixtime = new Unixtime(date);
65
- const addedUnixtime = unixtime.addSeconds(1);
66
- expect(addedUnixtime.toDate()).toEqual(new Date(date.getTime() + 1000));
67
- });
68
-
69
- it('should add minutes to Unixtime', () => {
70
- const date = new Date();
71
- const unixtime = new Unixtime(date);
72
- const addedUnixtime = unixtime.addMinutes(1);
73
- expect(addedUnixtime.toDate()).toEqual(new Date(date.getTime() + 60000));
74
- });
75
-
76
- it('should add hours to Unixtime', () => {
77
- const date = new Date();
78
- const unixtime = new Unixtime(date);
79
- const addedUnixtime = unixtime.addHours(1);
80
- expect(addedUnixtime.toDate()).toEqual(new Date(date.getTime() + 3600000));
81
- });
82
-
83
- it('should add days to Unixtime', () => {
84
- const date = new Date();
85
- const unixtime = new Unixtime(date);
86
- const addedUnixtime = unixtime.addDays(1);
87
- expect(addedUnixtime.toDate()).toEqual(new Date(date.getTime() + 86400000));
88
- });
89
-
90
- it('should add months to Unixtime', () => {
91
- const date = new Date();
92
- const unixtime = new Unixtime(date);
93
- const addedUnixtime = unixtime.addMonths(1);
94
- expect(addedUnixtime.toDate()).toEqual(new Date(date.setMonth(date.getMonth() + 1)));
95
- });
96
-
97
- it('should add years to Unixtime', () => {
98
- const date = new Date();
99
- const unixtime = new Unixtime(date);
100
- const addedUnixtime = unixtime.addYears(1);
101
- expect(addedUnixtime.toDate()).toEqual(new Date(date.setFullYear(date.getFullYear() + 1)));
102
- });
103
-
104
- it('clone should create brand new object', () => {
105
- const unixtime0 = new Unixtime(new Date())
106
- const unixtime1 = unixtime0.clone();
107
- expect(unixtime1).not.toBe(unixtime0);
108
- expect(unixtime0.toDate()).toEqual(unixtime1.toDate());
109
- });
110
-
111
-
112
- it('day,month,year should return correct values', () => {
113
- const unixtime = new Unixtime("2024-10-11T12:13:14Z");
114
- expect(unixtime.day).toEqual(11);
115
- expect(unixtime.month).toEqual(10);
116
- expect(unixtime.year).toEqual(2024);
117
- expect(unixtime.minutes).toEqual(13);
118
- expect(unixtime.seconds).toEqual(14);
119
- expect(unixtime.hours).toEqual(12);
120
- })
121
-
122
- it('fromYYYYMMDD should create Unixtime object from string', () => {
123
- const unixtime = Unixtime.fromYYYYMMDD('20241011');
124
- expect(unixtime.toISOString()).toEqual('2024-10-11T00:00:00.000Z');
125
- })
126
-
127
- it('yyyymmddhh should return correct values',() => {
128
- const unixtime = new Unixtime("2024-10-11T12:13:14Z");
129
- expect(unixtime.yyyymmdd()).toEqual('20241011');
130
- expect(unixtime.yyyymmddhh()).toEqual('2024101112');
131
- // should also work with optional seperators
132
- expect(unixtime.yyyymmddhh('-')).toEqual('2024-10-11-12');
133
- })
134
-
135
- it('randomPast should return random time in the past', () => {
136
- const end = Unixtime.now()
137
- const begin = end.clone().addYears(-1)
138
- for(let i=0;i<100000;i++) {
139
- const rand = Unixtime.randomPast(Timespan.years(1))
140
- expect(rand.toLongUnixtime()).toBeGreaterThan(begin.toLongUnixtime());
141
- expect(rand.toLongUnixtime()).toBeLessThan(end.toLongUnixtime());
142
- }
143
- })
144
-
145
- it('randomFuture should return random time in the future within given timespan of 1 year', () => {
146
- const begin = Unixtime.now()
147
- const end = begin.clone().addYears(1)
148
- for(let i=0;i<100000;i++) {
149
- const rand = Unixtime.randomFuture(Timespan.years(1))
150
- expect(rand.toLongUnixtime()).toBeGreaterThan(begin.toLongUnixtime());
151
- expect(rand.toLongUnixtime()).toBeLessThan(end.toLongUnixtime());
152
- }
153
- })
154
-
155
- it('yyyymmdd should work as designed',() => {
156
- const unixtime = new Unixtime("2024-10-11T12:13:14Z");
157
- expect(unixtime.yyyymmdd()).toEqual('20241011');
158
- expect(unixtime.yyyymmdd('-')).toEqual('2024-10-11');
159
- })
160
-
161
- it('fromYYYYMMDD should throw error when invalid date', () => {
162
- expect(() => Unixtime.fromYYYYMMDD('20243131')).toThrow('Invalid month');
163
- expect(() => Unixtime.fromYYYYMMDD('20241233')).toThrow('Invalid day');
164
- expect(() => Unixtime.fromYYYYMMDD('xx')).toThrow('Invalid yyyymmdd value');
165
- //@ts-ignore
166
- expect(() => Unixtime.fromYYYYMMDD([])).toThrow('Invalid yyyymmdd value');
167
- })
168
- });
@@ -1,208 +0,0 @@
1
- import { Timespan } from "./Timespan"
2
-
3
- // this will be a class to work with short and long version of unixtime format
4
- export class Unixtime {
5
- private value: Date
6
-
7
-
8
- static EMPTY = new Unixtime(new Date(0))
9
-
10
- static NOW() {
11
- return new Unixtime(Date.now())
12
- }
13
-
14
- static now() {
15
- return new Unixtime(Date.now())
16
- }
17
-
18
- greaterThan(other: Unixtime) {
19
- return this.toLongUnixtime() > other.toLongUnixtime()
20
- }
21
-
22
- isEmpty() {
23
- return this.toLongUnixtime() == 0
24
- }
25
-
26
- lessThan(other: Unixtime) {
27
- return this.toLongUnixtime() < other.toLongUnixtime()
28
- }
29
-
30
- get elapsed():Timespan {
31
- return new Timespan(Date.now() - this.toLongUnixtime())
32
- }
33
-
34
- toJSON() {
35
- return {
36
- __type:'Unixtime',
37
- value:this.toLongUnixtime()
38
- }
39
- }
40
-
41
-
42
- constructor(value: Date | string | number) {
43
- if (typeof value === 'string') {
44
- this.value = new Date(value)
45
- } else if (typeof value === 'number') {
46
- // the number might be short or long form(from nodejs Date.now()
47
- if (value < 10000000000) value *= 1000
48
- else
49
- value = Math.round(value)
50
- // set the value
51
- this.value = new Date(value)
52
- }
53
- else if (value instanceof Date) {
54
- this.value = value
55
- }
56
- else {
57
- throw new Error('Invalid value')
58
- }
59
-
60
- if (isNaN(this.value.getTime())) {
61
- throw new Error('Invalid date')
62
- }
63
- }
64
-
65
- public addTimespan(timespan: Timespan): Unixtime {
66
- this.value = new Date(this.value.getTime() + timespan.miliseconds)
67
- return this
68
- }
69
-
70
- public subtractTimespan(timespan: Timespan): Unixtime {
71
- this.value = new Date(this.value.getTime() - timespan.miliseconds)
72
- return this
73
- }
74
-
75
- public addMiliseconds(miliseconds: number = 1): Unixtime {
76
- this.value = new Date(this.value.getTime() + miliseconds)
77
- return this
78
- }
79
-
80
- public addSeconds(seconds: number = 1): Unixtime {
81
- this.value = new Date(this.value.getTime() + seconds * 1000)
82
- return this
83
- }
84
-
85
- public addMinutes(minutes: number = 1): Unixtime {
86
- this.value = new Date(this.value.getTime() + minutes * 60000)
87
- return this
88
- }
89
-
90
- public addHours(hours: number = 1): Unixtime {
91
- this.value = new Date(this.value.getTime() + hours * 3600000)
92
- return this
93
- }
94
-
95
- public addDays(days: number = 1): Unixtime {
96
- this.value = new Date(this.value.getTime() + days * 86400000)
97
- return this
98
- }
99
-
100
- public addMonths(months: number = 1): Unixtime {
101
- this.value.setUTCMonth(this.value.getMonth() + months)
102
- return this
103
- }
104
-
105
- public addYears(years: number = 1): Unixtime {
106
- this.value.setUTCFullYear(this.year + years)
107
- return this
108
- }
109
-
110
- public yyyymmdd(seperator: string=""): string {
111
- let mm = this.month
112
- let dd = this.day
113
- return [this.value.getFullYear(),
114
- (mm > 9 ? '' : '0') + mm,
115
- (dd > 9 ? '' : '0') + dd,
116
- ].join(seperator)
117
- }
118
-
119
- public yyyymmddhh(seperator: string=""): string {
120
- let mm = this.month
121
- let dd = this.day
122
- let hh = this.hours
123
- return [this.year,
124
- (mm > 9 ? '' : '0') + mm,
125
- (dd > 9 ? '' : '0') + dd,
126
- (hh > 9 ? '' : '0') + hh,
127
- ].join(seperator)
128
- }
129
-
130
- /**
131
- @deprecated use 'day' instead
132
- */
133
- public getDay() : number {return this.value.getUTCDay()}
134
-
135
- get day(): number { return this.value.getUTCDate() }
136
- get month(): number { return this.value.getUTCMonth() + 1 }
137
- get year(): number { return this.value.getUTCFullYear() }
138
- get hours(): number { return this.value.getUTCHours() }
139
- get minutes(): number { return this.value.getUTCMinutes() }
140
- get seconds(): number { return this.value.getUTCSeconds() }
141
-
142
- static from(value: Date | string | number) {
143
- return new Unixtime(value)
144
- }
145
-
146
- public toShortUnixtime(): number {
147
- return Math.round(this.toLongUnixtime() / 1000)
148
- }
149
-
150
- public toLongUnixtime(): number {
151
- return this.value.getTime()
152
- }
153
-
154
- public toDate(): Date {
155
- return this.value
156
- }
157
-
158
- public toISOString(): string {
159
- return this.value.toISOString()
160
- }
161
-
162
- public elapsedSeconds(): number {
163
- return Math.round((Date.now() - this.toLongUnixtime()) / 1000)
164
- }
165
-
166
- public elapsedMinutes(): number {
167
- return Math.round(this.elapsedSeconds() / 60)
168
- }
169
-
170
- clone():Unixtime {
171
- return new Unixtime(this.toLongUnixtime())
172
- }
173
-
174
- /**
175
- * @param max maximum timespan to subtract
176
- * @returns returns random time in the past within given timespan
177
- */
178
- static randomPast(max: Timespan=Timespan.years(1), base: Unixtime=Unixtime.now()): Unixtime {
179
- return base.addSeconds(Math.random()*max.seconds*-1)
180
- }
181
-
182
- /**
183
- * @param max maximum timespan to add
184
- * @returns returns random time in the future within given timespan
185
- */
186
- static randomFuture(max: Timespan=Timespan.years(1), base: Unixtime=Unixtime.now()): Unixtime {
187
- return base.addSeconds(Math.random()*max.seconds)
188
- }
189
-
190
- static fromYYYYMMDD(value: string): Unixtime {
191
- if (value.length != 8) throw new Error('Invalid yyyymmdd value')
192
- let year = parseInt(value.substring(0, 4))
193
- let month = parseInt(value.substring(4, 6)) - 1
194
- let day = parseInt(value.substring(6, 8))
195
- if (isNaN(year) || isNaN(month) || isNaN(day)) throw new Error('Invalid yyyymmdd value')
196
- if (month < 0 || month > 11) throw new Error('Invalid month')
197
- if (day < 1 || day > 31) throw new Error('Invalid day')
198
- return new Unixtime(new Date(Date.UTC(year, month, day)))
199
- }
200
-
201
- static try(value: Date | string | number): Unixtime | null {
202
- try {
203
- return new Unixtime(value)
204
- } catch (e) {
205
- return null
206
- }
207
- }
208
- }
package/ts/types.ts DELETED
@@ -1 +0,0 @@
1
- export type UnixtimeShort = number
package/tsconfig.json DELETED
@@ -1,36 +0,0 @@
1
- {
2
- "compilerOptions": {
3
- "target": "es2017",
4
- "experimentalDecorators": true,
5
- "emitDecoratorMetadata": true,
6
- "module": "commonjs",
7
- "moduleResolution" : "Node",
8
- "esModuleInterop": true,
9
- "forceConsistentCasingInFileNames": true,
10
- "strict": true,
11
- "declaration": true, // Generates corresponding .d.ts file
12
- "noImplicitReturns": true, // Report error when not all code paths in function return a value
13
- "noUnusedLocals": true, // Report errors on unused locals
14
- // "noUnusedParameters": true, // Report errors on unused parameters
15
- "noFallthroughCasesInSwitch": true, // Report errors for fallthrough cases in switch statement
16
- // "noUncheckedIndexedAccess": true, // Include 'undefined' in index signature results
17
- "noImplicitAny": true, // Raise error on expressions and declarations with an implied 'any' type
18
- "strictNullChecks": true, // Enable strict null checking
19
- "strictFunctionTypes": true, // Ensure function parameter types match
20
- "strictBindCallApply": true, // Ensure 'bind', 'call', and 'apply' methods match function types
21
- "strictPropertyInitialization": true, // Ensure non-undefined class properties are initialized in the constructor
22
- "alwaysStrict": true, // Parse in strict mode and emit "use strict" for each source file
23
- "sourceMap": true,
24
- "skipLibCheck": true,
25
- "baseUrl": ".",
26
- "paths": {
27
- "@root/*": ["./*"],
28
- "@models/*": ["./models/*"],
29
- "@inc/*": ["./inc/ts/*"]
30
- },
31
- "typeRoots": ["./node_modules/@types", "./types/"]
32
- },
33
- "exclude": [
34
- "**/*.test.ts"
35
- ]
36
- }