Skip to content

[MV3] Dart Debug Extension supports cross-extension communication with AngularDart DevTools #1866

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 10 commits into from
Jan 6, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion dwds/debug_extension_mv3/web/background.dart
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import 'package:js/js.dart';
import 'data_types.dart';
import 'debug_session.dart';
import 'chrome_api.dart';
import 'cross_extension_communication.dart';
import 'lifeline_ports.dart';
import 'logger.dart';
import 'messaging.dart';
Expand All @@ -29,7 +30,15 @@ void main() {
}

void _registerListeners() {
chrome.runtime.onMessage.addListener(allowInterop(_handleRuntimeMessages));
chrome.runtime.onMessage.addListener(
allowInterop(_handleRuntimeMessages),
);
// The only extension allowed to send messages to this extension is the
// AngularDart DevTools extension. Its permission is set in the manifest.json
// externally_connectable field.
chrome.runtime.onMessageExternal.addListener(
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe a comment indicating that we only allow the ACX extension to communicate with this extension due to the manifest config.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done, added one here and in cross_extension_communication

allowInterop(handleMessagesFromAngularDartDevTools),
);
chrome.tabs.onRemoved
.addListener(allowInterop((tabId, _) => maybeRemoveLifelinePort(tabId)));
// Update the extension icon on tab navigation:
Expand Down
2 changes: 2 additions & 0 deletions dwds/debug_extension_mv3/web/chrome_api.dart
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,8 @@ class Runtime {
external ConnectionHandler get onConnect;

external OnMessageHandler get onMessage;

external OnMessageHandler get onMessageExternal;
}

@JS()
Expand Down
161 changes: 161 additions & 0 deletions dwds/debug_extension_mv3/web/cross_extension_communication.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,161 @@
// Copyright (c) 2023, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

@JS()
library cross_extension_communication;

import 'package:js/js.dart';

import 'chrome_api.dart';
import 'data_types.dart';
import 'debug_session.dart';
import 'logger.dart';
import 'storage.dart';
import 'web_api.dart';

// The only extension allowed to communicate with this extension is the
// AngularDart DevTools extension.
//
// This ID is used to send messages to AngularDart DevTools, while the
// externally_connectable field in the manifest.json allows AngularDart DevTools
// to send messages to this extension.
const _angularDartDevToolsId = 'nbkbficgbembimioedhceniahniffgpl';

// A set of events to forward to the AngularDart DevTools extension.
final _eventsForAngularDartDevTools = {
'Overlay.inspectNodeRequested',
'dwds.encodedUri',
};

void handleMessagesFromAngularDartDevTools(
dynamic jsRequest, MessageSender sender, Function sendResponse) async {
if (jsRequest == null) return;
final message = jsRequest as ExternalExtensionMessage;
if (message.name == 'chrome.debugger.sendCommand') {
_forwardCommandToChromeDebugger(message, sendResponse);
} else if (message.name == 'dwds.encodedUri') {
_respondWithEncodedUri(message.tabId, sendResponse);
} else if (message.name == 'dwds.startDebugging') {
attachDebugger(message.tabId, trigger: Trigger.angularDartDevTools);
sendResponse(true);
} else {
sendResponse(
ErrorResponse()..error = 'Unknown message name: ${message.name}');
}
}

void maybeForwardMessageToAngularDartDevTools(
{required String method, required dynamic params, required int tabId}) {
if (!_eventsForAngularDartDevTools.contains(method)) return;

final message = method.startsWith('dwds')
? _dwdsEventMessage(method: method, params: params, tabId: tabId)
: _debugEventMessage(method: method, params: params, tabId: tabId);

_forwardMessageToAngularDartDevTools(message);
}

void _forwardCommandToChromeDebugger(
ExternalExtensionMessage message, Function sendResponse) {
try {
final options = message.options as SendCommandOptions;
chrome.debugger.sendCommand(
Debuggee(tabId: message.tabId),
options.method,
options.commandParams,
allowInterop(
([result]) => _respondWithChromeResult(result, sendResponse)),
);
} catch (e) {
sendResponse(ErrorResponse()..error = '$e');
}
}

void _respondWithChromeResult(Object? chromeResult, Function sendResponse) {
// No result indicates that an error occurred.
if (chromeResult == null) {
sendResponse(ErrorResponse()
..error = JSON.stringify(
chrome.runtime.lastError ?? 'Unknown error.',
));
} else {
sendResponse(chromeResult);
}
}

void _respondWithEncodedUri(int tabId, Function sendResponse) async {
final encodedUri = await fetchStorageObject<EncodedUri>(
type: StorageObject.encodedUri, tabId: tabId);
sendResponse(encodedUri ?? '');
}

void _forwardMessageToAngularDartDevTools(ExternalExtensionMessage message) {
chrome.runtime.sendMessage(
_angularDartDevToolsId,
message,
/* options */ null,
allowInterop(([result]) => _checkForErrors(result, message.name)),
);
}

void _checkForErrors(Object? chromeResult, String messageName) {
// No result indicates that an error occurred.
if (chromeResult == null) {
final errorMessage = chrome.runtime.lastError?.message ?? 'Unknown error.';
debugWarn('Error forwarding $messageName: $errorMessage');
}
}

ExternalExtensionMessage _debugEventMessage({
required String method,
required dynamic params,
required int tabId,
}) =>
ExternalExtensionMessage(
name: 'chrome.debugger.event',
tabId: tabId,
options: DebugEvent(method: method, params: params),
);

ExternalExtensionMessage _dwdsEventMessage({
required String method,
required dynamic params,
required int tabId,
}) =>
ExternalExtensionMessage(
name: method,
tabId: tabId,
options: params,
);

// This message is used for cross-extension communication between this extension
// and the AngularDart DevTools extension.
@JS()
@anonymous
class ExternalExtensionMessage {
external int get tabId;
external String get name;
external dynamic get options;
external factory ExternalExtensionMessage(
{required int tabId, required String name, required dynamic options});
}

@JS()
@anonymous
class DebugEvent {
external factory DebugEvent({String method, Object? params});
}

@JS()
@anonymous
class SendCommandOptions {
external String get method;
external Object get commandParams;
}

@JS()
@anonymous
class ErrorResponse {
external set error(String error);
}
1 change: 1 addition & 0 deletions dwds/debug_extension_mv3/web/data_serializers.dart
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ part 'data_serializers.g.dart';
DevToolsOpener,
DevToolsUrl,
DevToolsRequest,
EncodedUri,
ExtensionEvent,
ExtensionRequest,
ExtensionResponse,
Expand Down
1 change: 1 addition & 0 deletions dwds/debug_extension_mv3/web/data_serializers.g.dart

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

12 changes: 12 additions & 0 deletions dwds/debug_extension_mv3/web/data_types.dart
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,18 @@ abstract class DevToolsOpener
bool get newWindow;
}

// TODO(elliette): Standardize on uri or url here and across DWDS, instead of a
// combination of both.
abstract class EncodedUri implements Built<EncodedUri, EncodedUriBuilder> {
static Serializer<EncodedUri> get serializer => _$encodedUriSerializer;

factory EncodedUri([Function(EncodedUriBuilder) updates]) = _$EncodedUri;

EncodedUri._();

String get uri;
}

abstract class DevToolsUrl implements Built<DevToolsUrl, DevToolsUrlBuilder> {
static Serializer<DevToolsUrl> get serializer => _$devToolsUrlSerializer;

Expand Down
118 changes: 118 additions & 0 deletions dwds/debug_extension_mv3/web/data_types.g.dart

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading