-
Notifications
You must be signed in to change notification settings - Fork 47.4k
/
Copy pathbridge.js
451 lines (397 loc) · 13.4 KB
/
bridge.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
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
import EventEmitter from './events';
import type {ComponentFilter, Wall} from './types';
import type {
InspectedElementPayload,
OwnersList,
ProfilingDataBackend,
RendererID,
} from 'react-devtools-shared/src/backend/types';
import type {StyleAndLayout as StyleAndLayoutPayload} from 'react-devtools-shared/src/backend/NativeStyleEditor/types';
import type {BrowserTheme} from 'react-devtools-shared/src/devtools/views/DevTools';
const BATCH_DURATION = 100;
// This message specifies the version of the DevTools protocol currently supported by the backend,
// as well as the earliest NPM version (e.g. "4.13.0") that protocol is supported by on the frontend.
// This enables an older frontend to display an upgrade message to users for a newer, unsupported backend.
export type BridgeProtocol = {|
// Version supported by the current frontend/backend.
version: number,
// NPM version range that also supports this version.
// Note that 'maxNpmVersion' is only set when the version is bumped.
minNpmVersion: string,
maxNpmVersion: string | null,
|};
// Bump protocol version whenever a backwards breaking change is made
// in the messages sent between BackendBridge and FrontendBridge.
// This mapping is embedded in both frontend and backend builds.
//
// The backend protocol will always be the latest entry in the BRIDGE_PROTOCOL array.
//
// When an older frontend connects to a newer backend,
// the backend can send the minNpmVersion and the frontend can display an NPM upgrade prompt.
//
// When a newer frontend connects with an older protocol version,
// the frontend can use the embedded minNpmVersion/maxNpmVersion values to display a downgrade prompt.
export const BRIDGE_PROTOCOL: Array<BridgeProtocol> = [
// This version technically never existed,
// but a backwards breaking change was added in 4.11,
// so the safest guess to downgrade the frontend would be to version 4.10.
{
version: 0,
minNpmVersion: '"<4.11.0"',
maxNpmVersion: '"<4.11.0"',
},
{
version: 1,
minNpmVersion: '4.13.0',
maxNpmVersion: '4.21.0',
},
// Version 2 adds a StrictMode-enabled and supports-StrictMode bits to add-root operation.
{
version: 2,
minNpmVersion: '4.22.0',
maxNpmVersion: null,
},
];
export const currentBridgeProtocol: BridgeProtocol =
BRIDGE_PROTOCOL[BRIDGE_PROTOCOL.length - 1];
type ElementAndRendererID = {|id: number, rendererID: RendererID|};
type Message = {|
event: string,
payload: any,
|};
type HighlightElementInDOM = {|
...ElementAndRendererID,
displayName: string | null,
hideAfterTimeout: boolean,
openNativeElementsPanel: boolean,
scrollIntoView: boolean,
|};
type OverrideValue = {|
...ElementAndRendererID,
path: Array<string | number>,
wasForwarded?: boolean,
value: any,
|};
type OverrideHookState = {|
...OverrideValue,
hookID: number,
|};
type PathType = 'props' | 'hooks' | 'state' | 'context';
type DeletePath = {|
...ElementAndRendererID,
type: PathType,
hookID?: ?number,
path: Array<string | number>,
|};
type RenamePath = {|
...ElementAndRendererID,
type: PathType,
hookID?: ?number,
oldPath: Array<string | number>,
newPath: Array<string | number>,
|};
type OverrideValueAtPath = {|
...ElementAndRendererID,
type: PathType,
hookID?: ?number,
path: Array<string | number>,
value: any,
|};
type OverrideError = {|
...ElementAndRendererID,
forceError: boolean,
|};
type OverrideSuspense = {|
...ElementAndRendererID,
forceFallback: boolean,
|};
type CopyElementPathParams = {|
...ElementAndRendererID,
path: Array<string | number>,
|};
type ViewAttributeSourceParams = {|
...ElementAndRendererID,
path: Array<string | number>,
|};
type InspectElementParams = {|
...ElementAndRendererID,
forceFullData: boolean,
path: Array<number | string> | null,
requestID: number,
|};
type StoreAsGlobalParams = {|
...ElementAndRendererID,
count: number,
path: Array<string | number>,
|};
type NativeStyleEditor_RenameAttributeParams = {|
...ElementAndRendererID,
oldName: string,
newName: string,
value: string,
|};
type NativeStyleEditor_SetValueParams = {|
...ElementAndRendererID,
name: string,
value: string,
|};
type UpdateConsolePatchSettingsParams = {|
appendComponentStack: boolean,
breakOnConsoleErrors: boolean,
showInlineWarningsAndErrors: boolean,
hideConsoleLogsInStrictMode: boolean,
browserTheme: BrowserTheme,
|};
type SavedPreferencesParams = {|
appendComponentStack: boolean,
breakOnConsoleErrors: boolean,
componentFilters: Array<ComponentFilter>,
showInlineWarningsAndErrors: boolean,
hideConsoleLogsInStrictMode: boolean,
|};
export type BackendEvents = {|
backendVersion: [string],
bridgeProtocol: [BridgeProtocol],
extensionBackendInitialized: [],
fastRefreshScheduled: [],
getSavedPreferences: [],
inspectedElement: [InspectedElementPayload],
isBackendStorageAPISupported: [boolean],
isSynchronousXHRSupported: [boolean],
operations: [Array<number>],
ownersList: [OwnersList],
overrideComponentFilters: [Array<ComponentFilter>],
profilingData: [ProfilingDataBackend],
profilingStatus: [boolean],
reloadAppForProfiling: [],
selectFiber: [number],
shutdown: [],
stopInspectingNative: [boolean],
syncSelectionFromNativeElementsPanel: [],
syncSelectionToNativeElementsPanel: [],
unsupportedRendererVersion: [RendererID],
// React Native style editor plug-in.
isNativeStyleEditorSupported: [
{|isSupported: boolean, validAttributes: ?$ReadOnlyArray<string>|},
],
NativeStyleEditor_styleAndLayout: [StyleAndLayoutPayload],
|};
type FrontendEvents = {|
clearErrorsAndWarnings: [{|rendererID: RendererID|}],
clearErrorsForFiberID: [ElementAndRendererID],
clearNativeElementHighlight: [],
clearWarningsForFiberID: [ElementAndRendererID],
copyElementPath: [CopyElementPathParams],
deletePath: [DeletePath],
getBackendVersion: [],
getBridgeProtocol: [],
getOwnersList: [ElementAndRendererID],
getProfilingData: [{|rendererID: RendererID|}],
getProfilingStatus: [],
highlightNativeElement: [HighlightElementInDOM],
inspectElement: [InspectElementParams],
logElementToConsole: [ElementAndRendererID],
overrideError: [OverrideError],
overrideSuspense: [OverrideSuspense],
overrideValueAtPath: [OverrideValueAtPath],
profilingData: [ProfilingDataBackend],
reloadAndProfile: [boolean],
renamePath: [RenamePath],
savedPreferences: [SavedPreferencesParams],
selectFiber: [number],
setTraceUpdatesEnabled: [boolean],
shutdown: [],
startInspectingNative: [],
startProfiling: [boolean],
stopInspectingNative: [boolean],
stopProfiling: [],
storeAsGlobal: [StoreAsGlobalParams],
updateComponentFilters: [Array<ComponentFilter>],
updateConsolePatchSettings: [UpdateConsolePatchSettingsParams],
viewAttributeSource: [ViewAttributeSourceParams],
viewElementSource: [ElementAndRendererID],
// React Native style editor plug-in.
NativeStyleEditor_measure: [ElementAndRendererID],
NativeStyleEditor_renameAttribute: [NativeStyleEditor_RenameAttributeParams],
NativeStyleEditor_setValue: [NativeStyleEditor_SetValueParams],
// Temporarily support newer standalone front-ends sending commands to older embedded backends.
// We do this because React Native embeds the React DevTools backend,
// but cannot control which version of the frontend users use.
//
// Note that nothing in the newer backend actually listens to these events,
// but the new frontend still dispatches them (in case older backends are listening to them instead).
//
// Note that this approach does no support the combination of a newer backend with an older frontend.
// It would be more work to support both approaches (and not run handlers twice)
// so I chose to support the more likely/common scenario (and the one more difficult for an end user to "fix").
overrideContext: [OverrideValue],
overrideHookState: [OverrideHookState],
overrideProps: [OverrideValue],
overrideState: [OverrideValue],
|};
class Bridge<
OutgoingEvents: Object,
IncomingEvents: Object,
> extends EventEmitter<{|
...IncomingEvents,
...OutgoingEvents,
|}> {
_isShutdown: boolean = false;
_messageQueue: Array<any> = [];
_timeoutID: TimeoutID | null = null;
_wall: Wall;
_wallUnlisten: Function | null = null;
constructor(wall: Wall) {
super();
this._wall = wall;
this._wallUnlisten =
wall.listen((message: Message) => {
if (message && message.event) {
(this: any).emit(message.event, message.payload);
}
}) || null;
// Temporarily support older standalone front-ends sending commands to newer embedded backends.
// We do this because React Native embeds the React DevTools backend,
// but cannot control which version of the frontend users use.
this.addListener('overrideValueAtPath', this.overrideValueAtPath);
}
// Listening directly to the wall isn't advised.
// It can be used to listen for legacy (v3) messages (since they use a different format).
get wall(): Wall {
return this._wall;
}
send<EventName: $Keys<OutgoingEvents>>(
event: EventName,
...payload: $ElementType<OutgoingEvents, EventName>
) {
if (this._isShutdown) {
console.warn(
`Cannot send message "${event}" through a Bridge that has been shutdown.`,
);
return;
}
// When we receive a message:
// - we add it to our queue of messages to be sent
// - if there hasn't been a message recently, we set a timer for 0 ms in
// the future, allowing all messages created in the same tick to be sent
// together
// - if there *has* been a message flushed in the last BATCH_DURATION ms
// (or we're waiting for our setTimeout-0 to fire), then _timeoutID will
// be set, and we'll simply add to the queue and wait for that
this._messageQueue.push(event, payload);
if (!this._timeoutID) {
this._timeoutID = setTimeout(this._flush, 0);
}
}
shutdown() {
if (this._isShutdown) {
console.warn('Bridge was already shutdown.');
return;
}
// Queue the shutdown outgoing message for subscribers.
this.send('shutdown');
// Mark this bridge as destroyed, i.e. disable its public API.
this._isShutdown = true;
// Disable the API inherited from EventEmitter that can add more listeners and send more messages.
// $FlowFixMe This property is not writable.
this.addListener = function() {};
// $FlowFixMe This property is not writable.
this.emit = function() {};
// NOTE: There's also EventEmitter API like `on` and `prependListener` that we didn't add to our Flow type of EventEmitter.
// Unsubscribe this bridge incoming message listeners to be sure, and so they don't have to do that.
this.removeAllListeners();
// Stop accepting and emitting incoming messages from the wall.
const wallUnlisten = this._wallUnlisten;
if (wallUnlisten) {
wallUnlisten();
}
// Synchronously flush all queued outgoing messages.
// At this step the subscribers' code may run in this call stack.
do {
this._flush();
} while (this._messageQueue.length);
// Make sure once again that there is no dangling timer.
if (this._timeoutID !== null) {
clearTimeout(this._timeoutID);
this._timeoutID = null;
}
}
_flush = () => {
// This method is used after the bridge is marked as destroyed in shutdown sequence,
// so we do not bail out if the bridge marked as destroyed.
// It is a private method that the bridge ensures is only called at the right times.
if (this._timeoutID !== null) {
clearTimeout(this._timeoutID);
this._timeoutID = null;
}
if (this._messageQueue.length) {
for (let i = 0; i < this._messageQueue.length; i += 2) {
this._wall.send(this._messageQueue[i], ...this._messageQueue[i + 1]);
}
this._messageQueue.length = 0;
// Check again for queued messages in BATCH_DURATION ms. This will keep
// flushing in a loop as long as messages continue to be added. Once no
// more are, the timer expires.
this._timeoutID = setTimeout(this._flush, BATCH_DURATION);
}
};
// Temporarily support older standalone backends by forwarding "overrideValueAtPath" commands
// to the older message types they may be listening to.
overrideValueAtPath = ({
id,
path,
rendererID,
type,
value,
}: OverrideValueAtPath) => {
switch (type) {
case 'context':
this.send('overrideContext', {
id,
path,
rendererID,
wasForwarded: true,
value,
});
break;
case 'hooks':
this.send('overrideHookState', {
id,
path,
rendererID,
wasForwarded: true,
value,
});
break;
case 'props':
this.send('overrideProps', {
id,
path,
rendererID,
wasForwarded: true,
value,
});
break;
case 'state':
this.send('overrideState', {
id,
path,
rendererID,
wasForwarded: true,
value,
});
break;
}
};
}
export type BackendBridge = Bridge<BackendEvents, FrontendEvents>;
export type FrontendBridge = Bridge<FrontendEvents, BackendEvents>;
export default Bridge;