-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathhsync-web.js
More file actions
72 lines (61 loc) · 1.87 KB
/
hsync-web.js
File metadata and controls
72 lines (61 loc) · 1.87 KB
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
import mqtt from 'mqtt';
import { Buffer } from 'buffer';
import net from 'net-web';
import { createHsync, setNet, setMqtt } from './connection.js';
import { setRTC } from './lib/peers.js';
import rtc from './lib/rtc-web.js';
import config from './config.js';
// TODO need to make this work with web/service workers
if (typeof window !== 'undefined') {
window.Buffer = Buffer;
}
globalThis.Buffer = Buffer;
setRTC(rtc);
setNet(net);
setMqtt(mqtt);
async function dynamicConnect(configObj = { useLocalStorage: true }) {
const fullConfig = { ...config, ...configObj };
fullConfig.dynamicHost = fullConfig.dynamicHost || fullConfig.defaultDynamicHost;
if (fullConfig.net) {
setNet(fullConfig.net);
}
let con;
if (configObj.useLocalStorage) {
const localConfigStr = localStorage.getItem('hsyncConfig');
if (localConfigStr) {
const localConfig = JSON.parse(localConfigStr);
if (Date.now() - localConfig.created < localConfig.timeout * 0.66) {
fullConfig.hsyncSecret = localConfig.hsyncSecret;
fullConfig.hsyncServer = localConfig.hsyncServer;
} else {
localStorage.removeItem('hsyncConfig');
}
}
con = await createHsync(fullConfig);
if (!fullConfig.hsyncSecret) {
const storeConfig = {
hsyncSecret: con.hsyncSecret,
hsyncServer: con.hsyncServer,
timeout: con.dynamicTimeout,
created: Date.now(),
};
localStorage.setItem('hsyncConfig', JSON.stringify(storeConfig));
}
return con;
}
con = await createHsync(fullConfig);
return con;
}
function createConnection(configObj = {}) {
const fullConfig = { ...config, ...configObj };
return createHsync(fullConfig);
}
const hsync = globalThis.hsync || {
createConnection,
dynamicConnect,
net,
config,
};
globalThis.hsync = hsync;
export default hsync;
export { createConnection, dynamicConnect, config };