Skip to content

modifying DWDS Injector to always inject client and introduce runMainAtStart flag #2629

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

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
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
3 changes: 2 additions & 1 deletion dwds/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
## 24.3.11-wip
## 24.3.11

- Changed DWDS to always inject the client and use `runMainAtStart` flag to control whether main() execution is deferred or runs immediately.
- Added WebSocket-based hot reload support: `reloadSources` in `ChromeProxyService` and `DevHandler` now handle hot reload requests and responses over WebSockets.
- Refactored the injected client to use a reusable function for handling hot reload requests and responses over WebSockets.

Expand Down
7 changes: 6 additions & 1 deletion dwds/lib/dart_web_debug_service.dart
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,12 @@ class Dwds {
required Stream<BuildResult> buildResults,
required ConnectionProvider chromeConnection,
required ToolConfiguration toolConfiguration,
// ignore: avoid-unused-parameters
@Deprecated(
'Use runMainAtStart instead. This parameter is ignored and will be removed in a future version.',
)
bool injectDebuggingSupportCode = true,
bool runMainAtStart = false,
}) async {
globalToolConfiguration = toolConfiguration;
final debugSettings = toolConfiguration.debugSettings;
Expand Down Expand Up @@ -120,7 +125,7 @@ class Dwds {

final injected = DwdsInjector(
extensionUri: extensionUri,
injectDebuggingSupportCode: injectDebuggingSupportCode,
runMainAtStart: runMainAtStart,
);

final devHandler = DevHandler(
Expand Down
10 changes: 10 additions & 0 deletions dwds/lib/src/connections/app_connection.dart
Original file line number Diff line number Diff line change
Expand Up @@ -44,4 +44,14 @@ class AppConnection {
_connection.sink.add(jsonEncode(serializers.serialize(RunRequest())));
_startedCompleter.complete();
}

/// Marks the application as started by completing the _startedCompleter.
/// This can be used when the application starts through alternative means
/// (e.g., immediate execution) rather than through the runMain() flow.
void markAsStarted() {
if (_startedCompleter.isCompleted) {
throw StateError('Application has already been marked as started.');
}
_startedCompleter.complete();
}
}
44 changes: 22 additions & 22 deletions dwds/lib/src/handlers/injector.dart
Original file line number Diff line number Diff line change
Expand Up @@ -30,25 +30,23 @@ const _clientScript = 'dwds/src/injected/client';
/// to include the injected DWDS client, enabling debugging capabilities
/// and source mapping when running in a browser environment.
///
/// The `_injectDebuggingSupportCode` flag determines whether debugging-related
/// functionality should be included:
/// - When `true`, the DWDS client is injected, enabling debugging features.
/// - When `false`, debugging support is disabled, meaning the application will
/// run without debugging.
/// The `_runMainAtStart` flag determines whether main() execution should be
/// deferred or run immediately:
/// - When `true`, main() is executed immediately when the app is loaded.
/// - When `false`, main() execution is deferred, allowing for setup or
/// debugging initialization before main() runs.
///
/// This separation allows for scenarios where debugging is not needed or
/// should be explicitly avoided.
class DwdsInjector {
final Future<String>? _extensionUri;
final _devHandlerPaths = StreamController<String>();
final _logger = Logger('DwdsInjector');
final bool _injectDebuggingSupportCode;
final bool _runMainAtStart;

DwdsInjector({
Future<String>? extensionUri,
bool injectDebuggingSupportCode = true,
}) : _extensionUri = extensionUri,
_injectDebuggingSupportCode = injectDebuggingSupportCode;
DwdsInjector({Future<String>? extensionUri, bool runMainAtStart = true})
: _extensionUri = extensionUri,
_runMainAtStart = runMainAtStart;

/// Returns the embedded dev handler paths.
///
Expand Down Expand Up @@ -110,17 +108,15 @@ class DwdsInjector {
await globalToolConfiguration.loadStrategy.trackEntrypoint(
entrypoint,
);
// If true, inject the debugging client and hoist the main function
// to enable debugging support.
if (_injectDebuggingSupportCode) {
body = await _injectClientAndHoistMain(
body,
appId,
devHandlerPath,
entrypoint,
await _extensionUri,
);
}
// Always inject the debugging client and hoist the main function.
body = await _injectClientAndHoistMain(
body,
appId,
devHandlerPath,
entrypoint,
await _extensionUri,
_runMainAtStart,
);
body += await globalToolConfiguration.loadStrategy.bootstrapFor(
entrypoint,
);
Expand Down Expand Up @@ -156,6 +152,7 @@ Future<String> _injectClientAndHoistMain(
String devHandlerPath,
String entrypointPath,
String? extensionUri,
bool runMainAtStart,
) async {
final bodyLines = body.split('\n');
final extensionIndex = bodyLines.indexWhere(
Expand All @@ -174,6 +171,7 @@ Future<String> _injectClientAndHoistMain(
devHandlerPath,
entrypointPath,
extensionUri,
runMainAtStart,
);
result += '''
// Injected by dwds for debugging support.
Expand Down Expand Up @@ -205,6 +203,7 @@ Future<String> _injectedClientSnippet(
String devHandlerPath,
String entrypointPath,
String? extensionUri,
bool runMainAtStart,
) async {
final loadStrategy = globalToolConfiguration.loadStrategy;
final buildSettings = loadStrategy.buildSettings;
Expand All @@ -223,6 +222,7 @@ Future<String> _injectedClientSnippet(
'window.\$dartEmitDebugEvents = ${debugSettings.emitDebugEvents};\n'
'window.\$isInternalBuild = ${appMetadata.isInternalBuild};\n'
'window.\$isFlutterApp = ${buildSettings.isFlutterApp};\n'
'window.\$runMainAtStart = $runMainAtStart;\n'
'${loadStrategy is DdcLibraryBundleStrategy ? 'window.\$hotReloadSourcesPath = "${loadStrategy.hotReloadSourcesUri.toString()}";\n' : ''}'
'${loadStrategy.loadClientSnippet(_clientScript)}';

Expand Down
86 changes: 20 additions & 66 deletions dwds/lib/src/injected/client.js

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion dwds/lib/src/version.dart

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

2 changes: 1 addition & 1 deletion dwds/pubspec.yaml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
name: dwds
# Every time this changes you need to run `dart run build_runner build`.
version: 24.3.11-wip
version: 24.3.11

description: >-
A service that proxies between the Chrome debug protocol and the Dart VM
Expand Down
9 changes: 9 additions & 0 deletions dwds/test/handlers/injector_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -297,6 +297,15 @@ void main() {
expect(result.body, contains('\$isFlutterApp'));
});

test('the injected client contains a global \$runMainAtStart', () async {
final result = await http.get(
Uri.parse(
'http://localhost:${server.port}/dwds/src/injected/client.js',
),
);
expect(result.body, contains('\$runMainAtStart'));
});

test('serves the injected client', () async {
final result = await http.get(
Uri.parse(
Expand Down
36 changes: 19 additions & 17 deletions dwds/web/client.dart
Original file line number Diff line number Diff line change
Expand Up @@ -240,23 +240,18 @@ Future<void>? main() {
});
}

if (_isChromium) {
_trySendEvent(
client.sink,
jsonEncode(
serializers.serialize(
ConnectRequest(
(b) =>
b
..appId = dartAppId
..instanceId = dartAppInstanceId
..entrypointPath = dartEntrypointPath,
),
),
),
);
} else {
// If not Chromium we just invoke main, devtools aren't supported.
_sendConnectRequest(
client.sink,
ConnectRequest(
(b) =>
b
..appId = dartAppId
..instanceId = dartAppInstanceId
..entrypointPath = dartEntrypointPath,
),
);

if (runMainAtStart) {
runMain();
}
_launchCommunicationWithDebugExtension();
Expand Down Expand Up @@ -292,6 +287,10 @@ void _trySendEvent<T>(StreamSink<T> sink, T serialized) {
}
}

void _sendConnectRequest(StreamSink clientSink, ConnectRequest request) {
_trySendEvent(clientSink, jsonEncode(serializers.serialize(request)));
}

/// Returns [url] modified if necessary so that, if the current page is served
/// over `https`, then the URL is converted to `https`.
String _fixProtocol(String url) {
Expand Down Expand Up @@ -478,6 +477,9 @@ external String get reloadConfiguration;
@JS(r'$dartEntrypointPath')
external String get dartEntrypointPath;

@JS(r'$runMainAtStart')
external bool get runMainAtStart;

@JS(r'$dwdsEnableDevToolsLaunch')
external bool get dwdsEnableDevToolsLaunch;

Expand Down
Loading