-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathscope.ts
190 lines (166 loc) · 5.25 KB
/
scope.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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
import { fromEventPattern, merge, Observable } from 'rxjs'
import { filter, map } from 'rxjs/operators'
import { scopeAsyncOn, scopeOff, scopeOn } from './events'
import { scopeAsyncSend, scopeSend } from './send'
import {
AsyncMessageListener,
AsyncSendOptions,
MessageListener,
Sender,
SendOptions,
} from './types'
import { setupWaitForFirst } from './waitForFirst'
/**
* Get a messages scope by name.
*/
export function getScope(scope: string) {
const _asyncOn = scopeAsyncOn(scope)
const _asyncSend = scopeAsyncSend(scope)
const _off = scopeOff(scope)
const _on = scopeOn(scope)
const _send = scopeSend(scope)
/* ---------------------- SEND --------------------- */
/**
* Send a message. Options are optional.
*
* @param [options.async] Set to true to receive a response.
* @param [options.tabId] Use to send to a tab
* @param [options.frameId] Use to send to a specific frame in a tab
*/
function send<T, R>(data: T, options: AsyncSendOptions): Promise<R>
function send<T>(data: T, options: SendOptions): Promise<void>
function send<T>(data: T): Promise<void>
async function send<T, R>(data: T, options?: SendOptions & { async?: true }) {
const _options = options || {}
const { async = false, ...sendOptions } = _options
if (async) {
return _asyncSend(data, sendOptions)
} else {
return _send(data, sendOptions)
}
}
/* -------------------- RECEIVE -------------------- */
/** Listen for messages. */
function on<T, R>(
callback: (data: T, sender: Sender, respond: (data: R) => void) => void,
): void
function on<T>(callback: (data: T, sender: Sender) => void): void
function on(callback: MessageListener | AsyncMessageListener) {
if (isMessageListener(callback)) {
_on(callback)
} else {
_asyncOn(callback)
}
function isMessageListener(x: Function): x is MessageListener {
return x.length < 3
}
}
/** Remove a message listener from `on`. */
function off(fn: MessageListener | AsyncMessageListener): void {
return _off(fn)
}
/** Untyped Observable of all messages in scope */
const stream = merge(
fromEventPattern<[any, Sender]>(_on, _off),
fromEventPattern<[any, Sender, (data: any) => void]>(_asyncOn, _off),
)
/* ------------------ GET MESSAGE ----------------- */
const _greetings = new Set()
/**
* Get a paired send function and message Observable.
*
* @param greeting Unique id for message
* @param options.async Set true to send a response from the Observable
*/
function getMessage<T, R>(
greeting: string,
options: { async: true },
): [
((data: T, options?: SendOptions) => Promise<R>) & {
toTab: (options?: SendOptions) => Promise<R>
},
Observable<[T, Sender, (response: R) => void]>,
(predicate?: (x: T) => boolean) => Promise<T>,
]
function getMessage<T>(
greeting: string,
): [
((data: T, options?: SendOptions) => Promise<void>) & {
toTab: (options?: SendOptions) => Promise<void>
},
Observable<[T, Sender]>,
(predicate?: (x: T) => boolean) => Promise<T>,
]
function getMessage<T, R>(greeting: string, options?: { async: true }) {
if (_greetings.has(greeting)) throw new Error('greeting is not unique')
_greetings.add(greeting)
const { async } = options || {}
const _send = (data: T, _options?: SendOptions) => {
interface WrappedMessage {
greeting: string
data: T
}
_options = _options || ({} as SendOptions)
let tabId: number | undefined
if (typeof _options.tabId === 'number') {
tabId = _options.tabId
}
let frameId: number | undefined
if (typeof _options.frameId === 'number') {
frameId = _options.frameId
}
if (async) {
return send<WrappedMessage, R>(
{ greeting, data },
{ async, tabId, frameId },
)
} else {
return send<WrappedMessage>({ greeting, data }, { tabId, frameId })
}
}
/** Use this to send a message with no data to a tab */
_send.toTab = ({ tabId }: { tabId: number }) => {
interface WrappedMessage {
greeting: string
}
if (async) {
return send<WrappedMessage, R>({ greeting }, { async, tabId })
} else {
return send<WrappedMessage>({ greeting }, { tabId })
}
}
if (async) {
const _stream: Observable<[
T,
Sender,
(response: R) => void,
]> = stream.pipe(
// Filter line messages
filter(isMatchingMessage),
// Map message to data
map(([{ data }, s, r]) => [data, s, r]),
filter((x): x is [T, Sender, (response: R) => void] => x.length === 3),
)
return [_send, _stream, setupWaitForFirst(stream)]
} else {
const _stream: Observable<[T, Sender]> = stream.pipe(
// Filter line messages
filter(isMatchingMessage),
// Map message to data
map(([{ data }, s]) => [data, s]),
filter((x): x is [T, Sender] => x.length < 3),
)
return [_send, _stream, setupWaitForFirst(_stream)]
}
function isMatchingMessage([x]: any[]) {
return x && typeof x === 'object' && x.greeting === greeting
}
}
return {
send,
on,
off,
stream,
getMessage,
}
}