-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.js
474 lines (391 loc) · 10.6 KB
/
client.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
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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
const decoder = new TextDecoder()
const encoder = new TextEncoder()
/**
* @typedef {EventInit & { client?: Client }} ClientEventOptions
* @typedef {ClientEventOptions & { error?: Error }} ClientErrorEventOptions
*/
/**
* @template T
* @typedef {ClientEventOptions & { data?: { options: {} & T, payload: Uint8Array }}} ClientMessageEventOptions
*/
export class ClientEvent extends Event {
#client
/**
* @param {string} type
* @param {ClientEventOptions=} [options]
*/
constructor (type, options) {
super(type, options)
this.#client = options?.client ?? null
}
/**
* @type {Client|null}
*/
get client () {
return this.#client ?? null
}
}
export class ClientOpenEvent extends ClientEvent {}
export class ClientCloseEvent extends ClientEvent {}
export class ClientErrorEvent extends ClientEvent {
#error
/**
* @param {string} type
* @param {ClientErrorEventOptions=} [options]
*/
constructor (type, options) {
super(type, options)
this.#error = options?.error ?? null
}
/**
* @type {Error|null}
*/
get error () {
return this.#error ?? null
}
}
/**
* @template T
*/
export class ClientMessageEvent extends ClientEvent {
#data
/**
* @param {string} type
* @param {ClientMessageEventOptions<T>=} [options]
*/
constructor (type, options) {
super(type, options)
this.#data = options?.data ?? null
}
/**
* @type {T|null}
*/
get data () {
// @ts-ignore
return this.#data ?? null
}
}
/**
* @typedef {{
* id?: number,
* key: string,
* origin: string,
* WebSocket?: (function(string):WebSocket)
* }} ClientConnectOptions
*/
export class Client extends EventTarget {
/**
* @return {number}
*/
static id () {
return globalThis.crypto.getRandomValues(new Uint32Array(1))[0] ?? 0
}
/**
* @param {ClientConnectOptions} options
* @param {(function(Error|null, Client|undefined):any)=} [callback]
* @return {Promise<Client>}
*/
static async connect (options, callback = null) {
const {
WebSocket = globalThis.WebSocket,
origin,
key
} = options
const id = options.id || Client.id()
if (typeof WebSocket !== 'function') {
throw new TypeError(
'Unable to determine WebSocket implementation. Please provide one.'
)
}
const client = new Client(null, { WebSocket, origin, key, id })
await client.open()
try {
await new Promise((resolve, reject) => {
client.addEventListener('error', reject, { once: true })
client.addEventListener('open', resolve, { once: true })
})
} catch (err) {
if (typeof callback === 'function') {
callback(err, undefined)
return
}
throw err
}
if (typeof callback === 'function') {
callback(null, client)
}
return client
}
/**
* @type {new (string|URL): WebSocket}
*/
#WebSocket
/**
* @type {WebSocket}
*/
#socket
/**
* @type {string}
*/
#origin
/**
* @type {string}
*/
#key
/**
* @type {number}
*/
#id
constructor (socket, options) {
super()
this.#WebSocket = options.WebSocket
this.#socket = socket
this.#origin = options.origin
this.#key = options.key
this.#id = options.id
}
get WebSocket () {
return this.#WebSocket
}
get socket () {
return this.#socket
}
get origin () {
return this.#origin
}
get key () {
return this.#key
}
get id () {
return this.#id
}
/**
* @overload
* @param {'error'} type
* @param {function(ClientErrorEvent):any} callback
* @param {{ once?: boolean }=} [options]
* @return {void}
*
* @overload
* @param {'message'} type
* @param {function(ClientMessageEvent):any} callback
* @param {{ once?: boolean }=} [options]
* @return {void}
*
* @overload
* @param {'open'} type
* @param {function(ClientOpenEvent):any} callback
* @param {{ once?: boolean }=} [options]
* @return {void}
*
* @overload
* @param {'close'} type
* @param {function(ClientCloseEvent):any} callback
* @param {{ once?: boolean }=} [options]
* @return {void}
*/
addEventListener (type, callback, options = null) {
super.addEventListener(type, callback, options)
}
/**
* @param {Record<string, string|number|boolean>} options
* @param {Uint8Array=} [payload]
*/
send (options, payload = null) {
if (!payload) {
payload = new Uint8Array(0)
}
const message = encodeMessage(options, payload)
this.#socket.send(message)
}
/**
* @template T
* @param {string} command
* @param {Record<string, string|number|boolean>=} [options]
* @param {(Uint8Array|string)=} [payload]
* @return {Promise<T|ArrayBuffer|Uint8Array>}
*/
async call (command, options = null, payload = null) {
const token = Math.random().toString(16).slice(2)
const type = options?.type || null
options = { ...options }
if ('type' in options) {
delete options.type
}
if (command === 'window.eval' && options.value) {
options.value = encodeURIComponent(options.value)
}
if (ArrayBuffer.isView(payload)) {
let size = 0
const buffers = splitBuffer(payload, 1024)
for (const buffer of buffers) {
size += buffer.byteLength
console.log({buffer})
this.send({}, buffer)
}
console.log({ size, payload })
}
// @ts-ignore
this.send({ route: command, token, 'ipc-token': token, ...options })
return await new Promise((resolve, reject) => {
this.addEventListener('message', function onMessage (e) {
if (e.data.options.token === token) {
try {
const result = JSON.parse(decoder.decode(e.data.payload))
if (result.err) {
return reject(new Error(result.err?.message ?? result.err))
} else {
if (type === 'arraybuffer') {
return resolve(e.data.payload)
}
return resolve(result.data ?? result)
}
} catch {
return resolve(e.data.payload)
}
}
})
})
}
async open () {
if (this.#socket) {
return
}
const url = new URL(`/${this.#id}/0?key=${this.#key}`, this.#origin)
this.#socket = Object.assign(new this.#WebSocket(url.href), {
id: this.#id
})
this.#socket.addEventListener('error', (e) => {
this.dispatchEvent(new ClientErrorEvent('error', {
client: this,
// @ts-ignore
error: e.error
}))
})
this.#socket.addEventListener('open', () => {
this.dispatchEvent(new ClientOpenEvent('open', {
client: this
}))
})
this.#socket.addEventListener('close', () => {
this.dispatchEvent(new ClientCloseEvent('close', {
client: this
}))
})
this.#socket.addEventListener('message', async (event) => {
let decoded
try {
// @ts-ignore
const data = ArrayBuffer.isView(event.data)
? event.data
: new Uint8Array(await event.data?.arrayBuffer?.() ?? 0)
// @ts-ignore
decoded = decodeMessage(data)
} catch (err) {
console.log(err)
this.dispatchEvent(new ClientErrorEvent('error', {
client: this,
error: err
}))
return
}
this.dispatchEvent(new ClientMessageEvent('message', {
data: decoded,
client: this
}))
})
}
async close () {
this.#socket.close()
await new Promise((resolve) => this.addEventListener('close', resolve, { once: true }))
}
}
/**
* @see {@link https://github.com/socketsupply/socket/blob/master/api/internal/conduit.js}
* @param {string} key
* @param {string} value
* @return {Uint8Array}
*/
export function encodeOption (key, value) {
const keyLength = key.length
const keyBuffer = encoder.encode(key)
const valueBuffer = encoder.encode(value)
const valueLength = valueBuffer.length
const buffer = new ArrayBuffer(1 + keyLength + 2 + valueLength)
const view = new DataView(buffer)
view.setUint8(0, keyLength)
new Uint8Array(buffer, 1, keyLength).set(keyBuffer)
view.setUint16(1 + keyLength, valueLength, false)
new Uint8Array(buffer, 3 + keyLength, valueLength).set(valueBuffer)
return new Uint8Array(buffer)
}
/**
* @param {Record<string, string|number|boolean>} options
* @param {Uint8Array} payload
* @return {Uint8Array}
*/
export function encodeMessage (options, payload) {
const headerBuffers = Object.entries(options)
.map(([key, value]) => encodeOption(key, String(value)))
const totalOptionLength = headerBuffers.reduce((sum, buf) => sum + buf.length, 0)
const bodyLength = payload.length
const buffer = new ArrayBuffer(1 + totalOptionLength + 2 + bodyLength)
const view = new DataView(buffer)
view.setUint8(0, headerBuffers.length)
let offset = 1
headerBuffers.forEach(headerBuffer => {
new Uint8Array(buffer, offset, headerBuffer.length).set(headerBuffer)
offset += headerBuffer.length
})
view.setUint16(offset, bodyLength, false)
offset += 2
new Uint8Array(buffer, offset, bodyLength).set(payload)
return new Uint8Array(buffer)
}
/**
* @param {Uint8Array} data
* @return {{ options: Record<string, string|number|boolean>, payload: Uint8Array }}
*/
export function decodeMessage (data) {
const view = new DataView(data.buffer, data.byteOffset, data.byteLength)
const length = view.getUint8(0)
let offset = 1
const options = /** @type {Record<string, string|number|boolean>} */ ({})
for (let i = 0; i < length; i++) {
const keyLength = view.getUint8(offset)
offset += 1
const key = decoder.decode(data.slice(offset, offset + keyLength))
offset += keyLength
const valueLength = view.getUint16(offset, false)
offset += 2
const valueBuffer = data.slice(offset, offset + valueLength)
offset += valueLength
const value = decoder.decode(valueBuffer)
options[key] = value
}
const bodyLength = view.getUint16(offset, false)
offset += 2
const payload = data.subarray(offset, offset + bodyLength)
return { options, payload }
}
/**
* @param {ClientConnectOptions} options
* @param {(function(Error|null, Client|undefined):any)=} [callback]
* @return {Promise<Client>}
*/
export async function connect (options, callback = null) {
return await Client.connect(options, callback)
}
export default Client
export function splitBuffer (buffer, highWaterMark) {
const buffers = []
buffer = Uint8Array.from(buffer)
do {
buffers.push(buffer.slice(0, highWaterMark))
buffer = buffer.slice(highWaterMark)
} while (buffer.length > highWaterMark)
if (buffer.length) {
buffers.push(buffer)
}
return buffers
}