This repository has been archived by the owner on Mar 16, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 104
/
acceptConnection.js
76 lines (67 loc) · 2.03 KB
/
acceptConnection.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import {
connectionRequestEvent,
connectionApprovedEvent,
backgroundReadyEvent,
uiCloseEvent,
} from '~/config/event';
import {
getResourceUrl,
} from '~/utils/versionControl';
import {
permissionError,
} from '~/utils/error';
import Connection from '../utils/connection';
import migrateIndexedDB from './migrateIndexedDB';
import setupNetworkConfig from './setupNetworkConfig';
const resourceOrigin = getResourceUrl('origin');
export default function acceptConnection() {
window.parent.postMessage({
type: backgroundReadyEvent,
}, '*');
const connection = new Connection();
let networkConfig;
window.addEventListener('message', async (event) => {
if (event.data.type === connectionRequestEvent) {
const {
requestId,
clientProfile,
} = event.data;
if (clientProfile) {
try {
await migrateIndexedDB();
networkConfig = await setupNetworkConfig(clientProfile);
connection.initUi();
} catch (e) {
const error = e.code === 4001
? permissionError('user.denied.auth')
: e;
networkConfig = {
error,
};
}
} else if (event.origin !== resourceOrigin) {
return;
}
const channel = new MessageChannel();
const {
data,
} = event;
connection.registerClient({
data,
port: channel.port1,
});
event.source.postMessage({
type: connectionApprovedEvent,
code: '200',
data: networkConfig,
requestId,
}, '*', [channel.port2]);
}
});
window.addEventListener(uiCloseEvent, (e) => {
const {
detail,
} = e;
connection.abortUi(detail);
});
}