@bitblit/ratchet-common 4.0.115-alpha → 4.0.119-alpha

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 (114) hide show
  1. package/lib/index.d.ts +73 -1
  2. package/lib/index.mjs +4 -0
  3. package/lib/index.mjs.map +1 -0
  4. package/lib/lang/base64-ratchet.d.ts +1 -1
  5. package/lib/stream/buffer-writable.d.ts +2 -2
  6. package/lib/stream/multi-stream.d.ts +1 -1
  7. package/lib/stream/stream-ratchet.d.ts +2 -2
  8. package/lib/stream/string-writable.d.ts +1 -1
  9. package/package.json +9 -5
  10. package/lib/2d/line-2d.js +0 -1
  11. package/lib/2d/plane-2d.js +0 -1
  12. package/lib/2d/point-2d.js +0 -1
  13. package/lib/2d/poly-line-2d.js +0 -1
  14. package/lib/2d/ratchet-2d.js +0 -245
  15. package/lib/2d/ratchet-2d.spec.js +0 -117
  16. package/lib/build/build-information.js +0 -1
  17. package/lib/build/ratchet-common-info.js +0 -14
  18. package/lib/histogram/histogram-entry.js +0 -1
  19. package/lib/histogram/histogram.js +0 -48
  20. package/lib/histogram/histogram.spec.js +0 -19
  21. package/lib/index.js +0 -1
  22. package/lib/jwt/common-jwt-token.js +0 -1
  23. package/lib/jwt/expired-jwt-handling.js +0 -6
  24. package/lib/jwt/jwt-ratchet-like.js +0 -1
  25. package/lib/jwt/jwt-ratchet.js +0 -164
  26. package/lib/jwt/jwt-ratchet.spec.js +0 -49
  27. package/lib/jwt/jwt-token-base.js +0 -1
  28. package/lib/lang/array-ratchet.js +0 -83
  29. package/lib/lang/array-ratchet.spec.js +0 -68
  30. package/lib/lang/base64-ratchet.js +0 -45
  31. package/lib/lang/base64-ratchet.spec.js +0 -28
  32. package/lib/lang/boolean-ratchet.js +0 -45
  33. package/lib/lang/boolean-ratchet.spec.js +0 -81
  34. package/lib/lang/composite-last-success-provider.js +0 -26
  35. package/lib/lang/composite-last-success-provider.spec.js +0 -26
  36. package/lib/lang/date-ratchet.js +0 -29
  37. package/lib/lang/date-ratchet.spec.js +0 -21
  38. package/lib/lang/duration-ratchet.js +0 -42
  39. package/lib/lang/duration-ratchet.spec.js +0 -39
  40. package/lib/lang/enum-ratchet.js +0 -30
  41. package/lib/lang/enum-ratchet.spec.js +0 -31
  42. package/lib/lang/error-ratchet.js +0 -44
  43. package/lib/lang/error-ratchet.spec.js +0 -20
  44. package/lib/lang/esm-ratchet.js +0 -17
  45. package/lib/lang/expiring-object.js +0 -72
  46. package/lib/lang/expiring-object.spec.js +0 -51
  47. package/lib/lang/geolocation-ratchet.js +0 -263
  48. package/lib/lang/geolocation-ratchet.spec.js +0 -74
  49. package/lib/lang/global-ratchet.js +0 -43
  50. package/lib/lang/global-ratchet.spec.js +0 -14
  51. package/lib/lang/key-value.js +0 -4
  52. package/lib/lang/last-success-provider.js +0 -1
  53. package/lib/lang/map-ratchet.js +0 -164
  54. package/lib/lang/map-ratchet.spec.js +0 -90
  55. package/lib/lang/no.js +0 -4
  56. package/lib/lang/no.spec.js +0 -7
  57. package/lib/lang/number-ratchet.js +0 -155
  58. package/lib/lang/number-ratchet.spec.js +0 -118
  59. package/lib/lang/parsed-url.js +0 -1
  60. package/lib/lang/promise-ratchet.js +0 -138
  61. package/lib/lang/promise-ratchet.spec.js +0 -74
  62. package/lib/lang/require-ratchet.js +0 -56
  63. package/lib/lang/require-ratchet.spec.js +0 -80
  64. package/lib/lang/stop-watch.js +0 -114
  65. package/lib/lang/string-ratchet.js +0 -201
  66. package/lib/lang/string-ratchet.spec.js +0 -158
  67. package/lib/lang/time-zone-ratchet.js +0 -77
  68. package/lib/lang/time-zone-ratchet.spec.js +0 -40
  69. package/lib/lang/timeout-token.js +0 -17
  70. package/lib/lang/timeout-token.spec.js +0 -9
  71. package/lib/lang/transform-ratchet.js +0 -66
  72. package/lib/lang/transform-ratchet.spec.js +0 -118
  73. package/lib/logger/classic-single-line-log-message-formatter.js +0 -13
  74. package/lib/logger/log-message-builder.js +0 -48
  75. package/lib/logger/log-message-format-type.js +0 -6
  76. package/lib/logger/log-message-formatter.js +0 -1
  77. package/lib/logger/log-message-processor.js +0 -1
  78. package/lib/logger/log-message.js +0 -1
  79. package/lib/logger/log-snapshot.js +0 -1
  80. package/lib/logger/logger-instance.js +0 -208
  81. package/lib/logger/logger-level-name.js +0 -9
  82. package/lib/logger/logger-meta.js +0 -1
  83. package/lib/logger/logger-options.js +0 -1
  84. package/lib/logger/logger-output-function.js +0 -6
  85. package/lib/logger/logger-ring-buffer.js +0 -73
  86. package/lib/logger/logger-util.js +0 -44
  87. package/lib/logger/logger-util.spec.js +0 -9
  88. package/lib/logger/logger.js +0 -134
  89. package/lib/logger/logger.spec.js +0 -134
  90. package/lib/logger/none-log-message-formatter.js +0 -5
  91. package/lib/logger/structured-json-log-message-formatter.js +0 -19
  92. package/lib/network/browser-local-ip-provider.js +0 -21
  93. package/lib/network/browser-local-ip-provider.spec.js +0 -16
  94. package/lib/network/fixed-local-ip-provider.js +0 -9
  95. package/lib/network/local-ip-provider.js +0 -1
  96. package/lib/network/network-ratchet.js +0 -102
  97. package/lib/network/network-ratchet.spec.js +0 -13
  98. package/lib/stream/buffer-writable.js +0 -16
  99. package/lib/stream/multi-stream.js +0 -12
  100. package/lib/stream/stream-ratchet.js +0 -68
  101. package/lib/stream/stream-ratchet.spec.js +0 -13
  102. package/lib/stream/string-writable.js +0 -14
  103. package/lib/stream/string-writable.spec.js +0 -12
  104. package/lib/third-party/google/google-recaptcha-ratchet.js +0 -28
  105. package/lib/third-party/google/google-recaptcha-ratchet.spec.js +0 -20
  106. package/lib/third-party/twilio/twilio-ratchet.js +0 -73
  107. package/lib/transform/built-in-transforms.js +0 -191
  108. package/lib/transform/transform-rule.js +0 -1
  109. package/lib/tx/transaction-configuration.js +0 -1
  110. package/lib/tx/transaction-final-state.js +0 -6
  111. package/lib/tx/transaction-ratchet.js +0 -76
  112. package/lib/tx/transaction-ratchet.spec.js +0 -130
  113. package/lib/tx/transaction-result.js +0 -1
  114. package/lib/tx/transaction-step.js +0 -1
