This repository has been archived by the owner on Dec 6, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
reactotron-core-client.ts
538 lines (453 loc) · 14.1 KB
/
reactotron-core-client.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
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
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
import * as WebSocket from "ws"
import validate from "./validate"
import logger from "./plugins/logger"
import image from "./plugins/image"
import benchmark from "./plugins/benchmark"
import stateResponses from "./plugins/state-responses"
import apiResponse from "./plugins/api-response"
import clear from "./plugins/clear"
import repl from "./plugins/repl"
import serialize from "./serialize"
import { start } from "./stopwatch"
import { ClientOptions } from "./client-options"
export const corePlugins = [
image(),
logger(),
benchmark(),
stateResponses(),
apiResponse(),
clear(),
repl(),
]
const DEFAULT_OPTIONS: ClientOptions = {
createSocket: null,
host: "localhost",
port: 9090,
name: "reactotron-core-client",
secure: false,
plugins: corePlugins,
safeRecursion: true,
onCommand: () => null,
onConnect: () => null,
onDisconnect: () => null,
}
// these are not for you.
const reservedFeatures = [
"options",
"connected",
"socket",
"plugins",
"configure",
"connect",
"send",
"use",
"startTimer",
]
const isReservedFeature = (value: string) => reservedFeatures.some(res => res === value)
function emptyPromise() {
return Promise.resolve("")
}
export enum ArgType {
String = "string",
}
export interface CustomCommandArg {
name: string
type: ArgType
}
export interface CustomCommand {
id?: number
command: string
handler: (args?: any) => void
title?: string
description?: string
args?: CustomCommandArg[]
}
export interface ReactotronCore {
startTimer: () => () => number
close: () => void
send: (type: any, payload?: any, important?: boolean) => void
display: (config?: any) => void
reportError: (this: any, error: any) => void
onCustomCommand: (config: CustomCommand | string, optHandler?: () => void) => () => void
/* Provided by plugins */
// API Response Plugin
apiResponse?: (request: any, response: any, duration: any) => void
// Benchmark Plugin
benchmark?: (
title: string
) => {
step: (stepName: string) => void
stop: (stopTitle: string) => void
last: (stopTitle: string) => void
}
// Clear Plugin
clear?: () => void
// Image Plugin
image?: (options: {
uri: any
preview: any
filename: any
width: any
height: any
caption: any
}) => void
// Logger Plugin
log?: (...args: any[]) => void
logImportant?: (...args: any[]) => void
debug?: (message: any, important?: boolean) => void
warn?: (message: any) => void
error?: (message: any, stack: any) => void
// State Plugin
stateActionComplete?: (name: any, action: any, important?: boolean) => void
stateValuesResponse?: (path: any, value: any, valid?: boolean) => void
stateKeysResponse?: (path: any, keys: any, valid?: boolean) => void
stateValuesChange?: (changes: any) => void
stateBackupResponse?: (state: any) => void
// REPL Plugin
repl?: (name: string, value: object | Function | string | number) => void
}
export interface Reactotron<ReactotronSubtype = ReactotronCore> extends ReactotronCore {
/**
* Set the configuration options.
*/
configure: (options?: ClientOptions) => Reactotron<ReactotronSubtype> & ReactotronSubtype
use: (
pluginCreator?: (client: Reactotron<ReactotronSubtype> & ReactotronSubtype) => any
) => Reactotron<ReactotronSubtype> & ReactotronSubtype
connect: () => Reactotron<ReactotronSubtype> & ReactotronSubtype
}
export class ReactotronImpl<ReactotronSubtype = ReactotronCore>
implements Reactotron<ReactotronSubtype> {
// the configuration options
options: ClientOptions = Object.assign({}, DEFAULT_OPTIONS)
/**
* Are we connected to a server?
*/
connected = false
/**
* The socket we're using.
*/
socket: WebSocket = null
/**
* Available plugins.
*/
plugins: any[] = []
/**
* Messages that need to be sent.
*/
sendQueue: any[] = []
/**
* Are we ready to start communicating?
*/
isReady = false
/**
* The last time we sent a message.
*/
lastMessageDate = new Date()
/**
* The registered custom commands
*/
customCommands: CustomCommand[] = []
/**
* The current ID for custom commands
*/
customCommandLatestId = 1
/**
* Starts a timer and returns a function you can call to stop it and return the elapsed time.
*/
startTimer = () => start()
/**
* Set the configuration options.
*/
configure(options: ClientOptions = {}): Reactotron<ReactotronSubtype> & ReactotronSubtype {
// options get merged & validated before getting set
const newOptions = Object.assign({}, this.options, options)
validate(newOptions)
this.options = newOptions
// if we have plugins, let's add them here
if (Array.isArray(this.options.plugins)) {
this.options.plugins.forEach(p => this.use(p))
}
return (this as any) as Reactotron<ReactotronSubtype> & ReactotronSubtype // cast needed to allow patching by other implementations like reactotron-react-native
}
close() {
this.connected = false
this.socket && this.socket.close && this.socket.close()
}
/**
* Connect to the Reactotron server.
*/
connect(): Reactotron<ReactotronSubtype> & ReactotronSubtype {
this.connected = true
const {
createSocket,
secure,
host,
environment,
port,
name,
client = {},
getClientId,
} = this.options
const { onCommand, onConnect, onDisconnect } = this.options
// establish a connection to the server
const protocol = secure ? "wss" : "ws"
const socket = createSocket(`${protocol}://${host}:${port}`)
// fires when we talk to the server
const onOpen = () => {
// fire our optional onConnect handler
onConnect && onConnect()
// trigger our plugins onConnect
this.plugins.forEach(p => p.onConnect && p.onConnect())
const getClientIdPromise = getClientId || emptyPromise
getClientIdPromise().then(clientId => {
this.isReady = true
// introduce ourselves
this.send("client.intro", {
environment,
...client,
name,
clientId,
reactotronCoreClientVersion: "REACTOTRON_CORE_CLIENT_VERSION",
})
// flush the send queue
while (this.sendQueue.length > 0) {
const h = this.sendQueue[0]
this.sendQueue = this.sendQueue.slice(1)
this.socket.send(h)
}
})
}
// fires when we disconnect
const onClose = () => {
this.isReady = false
// trigger our disconnect handler
onDisconnect && onDisconnect()
// as well as the plugin's onDisconnect
this.plugins.forEach(p => p.onDisconnect && p.onDisconnect())
}
// fires when we receive a command, just forward it off
const onMessage = (data: any) => {
const command = typeof data === "string" ? JSON.parse(data) : data
// trigger our own command handler
onCommand && onCommand(command)
// trigger our plugins onCommand
this.plugins.forEach(p => p.onCommand && p.onCommand(command))
// trigger our registered custom commands
if (command.type === "custom") {
this.customCommands
.filter(cc => {
if (typeof command.payload === "string") {
return cc.command === command.payload
}
return cc.command === command.payload.command
})
.forEach(cc =>
cc.handler(typeof command.payload === "object" ? command.payload.args : undefined)
)
} else if (command.type === "setClientId") {
this.options.setClientId && this.options.setClientId(command.payload)
}
}
// this is ws style from require('ws') on node js
if (socket.on) {
socket.on("open", onOpen)
socket.on("close", onClose)
socket.on("message", onMessage)
} else {
// this is a browser
socket.onopen = onOpen
socket.onclose = onClose
socket.onmessage = evt => onMessage(evt.data)
}
// assign the socket to the instance
this.socket = socket
return (this as any) as Reactotron<ReactotronSubtype> & ReactotronSubtype // cast needed to allow patching by other implementations like reactotron-react-native
}
/**
* Sends a command to the server
*/
send = (type, payload = {}, important = false) => {
// set the timing info
const date = new Date()
let deltaTime = date.getTime() - this.lastMessageDate.getTime()
// glitches in the matrix
if (deltaTime < 0) {
deltaTime = 0
}
this.lastMessageDate = date
const fullMessage = {
type,
payload,
important: !!important,
date: date.toISOString(),
deltaTime,
}
const serializedMessage = serialize(fullMessage, this.options.proxyHack)
if (this.isReady) {
// send this command
try {
this.socket.send(serializedMessage)
} catch {
this.isReady = false
console.log("An error occured communicating with reactotron. Please reload your app")
}
} else {
// queue it up until we can connect
this.sendQueue.push(serializedMessage)
}
}
/**
* Sends a custom command to the server to displays nicely.
*/
display(config: any = {}) {
const { name, value, preview, image: img, important = false } = config
const payload = {
name,
value: value || null,
preview: preview || null,
image: img || null,
}
this.send("display", payload, important)
}
/**
* Client libraries can hijack this to report errors.
*/
reportError(this: any, error) {
this.error(error)
}
/**
* Adds a plugin to the system
*/
use(
pluginCreator?: (client: Reactotron<ReactotronSubtype> & ReactotronSubtype) => any
): Reactotron<ReactotronSubtype> & ReactotronSubtype {
// we're supposed to be given a function
if (typeof pluginCreator !== "function") {
throw new Error("plugins must be a function")
}
// execute it immediately passing the send function
const plugin = pluginCreator.bind(this)(this)
// ensure we get an Object-like creature back
if (typeof plugin !== "object") {
throw new Error("plugins must return an object")
}
// do we have features to mixin?
if (plugin.features) {
// validate
if (typeof plugin.features !== "object") {
throw new Error("features must be an object")
}
// here's how we're going to inject these in
const inject = (key: string) => {
// grab the function
const featureFunction = plugin.features[key]
// only functions may pass
if (typeof featureFunction !== "function") {
throw new Error(`feature ${key} is not a function`)
}
// ditch reserved names
if (isReservedFeature(key)) {
throw new Error(`feature ${key} is a reserved name`)
}
// ok, let's glue it up... and lose all respect from elite JS champions.
this[key] = featureFunction
}
// let's inject
Object.keys(plugin.features).forEach(key => inject(key))
}
// add it to the list
this.plugins.push(plugin)
// call the plugins onPlugin
plugin.onPlugin && typeof plugin.onPlugin === "function" && plugin.onPlugin.bind(this)(this)
// chain-friendly
return (this as any) as Reactotron<ReactotronSubtype> & ReactotronSubtype // cast needed to allow patching by other implementations like reactotron-react-native
}
onCustomCommand(config: CustomCommand | string, optHandler?: () => void): () => void {
let command: string
let handler: () => void
let title: string
let description: string
let args: CustomCommandArg[]
if (typeof config === "string") {
command = config
handler = optHandler
} else {
command = config.command
handler = config.handler
title = config.title
description = config.description
args = config.args
}
// Validations
// Make sure there is a command
if (!command) {
throw new Error("A command is required")
}
// Make sure there is a handler
if (!handler) {
throw new Error(`A handler is required for command "${command}"`)
}
// Make sure the command doesn't already exist
const existingCommands = this.customCommands.filter(cc => cc.command === command)
if (existingCommands.length > 0) {
existingCommands.forEach(command => {
console.log(command)
this.customCommands = this.customCommands.filter(cc => cc.id !== command.id)
this.send("customCommand.unregister", {
id: command.id,
command: command.command,
})
})
}
if (args) {
const argNames = []
args.forEach(arg => {
if (!arg.name) {
throw new Error(`A arg on the command "${command}" is missing a name`)
}
if (argNames.indexOf(arg.name) > -1) {
throw new Error(
`A arg with the name "${arg.name}" already exists in the command "${command}"`
)
}
argNames.push(arg.name)
})
}
// Create this command handlers object
const customHandler: CustomCommand = {
id: this.customCommandLatestId,
command,
handler,
title,
description,
args,
}
// Increment our id counter
this.customCommandLatestId += 1
// Add it to our array
this.customCommands.push(customHandler)
this.send("customCommand.register", {
id: customHandler.id,
command: customHandler.command,
title: customHandler.title,
description: customHandler.description,
args: customHandler.args,
})
return () => {
this.customCommands = this.customCommands.filter(cc => cc.id !== customHandler.id)
this.send("customCommand.unregister", {
id: customHandler.id,
command: customHandler.command,
})
}
}
}
// convenience factory function
export function createClient<ReactotronSubtype = ReactotronCore>(
options?: ClientOptions
): Reactotron<ReactotronSubtype> & ReactotronSubtype {
const client = new ReactotronImpl<ReactotronSubtype>()
client.configure(options)
return (client as any) as Reactotron<ReactotronSubtype> & ReactotronSubtype // cast needed to allow patching by other implementations like reactotron-react-native
}