-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
165 lines (144 loc) · 5.13 KB
/
index.ts
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
import {TinyEmitter} from 'tiny-emitter';
export default class WindowBus {
private readonly emitter = new TinyEmitter();
private readonly frame: Window = null;
private _client: Promise<void> = null;
private _server: Promise<void> = null;
private origin: string = null;
private id = 1;
private queue = {};
private channel = 'window-bus';
constructor(targetWindow?: Window, channel?: string) {
this.frame = targetWindow || (window.parent !== window && window.parent);
if (!this.frame) {
throw new Error('A frame is required')
}
if (channel) {
this.setChannel(channel);
}
window.addEventListener("message", (event) => {
if (this.origin && event.origin !== this.origin)
return;
try {
const data = typeof event.data === "object" ? event.data : JSON.parse(event.data);
if (typeof data === "object" && data.target === this.channel && data.id) {
if (data.reply === true && this.queue[data.id]) {
this.queue[data.id][data.error ? 'reject' : 'resolve'](data.payload);
delete this.queue[data.id];
} else if (data.reply !== true) {
let chain = Promise.resolve(data.payload);
this.emitter.emit(data.action, (cb) => {
chain = chain.then((v) => cb(v, data.payload))
});
chain.then((payload?: any) => {
this.reply(event, data.id, payload);
}, (payload?: any) => {
this.reply(event, data.id, payload, true);
});
}
}
} catch (e) {
}
});
}
startClient(origin: string = document.referrer, payload?) {
if (this._client) {
throw new Error('Client already started');
}
if (origin) {
this.origin = new URL(origin).origin;
} else {
this.origin = document.location.origin;
}
return this._client = this.dispatch('bus-handshake', {
payload,
origin: document.location.origin,
});
}
get client(): null | Promise<any> {
return this._client;
}
startServer(origins?: Array<string>, replyPayload?: any): Promise<any> {
if (this._server) {
throw new Error('Server already started');
}
return this._server = new Promise((resolve, reject) => {
const t = setTimeout(() => {
reject(new Error('Window bus timed out, did you forget to startClient?'))
}, 10000);
this.once('bus-handshake', ({origin, payload}) => {
if (!origins || origins.includes(origin)) {
this.origin = origin;
clearTimeout(t);
resolve(payload);
return replyPayload;
} else {
reject(new Error('Origin ' + origin + ' is not allowed'))
}
});
});
}
get server(): null | Promise<any> {
return this._client;
}
setChannel(channel: string) {
this.channel = channel;
}
private reply(event, id, payload?: any, error?: boolean) {
event.source && event.source.postMessage({
reply: true,
target: this.channel,
id,
payload,
error,
}, event.origin);
}
dispatch(action: string, payload?: any, timeout: number = 30000): Promise<any> {
return new Promise((resolve, reject) => {
let t = null;
if (timeout) {
t = setTimeout(() => {
const e = new Error(action + ' timed out') as any;
e.payload = payload;
e.timeout = true;
e.action = action;
reject(e)
}, timeout);
}
this.queue[this.id] = {
resolve: (args) => {
t && clearTimeout(t);
resolve(args);
},
reject
};
this.frame.postMessage({
action,
target: this.channel,
id: this.id++,
payload,
}, this.origin);
});
}
private chains = {};
private chainWrap(fn, action, cb) {
const c = (chain) => chain(cb);
(this.chains[action] || (this.chains[action] = [])).push({cb, c});
this.emitter[fn](action, c);
}
on(action: string, cb: CallableFunction) {
this.chainWrap('on', action, cb);
}
once(action: string, cb: CallableFunction) {
this.chainWrap('once', action, cb);
}
off(action: string, cb?: CallableFunction) {
if (cb) {
const res = (this.chains[action] || []).find((v) => v.cb === cb);
if (res) {
cb = res.c;
}
}
this.emitter.off(action, cb);
}
}