@@ -1,164 +0,0 @@
1
- import jwt from 'jsonwebtoken';
2
- import { RequireRatchet } from '../lang/require-ratchet.js';
3
- import { Logger } from '../logger/logger.js';
4
- import { StringRatchet } from '../lang/string-ratchet.js';
5
- import { DurationRatchet } from '../lang/duration-ratchet.js';
6
- import { LoggerLevelName } from '../logger/logger-level-name.js';
7
- import { ExpiredJwtHandling } from './expired-jwt-handling.js';
8
- export class JwtRatchet {
9
- _encryptionKeyPromise;
10
- _decryptKeysPromise;
11
- _jtiGenerator;
12
- _decryptOnlyKeyUseLogLevel;
13
- _parseFailureLogLevel;
14
- static EXPIRED_FLAG_NAME = '__jwtServiceExpiredFlag';
15
- constructor(_encryptionKeyPromise, _decryptKeysPromise, _jtiGenerator = StringRatchet.createType4Guid, _decryptOnlyKeyUseLogLevel = LoggerLevelName.info, _parseFailureLogLevel = LoggerLevelName.debug) {
16
- this._encryptionKeyPromise = _encryptionKeyPromise;
17
- this._decryptKeysPromise = _decryptKeysPromise;
18
- this._jtiGenerator = _jtiGenerator;
19
- this._decryptOnlyKeyUseLogLevel = _decryptOnlyKeyUseLogLevel;
20
- this._parseFailureLogLevel = _parseFailureLogLevel;
21
- RequireRatchet.notNullOrUndefined(_encryptionKeyPromise, 'encryptionKeyPromise');
22
- }
23
- get encryptionKeyPromise() {
24
- return this._encryptionKeyPromise;
25
- }
26
- get decryptKeysPromise() {
27
- return this._decryptKeysPromise;
28
- }
29
- get jtiGenerator() {
30
- return this._jtiGenerator;
31
- }
32
- get decryptOnlyKeyUseLogLevel() {
33
- return this._decryptOnlyKeyUseLogLevel;
34
- }
35
- get parseFailureLogLevel() {
36
- return this._parseFailureLogLevel;
37
- }
38
- static hasExpiredFlag(ob) {
39
- return ob && ob[JwtRatchet.EXPIRED_FLAG_NAME] === true;
40
- }
41
- static async invalidSafeDecode(payloadString, decryptKey, logLevel = LoggerLevelName.silly) {
42
- let rval = null;
43
- try {
44
- rval = jwt.verify(payloadString, decryptKey, { ignoreExpiration: true });
45
- }
46
- catch (err) {
47
- Logger.logByLevel(logLevel, 'Caught %s - ignoring', err);
48
- }
49
- return rval;
50
- }
51
- static async secondsRemainingUntilExpiration(payloadString) {
52
- let rval = null;
53
- if (StringRatchet.trimToNull(payloadString)) {
54
- const output = await JwtRatchet.decodeTokenNoVerify(payloadString);
55
- const nowSecond = Math.floor(Date.now() / 1000);
56
- if (output.exp) {
57
- const expSeconds = output.exp > nowSecond * 100 ? Math.floor(output.exp / 1000) : output.exp;
58
- rval = Math.max(0, expSeconds - nowSecond);
59
- }
60
- }
61
- return rval;
62
- }
63
- static async msRemainingUntilExpiration(payloadString) {
64
- const secs = await JwtRatchet.secondsRemainingUntilExpiration(payloadString);
65
- let rval = null;
66
- if (secs !== null && secs !== undefined) {
67
- rval = secs * 1000;
68
- }
69
- return rval;
70
- }
71
- async decodeToken(payloadString, expiredHandling = ExpiredJwtHandling.RETURN_NULL) {
72
- const encKeys = await this.encryptionKeyArray();
73
- let decKeys = Object.assign([], encKeys);
74
- if (this.decryptKeysPromise) {
75
- decKeys = decKeys.concat(await this.decryptKeysPromise);
76
- }
77
- const keysTried = [];
78
- let payload = null;
79
- for (let i = 0; i < decKeys.length && !payload; i++) {
80
- keysTried.push(StringRatchet.obscure(decKeys[i], 1, 1));
81
- const logLevel = i === decKeys.length - 1 && this.parseFailureLogLevel ? this.parseFailureLogLevel : LoggerLevelName.silly;
82
- payload = await JwtRatchet.invalidSafeDecode(payloadString, decKeys[i], logLevel);
83
- if (payload && i >= encKeys.length) {
84
- Logger.logByLevel(this.decryptOnlyKeyUseLogLevel, 'Used old key to decode token : %s', StringRatchet.obscure(decKeys[i], 2));
85
- }
86
- }
87
- if (payload) {
88
- const nowSeconds = Math.floor(Date.now() / 1000);
89
- const expSeconds = payload?.exp && payload.exp > nowSeconds * 100 ? Math.floor(payload.exp / 1000) : payload?.exp;
90
- const nbfSeconds = payload?.nbf && payload.nbf > nowSeconds * 100 ? Math.floor(payload.nbf / 1000) : payload?.nbf;
91
- if ((expSeconds && nowSeconds >= expSeconds) || (nbfSeconds && nowSeconds <= nbfSeconds)) {
92
- const age = nowSeconds - expSeconds;
93
- Logger.debug('JWT token expired or before NBF : on %d, %s ago', payload.exp, DurationRatchet.formatMsDuration(age * 1000));
94
- switch (expiredHandling) {
95
- case ExpiredJwtHandling.THROW_EXCEPTION:
96
- throw new Error('JWT Token was expired');
97
- case ExpiredJwtHandling.ADD_FLAG:
98
- payload[JwtRatchet.EXPIRED_FLAG_NAME] = true;
99
- break;
100
- default:
101
- payload = null;
102
- break;
103
- }
104
- }
105
- }
106
- else {
107
- Logger.warn('Unable to parse a payload (Tried %j) from : %s', keysTried, payloadString);
108
- }
109
- return payload;
110
- }
111
- async encryptionKeyArray() {
112
- const encKey = await this.encryptionKeyPromise;
113
- const rval = Array.isArray(encKey) ? encKey : [encKey];
114
- if (rval.length < 1) {
115
- throw new Error('Cannot create JwtRatchet with empty encryption key set');
116
- }
117
- return rval;
118
- }
119
- async selectRandomEncryptionKey() {
120
- const encKey = await this.encryptionKeyArray();
121
- const rval = encKey[Math.floor(Math.random() * encKey.length)];
122
- return rval;
123
- }
124
- async createTokenString(payload, expirationSeconds, overrideEncryptionKey) {
125
- const encKey = StringRatchet.trimToNull(overrideEncryptionKey)
126
- ? StringRatchet.trimToNull(overrideEncryptionKey)
127
- : await this.selectRandomEncryptionKey();
128
- RequireRatchet.notNullOrUndefined(payload, 'payload');
129
- payload.jti = this.jtiGenerator ? this.jtiGenerator() : null;
130
- if (expirationSeconds) {
131
- const nowSeconds = Math.floor(Date.now() / 1000);
132
- const expires = nowSeconds + expirationSeconds;
133
- Logger.debug('Forcing expiration to %d', expires);
134
- payload.exp = expires;
135
- }
136
- const token = jwt.sign(payload, encKey);
137
- return token;
138
- }
139
- async refreshJWTString(tokenString, allowExpired, expirationSeconds) {
140
- const handling = allowExpired ? ExpiredJwtHandling.ADD_FLAG : ExpiredJwtHandling.THROW_EXCEPTION;
141
- const payload = await this.decodeToken(tokenString, handling);
142
- const originalDurationSeconds = payload.exp && payload.iat ? payload.exp - payload.iat : null;
143
- const newExpirationSeconds = expirationSeconds || originalDurationSeconds;
144
- JwtRatchet.removeJwtFields(payload);
145
- JwtRatchet.removeExpiredFlag(payload);
146
- const token = await this.createTokenString(payload, newExpirationSeconds);
147
- return token;
148
- }
149
- static decodeTokenNoVerify(token) {
150
- return jwt.decode(token);
151
- }
152
- static removeJwtFields(ob) {
153
- if (ob) {
154
- ['iss', 'sub', 'aud', 'exp', 'nbf', 'iat', 'jti'].forEach((k) => {
155
- delete ob[k];
156
- });
157
- }
158
- }
159
- static removeExpiredFlag(ob) {
160
- if (ob) {
161
- delete ob[JwtRatchet.EXPIRED_FLAG_NAME];
162
- }
163
- }
164
- }
@@ -1,49 +0,0 @@
1
- import { JwtRatchet } from './jwt-ratchet.js';
2
- import { ExpiredJwtHandling } from './expired-jwt-handling.js';
3
- describe('#jwtRatchet', function () {
4
- it('should test expiration flag for a token with millisecond expiration', async () => {
5
- const jwt = new JwtRatchet(Promise.resolve('test1234'), Promise.resolve([]));
6
- const token1 = await jwt.createTokenString({ test: 1, exp: Date.now() - 100 }, null);
7
- const output = await jwt.decodeToken(token1, ExpiredJwtHandling.ADD_FLAG);
8
- expect(output).not.toBeNull();
9
- expect(JwtRatchet.hasExpiredFlag(output)).toBeTruthy();
10
- });
11
- it('should test expiration calculation for a token', async () => {
12
- const jwt = new JwtRatchet(Promise.resolve('test1234'), Promise.resolve([]));
13
- const token1 = await jwt.createTokenString({ test: 1 }, 120);
14
- const output = await JwtRatchet.secondsRemainingUntilExpiration(token1);
15
- expect(output).not.toBeNull();
16
- expect(output).toBeLessThan(121);
17
- expect(output).toBeGreaterThan(115);
18
- });
19
- it('should test round-trip for a token', async () => {
20
- const jwt = new JwtRatchet(Promise.resolve('test1234'), Promise.resolve([]));
21
- const token1 = await jwt.createTokenString({ test: 1 }, 120);
22
- const output = await jwt.decodeToken(token1);
23
- expect(output).not.toBeNull();
24
- expect(output['test']).toEqual(1);
25
- });
26
- it('should test round-trip for a token with array enc keys', async () => {
27
- const jwt = new JwtRatchet(Promise.resolve(['test1234', 'test5678']), Promise.resolve([]));
28
- const token1 = await jwt.createTokenString({ test: 1 }, 120);
29
- const token2 = await jwt.createTokenString({ test: 1 }, 120);
30
- const token3 = await jwt.createTokenString({ test: 1 }, 120);
31
- const output1 = await jwt.decodeToken(token1);
32
- const output2 = await jwt.decodeToken(token2);
33
- const output3 = await jwt.decodeToken(token3);
34
- expect(output1).not.toBeNull();
35
- expect(output1['test']).toEqual(1);
36
- expect(output2).not.toBeNull();
37
- expect(output2['test']).toEqual(1);
38
- expect(output3).not.toBeNull();
39
- expect(output3['test']).toEqual(1);
40
- });
41
- it('should decode with a decode key', async () => {
42
- const jwtOld = new JwtRatchet(Promise.resolve('oldKey'), Promise.resolve([]));
43
- const jwtNew = new JwtRatchet(Promise.resolve('newKey'), Promise.resolve(['oldKey']));
44
- const token1 = await jwtOld.createTokenString({ test: 1 }, 120);
45
- const output = await jwtNew.decodeToken(token1);
46
- expect(output).not.toBeNull();
47
- expect(output['test']).toEqual(1);
48
- });
49
- });
@@ -1 +0,0 @@
1
- export {};
@@ -1,83 +0,0 @@
1
- import { RequireRatchet } from './require-ratchet.js';
2
- import { MapRatchet } from './map-ratchet.js';
3
- export class ArrayRatchet {
4
- static wrapElementsInArray(input) {
5
- return input.map((i) => [i]);
6
- }
7
- static compareTwoArrays(ar1, ar2, fn) {
8
- ar1.sort(fn);
9
- ar2.sort(fn);
10
- let id1 = 0;
11
- let id2 = 0;
12
- const rval = {
13
- matching: [],
14
- setOneOnly: [],
15
- setTwoOnly: [],
16
- };
17
- while (id1 < ar1.length && id2 < ar2.length) {
18
- const aVal = ar1[id1];
19
- const pVal = ar2[id2];
20
- const comp = fn(aVal, pVal);
21
- if (comp === 0) {
22
- rval.matching.push(aVal);
23
- id1++;
24
- id2++;
25
- }
26
- else if (comp < 0) {
27
- rval.setOneOnly.push(aVal);
28
- id1++;
29
- }
30
- else {
31
- rval.setTwoOnly.push(pVal);
32
- id2++;
33
- }
34
- }
35
- if (id1 < ar1.length - 1) {
36
- rval.setOneOnly = rval.setOneOnly.concat(ar1.slice(id1));
37
- }
38
- if (id2 < ar2.length - 1) {
39
- rval.setTwoOnly = rval.setTwoOnly.concat(ar2.slice(id2));
40
- }
41
- return rval;
42
- }
43
- static extractSubarrayFromSortedByNumberField(input, fieldDotPath, minInclusive, maxExclusive) {
44
- if (!input || input.length === 0) {
45
- return input;
46
- }
47
- let bottomIdx = minInclusive === null ? 0 : ArrayRatchet.findSplit(input, fieldDotPath, minInclusive) || 0;
48
- const topIdx = maxExclusive === null ? input.length : ArrayRatchet.findSplit(input, fieldDotPath, maxExclusive);
49
- const bottomValue = MapRatchet.findValueDotPath(input[bottomIdx], fieldDotPath);
50
- if (bottomIdx === input.length - 1 && bottomValue < minInclusive) {
51
- return [];
52
- }
53
- if (bottomIdx < input.length && bottomIdx < topIdx && bottomValue < minInclusive) {
54
- bottomIdx++;
55
- }
56
- return input.slice(bottomIdx, topIdx + 1);
57
- }
58
- static findSplit(input, fieldDotPath, target) {
59
- RequireRatchet.notNullOrUndefined(input);
60
- RequireRatchet.notNullOrUndefined(fieldDotPath);
61
- RequireRatchet.notNullOrUndefined(target);
62
- if (input.length === 0 || MapRatchet.findValueDotPath(input[0], fieldDotPath) > target) {
63
- return null;
64
- }
65
- let min = 0;
66
- let max = input.length;
67
- let rval = null;
68
- while (rval === null) {
69
- const curIdx = Math.floor((min + max) / 2);
70
- const curVal = MapRatchet.findValueDotPath(input[curIdx], fieldDotPath);
71
- if (min === max || min === max - 1) {
72
- rval = min;
73
- }
74
- else if (curVal <= target) {
75
- min = curIdx;
76
- }
77
- else {
78
- max = curIdx;
79
- }
80
- }
81
- return rval;
82
- }
83
- }
@@ -1,68 +0,0 @@
1
- import { ArrayRatchet } from './array-ratchet.js';
2
- const sortedArr = [
3
- {
4
- n: 'test1',
5
- v: 1,
6
- },
7
- {
8
- n: 'test1',
9
- v: 2,
10
- },
11
- {
12
- n: 'test1',
13
- v: 4,
14
- },
15
- {
16
- n: 'test1',
17
- v: 4,
18
- },
19
- {
20
- n: 'test1',
21
- v: 7,
22
- },
23
- {
24
- n: 'test1',
25
- v: 12,
26
- },
27
- {
28
- n: 'test1',
29
- v: 25,
30
- },
31
- {
32
- n: 'test1',
33
- v: 30,
34
- },
35
- ];
36
- describe('#extractSubarrayFromSortedByNumberField', function () {
37
- it('should extract the subarray', function () {
38
- const subArr1 = ArrayRatchet.extractSubarrayFromSortedByNumberField(sortedArr, 'v', 5, 14);
39
- expect(subArr1.length).toEqual(2);
40
- const subArr2 = ArrayRatchet.extractSubarrayFromSortedByNumberField(sortedArr, 'v', null, 4);
41
- expect(subArr2.length).toEqual(4);
42
- const subArr3 = ArrayRatchet.extractSubarrayFromSortedByNumberField(sortedArr, 'v', 7, null);
43
- expect(subArr3.length).toEqual(4);
44
- });
45
- });
46
- describe('#compareTwoArrays', function () {
47
- it('should create a match report', function () {
48
- const arr1 = ['a', 'b', 'c'];
49
- const arr2 = ['a', 'e', 'i', 'o', 'u'];
50
- const report = ArrayRatchet.compareTwoArrays(arr1, arr2, (a, b) => a.localeCompare(b));
51
- expect(report).toBeTruthy();
52
- expect(report.setOneOnly.length).toEqual(2);
53
- expect(report.setTwoOnly.length).toEqual(4);
54
- expect(report.matching.length).toEqual(1);
55
- });
56
- });
57
- describe('#findSplit', function () {
58
- it('should find the split', function () {
59
- const split10 = ArrayRatchet.findSplit(sortedArr, 'v', 10);
60
- const split4 = ArrayRatchet.findSplit(sortedArr, 'v', 4);
61
- const split0 = ArrayRatchet.findSplit(sortedArr, 'v', 0);
62
- const split32 = ArrayRatchet.findSplit(sortedArr, 'v', 32);
63
- expect(split10).toEqual(4);
64
- expect(split4).toEqual(3);
65
- expect(split0).toEqual(null);
66
- expect(split32).toEqual(7);
67
- });
68
- });
@@ -1,45 +0,0 @@
1
- import { Logger } from '../logger/logger.js';
2
- export class Base64Ratchet {
3
- static safeObjectToBase64JSON(input) {
4
- return !!input ? Base64Ratchet.generateBase64VersionOfString(JSON.stringify(input)) : null;
5
- }
6
- static safeBase64JSONParse(input) {
7
- let rval = {};
8
- try {
9
- if (input) {
10
- rval = JSON.parse(Base64Ratchet.base64StringToString(input));
11
- }
12
- }
13
- catch (err) {
14
- Logger.warn('Error parsing b64/json : %s as json, got %s', input, err, err);
15
- rval = {};
16
- }
17
- return rval;
18
- }
19
- static generateBase64VersionOfBlob(blob) {
20
- return new Promise(function (resolve, reject) {
21
- if (!blob || blob.size == 0) {
22
- reject('Wont convert null or non-blob or empty blob');
23
- }
24
- else {
25
- const reader = new FileReader();
26
- reader.onloadend = function () {
27
- resolve(reader.result.toString());
28
- };
29
- reader.readAsDataURL(blob);
30
- }
31
- });
32
- }
33
- static generateBase64VersionOfString(input) {
34
- return Base64Ratchet.generateBase64VersionOfBuffer(Buffer.from(input));
35
- }
36
- static generateBase64VersionOfBuffer(input) {
37
- return input.toString('base64');
38
- }
39
- static base64StringToBuffer(input) {
40
- return Buffer.from(input, 'base64');
41
- }
42
- static base64StringToString(input, encoding = 'utf8') {
43
- return Buffer.from(input, 'base64').toString(encoding);
44
- }
45
- }
@@ -1,28 +0,0 @@
1
- import { Base64Ratchet } from './base64-ratchet.js';
2
- describe('#base64', function () {
3
- it('should parse a buffer from base64', function () {
4
- const result = Base64Ratchet.base64StringToBuffer('dGVzdHVzZXI6dGVzdHBhc3M=');
5
- expect(result).toBeTruthy();
6
- expect(result.length).toEqual(17);
7
- });
8
- it('should parse a string from base64', function () {
9
- const result = Base64Ratchet.base64StringToString('dGVzdHVzZXI6dGVzdHBhc3M=');
10
- expect(result).toBeTruthy();
11
- expect(result.length).toEqual(17);
12
- });
13
- it('should round-trip a string', function () {
14
- const testString = 'teststring';
15
- const enc = Base64Ratchet.generateBase64VersionOfString(testString);
16
- const result = Base64Ratchet.base64StringToString(enc);
17
- expect(result).toBeTruthy();
18
- expect(result).toEqual(testString);
19
- });
20
- it('should round-trip an object', function () {
21
- const testOb = { a: 'teststring', b: 27 };
22
- const enc = Base64Ratchet.safeObjectToBase64JSON(testOb);
23
- const result = Base64Ratchet.safeBase64JSONParse(enc);
24
- expect(result).toBeTruthy();
25
- expect(result.a).toEqual(testOb.a);
26
- expect(result.b).toEqual(testOb.b);
27
- });
28
- });
@@ -1,45 +0,0 @@
1
- import { NumberRatchet } from './number-ratchet.js';
2
- export class BooleanRatchet {
3
- static allTrue(vals, emptyArraysReturn = false) {
4
- let rval = null;
5
- if (!!vals) {
6
- if (vals.length > 0) {
7
- rval = vals.reduce((a, i) => a && i, true);
8
- }
9
- else {
10
- rval = emptyArraysReturn;
11
- }
12
- }
13
- else {
14
- rval = false;
15
- }
16
- return rval;
17
- }
18
- static anyTrue(vals, emptyArraysReturn = false) {
19
- let rval = null;
20
- if (!!vals) {
21
- if (vals.length > 0) {
22
- rval = vals.reduce((a, i) => a || i, false);
23
- }
24
- else {
25
- rval = emptyArraysReturn;
26
- }
27
- }
28
- else {
29
- rval = false;
30
- }
31
- return rval;
32
- }
33
- static parseBool(val) {
34
- return val === true || (val !== null && val !== undefined && typeof val === 'string' && val.toLowerCase() === 'true');
35
- }
36
- static intToBool(val) {
37
- if (val === null || val === undefined) {
38
- return false;
39
- }
40
- return NumberRatchet.safeNumber(val) !== 0;
41
- }
42
- static boolToInt(val) {
43
- return BooleanRatchet.parseBool(val) ? 1 : 0;
44
- }
45
- }
@@ -1,81 +0,0 @@
1
- import { BooleanRatchet } from './boolean-ratchet.js';
2
- import { NumberRatchet } from './number-ratchet.js';
3
- describe('#parseBool', function () {
4
- it('should check all true', function () {
5
- expect(BooleanRatchet.allTrue(null)).toEqual(false);
6
- expect(BooleanRatchet.allTrue([])).toEqual(false);
7
- expect(BooleanRatchet.allTrue([], true)).toEqual(true);
8
- expect(BooleanRatchet.allTrue([true])).toEqual(true);
9
- expect(BooleanRatchet.allTrue([true, true])).toEqual(true);
10
- expect(BooleanRatchet.allTrue([true, false, true])).toEqual(false);
11
- expect(BooleanRatchet.allTrue([false])).toEqual(false);
12
- expect(BooleanRatchet.allTrue([false, false])).toEqual(false);
13
- });
14
- it('should check any true', function () {
15
- expect(BooleanRatchet.anyTrue(null)).toEqual(false);
16
- expect(BooleanRatchet.anyTrue([])).toEqual(false);
17
- expect(BooleanRatchet.anyTrue([], true)).toEqual(true);
18
- expect(BooleanRatchet.anyTrue([true])).toEqual(true);
19
- expect(BooleanRatchet.anyTrue([true, true])).toEqual(true);
20
- expect(BooleanRatchet.anyTrue([true, false, true])).toEqual(true);
21
- expect(BooleanRatchet.anyTrue([false])).toEqual(false);
22
- expect(BooleanRatchet.anyTrue([false, false])).toEqual(false);
23
- });
24
- it('should xxx', function () {
25
- const val = 'false';
26
- const r1 = BooleanRatchet.parseBool(val);
27
- const r2 = BooleanRatchet.intToBool(val);
28
- const result = BooleanRatchet.parseBool(val) || BooleanRatchet.intToBool(NumberRatchet.safeNumber(val));
29
- expect(result).toEqual(false);
30
- });
31
- it('should parse the string true as true', function () {
32
- const result = BooleanRatchet.parseBool('true');
33
- expect(result).toEqual(true);
34
- });
35
- it('should parse the string TRUE as true', function () {
36
- const result = BooleanRatchet.parseBool('TRUE');
37
- expect(result).toEqual(true);
38
- });
39
- it('should parse the boolean true as true', function () {
40
- const result = BooleanRatchet.parseBool(true);
41
- expect(result).toEqual(true);
42
- });
43
- it('should parse the empty string as false', function () {
44
- const result = BooleanRatchet.parseBool('');
45
- expect(result).toEqual(false);
46
- });
47
- it('should parse null as false', function () {
48
- const result = BooleanRatchet.parseBool(null);
49
- expect(result).toEqual(false);
50
- });
51
- it('should parse "asdf" as false', function () {
52
- const result = BooleanRatchet.parseBool('asdf');
53
- expect(result).toEqual(false);
54
- });
55
- });
56
- describe('#intToBool', function () {
57
- it('should parse null as false', function () {
58
- const result = BooleanRatchet.intToBool(null);
59
- expect(result).toEqual(false);
60
- });
61
- it('should parse 0 as false', function () {
62
- const result = BooleanRatchet.intToBool(0);
63
- expect(result).toEqual(false);
64
- });
65
- it('should parse "0" as false', function () {
66
- const result = BooleanRatchet.intToBool('0');
67
- expect(result).toEqual(false);
68
- });
69
- it('should parse 1 as true', function () {
70
- const result = BooleanRatchet.intToBool(1);
71
- expect(result).toEqual(true);
72
- });
73
- it('should parse "1" as true', function () {
74
- const result = BooleanRatchet.intToBool('1');
75
- expect(result).toEqual(true);
76
- });
77
- it('should parse "2" as true', function () {
78
- const result = BooleanRatchet.intToBool('2');
79
- expect(result).toEqual(true);
80
- });
81
- });
@@ -1,26 +0,0 @@
1
- export class CompositeLastSuccessProvider {
2
- sources;
3
- mostRecent;
4
- constructor(src, mostRecentSrc = true) {
5
- if (!src || src.length == 0) {
6
- throw Error('Cannot create composite provider with null/empty sources');
7
- }
8
- this.sources = src;
9
- this.mostRecent = mostRecentSrc;
10
- }
11
- lastSuccess() {
12
- let rval = null;
13
- this.sources.forEach((s) => {
14
- const val = s.lastSuccess();
15
- if (val != null) {
16
- if (rval == null) {
17
- rval = val;
18
- }
19
- else {
20
- rval = (val > rval && this.mostRecent) || (val < rval && !this.mostRecent) ? val : rval;
21
- }
22
- }
23
- });
24
- return rval;
25
- }
26
- }
@@ -1,26 +0,0 @@
1
- import { CompositeLastSuccessProvider } from './composite-last-success-provider.js';
2
- describe('#lastSuccess', function () {
3
- const last5 = {
4
- lastSuccess() {
5
- return 5;
6
- },
7
- };
8
- const last4 = {
9
- lastSuccess() {
10
- return 4;
11
- },
12
- };
13
- const lastNull = {
14
- lastSuccess() {
15
- return null;
16
- },
17
- };
18
- it('should return 4 as last (min)', function () {
19
- const result = new CompositeLastSuccessProvider([last5, last4, lastNull], false).lastSuccess();
20
- expect(result).toEqual(4);
21
- });
22
- it('should return 5 as last (max)', function () {
23
- const result = new CompositeLastSuccessProvider([last5, last4, lastNull], true).lastSuccess();
24
- expect(result).toEqual(5);
25
- });
26
- });
@@ -1,29 +0,0 @@
1
- import { DateTime } from 'luxon';
2
- export class DateRatchet {
3
- static COMMON_US_DATE_FORMAT = 'MM/dd/yyyy';
4
- static DEFAULT_DATE_FORMAT = 'yyyy-MM-dd';
5
- static FULL_DATE_FORMAT = 'yyyy-MM-dd_HH_mm_ss';
6
- static PACIFIC_TIME_ZONE = 'America/Los_Angeles';
7
- static UTC_TIME_ZONE = 'etc/UTC';
8
- static formatFullDate(input) {
9
- return DateTime.fromJSDate(input).toFormat(DateRatchet.FULL_DATE_FORMAT);
10
- }
11
- static formatDefaultDateOnly(input) {
12
- return DateTime.fromJSDate(input).toFormat(DateRatchet.DEFAULT_DATE_FORMAT);
13
- }
14
- static parseDefaultDate(input) {
15
- const rval = DateTime.fromFormat(input, DateRatchet.DEFAULT_DATE_FORMAT).toJSDate();
16
- return rval;
17
- }
18
- static parseCommonUsDate(input) {
19
- let rval = null;
20
- if (!!input) {
21
- let templ = DateRatchet.COMMON_US_DATE_FORMAT;
22
- if (input.indexOf('-') === 2) {
23
- templ = templ.split('/').join('-');
24
- }
25
- rval = DateTime.fromFormat(input, templ).toJSDate();
26
- }
27
- return rval;
28
- }
29
- }
@@ -1,21 +0,0 @@
1
- import { DateRatchet } from './date-ratchet.js';
2
- describe('#dateRatchet', function () {
3
- it('should parse my common date format', function () {
4
- const dt = DateRatchet.parseDefaultDate('1976-07-04');
5
- expect(dt.getFullYear()).toEqual(1976);
6
- expect(dt.getMonth()).toEqual(6);
7
- expect(dt.getDate()).toEqual(4);
8
- });
9
- it('should parse us with slashes', function () {
10
- const dt = DateRatchet.parseCommonUsDate('07/04/1976');
11
- expect(dt.getFullYear()).toEqual(1976);
12
- expect(dt.getMonth()).toEqual(6);
13
- expect(dt.getDate()).toEqual(4);
14
- });
15
- it('should parse us with dashes', function () {
16
- const dt = DateRatchet.parseCommonUsDate('07-04-1976');
17
- expect(dt.getFullYear()).toEqual(1976);
18
- expect(dt.getMonth()).toEqual(6);
19
- expect(dt.getDate()).toEqual(4);
20
- });
21
- });