@dronedeploy/rocos-js-sdk 3.0.1-alpha.11 → 3.0.1-alpha.14

Sign up to get free protection for your applications and to get access to all the features.
Files changed (121) hide show
  1. package/cjs/RocosSDK.d.ts +3 -1
  2. package/cjs/RocosSDK.js +1 -0
  3. package/cjs/api/streams/caller/CallerStream.js +5 -2
  4. package/cjs/api/streams/caller/CallerStreamNode.js +2 -1
  5. package/cjs/api/streams/command/CommandStream.js +5 -2
  6. package/cjs/api/streams/command/CommandStreamNode.js +2 -1
  7. package/cjs/api/streams/control/ControlStream.js +5 -2
  8. package/cjs/api/streams/control/ControlStreamAbstract.d.ts +1 -1
  9. package/cjs/api/streams/control/ControlStreamNode.js +2 -1
  10. package/cjs/api/streams/fileAccessor/FileAccessorStream.js +4 -1
  11. package/cjs/api/streams/fileAccessor/FileAccessorStreamNode.js +3 -1
  12. package/cjs/api/streams/search/SearchStream.js +5 -2
  13. package/cjs/api/streams/search/SearchStreamNode.js +2 -1
  14. package/cjs/api/streams/telemetry/TelemetryStream.js +4 -1
  15. package/cjs/api/streams/telemetry/TelemetryStreamAbstract.d.ts +1 -1
  16. package/cjs/api/streams/telemetry/TelemetryStreamNode.js +2 -1
  17. package/cjs/api/streams/webRTCSignalling/WebRTCSignallingStream.js +5 -2
  18. package/cjs/constants/api.d.ts +2 -0
  19. package/cjs/constants/api.js +4 -2
  20. package/cjs/helpers/getUniqueConfigKey.d.ts +6 -2
  21. package/cjs/helpers/getUniqueConfigKey.js +7 -2
  22. package/cjs/services/ProfileService.d.ts +23 -0
  23. package/cjs/services/ProfileService.js +28 -0
  24. package/cjs/services/RTPWebRTCService.d.ts +1 -1
  25. package/cjs/services/RTPWebRTCService.js +4 -2
  26. package/cjs/store/RocosStore.d.ts +1 -2
  27. package/esm/RocosSDK.d.ts +3 -1
  28. package/esm/RocosSDK.js +1 -0
  29. package/esm/api/streams/caller/CallerStream.js +5 -2
  30. package/esm/api/streams/caller/CallerStreamNode.js +2 -1
  31. package/esm/api/streams/command/CommandStream.js +5 -2
  32. package/esm/api/streams/command/CommandStreamNode.js +2 -1
  33. package/esm/api/streams/control/ControlStream.js +5 -2
  34. package/esm/api/streams/control/ControlStreamAbstract.d.ts +1 -1
  35. package/esm/api/streams/control/ControlStreamNode.js +2 -1
  36. package/esm/api/streams/fileAccessor/FileAccessorStream.js +4 -1
  37. package/esm/api/streams/fileAccessor/FileAccessorStreamNode.js +3 -1
  38. package/esm/api/streams/search/SearchStream.js +5 -2
  39. package/esm/api/streams/search/SearchStreamNode.js +2 -1
  40. package/esm/api/streams/telemetry/TelemetryStream.js +4 -1
  41. package/esm/api/streams/telemetry/TelemetryStreamAbstract.d.ts +1 -1
  42. package/esm/api/streams/telemetry/TelemetryStreamNode.js +2 -1
  43. package/esm/api/streams/webRTCSignalling/WebRTCSignallingStream.js +5 -2
  44. package/esm/constants/api.d.ts +2 -0
  45. package/esm/constants/api.js +2 -0
  46. package/esm/helpers/getUniqueConfigKey.d.ts +6 -2
  47. package/esm/helpers/getUniqueConfigKey.js +7 -2
  48. package/esm/services/ProfileService.d.ts +23 -0
  49. package/esm/services/ProfileService.js +29 -1
  50. package/esm/services/RTPWebRTCService.d.ts +1 -1
  51. package/esm/services/RTPWebRTCService.js +4 -2
  52. package/esm/store/RocosStore.d.ts +1 -2
  53. package/package.json +1 -1
  54. package/cjs/helpers/cleanObject.spec.d.ts +0 -1
  55. package/cjs/helpers/cleanObject.spec.js +0 -55
  56. package/cjs/helpers/flattenObject.spec.d.ts +0 -1
  57. package/cjs/helpers/flattenObject.spec.js +0 -31
  58. package/cjs/helpers/flattenOneOf.spec.d.ts +0 -1
  59. package/cjs/helpers/flattenOneOf.spec.js +0 -159
  60. package/cjs/helpers/formatServiceUrl.spec.d.ts +0 -1
  61. package/cjs/helpers/formatServiceUrl.spec.js +0 -18
  62. package/cjs/helpers/getSha256Hex.spec.d.ts +0 -1
  63. package/cjs/helpers/getSha256Hex.spec.js +0 -19
  64. package/cjs/helpers/getSha256HexNode.spec.d.ts +0 -1
  65. package/cjs/helpers/getSha256HexNode.spec.js +0 -10
  66. package/cjs/helpers/getURLSearchParams.spec.d.ts +0 -1
  67. package/cjs/helpers/getURLSearchParams.spec.js +0 -21
  68. package/cjs/helpers/nanosecondToMillisecond.spec.d.ts +0 -1
  69. package/cjs/helpers/nanosecondToMillisecond.spec.js +0 -22
  70. package/cjs/helpers/splitRobotTopic.spec.d.ts +0 -1
  71. package/cjs/helpers/splitRobotTopic.spec.js +0 -53
  72. package/cjs/helpers/standardDeviation.spec.d.ts +0 -1
  73. package/cjs/helpers/standardDeviation.spec.js +0 -13
  74. package/cjs/helpers/websandbox/frame/worker/manager.spec.d.ts +0 -4
  75. package/cjs/helpers/websandbox/frame/worker/manager.spec.js +0 -132
  76. package/cjs/models/Token.spec.d.ts +0 -1
  77. package/cjs/models/Token.spec.js +0 -110
  78. package/cjs/services/AuthService.spec.d.ts +0 -1
  79. package/cjs/services/AuthService.spec.js +0 -165
  80. package/cjs/services/CallerService.spec.d.ts +0 -1
  81. package/cjs/services/CallerService.spec.js +0 -229
  82. package/cjs/services/PlatformTimeService.spec.d.ts +0 -1
  83. package/cjs/services/PlatformTimeService.spec.js +0 -182
  84. package/cjs/services/RTPWebRTCService.spec.d.ts +0 -4
  85. package/cjs/services/RTPWebRTCService.spec.js +0 -171
  86. package/cjs/services/TelemetryService.spec.d.ts +0 -1
  87. package/cjs/services/TelemetryService.spec.js +0 -39
  88. package/esm/helpers/cleanObject.spec.d.ts +0 -1
  89. package/esm/helpers/cleanObject.spec.js +0 -53
  90. package/esm/helpers/flattenObject.spec.d.ts +0 -1
  91. package/esm/helpers/flattenObject.spec.js +0 -29
  92. package/esm/helpers/flattenOneOf.spec.d.ts +0 -1
  93. package/esm/helpers/flattenOneOf.spec.js +0 -157
  94. package/esm/helpers/formatServiceUrl.spec.d.ts +0 -1
  95. package/esm/helpers/formatServiceUrl.spec.js +0 -16
  96. package/esm/helpers/getSha256Hex.spec.d.ts +0 -1
  97. package/esm/helpers/getSha256Hex.spec.js +0 -14
  98. package/esm/helpers/getSha256HexNode.spec.d.ts +0 -1
  99. package/esm/helpers/getSha256HexNode.spec.js +0 -8
  100. package/esm/helpers/getURLSearchParams.spec.d.ts +0 -1
  101. package/esm/helpers/getURLSearchParams.spec.js +0 -19
  102. package/esm/helpers/nanosecondToMillisecond.spec.d.ts +0 -1
  103. package/esm/helpers/nanosecondToMillisecond.spec.js +0 -20
  104. package/esm/helpers/splitRobotTopic.spec.d.ts +0 -1
  105. package/esm/helpers/splitRobotTopic.spec.js +0 -51
  106. package/esm/helpers/standardDeviation.spec.d.ts +0 -1
  107. package/esm/helpers/standardDeviation.spec.js +0 -11
  108. package/esm/helpers/websandbox/frame/worker/manager.spec.d.ts +0 -4
  109. package/esm/helpers/websandbox/frame/worker/manager.spec.js +0 -127
  110. package/esm/models/Token.spec.d.ts +0 -1
  111. package/esm/models/Token.spec.js +0 -108
  112. package/esm/services/AuthService.spec.d.ts +0 -1
  113. package/esm/services/AuthService.spec.js +0 -163
  114. package/esm/services/CallerService.spec.d.ts +0 -1
  115. package/esm/services/CallerService.spec.js +0 -227
  116. package/esm/services/PlatformTimeService.spec.d.ts +0 -1
  117. package/esm/services/PlatformTimeService.spec.js +0 -180
  118. package/esm/services/RTPWebRTCService.spec.d.ts +0 -4
  119. package/esm/services/RTPWebRTCService.spec.js +0 -169
  120. package/esm/services/TelemetryService.spec.d.ts +0 -1
  121. package/esm/services/TelemetryService.spec.js +0 -37
