forked from WorldBrain/Memex
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwebextensionRPC.ts
363 lines (321 loc) · 11.3 KB
/
webextensionRPC.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
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
// A Remote Procedure Call abstraction around the message passing available to
// WebExtension scripts. Usable to call a function in the background script from
// a tab's content script, or vice versa.
//
// The calling side always gets a Promise of the return value. The executing
// (remote) function can be an async function (= it returns a Promise), whose
// completion then will then be waited for.
// Example use:
//
// === background.js ===
// function myFunc(arg) {
// return arg*2
// }
// makeRemotelyCallable({myFunc})
//
// === content_script.js ===
// const myRemoteFunc = remoteFunction('myFunc')
// myRemoteFunc(21).then(result => { ... result is 42! ... })
import mapValues from 'lodash/fp/mapValues'
import { browser } from 'webextension-polyfill-ts'
import { RemoteFunctionImplementations } from 'src/util/remote-functions-background'
import TypedEventEmitter from 'typed-emitter'
import { EventEmitter } from 'events'
import { AuthRemoteEvents } from 'src/authentication/background/types'
import { InitialSyncEvents } from '@worldbrain/storex-sync/lib/integration/initial-sync'
import { AuthenticatedUser } from '@worldbrain/memex-common/lib/authentication/types'
import { Claims } from '@worldbrain/memex-common/lib/subscriptions/types'
// Our secret tokens to recognise our messages
const RPC_CALL = '__RPC_CALL__'
const RPC_RESPONSE = '__RPC_RESPONSE__'
export class RpcError extends Error {
constructor(message) {
super(message)
this.name = this.constructor.name
}
}
export class RemoteError extends Error {
constructor(message) {
super(message)
this.name = this.constructor.name
}
}
// === Initiating side ===
// The extra options available when calling a remote function
interface RPCOpts {
tabId?: number
}
// runInBackground and runInTab create a Proxy object that looks like the real interface but actually calls remote functions
//
// When the Proxy is asked for a property (such as a method)
// return a function that executes the requested method over the RPC interface
//
// Example Usage:
// interface AnalyticsInterface { trackEvent({}) => any }
// const analytics = runInBackground<AnalyticsInterface>()
// analytics.trackEvent(...)
// Runs a remoteFunction in the background script
export function runInBackground<T extends object>(): T {
return new Proxy<T>({} as T, {
get(target, property): any {
return (...args) => {
return _remoteFunction(property.toString())(...args)
}
},
})
}
// Runs a remoteFunction in the content script on a certain tab
export function runInTab<T extends object>(tabId): T {
return new Proxy<T>({} as T, {
get(target, property): any {
return (...args) => {
return _remoteFunction(property.toString(), { tabId })(...args)
}
},
})
}
// @depreciated - Don't call this function directly. Instead use the above typesafe version runInBackground
export function remoteFunction(
funcName: string,
{ tabId }: { tabId?: number } = {},
) {
return _remoteFunction(funcName, { tabId })
}
// Create a proxy function that invokes the specified remote function.
// Arguments
// - funcName (required): name of the function as registered on the remote side.
// - options (optional): {
// tabId: The id of the tab whose content script is the remote side.
// Leave undefined to call the background script (from a tab).
// }
function _remoteFunction(funcName: string, { tabId }: { tabId?: number } = {}) {
const otherSide =
tabId !== undefined
? "the tab's content script"
: 'the background script'
const f = async function(...args) {
const message = {
[RPC_CALL]: RPC_CALL,
funcName,
args,
}
// Try send the message and await the response.
let response
try {
response =
tabId !== undefined
? await browser.tabs.sendMessage(tabId, message)
: await browser.runtime.sendMessage(message)
} catch (err) {
return
}
// Check if it was *our* listener that responded.
if (!response || response[RPC_RESPONSE] !== RPC_RESPONSE) {
throw new RpcError(
`RPC got a response from an interfering listener. Wanted ${RPC_RESPONSE} but got ${response[RPC_RESPONSE]}. Response:${response}`,
)
}
// If we could not invoke the function on the other side, throw an error.
if (response.rpcError) {
throw new RpcError(response.rpcError)
}
// Return the value or throw the error we received from the other side.
if (response.errorMessage) {
console.error(
`Error occured on remote side, please check it's console for more details`,
)
throw new RemoteError(response.errorMessage)
} else {
return response.returnValue
}
}
// Give it a name, could be helpful in debugging
Object.defineProperty(f, 'name', { value: `${funcName}_RPC` })
return f
}
// === Executing side ===
const remotelyCallableFunctions = {}
async function incomingRPCListener(message, sender) {
if (!message || message[RPC_CALL] !== RPC_CALL) {
return
}
const funcName = message.funcName
const args = message.hasOwnProperty('args') ? message.args : []
const func = remotelyCallableFunctions[funcName]
if (func === undefined) {
console.error(`Received RPC for unknown function: ${funcName}`)
return {
rpcError: `No such function registered for RPC: ${funcName}`,
[RPC_RESPONSE]: RPC_RESPONSE,
}
}
const extraArg = {
tab: sender.tab,
}
// Run the function
let returnValue
try {
returnValue = func(extraArg, ...args)
} catch (error) {
console.error(error)
return {
errorMessage: error.message,
[RPC_RESPONSE]: RPC_RESPONSE,
}
}
try {
returnValue = await returnValue
return {
returnValue,
[RPC_RESPONSE]: RPC_RESPONSE,
}
} catch (error) {
console.error(error)
return {
errorMessage: error.message,
[RPC_RESPONSE]: RPC_RESPONSE,
}
}
}
// A bit of global state to ensure we only attach the event listener once.
let enabled = false
export function setupRemoteFunctionsImplementations<T>(
implementations: RemoteFunctionImplementations,
): void {
for (const [group, functions] of Object.entries(implementations)) {
makeRemotelyCallableType<typeof functions>(functions)
}
}
// Register a function to allow remote scripts to call it.
// Arguments:
// - functions (required):
// An object with a {functionName: function} mapping.
// Each function will be callable with the given name.
// - options (optional): {
// insertExtraArg:
// If truthy, each executed function also receives, as its first
// argument before the arguments it was invoked with, an object with
// the details of the tab that sent the message.
// }
export function makeRemotelyCallableType<T = never>(
functions: { [P in keyof T]: T[P] },
{ insertExtraArg = false } = {},
) {
return makeRemotelyCallable(functions, { insertExtraArg })
}
// @Depreciated to call this directly. Should use the above typesafe version
export function makeRemotelyCallable<T>(
functions: { [P in keyof T]: T[P] },
{ insertExtraArg = false } = {},
) {
// Every function is passed an extra argument with sender information,
// so remove this from the call if this was not desired.
if (!insertExtraArg) {
// Replace each func with...
// @ts-ignore
const wrapFunctions = mapValues(func =>
// ...a function that calls func, but hides the inserted argument.
// @ts-ignore
(extraArg, ...args) => func(...args),
)
// @ts-ignore
functions = wrapFunctions(functions)
}
for (const functionName of Object.keys(functions)) {
if (remotelyCallableFunctions.hasOwnProperty(functionName)) {
const error = `RPC function with name ${functionName} has already been registered `
console.warn(error)
}
}
// Add the functions to our global repetoir.
Object.assign(remotelyCallableFunctions, functions)
// Enable the listener if needed.
if (!enabled) {
browser.runtime.onMessage.addListener(incomingRPCListener)
enabled = true
}
}
export class RemoteFunctionRegistry {
registerRemotelyCallable(functions, { insertExtraArg = false } = {}) {
makeRemotelyCallable(functions, { insertExtraArg })
}
}
export function fakeRemoteFunctions(functions: {
[name: string]: (...args) => any
}) {
return name => {
if (!functions[name]) {
throw new Error(
`Tried to call fake remote function '${name}' for which no implementation was provided`,
)
}
return (...args) => {
return Promise.resolve(functions[name](...args))
}
}
}
export interface RemoteEventEmitter<T> {
emit: (eventName: keyof T, data: any) => Promise<any>
}
const __REMOTE_EVENT__ = '__REMOTE_EVENT__'
const __REMOTE_EVENT_TYPE__ = '__REMOTE_EVENT_TYPE__'
const __REMOTE_EVENT_NAME__ = '__REMOTE_EVENT_NAME__'
// Sending Side, (e.g. background script)
export function remoteEventEmitter<T>(
eventType: string,
): RemoteEventEmitter<T> {
const message = {
__REMOTE_EVENT__,
__REMOTE_EVENT_TYPE__: eventType,
}
return {
emit: async (eventName, data) =>
browser.runtime.sendMessage({
...message,
__REMOTE_EVENT_NAME__: eventName,
data,
}),
}
}
// Receiving Side (e.g. content script, options page, etc)
const remoteEventEmitters: RemoteEventEmitters = {} as RemoteEventEmitters
type RemoteEventEmitters = {
[K in keyof RemoteEvents]?: TypedRemoteEventEmitter<K>
}
export type TypedRemoteEventEmitter<
T extends keyof RemoteEvents
> = TypedEventEmitter<RemoteEvents[T]>
// Statically defined types for now, move this to a registry
interface RemoteEvents {
auth: AuthRemoteEvents
sync: InitialSyncEvents
}
function registerRemoteEventForwarder() {
if (browser.runtime.onMessage.hasListener(remoteEventForwarder)) {
return
}
browser.runtime.onMessage.addListener(remoteEventForwarder)
}
const remoteEventForwarder = (message, _) => {
if (message == null || message[__REMOTE_EVENT__] !== __REMOTE_EVENT__) {
return
}
const emitterType = message[__REMOTE_EVENT_TYPE__]
const emitter = remoteEventEmitters[emitterType]
if (emitter == null) {
return
}
emitter.emit(message[__REMOTE_EVENT_NAME__], message.data)
}
export function getRemoteEventEmitter<EventType extends keyof RemoteEvents>(
eventType: EventType,
): RemoteEventEmitters[EventType] {
const existingEmitter = remoteEventEmitters[eventType]
if (existingEmitter) {
return existingEmitter
}
const newEmitter = new EventEmitter() as any
remoteEventEmitters[eventType] = newEmitter
registerRemoteEventForwarder()
return newEmitter
}