@@ -1,14 +0,0 @@
1
- import crypto from 'crypto';
2
- import { getSha256Hex } from './getSha256Hex';
3
- Object.defineProperty(globalThis, 'crypto', {
4
- value: {
5
- subtle: crypto.webcrypto.subtle,
6
- },
7
- });
8
- describe('getSha256Hex', () => {
9
- it('should return the correct SHA-256 hash', async () => {
10
- const buffer = new TextEncoder().encode('Hello, World!');
11
- const hash = await getSha256Hex(buffer);
12
- expect(hash).toBe('dffd6021bb2bd5b0af676290809ec3a53191dd81c7f70a4b28688a362182986f');
13
- });
14
- });
@@ -1 +0,0 @@
1
- export {};
@@ -1,8 +0,0 @@
1
- import { getSha256HexNode } from './getSha256HexNode';
2
- describe('getSha256HexNode', () => {
3
- it('should return the correct SHA-256 hash', async () => {
4
- const buffer = new TextEncoder().encode('Hello, World!');
5
- const hash = await getSha256HexNode(buffer);
6
- expect(hash).toBe('dffd6021bb2bd5b0af676290809ec3a53191dd81c7f70a4b28688a362182986f');
7
- });
8
- });
@@ -1 +0,0 @@
1
- export {};
@@ -1,19 +0,0 @@
1
- import { getURLSearchParams } from './getURLSearchParams';
2
- describe('getURLSearchParams', () => {
3
- it('Should return the original param if URLSearchParams', () => {
4
- const param = new URLSearchParams();
5
- const searchParam = getURLSearchParams(param);
6
- expect(searchParam).toBe(param);
7
- });
8
- it('Should a new URLSearchParams ', () => {
9
- const param = {
10
- foo: 'bar',
11
- bar: true,
12
- foobar: 123,
13
- };
14
- const searchParam = getURLSearchParams(param);
15
- expect(searchParam.get('foo')).toBe('bar');
16
- expect(searchParam.get('bar')).toBe('true');
17
- expect(searchParam.get('foobar')).toBe('123');
18
- });
19
- });
@@ -1 +0,0 @@
1
- export {};
@@ -1,20 +0,0 @@
1
- import { nanosecondToMillisecond } from './nanosecondToMillisecond';
2
- describe('nanosecondToMillisecond', () => {
3
- it.each `
4
- input | expected
5
- ${'0.0001'} | ${0.0000000001}
6
- ${'1'} | ${0.000001}
7
- ${'1000000'} | ${1}
8
- ${'10000000'} | ${10}
9
- ${'-100000006'} | ${-100.000006}
10
- ${'1000000000000000000'} | ${1000000000000}
11
- ${'1234567891011100001'} | ${1234567891011.100001}
12
- ${'1234567891011100000'} | ${1234567891011.1}
13
- ${0.0001} | ${0.0000000001}
14
- ${1} | ${0.000001}
15
- ${1000000} | ${1}
16
- ${1000000000000001} | ${1000000000.000001}
17
- `('should convert $input to $expected', ({ input, expected }) => {
18
- expect(nanosecondToMillisecond(input)).toBe(expected);
19
- });
20
- });
@@ -1 +0,0 @@
1
- export {};
@@ -1,51 +0,0 @@
1
- import { splitRobotTopic } from './splitRobotTopic';
2
- describe('splitRobotTopic', () => {
3
- it('should split a path with a single topic', () => {
4
- expect(splitRobotTopic('/component/topic')).toEqual({
5
- component: 'component',
6
- topic: 'topic',
7
- });
8
- });
9
- it('should split a path with multiple topics', () => {
10
- expect(splitRobotTopic('/component/topic/with/multiple/topics')).toEqual({
11
- component: 'component',
12
- topic: 'topic/with/multiple/topics',
13
- });
14
- });
15
- it('should split a path with no topics', () => {
16
- expect(splitRobotTopic('/component')).toEqual({
17
- component: 'component',
18
- topic: '',
19
- });
20
- });
21
- it('should split a path with no forward slash', () => {
22
- expect(splitRobotTopic('component/topic')).toEqual({
23
- component: 'component',
24
- topic: 'topic',
25
- });
26
- });
27
- it('should split a path with no forward slash and no topics', () => {
28
- expect(splitRobotTopic('component')).toEqual({
29
- component: 'component',
30
- topic: '',
31
- });
32
- });
33
- it('should split a path with no forward slash and multiple topics', () => {
34
- expect(splitRobotTopic('component/topic/with/multiple/topics')).toEqual({
35
- component: 'component',
36
- topic: 'topic/with/multiple/topics',
37
- });
38
- });
39
- it('should handle a path with multiple forward slashes', () => {
40
- expect(splitRobotTopic('///component/topic/with/multiple/topics')).toEqual({
41
- component: 'component',
42
- topic: 'topic/with/multiple/topics',
43
- });
44
- });
45
- it('should handle a path with multiple forward slashes and no topics', () => {
46
- expect(splitRobotTopic('///component')).toEqual({
47
- component: 'component',
48
- topic: '',
49
- });
50
- });
51
- });
@@ -1 +0,0 @@
1
- export {};
@@ -1,11 +0,0 @@
1
- import { standardDeviation } from './standardDeviation';
2
- describe('standardDeviation', () => {
3
- it('should calculate standard deviation correctly', () => {
4
- let numbers = [10, 12, 23, 23, 16, 23, 21, 16];
5
- let stdDev = standardDeviation(numbers);
6
- expect(Math.abs(stdDev - 4.8989794855664)).toBeLessThan(0.000001);
7
- numbers = [100, 12, 23, 23, 116, 23, 21, 162];
8
- stdDev = standardDeviation(numbers);
9
- expect(Math.abs(stdDev - 53.702886328394)).toBeLessThan(0.000001);
10
- });
11
- });
@@ -1,4 +0,0 @@
1
- /**
2
- * @jest-environment jsdom
3
- */
4
- export {};
@@ -1,127 +0,0 @@
1
- /**
2
- * @jest-environment jsdom
3
- */
4
- import WorkerManager from './manager';
5
- const WorkerMocks = {
6
- postMessage: jest.fn(),
7
- terminate: jest.fn(),
8
- addEventListener: jest.fn(),
9
- removeEventListener: jest.fn(),
10
- onerror: jest.fn(),
11
- onmessage: jest.fn(),
12
- onmessageerror: jest.fn(),
13
- dispatchEvent: jest.fn(),
14
- clearAllMocks() {
15
- this.postMessage.mockClear();
16
- this.terminate.mockClear();
17
- this.addEventListener.mockClear();
18
- this.removeEventListener.mockClear();
19
- this.onerror.mockClear();
20
- this.onmessage.mockClear();
21
- this.onmessageerror.mockClear();
22
- this.dispatchEvent.mockClear();
23
- },
24
- };
25
- class MockWorkerClass {
26
- constructor() {
27
- this.postMessage = WorkerMocks.postMessage;
28
- this.terminate = WorkerMocks.terminate;
29
- this.addEventListener = WorkerMocks.addEventListener;
30
- this.removeEventListener = WorkerMocks.removeEventListener;
31
- this.onerror = WorkerMocks.onerror;
32
- this.onmessage = WorkerMocks.onmessage;
33
- this.onmessageerror = WorkerMocks.onmessageerror;
34
- this.dispatchEvent = WorkerMocks.dispatchEvent;
35
- }
36
- }
37
- Object.defineProperty(window, 'Worker', {
38
- value: MockWorkerClass,
39
- writable: true,
40
- });
41
- Object.defineProperty(window, 'URL', {
42
- value: {
43
- createObjectURL: jest.fn(),
44
- },
45
- });
46
- // add mock to AbortSignal.timeout
47
- Object.defineProperty(AbortSignal, 'timeout', {
48
- value: jest.fn().mockImplementation((timeout) => {
49
- return new AbortController().signal;
50
- }),
51
- });
52
- const task = {
53
- id: 'test',
54
- code: '1',
55
- timeout: 1000,
56
- };
57
- const response = {
58
- data: {
59
- id: 'test',
60
- success: true,
61
- result: 'test',
62
- },
63
- };
64
- describe('WorkerManager', () => {
65
- beforeEach(() => {
66
- WorkerMocks.clearAllMocks();
67
- });
68
- it('should send a task to the worker', async () => {
69
- const listeners = [];
70
- WorkerMocks.addEventListener.mockImplementation((_, listener) => {
71
- listeners.push(listener);
72
- });
73
- WorkerMocks.postMessage.mockImplementation((msg) => {
74
- listeners.forEach((listener) => {
75
- listener(response);
76
- });
77
- });
78
- const manager = new WorkerManager();
79
- const result = await manager.execute(task);
80
- expect(result).toEqual('test');
81
- });
82
- it('should handle listener for a single task', async () => {
83
- const listeners = [];
84
- WorkerMocks.addEventListener.mockImplementation((_, listener) => {
85
- listeners.push(listener);
86
- });
87
- WorkerMocks.removeEventListener.mockImplementation((_, listener) => {
88
- const index = listeners.indexOf(listener);
89
- listeners.splice(index, 1);
90
- });
91
- const manager = new WorkerManager();
92
- expect(listeners.length).toEqual(0);
93
- const result = manager.execute(task);
94
- expect(listeners.length).toEqual(1);
95
- listeners[0](response);
96
- await result;
97
- expect(listeners.length).toEqual(0);
98
- });
99
- it('should handle listener for multiple simultaneous task', async () => {
100
- const listeners = [];
101
- WorkerMocks.addEventListener.mockImplementation((_, listener) => {
102
- listeners.push(listener);
103
- });
104
- WorkerMocks.removeEventListener.mockImplementation((_, listener) => {
105
- const index = listeners.indexOf(listener);
106
- listeners.splice(index, 1);
107
- });
108
- const manager = new WorkerManager();
109
- expect(listeners.length).toEqual(0);
110
- const result1 = manager.execute(task);
111
- const result2 = manager.execute(task);
112
- expect(listeners.length).toEqual(2);
113
- const result3 = manager.execute(task);
114
- expect(listeners.length).toEqual(3);
115
- const [listener1, listener2, listener3] = listeners;
116
- listener1(response);
117
- await result1;
118
- expect(listeners.length).toEqual(2);
119
- listener3(response);
120
- await result3;
121
- expect(listeners.length).toEqual(1);
122
- listener2(response);
123
- await result2;
124
- expect(listeners.length).toEqual(0);
125
- expect(WorkerMocks.removeEventListener).toHaveBeenCalledTimes(3);
126
- });
127
- });
@@ -1 +0,0 @@
1
- export {};
@@ -1,108 +0,0 @@
1
- import { Token } from './Token';
2
- const generateToken = (config) => {
3
- const defaultPayload = {
4
- iat: 1234567890,
5
- exp: 9876543210,
6
- iss: 'myissuer',
7
- aud: 'myaudience',
8
- sub: 'mysubject',
9
- };
10
- const encodedHeader = Buffer.from(JSON.stringify(config?.header ?? { alg: 'HS256', typ: 'JWT' })).toString('base64');
11
- const encodedPayload = Buffer.from(JSON.stringify(config?.payload ?? defaultPayload)).toString('base64');
12
- if (config?.signature === null) {
13
- return `${encodedHeader}.${encodedPayload}`;
14
- }
15
- return `${encodedHeader}.${encodedPayload}.${config?.signature ?? 'signature'}`;
16
- };
17
- describe('Token', () => {
18
- describe('constructor', () => {
19
- it('can get information from a valid token', () => {
20
- const token = new Token(generateToken());
21
- expect(token.issuedAt).toEqual(new Date(1234567890000));
22
- expect(token.expires).toEqual(new Date(9876543210000));
23
- expect(token.issuer).toEqual('myissuer');
24
- expect(token.audience).toEqual('myaudience');
25
- expect(token.subject).toEqual('mysubject');
26
- });
27
- it('should throw an error for a non-jwt', () => {
28
- // completely invalid string
29
- expect(() => new Token('not a jwt')).toThrowError('Invalid token');
30
- // invalid header
31
- expect(() => {
32
- new Token(generateToken({
33
- header: {
34
- alg: 'HS256',
35
- typ: 'Not-a-JWT',
36
- },
37
- }));
38
- }).toThrowError('Invalid token');
39
- // too many parts
40
- expect(() => {
41
- new Token('a.b.c.d');
42
- }).toThrowError('Invalid token');
43
- });
44
- it('should allow a token with no signature', () => {
45
- const token = new Token(generateToken({ signature: null }));
46
- expect(token.issuedAt).toEqual(new Date(1234567890000));
47
- expect(token.expires).toEqual(new Date(9876543210000));
48
- expect(token.issuer).toEqual('myissuer');
49
- expect(token.audience).toEqual('myaudience');
50
- expect(token.subject).toEqual('mysubject');
51
- });
52
- });
53
- describe('isExpired', () => {
54
- const baseDate = new Date(2021, 0, 1, 0, 0, 0, 0);
55
- beforeEach(() => {
56
- jest.useFakeTimers();
57
- jest.setSystemTime(baseDate);
58
- });
59
- afterEach(() => {
60
- jest.useRealTimers();
61
- });
62
- const expiredDate = (baseDate.getTime() - 1000 * 60 * 5) / 1000; // 5 minutes ago
63
- const notExpiredDate = (baseDate.getTime() + 1000 * 60 * 60 * 24) / 1000; // 1 day from now
64
- it('should return true if the token is expired', () => {
65
- const token = new Token(generateToken({ payload: { exp: expiredDate } }));
66
- expect(token.isExpired()).toEqual(true);
67
- });
68
- it('should return false if the token is not expired', () => {
69
- const token = new Token(generateToken({ payload: { exp: notExpiredDate } }));
70
- expect(token.isExpired()).toEqual(false);
71
- });
72
- });
73
- describe('isExpiredIn', () => {
74
- const baseDate = new Date(2021, 0, 1, 0, 0, 0, 0);
75
- beforeEach(() => {
76
- jest.useFakeTimers();
77
- jest.setSystemTime(baseDate);
78
- });
79
- afterEach(() => {
80
- jest.useRealTimers();
81
- });
82
- const expiredDate = (baseDate.getTime() - 1000 * 60 * 5) / 1000; // 5 minutes ago
83
- const expiredIn5MinsDate = (baseDate.getTime() + 1000 * 60 * 5) / 1000; // 5 minutes from now
84
- const expiredIn25MinsDate = (baseDate.getTime() + 1000 * 60 * 25) / 1000; // 25 minutes from now
85
- const expiredIn2HoursDate = (baseDate.getTime() + 1000 * 60 * 60 * 2) / 1000; // 2 hours from now
86
- it('should return true if the token is expired in the given time', () => {
87
- const token = new Token(generateToken({ payload: { exp: expiredIn5MinsDate } }));
88
- expect(token.isExpiredIn(5, 'minutes')).toEqual(true);
89
- expect(token.isExpiredIn(25, 'minutes')).toEqual(true);
90
- expect(token.isExpiredIn(2, 'hours')).toEqual(true);
91
- const token2 = new Token(generateToken({ payload: { exp: expiredIn25MinsDate } }));
92
- expect(token2.isExpiredIn(25, 'minutes')).toEqual(true);
93
- expect(token2.isExpiredIn(2, 'hours')).toEqual(true);
94
- const token3 = new Token(generateToken({ payload: { exp: expiredDate } }));
95
- expect(token3.isExpiredIn(5, 'minutes')).toEqual(true);
96
- expect(token3.isExpiredIn(25, 'minutes')).toEqual(true);
97
- expect(token3.isExpiredIn(2, 'hours')).toEqual(true);
98
- });
99
- it('should return false if the token is not expired in the given time', () => {
100
- const token = new Token(generateToken({ payload: { exp: expiredIn5MinsDate } }));
101
- expect(token.isExpiredIn(4, 'minutes')).toEqual(false);
102
- const token2 = new Token(generateToken({ payload: { exp: expiredIn25MinsDate } }));
103
- expect(token2.isExpiredIn(24, 'minutes')).toEqual(false);
104
- const token3 = new Token(generateToken({ payload: { exp: expiredIn2HoursDate } }));
105
- expect(token3.isExpiredIn(1, 'hours')).toEqual(false);
106
- });
107
- });
108
- });
@@ -1 +0,0 @@
1
- export {};
@@ -1,163 +0,0 @@
1
- import { issuer } from '../constants/auth';
2
- import { AuthService } from './AuthService';
3
- import { Token } from '../models';
4
- describe('authService', () => {
5
- const baseDate = new Date(2021, 0, 1, 0, 0, 0, 0);
6
- beforeEach(() => {
7
- jest.useFakeTimers();
8
- jest.setSystemTime(baseDate);
9
- });
10
- const expiredDate = new Date(baseDate.getTime() - 1000 * 60 * 5); // 5 minutes ago
11
- const almostExpiredDate = new Date(baseDate.getTime() + 1000 * 60 * 5); // 5 minutes from now
12
- const almostAlmostExpiredDate = new Date(baseDate.getTime() + 1000 * 60 * 25); // 35 minutes from now
13
- const notExpiredDate = new Date(baseDate.getTime() + 1000 * 60 * 60 * 24); // 1 day from now
14
- const getToken = (config) => {
15
- const header = {
16
- alg: 'HS256',
17
- typ: 'JWT',
18
- };
19
- const payload = {
20
- iat: Math.floor((config.iat ?? expiredDate).getTime() / 1000),
21
- exp: Math.floor((config.exp ?? notExpiredDate).getTime() / 1000),
22
- iss: config.iss ?? issuer,
23
- aud: config.aud ?? 'myaudience',
24
- sub: config.sub ?? 'mysubject',
25
- };
26
- const encodedHeader = Buffer.from(JSON.stringify(header)).toString('base64');
27
- const encodedPayload = Buffer.from(JSON.stringify(payload)).toString('base64');
28
- if (config.signature === false) {
29
- return `${encodedHeader}.${encodedPayload}`;
30
- }
31
- return `${encodedHeader}.${encodedPayload}.signature`;
32
- };
33
- afterAll(() => jest.useRealTimers());
34
- describe('getToken', () => {
35
- it('should return the current token if it is not expired', async () => {
36
- // Arrange
37
- const token = getToken({ exp: notExpiredDate });
38
- const service = new AuthService({
39
- token,
40
- url: 'http://localhost:0',
41
- });
42
- service.setToken(token);
43
- // Act
44
- const newToken = await service.getToken();
45
- // Assert
46
- expect(newToken.value).toEqual(token);
47
- });
48
- it('should refresh the token if it is about to expire', async () => {
49
- // Arrange
50
- const token = getToken({ exp: almostExpiredDate });
51
- const service = new AuthService({
52
- token,
53
- url: 'http://localhost:0',
54
- });
55
- service.setToken(token);
56
- const expected = getToken({ signature: false });
57
- jest.spyOn(AuthService.prototype, 'refreshToken').mockResolvedValue(new Token(expected));
58
- // Act
59
- const newToken = await service.getToken();
60
- // Assert
61
- expect(newToken.value).not.toEqual(token);
62
- expect(newToken.value).toEqual(expected);
63
- expect(AuthService.prototype.refreshToken).toHaveBeenCalled();
64
- });
65
- it('should get a new token if there is no current token', async () => {
66
- // Arrange
67
- const token = getToken({ signature: false });
68
- const service = new AuthService({
69
- url: 'http://localhost:0',
70
- token,
71
- });
72
- service.clearToken();
73
- const expected = getToken({ signature: false });
74
- jest.spyOn(AuthService.prototype, 'getNewUserToken').mockResolvedValue(new Token(expected));
75
- // Act
76
- const newToken = await service.getToken();
77
- // Assert
78
- expect(newToken.value).toEqual(expected);
79
- expect(AuthService.prototype.getNewUserToken).toHaveBeenCalled();
80
- });
81
- });
82
- describe('tokenRefreshLoop', () => {
83
- jest.spyOn(AuthService.prototype, 'refreshTokenIfExpired').mockImplementation(() => {
84
- // make sure the promise is resolved synchronously
85
- return {
86
- catch: () => {
87
- return {
88
- finally(onfinally) {
89
- onfinally?.();
90
- return Promise.resolve();
91
- },
92
- };
93
- },
94
- };
95
- });
96
- beforeEach(() => {
97
- jest.clearAllTimers();
98
- jest.clearAllMocks();
99
- jest.useFakeTimers();
100
- jest.setSystemTime(baseDate);
101
- });
102
- it('should check the token every 10 minutes', async () => {
103
- // Arrange
104
- const token = getToken({ exp: almostAlmostExpiredDate });
105
- const service = new AuthService({
106
- token,
107
- url: 'http://localhost:0',
108
- });
109
- service.setToken(token);
110
- // Act
111
- service.startTokenRefreshChecker();
112
- expect(AuthService.prototype.refreshTokenIfExpired).toHaveBeenCalledTimes(1);
113
- jest.advanceTimersByTime(1000 * 60 * 10); // 10 minutes
114
- expect(AuthService.prototype.refreshTokenIfExpired).toHaveBeenCalledTimes(2);
115
- jest.advanceTimersByTime(1000 * 60); // 1 minutes - 24 minutes left
116
- expect(AuthService.prototype.refreshTokenIfExpired).toHaveBeenCalledTimes(3);
117
- jest.advanceTimersByTime(1000 * 60 * 10); // 10 minutes - 14 minutes left
118
- jest.runOnlyPendingTimers(); // wait for the next timer to run
119
- service.stopTokenRefreshChecker();
120
- });
121
- it('should not run again when cancelled', () => {
122
- // Arrange
123
- const token = getToken({ exp: notExpiredDate });
124
- const service = new AuthService({
125
- token,
126
- url: 'http://localhost:0',
127
- });
128
- service.setToken(token);
129
- // Act
130
- service.startTokenRefreshChecker();
131
- expect(AuthService.prototype.refreshTokenIfExpired).toHaveBeenCalledTimes(1);
132
- service.stopTokenRefreshChecker();
133
- jest.runOnlyPendingTimers();
134
- expect(AuthService.prototype.refreshTokenIfExpired).toHaveBeenCalledTimes(1);
135
- });
136
- it('should correctly report running status', () => {
137
- const token = getToken({ exp: notExpiredDate });
138
- const service = new AuthService({
139
- token,
140
- url: 'http://localhost:0',
141
- });
142
- service.setToken(token);
143
- expect(service.isTokenRefreshCheckerRunning()).toBe(false);
144
- service.startTokenRefreshChecker();
145
- expect(service.isTokenRefreshCheckerRunning()).toBe(true);
146
- service.stopTokenRefreshChecker();
147
- expect(service.isTokenRefreshCheckerRunning()).toBe(false);
148
- });
149
- it('should correctly report running status', () => {
150
- const token = getToken({ exp: notExpiredDate });
151
- const service = new AuthService({
152
- token,
153
- url: 'http://localhost:0',
154
- });
155
- service.setToken(token);
156
- expect(service.isTokenRefreshCheckerRunning()).toBe(false);
157
- service.startTokenRefreshChecker();
158
- expect(service.isTokenRefreshCheckerRunning()).toBe(true);
159
- service.stopTokenRefreshChecker();
160
- expect(service.isTokenRefreshCheckerRunning()).toBe(false);
161
- });
162
- });
163
- });
@@ -1 +0,0 @@
1
- export {};