diff --git a/_analysis_config/pubspec.yaml b/_analysis_config/pubspec.yaml index 9325812fb..984a34582 100644 --- a/_analysis_config/pubspec.yaml +++ b/_analysis_config/pubspec.yaml @@ -4,7 +4,7 @@ description: The shared analysis configuration for the webdev packages. publish_to: none environment: - sdk: ^3.1.0 + sdk: ^3.8.0 dependencies: lints: ^5.0.0 diff --git a/dwds/CHANGELOG.md b/dwds/CHANGELOG.md index abff4fdf2..6ef9f1c6f 100644 --- a/dwds/CHANGELOG.md +++ b/dwds/CHANGELOG.md @@ -1,5 +1,6 @@ ## 24.4.2-wip +- Bump minimum SDK version to 3.8.0 - Update a call to the `package:shelf_web_socket` `webSocketHandler()` function. ## 24.4.1 diff --git a/dwds/debug_extension/pubspec.yaml b/dwds/debug_extension/pubspec.yaml index b4c938a53..83d305ad5 100644 --- a/dwds/debug_extension/pubspec.yaml +++ b/dwds/debug_extension/pubspec.yaml @@ -5,7 +5,7 @@ description: >- A Chrome extension for Dart debugging. environment: - sdk: ^3.5.0 + sdk: ^3.8.0 dependencies: built_value: ^8.9.0 diff --git a/dwds/debug_extension/tool/build_extension.dart b/dwds/debug_extension/tool/build_extension.dart index 418c24567..f5c1d7a01 100644 --- a/dwds/debug_extension/tool/build_extension.dart +++ b/dwds/debug_extension/tool/build_extension.dart @@ -20,8 +20,8 @@ import 'package:path/path.dart' as p; const _prodFlag = 'prod'; void main(List arguments) async { - final parser = - ArgParser()..addFlag(_prodFlag, negatable: true, defaultsTo: false); + final parser = ArgParser() + ..addFlag(_prodFlag, negatable: true, defaultsTo: false); final argResults = parser.parse(arguments); exitCode = await run(isProd: argResults[_prodFlag] as bool); diff --git a/dwds/debug_extension/tool/update_dev_files.dart b/dwds/debug_extension/tool/update_dev_files.dart index 24c4bdfad..358dee745 100644 --- a/dwds/debug_extension/tool/update_dev_files.dart +++ b/dwds/debug_extension/tool/update_dev_files.dart @@ -12,10 +12,9 @@ void main() async { Future _updateManifestJson() async { final manifestJson = File('compiled/manifest.json'); final extensionKeyTxt = File('extension_key.txt'); - final extensionKey = - await extensionKeyTxt.exists() - ? await extensionKeyTxt.readAsString() - : null; + final extensionKey = await extensionKeyTxt.exists() + ? await extensionKeyTxt.readAsString() + : null; return _transformDevFile(manifestJson, (line) { if (_matchesKey(line: line, key: 'name')) { return [ diff --git a/dwds/debug_extension/web/background.dart b/dwds/debug_extension/web/background.dart index e112b16be..22dc2a9d7 100644 --- a/dwds/debug_extension/web/background.dart +++ b/dwds/debug_extension/web/background.dart @@ -217,20 +217,19 @@ bool _isInternalNavigation(NavigationInfo navigationInfo) { DebugInfo _addTabInfo(DebugInfo debugInfo, {required Tab tab}) { return DebugInfo( - (b) => - b - ..appEntrypointPath = debugInfo.appEntrypointPath - ..appId = debugInfo.appId - ..appInstanceId = debugInfo.appInstanceId - ..appOrigin = debugInfo.appOrigin - ..appUrl = debugInfo.appUrl - ..authUrl = debugInfo.authUrl - ..extensionUrl = debugInfo.extensionUrl - ..isInternalBuild = debugInfo.isInternalBuild - ..isFlutterApp = debugInfo.isFlutterApp - ..workspaceName = debugInfo.workspaceName - ..tabUrl = tab.url - ..tabId = tab.id, + (b) => b + ..appEntrypointPath = debugInfo.appEntrypointPath + ..appId = debugInfo.appId + ..appInstanceId = debugInfo.appInstanceId + ..appOrigin = debugInfo.appOrigin + ..appUrl = debugInfo.appUrl + ..authUrl = debugInfo.authUrl + ..extensionUrl = debugInfo.extensionUrl + ..isInternalBuild = debugInfo.isInternalBuild + ..isFlutterApp = debugInfo.isFlutterApp + ..workspaceName = debugInfo.workspaceName + ..tabUrl = tab.url + ..tabId = tab.id, ); } @@ -280,8 +279,9 @@ void _setWarningIcon(int tabId) { } void _setDefaultIcon(int tabId) { - final iconPath = - isDevMode ? 'static_assets/dart_dev.png' : 'static_assets/dart_grey.png'; + final iconPath = isDevMode + ? 'static_assets/dart_dev.png' + : 'static_assets/dart_grey.png'; setExtensionIcon(IconInfo(path: iconPath)); setExtensionPopup(PopupDetails(popup: '', tabId: tabId)); } diff --git a/dwds/debug_extension/web/cross_extension_communication.dart b/dwds/debug_extension/web/cross_extension_communication.dart index da8677917..8b7261e0e 100644 --- a/dwds/debug_extension/web/cross_extension_communication.dart +++ b/dwds/debug_extension/web/cross_extension_communication.dart @@ -58,10 +58,9 @@ void maybeForwardMessageToAngularDartDevTools({ }) { if (!_eventsForAngularDartDevTools.contains(method)) return; - final message = - method.startsWith('dwds') - ? _dwdsEventMessage(method: method, params: params, tabId: tabId) - : _debugEventMessage(method: method, params: params, tabId: tabId); + final message = method.startsWith('dwds') + ? _dwdsEventMessage(method: method, params: params, tabId: tabId) + : _debugEventMessage(method: method, params: params, tabId: tabId); _forwardMessageToAngularDartDevTools(message); } diff --git a/dwds/debug_extension/web/data_types.g.dart b/dwds/debug_extension/web/data_types.g.dart index 831d48344..4a2c569e1 100644 --- a/dwds/debug_extension/web/data_types.g.dart +++ b/dwds/debug_extension/web/data_types.g.dart @@ -411,8 +411,9 @@ class _$DevToolsOpener extends DevToolsOpener { @override String toString() { - return (newBuiltValueToStringHelper(r'DevToolsOpener') - ..add('newWindow', newWindow)).toString(); + return (newBuiltValueToStringHelper( + r'DevToolsOpener', + )..add('newWindow', newWindow)).toString(); } } diff --git a/dwds/debug_extension/web/debug_info.dart b/dwds/debug_extension/web/debug_info.dart index 611ac966a..24d66fd5c 100644 --- a/dwds/debug_extension/web/debug_info.dart +++ b/dwds/debug_extension/web/debug_info.dart @@ -30,17 +30,15 @@ String _readDartDebugInfo() { return jsonEncode( serializers.serialize( DebugInfo( - (b) => - b - ..appEntrypointPath = - windowContext['\$dartEntrypointPath'] as String? - ..appId = windowContext['\$dartAppId'] as String? - ..appInstanceId = windowContext['\$dartAppInstanceId'] as String? - ..appOrigin = window.location.origin - ..appUrl = window.location.href - ..extensionUrl = windowContext['\$dartExtensionUri'] as String? - ..isInternalBuild = windowContext['\$isInternalBuild'] as bool? - ..isFlutterApp = windowContext['\$isFlutterApp'] as bool?, + (b) => b + ..appEntrypointPath = windowContext['\$dartEntrypointPath'] as String? + ..appId = windowContext['\$dartAppId'] as String? + ..appInstanceId = windowContext['\$dartAppInstanceId'] as String? + ..appOrigin = window.location.origin + ..appUrl = window.location.href + ..extensionUrl = windowContext['\$dartExtensionUri'] as String? + ..isInternalBuild = windowContext['\$isInternalBuild'] as bool? + ..isFlutterApp = windowContext['\$isFlutterApp'] as bool?, ), ), ); diff --git a/dwds/debug_extension/web/debug_session.dart b/dwds/debug_extension/web/debug_session.dart index 717d08019..3daf21016 100644 --- a/dwds/debug_extension/web/debug_session.dart +++ b/dwds/debug_extension/web/debug_session.dart @@ -351,12 +351,9 @@ Future _connectToDwds({ } final uri = Uri.parse(extensionUrl); // Start the client connection with DWDS: - final client = - uri.isScheme('ws') || uri.isScheme('wss') - ? WebSocketClient(WebSocketChannel.connect(uri)) - : SseSocketClient( - SseClient(uri.toString(), debugKey: 'DebugExtension'), - ); + final client = uri.isScheme('ws') || uri.isScheme('wss') + ? WebSocketClient(WebSocketChannel.connect(uri)) + : SseSocketClient(SseClient(uri.toString(), debugKey: 'DebugExtension')); final trigger = _tabIdToTrigger[dartAppTabId]; debugLog('Connecting to DWDS...', verbose: true); final debugSession = _DebugSession( @@ -386,14 +383,13 @@ Future _connectToDwds({ final tabUrl = await _getTabUrl(dartAppTabId); debugSession.sendEvent( DevToolsRequest( - (b) => - b - ..appId = debugInfo.appId - ..instanceId = debugInfo.appInstanceId - ..contextId = dartAppContextId - ..tabUrl = tabUrl - ..uriOnly = true - ..client = trigger?.clientName ?? 'unknown', + (b) => b + ..appId = debugInfo.appId + ..instanceId = debugInfo.appInstanceId + ..contextId = dartAppContextId + ..tabUrl = tabUrl + ..uriOnly = true + ..client = trigger?.clientName ?? 'unknown', ), ); return true; @@ -445,10 +441,9 @@ void _forwardDwdsEventToChromeDebugger( ) { try { final messageParams = message.commandParams; - final params = - messageParams == null - ? {} - : BuiltMap(json.decode(messageParams)).toMap(); + final params = messageParams == null + ? {} + : BuiltMap(json.decode(messageParams)).toMap(); chrome.debugger.sendCommand( Debuggee(tabId: tabId), @@ -461,11 +456,10 @@ void _forwardDwdsEventToChromeDebugger( jsonEncode( serializers.serialize( ExtensionResponse( - (b) => - b - ..id = message.id - ..success = false - ..result = JSON.stringify(chrome.runtime.lastError), + (b) => b + ..id = message.id + ..success = false + ..result = JSON.stringify(chrome.runtime.lastError), ), ), ), @@ -475,11 +469,10 @@ void _forwardDwdsEventToChromeDebugger( jsonEncode( serializers.serialize( ExtensionResponse( - (b) => - b - ..id = message.id - ..success = true - ..result = JSON.stringify(e), + (b) => b + ..id = message.id + ..success = true + ..result = JSON.stringify(e), ), ), ), @@ -612,10 +605,9 @@ Future _sendConnectFailureMessage( final json = jsonEncode( serializers.serialize( ConnectFailure( - (b) => - b - ..tabId = dartAppTabId - ..reason = reason.name, + (b) => b + ..tabId = dartAppTabId + ..reason = reason.name, ), ), ); @@ -634,11 +626,10 @@ Future _sendStopDebuggingMessage( final json = jsonEncode( serializers.serialize( DebugStateChange( - (b) => - b - ..tabId = dartAppTabId - ..reason = reason.name - ..newState = DebugStateChange.stopDebugging, + (b) => b + ..tabId = dartAppTabId + ..reason = reason.name + ..newState = DebugStateChange.stopDebugging, ), ), ); @@ -747,10 +738,9 @@ DebuggerLocation? _debuggerLocation(int dartAppTabId) { /// Construct an [ExtensionEvent] from [method] and [params]. ExtensionEvent _extensionEventFor(String method, dynamic params) { return ExtensionEvent( - (b) => - b - ..params = jsonEncode(json.decode(JSON.stringify(params))) - ..method = jsonEncode(method), + (b) => b + ..params = jsonEncode(json.decode(JSON.stringify(params))) + ..method = jsonEncode(method), ); } diff --git a/dwds/debug_extension/web/messaging.dart b/dwds/debug_extension/web/messaging.dart index dad8d4545..8d84ca924 100644 --- a/dwds/debug_extension/web/messaging.dart +++ b/dwds/debug_extension/web/messaging.dart @@ -154,8 +154,12 @@ Future _sendMessage({ required Script recipient, int? tabId, }) { - final message = - Message(to: recipient, from: sender, type: type, body: body).toJSON(); + final message = Message( + to: recipient, + from: sender, + type: type, + body: body, + ).toJSON(); final completer = Completer(); void responseHandler([dynamic _]) { final error = chrome.runtime.lastError; diff --git a/dwds/debug_extension/web/panel.dart b/dwds/debug_extension/web/panel.dart index c78600a72..825c8fa75 100644 --- a/dwds/debug_extension/web/panel.dart +++ b/dwds/debug_extension/web/panel.dart @@ -276,10 +276,9 @@ Future _launchDebugConnection(Event _) async { final json = jsonEncode( serializers.serialize( DebugStateChange( - (b) => - b - ..tabId = _tabId - ..newState = DebugStateChange.startDebugging, + (b) => b + ..tabId = _tabId + ..newState = DebugStateChange.startDebugging, ), ), ); diff --git a/dwds/debug_extension/web/popup.dart b/dwds/debug_extension/web/popup.dart index 7432ca783..ab62c09fc 100644 --- a/dwds/debug_extension/web/popup.dart +++ b/dwds/debug_extension/web/popup.dart @@ -109,10 +109,9 @@ Future _insertAppId() async { Future _openIssueTracker(Event _) async { final debugInfo = await _fetchDebugInfo(await _tabId); final isInternalBuild = debugInfo?.isInternalBuild ?? false; - final issueTrackerLink = - isInternalBuild - ? 'http://b/issues/new?component=775375&template=1791321' - : 'https://github.com/dart-lang/webdev/issues/new?labels=dart-debug-extension&projects=&template=dart_debug_extension.md'; + final issueTrackerLink = isInternalBuild + ? 'http://b/issues/new?component=775375&template=1791321' + : 'https://github.com/dart-lang/webdev/issues/new?labels=dart-debug-extension&projects=&template=dart_debug_extension.md'; await createTab(issueTrackerLink); } @@ -121,10 +120,9 @@ Future _launchDevTools(Event _) async { final json = jsonEncode( serializers.serialize( DebugStateChange( - (b) => - b - ..tabId = tabId - ..newState = DebugStateChange.startDebugging, + (b) => b + ..tabId = tabId + ..newState = DebugStateChange.startDebugging, ), ), ); diff --git a/dwds/debug_extension/web/storage.dart b/dwds/debug_extension/web/storage.dart index 0b79b3655..3413f0302 100644 --- a/dwds/debug_extension/web/storage.dart +++ b/dwds/debug_extension/web/storage.dart @@ -47,8 +47,9 @@ Future setStorageObject({ void Function()? callback, }) { final storageKey = _createStorageKey(type, tabId); - final json = - value is String ? value : jsonEncode(serializers.serialize(value)); + final json = value is String + ? value + : jsonEncode(serializers.serialize(value)); final storageObj = {storageKey: json}; final completer = Completer(); final storageArea = _getStorageArea(type.persistence); diff --git a/dwds/debug_extension/web/utils.dart b/dwds/debug_extension/web/utils.dart index d6be21a80..ca842f77c 100644 --- a/dwds/debug_extension/web/utils.dart +++ b/dwds/debug_extension/web/utils.dart @@ -74,8 +74,9 @@ void displayNotification( NotificationOptions( title: '${isError ? '[Error] ' : ''}Dart Debug Extension', message: message, - iconUrl: - isError ? 'static_assets/dart_warning.png' : 'static_assets/dart.png', + iconUrl: isError + ? 'static_assets/dart_warning.png' + : 'static_assets/dart.png', type: 'basic', ), callback, diff --git a/dwds/lib/dart_web_debug_service.dart b/dwds/lib/dart_web_debug_service.dart index 587e8af43..0f7b3d6e3 100644 --- a/dwds/lib/dart_web_debug_service.dart +++ b/dwds/lib/dart_web_debug_service.dart @@ -88,19 +88,18 @@ class Dwds { Future? extensionUri; ExtensionBackend? extensionBackend; if (debugSettings.enableDebugExtension) { - final handler = - debugSettings.useSseForDebugBackend - ? SseSocketHandler( - SseHandler( - Uri.parse('/\$debug'), - // Proxy servers may actively kill long standing connections. - // Allow for clients to reconnect in a short window. Making the - // window too long may cause issues if the user closes a debug - // session and initiates a new one during the keepAlive window. - keepAlive: const Duration(seconds: 5), - ), - ) - : WebSocketSocketHandler(); + final handler = debugSettings.useSseForDebugBackend + ? SseSocketHandler( + SseHandler( + Uri.parse('/\$debug'), + // Proxy servers may actively kill long standing connections. + // Allow for clients to reconnect in a short window. Making the + // window too long may cause issues if the user closes a debug + // session and initiates a new one during the keepAlive window. + keepAlive: const Duration(seconds: 5), + ), + ) + : WebSocketSocketHandler(); extensionBackend = await ExtensionBackend.start( handler, diff --git a/dwds/lib/data/build_result.g.dart b/dwds/lib/data/build_result.g.dart index 1b7087249..e911d1592 100644 --- a/dwds/lib/data/build_result.g.dart +++ b/dwds/lib/data/build_result.g.dart @@ -137,8 +137,9 @@ class _$BuildResult extends BuildResult { @override String toString() { - return (newBuiltValueToStringHelper(r'BuildResult') - ..add('status', status)).toString(); + return (newBuiltValueToStringHelper( + r'BuildResult', + )..add('status', status)).toString(); } } diff --git a/dwds/lib/data/debug_event.g.dart b/dwds/lib/data/debug_event.g.dart index a4a316be1..9555078c2 100644 --- a/dwds/lib/data/debug_event.g.dart +++ b/dwds/lib/data/debug_event.g.dart @@ -316,8 +316,9 @@ class _$BatchedDebugEvents extends BatchedDebugEvents { @override String toString() { - return (newBuiltValueToStringHelper(r'BatchedDebugEvents') - ..add('events', events)).toString(); + return (newBuiltValueToStringHelper( + r'BatchedDebugEvents', + )..add('events', events)).toString(); } } diff --git a/dwds/lib/data/extension_request.g.dart b/dwds/lib/data/extension_request.g.dart index 98a8a8da2..16b464c5e 100644 --- a/dwds/lib/data/extension_request.g.dart +++ b/dwds/lib/data/extension_request.g.dart @@ -723,8 +723,9 @@ class _$BatchedEvents extends BatchedEvents { @override String toString() { - return (newBuiltValueToStringHelper(r'BatchedEvents') - ..add('events', events)).toString(); + return (newBuiltValueToStringHelper( + r'BatchedEvents', + )..add('events', events)).toString(); } } diff --git a/dwds/lib/data/hot_reload_request.g.dart b/dwds/lib/data/hot_reload_request.g.dart index d45012443..76ab45b5b 100644 --- a/dwds/lib/data/hot_reload_request.g.dart +++ b/dwds/lib/data/hot_reload_request.g.dart @@ -95,8 +95,9 @@ class _$HotReloadRequest extends HotReloadRequest { @override String toString() { - return (newBuiltValueToStringHelper(r'HotReloadRequest') - ..add('id', id)).toString(); + return (newBuiltValueToStringHelper( + r'HotReloadRequest', + )..add('id', id)).toString(); } } diff --git a/dwds/lib/data/service_extension_request.dart b/dwds/lib/data/service_extension_request.dart index 7539a9b3b..53ad2446f 100644 --- a/dwds/lib/data/service_extension_request.dart +++ b/dwds/lib/data/service_extension_request.dart @@ -15,10 +15,9 @@ abstract class ServiceExtensionRequest get argsJson; // Store args as JSON string for built_value compatibility // Helper method to get args as Map - Map get args => - argsJson.isEmpty - ? {} - : json.decode(argsJson) as Map; + Map get args => argsJson.isEmpty + ? {} + : json.decode(argsJson) as Map; ServiceExtensionRequest._(); factory ServiceExtensionRequest([ @@ -31,11 +30,10 @@ abstract class ServiceExtensionRequest required String method, required Map args, }) => ServiceExtensionRequest( - (b) => - b - ..id = id - ..method = method - ..argsJson = json.encode(args), + (b) => b + ..id = id + ..method = method + ..argsJson = json.encode(args), ); static Serializer get serializer => diff --git a/dwds/lib/data/service_extension_response.dart b/dwds/lib/data/service_extension_response.dart index 854526951..8d833894a 100644 --- a/dwds/lib/data/service_extension_response.dart +++ b/dwds/lib/data/service_extension_response.dart @@ -18,10 +18,9 @@ abstract class ServiceExtensionResponse String? get errorMessage; // Helper method to get result as Map - Map? get result => - resultJson == null || resultJson!.isEmpty - ? null - : json.decode(resultJson!) as Map; + Map? get result => resultJson == null || resultJson!.isEmpty + ? null + : json.decode(resultJson!) as Map; ServiceExtensionResponse._(); factory ServiceExtensionResponse([ @@ -36,13 +35,12 @@ abstract class ServiceExtensionResponse int? errorCode, String? errorMessage, }) => ServiceExtensionResponse( - (b) => - b - ..id = id - ..success = success - ..resultJson = result != null ? json.encode(result) : null - ..errorCode = errorCode - ..errorMessage = errorMessage, + (b) => b + ..id = id + ..success = success + ..resultJson = result != null ? json.encode(result) : null + ..errorCode = errorCode + ..errorMessage = errorMessage, ); static Serializer get serializer => diff --git a/dwds/lib/src/connections/debug_connection.dart b/dwds/lib/src/connections/debug_connection.dart index 06efd932c..c9d805d7b 100644 --- a/dwds/lib/src/connections/debug_connection.dart +++ b/dwds/lib/src/connections/debug_connection.dart @@ -41,15 +41,14 @@ class DebugConnection { /// A client of the Dart VM Service with DWDS specific extensions. VmService get vmService => _appDebugServices.dwdsVmClient.client; - Future close() => - _closed ??= () async { - final proxyService = _appDebugServices.proxyService; - if (proxyService is ChromeProxyService) { - await proxyService.remoteDebugger.close(); - } - await _appDebugServices.close(); - _onDoneCompleter.complete(); - }(); + Future close() => _closed ??= () async { + final proxyService = _appDebugServices.proxyService; + if (proxyService is ChromeProxyService) { + await proxyService.remoteDebugger.close(); + } + await _appDebugServices.close(); + _onDoneCompleter.complete(); + }(); Future get onDone => _onDoneCompleter.future; } diff --git a/dwds/lib/src/debugging/classes.dart b/dwds/lib/src/debugging/classes.dart index b5b814661..72d2f467d 100644 --- a/dwds/lib/src/debugging/classes.dart +++ b/dwds/lib/src/debugging/classes.dart @@ -141,10 +141,9 @@ class ClassHelper extends Domain { final superClassLibraryId = classDescriptor['superClassLibraryId']; final superClassName = classDescriptor['superClassName']; - final superClassRef = - superClassName == null - ? null - : classRefFor(superClassLibraryId, superClassName); + final superClassRef = superClassName == null + ? null + : classRefFor(superClassLibraryId, superClassName); // TODO: Implement the rest of these // https://github.com/dart-lang/webdev/issues/176. diff --git a/dwds/lib/src/debugging/dart_runtime_debugger.dart b/dwds/lib/src/debugging/dart_runtime_debugger.dart index 1f0f4582b..a3e24bb7e 100644 --- a/dwds/lib/src/debugging/dart_runtime_debugger.dart +++ b/dwds/lib/src/debugging/dart_runtime_debugger.dart @@ -198,7 +198,8 @@ class DartRuntimeDebugger { /// Generates a JS expression for calling a library method. String callLibraryMethodJsExpression(String libraryUri, String methodName) { - final findLibraryExpression = ''' + final findLibraryExpression = + ''' (function() { const sdk = ${_loadStrategy.loadModuleSnippet}('dart_sdk'); const dart = sdk.dart; diff --git a/dwds/lib/src/debugging/debugger.dart b/dwds/lib/src/debugging/debugger.dart index e68e5d315..ba2902a5f 100644 --- a/dwds/lib/src/debugging/debugger.dart +++ b/dwds/lib/src/debugging/debugger.dart @@ -82,10 +82,9 @@ class Debugger extends Domain { // DevTools is showing an overlay. Both cannot be shown at the same time: // bool _pausedOverlayVisible = false; - String get pauseState => - _pauseModePauseStates.entries - .firstWhere((entry) => entry.value == _pauseState) - .key; + String get pauseState => _pauseModePauseStates.entries + .firstWhere((entry) => entry.value == _pauseState) + .key; /// The JS frames at the current paused location. /// @@ -523,17 +522,15 @@ class Debugger extends Domain { final timestamp = DateTime.now().millisecondsSinceEpoch; final jsBreakpointIds = e.hitBreakpoints ?? []; if (jsBreakpointIds.isNotEmpty) { - final breakpointIds = - jsBreakpointIds - .map((id) => _breakpoints._dartIdByJsId[id]) - // In case the breakpoint was set in Chrome DevTools outside of - // package:dwds. - .where((entry) => entry != null) - .toSet(); - final pauseBreakpoints = - isolate.breakpoints - ?.where((bp) => breakpointIds.contains(bp.id)) - .toList(); + final breakpointIds = jsBreakpointIds + .map((id) => _breakpoints._dartIdByJsId[id]) + // In case the breakpoint was set in Chrome DevTools outside of + // package:dwds. + .where((entry) => entry != null) + .toSet(); + final pauseBreakpoints = isolate.breakpoints + ?.where((bp) => breakpointIds.contains(bp.id)) + .toList(); event = Event( kind: EventKind.kPauseBreakpoint, timestamp: timestamp, diff --git a/dwds/lib/src/debugging/inspector.dart b/dwds/lib/src/debugging/inspector.dart index 25cf1b61a..3b6d6f029 100644 --- a/dwds/lib/src/debugging/inspector.dart +++ b/dwds/lib/src/debugging/inspector.dart @@ -305,8 +305,10 @@ class AppInspector implements AppInspectorInterface { String selector, [ List arguments = const [], ]) async { - final remoteArguments = - arguments.cast().map(remoteObjectFor).toList(); + final remoteArguments = arguments + .cast() + .map(remoteObjectFor) + .toList(); // We special case the Dart library, where invokeMethod won't work because // it's not really a Dart object. if (isLibraryId(targetId)) { @@ -333,15 +335,15 @@ class AppInspector implements AppInspectorInterface { } return globalToolConfiguration.loadStrategy is DdcLibraryBundleStrategy ? _evaluateLibraryMethodWithDdcLibraryBundle( - libraryUri, - selector, - arguments, - ) + libraryUri, + selector, + arguments, + ) : _evaluateInLibrary( - libraryUri, - 'function () { return this.$selector.apply(this, arguments); }', - arguments, - ); + libraryUri, + 'function () { return this.$selector.apply(this, arguments); }', + arguments, + ); } /// Evaluate [expression] by calling Chrome's Runtime.evaluate. @@ -677,14 +679,15 @@ class AppInspector implements AppInspectorInterface { offset: offset, length: length, ); - final args = - [offset, rangeCount].map(dartIdFor).map(remoteObjectFor).toList(); + final args = [ + offset, + rangeCount, + ].map(dartIdFor).map(remoteObjectFor).toList(); // If this is a List, just call sublist. If it's a Map, get the entries, but // avoid doing a toList on a large map using skip/take to get the section we // want. To make those alternatives easier in JS, pass both count and end. - final expression = - globalToolConfiguration.loadStrategy.dartRuntimeDebugger - .getSubRangeJsExpression(); + final expression = globalToolConfiguration.loadStrategy.dartRuntimeDebugger + .getSubRangeJsExpression(); return await jsCallFunctionOn(receiver, expression, args); } @@ -736,10 +739,9 @@ class AppInspector implements AppInspectorInterface { ModifiedModuleReport? modifiedModuleReport, }) { return _scriptCacheMemoizer.runOnce(() async { - final scripts = - await globalToolConfiguration.loadStrategy - .metadataProviderFor(appConnection.request.entrypointPath) - .scripts; + final scripts = await globalToolConfiguration.loadStrategy + .metadataProviderFor(appConnection.request.entrypointPath) + .scripts; if (modifiedModuleReport != null) { // Invalidate any script caches that were computed for the now invalid // libraries. They will get repopulated below. @@ -819,9 +821,8 @@ class AppInspector implements AppInspectorInterface { /// /// Updates [Isolate.extensionRPCs] to this set. Future> getExtensionRpcs() async { - final expression = - globalToolConfiguration.loadStrategy.dartRuntimeDebugger - .getDartDeveloperExtensionNamesJsExpression(); + final expression = globalToolConfiguration.loadStrategy.dartRuntimeDebugger + .getDartDeveloperExtensionNamesJsExpression(); final extensionRpcs = {}; final params = { 'expression': expression, diff --git a/dwds/lib/src/debugging/instance.dart b/dwds/lib/src/debugging/instance.dart index de55b96ce..4c03dcd52 100644 --- a/dwds/lib/src/debugging/instance.dart +++ b/dwds/lib/src/debugging/instance.dart @@ -269,8 +269,9 @@ class InstanceHelper extends Domain { objectId, offset: offset, count: count, - length: - metaData.kind != InstanceKind.kPlainInstance ? metaData.length : null, + length: metaData.kind != InstanceKind.kPlainInstance + ? metaData.length + : null, ); final dartProperties = await _dartFieldsFor(properties, remoteObject); @@ -309,9 +310,8 @@ class InstanceHelper extends Domain { // We do this in in awkward way because we want the keys and values, but we // can't return things by value or some Dart objects will come back as // values that we need to be RemoteObject, e.g. a List of int. - final expression = - globalToolConfiguration.loadStrategy.dartRuntimeDebugger - .getMapElementsJsExpression(); + final expression = globalToolConfiguration.loadStrategy.dartRuntimeDebugger + .getMapElementsJsExpression(); final keysAndValues = await inspector.jsCallFunctionOn(map, expression, []); final keys = await inspector.loadField(keysAndValues, 'keys'); @@ -509,10 +509,12 @@ class InstanceHelper extends Domain { // Collect named fields in the requested range. // Account for already collected positional fields. - final namedRangeOffset = - offset == null ? null : _remainingCount(positionalCount, offset); - final namedRangeCount = - count == null ? null : _remainingCount(positionalRangeCount, count); + final namedRangeOffset = offset == null + ? null + : _remainingCount(positionalCount, offset); + final namedRangeCount = count == null + ? null + : _remainingCount(positionalRangeCount, count); final namedInstance = await instanceFor( namedObject, offset: namedRangeOffset, @@ -539,9 +541,8 @@ class InstanceHelper extends Domain { // We do this in in awkward way because we want the keys and values, but we // can't return things by value or some Dart objects will come back as // values that we need to be RemoteObject, e.g. a List of int. - final expression = - globalToolConfiguration.loadStrategy.dartRuntimeDebugger - .getRecordFieldsJsExpression(); + final expression = globalToolConfiguration.loadStrategy.dartRuntimeDebugger + .getRecordFieldsJsExpression(); final result = await inspector.jsCallFunctionOn(record, expression, []); final fieldNameElements = await _recordShapeFields( @@ -678,9 +679,8 @@ class InstanceHelper extends Domain { // We do this in in awkward way because we want the names and types, but we // can't return things by value or some Dart objects will come back as // values that we need to be RemoteObject, e.g. a List of int. - final expression = - globalToolConfiguration.loadStrategy.dartRuntimeDebugger - .getRecordTypeFieldsJsExpression(); + final expression = globalToolConfiguration.loadStrategy.dartRuntimeDebugger + .getRecordTypeFieldsJsExpression(); final result = await inspector.jsCallFunctionOn(record, expression, []); final fieldNameElements = await _recordShapeFields( @@ -709,9 +709,8 @@ class InstanceHelper extends Domain { final length = metaData.length; final objectId = remoteObject.objectId; if (objectId == null) return null; - final expression = - globalToolConfiguration.loadStrategy.dartRuntimeDebugger - .getSetElementsJsExpression(); + final expression = globalToolConfiguration.loadStrategy.dartRuntimeDebugger + .getSetElementsJsExpression(); final result = await inspector.jsCallFunctionOn( remoteObject, @@ -814,9 +813,10 @@ class InstanceHelper extends Domain { // // For maps and lists it's more complicated. Treat the actual SDK versions // of these as special. - final fieldNameExpression = - globalToolConfiguration.loadStrategy.dartRuntimeDebugger - .getObjectFieldNamesJsExpression(); + final fieldNameExpression = globalToolConfiguration + .loadStrategy + .dartRuntimeDebugger + .getObjectFieldNamesJsExpression(); final result = await inspector.jsCallFunctionOn( remoteObject, fieldNameExpression, @@ -834,10 +834,9 @@ class InstanceHelper extends Domain { /// be something returned by value from Chrome, e.g. number, boolean, or /// String. Future instanceRefFor(Object value) { - final remote = - value is RemoteObject - ? value - : RemoteObject({'value': value, 'type': _chromeType(value)}); + final remote = value is RemoteObject + ? value + : RemoteObject({'value': value, 'type': _chromeType(value)}); return _instanceRefForRemote(remote); } diff --git a/dwds/lib/src/debugging/libraries.dart b/dwds/lib/src/debugging/libraries.dart index 1dc07a4c8..4bb07623c 100644 --- a/dwds/lib/src/debugging/libraries.dart +++ b/dwds/lib/src/debugging/libraries.dart @@ -84,10 +84,9 @@ class LibraryHelper extends Domain { /// using [initialize]. Future> get libraryRefs async { if (_libraryRefsById.isNotEmpty) return _libraryRefsById.values.toList(); - final libraries = - await globalToolConfiguration.loadStrategy - .metadataProviderFor(inspector.appConnection.request.entrypointPath) - .libraries; + final libraries = await globalToolConfiguration.loadStrategy + .metadataProviderFor(inspector.appConnection.request.entrypointPath) + .libraries; for (final library in libraries) { _libraryRefsById[library] = _createLibraryRef(library); } diff --git a/dwds/lib/src/debugging/metadata/class.dart b/dwds/lib/src/debugging/metadata/class.dart index 22ee5fc29..d6c0bd15e 100644 --- a/dwds/lib/src/debugging/metadata/class.dart +++ b/dwds/lib/src/debugging/metadata/class.dart @@ -149,9 +149,10 @@ class ClassMetaDataHelper { /// Returns null if the [remoteObject] is not a Dart class. Future metaDataFor(RemoteObject remoteObject) async { try { - final evalExpression = - globalToolConfiguration.loadStrategy.dartRuntimeDebugger - .getObjectMetadataJsExpression(); + final evalExpression = globalToolConfiguration + .loadStrategy + .dartRuntimeDebugger + .getObjectMetadataJsExpression(); final result = await _inspector.jsCallFunctionOn( remoteObject, diff --git a/dwds/lib/src/debugging/metadata/function.dart b/dwds/lib/src/debugging/metadata/function.dart index 2e6488a5d..62cdf9176 100644 --- a/dwds/lib/src/debugging/metadata/function.dart +++ b/dwds/lib/src/debugging/metadata/function.dart @@ -17,9 +17,10 @@ class FunctionMetaData { RemoteDebugger remoteDebugger, RemoteObject remoteObject, ) async { - final evalExpression = - globalToolConfiguration.loadStrategy.dartRuntimeDebugger - .getFunctionMetadataJsExpression(); + final evalExpression = globalToolConfiguration + .loadStrategy + .dartRuntimeDebugger + .getFunctionMetadataJsExpression(); final response = await remoteDebugger.sendCommand( 'Runtime.callFunctionOn', diff --git a/dwds/lib/src/debugging/metadata/provider.dart b/dwds/lib/src/debugging/metadata/provider.dart index 86fb5e730..98ef03251 100644 --- a/dwds/lib/src/debugging/metadata/provider.dart +++ b/dwds/lib/src/debugging/metadata/provider.dart @@ -261,10 +261,9 @@ class MetadataProvider { } // The libraries that are removed from the program are those that we // invalidated but were never added again. - final deletedLibraries = - invalidatedLibraries - .where((library) => !_libraries.contains(library)) - .toSet(); + final deletedLibraries = invalidatedLibraries + .where((library) => !_libraries.contains(library)) + .toSet(); return ModifiedModuleReport( deletedModules: deletedModules, deletedLibraries: deletedLibraries, diff --git a/dwds/lib/src/debugging/modules.dart b/dwds/lib/src/debugging/modules.dart index a57bfb5b2..b6b6b92a3 100644 --- a/dwds/lib/src/debugging/modules.dart +++ b/dwds/lib/src/debugging/modules.dart @@ -101,10 +101,9 @@ class Modules { return chromePathToRuntimeScriptId[serverPath]; } - String _getLibraryServerPath(String library) => - library.startsWith('dart:') - ? library - : DartUri(library, _root).serverPath; + String _getLibraryServerPath(String library) => library.startsWith('dart:') + ? library + : DartUri(library, _root).serverPath; /// Initializes [_sourceToModule], [_moduleToSources], and [_sourceToLibrary]. /// diff --git a/dwds/lib/src/debugging/skip_list.dart b/dwds/lib/src/debugging/skip_list.dart index 7b5f94291..6256f823c 100644 --- a/dwds/lib/src/debugging/skip_list.dart +++ b/dwds/lib/src/debugging/skip_list.dart @@ -56,9 +56,8 @@ class SkipLists { ) { if (_idToList.containsKey(scriptId)) return _idToList[scriptId]!; - final sortedLocations = - locations.toList() - ..sort((a, b) => a.jsLocation.compareTo(b.jsLocation)); + final sortedLocations = locations.toList() + ..sort((a, b) => a.jsLocation.compareTo(b.jsLocation)); final ranges = >[]; var startLine = 0; diff --git a/dwds/lib/src/dwds_vm_client.dart b/dwds/lib/src/dwds_vm_client.dart index 815e51e3d..49a490dd2 100644 --- a/dwds/lib/src/dwds_vm_client.dart +++ b/dwds/lib/src/dwds_vm_client.dart @@ -73,12 +73,11 @@ class ChromeDwdsVmClient implements DwdsVmClient { ); @override - Future close() => - _closed ??= () async { - await _requestController.close(); - await _responseController.close(); - await client.dispose(); - }(); + Future close() => _closed ??= () async { + await _requestController.close(); + await _responseController.close(); + await client.dispose(); + }(); static Future create( ChromeDebugService debugService, @@ -108,14 +107,13 @@ class ChromeDwdsVmClient implements DwdsVmClient { clientFuture: clientCompleter.future, ); - final client = - ddsUri == null - ? _setUpVmClient( - responseStream: responseStream, - requestController: requestController, - requestSink: requestSink, - ) - : await _setUpDdsClient(ddsUri: ddsUri); + final client = ddsUri == null + ? _setUpVmClient( + responseStream: responseStream, + requestController: requestController, + requestSink: requestSink, + ) + : await _setUpDdsClient(ddsUri: ddsUri); if (!clientCompleter.isCompleted) { clientCompleter.complete(client); @@ -326,12 +324,11 @@ class WebSocketDwdsVmClient implements DwdsVmClient { ); @override - Future close() => - _closed ??= () async { - await _requestController.close(); - await _responseController.close(); - await client.dispose(); - }(); + Future close() => _closed ??= () async { + await _requestController.close(); + await _responseController.close(); + await client.dispose(); + }(); static Future create( WebSocketDebugService debugService, @@ -515,14 +512,16 @@ void _recordDwdsStats(DwdsStats dwdsStats, String screen) { final devToolsStart = dwdsStats.devToolsStart; final debuggerStart = dwdsStats.debuggerStart; if (devToolsStart != null) { - final devToolLoadTime = - DateTime.now().difference(devToolsStart).inMilliseconds; + final devToolLoadTime = DateTime.now() + .difference(devToolsStart) + .inMilliseconds; emitEvent(DwdsEvent.devToolsLoad(devToolLoadTime, screen)); _chromeLogger.fine('DevTools load time: $devToolLoadTime ms'); } if (debuggerStart != null) { - final debuggerReadyTime = - DateTime.now().difference(debuggerStart).inMilliseconds; + final debuggerReadyTime = DateTime.now() + .difference(debuggerStart) + .inMilliseconds; emitEvent(DwdsEvent.debuggerReady(debuggerReadyTime, screen)); _chromeLogger.fine('Debugger ready time: $debuggerReadyTime ms'); } diff --git a/dwds/lib/src/handlers/dev_handler.dart b/dwds/lib/src/handlers/dev_handler.dart index c93e16719..de31bdcdb 100644 --- a/dwds/lib/src/handlers/dev_handler.dart +++ b/dwds/lib/src/handlers/dev_handler.dart @@ -117,19 +117,18 @@ class DevHandler { return Response.notFound(''); }; - Future close() => - _closed ??= () async { - for (final sub in _subs) { - await sub.cancel(); - } - for (final handler in _sseHandlers.values) { - handler.shutdown(); - } - await Future.wait( - _servicesByAppId.values.map((service) => service.close()), - ); - _servicesByAppId.clear(); - }(); + Future close() => _closed ??= () async { + for (final sub in _subs) { + await sub.cancel(); + } + for (final handler in _sseHandlers.values) { + handler.shutdown(); + } + await Future.wait( + _servicesByAppId.values.map((service) => service.close()), + ); + _servicesByAppId.clear(); + }(); void _emitBuildResults(BuildResult result) { if (result.status != BuildStatus.succeeded) return; @@ -340,13 +339,12 @@ class DevHandler { 'https://github.com/dart-lang/webdev/issues/new.', ); } - appConnection = - useWebSocketConnection - ? await _handleWebSocketConnectRequest( - message, - injectedConnection, - ) - : await _handleConnectRequest(message, injectedConnection); + appConnection = useWebSocketConnection + ? await _handleWebSocketConnectRequest( + message, + injectedConnection, + ) + : await _handleConnectRequest(message, injectedConnection); } else { final connection = appConnection; if (connection == null) { @@ -368,10 +366,9 @@ class DevHandler { jsonEncode( serializers.serialize( ErrorResponse( - (b) => - b - ..error = '$e' - ..stackTrace = '$s', + (b) => b + ..error = '$e' + ..stackTrace = '$s', ), ), ), @@ -436,8 +433,9 @@ class DevHandler { } else if (message is RegisterEvent) { proxyService.parseRegisterEvent(message); } else { - final serviceType = - proxyService is WebSocketProxyService ? 'WebSocket' : 'Chrome'; + final serviceType = proxyService is WebSocketProxyService + ? 'WebSocket' + : 'Chrome'; throw UnsupportedError( 'Message type ${message.runtimeType} is not supported in $serviceType mode', ); @@ -453,14 +451,13 @@ class DevHandler { jsonEncode( serializers.serialize( DevToolsResponse( - (b) => - b - ..success = false - ..promptExtension = false - ..error = - 'Debugging is not enabled.\n\n' - 'If you are using webdev please pass the --debug flag.\n' - 'Otherwise check the docs for the tool you are using.', + (b) => b + ..success = false + ..promptExtension = false + ..error = + 'Debugging is not enabled.\n\n' + 'If you are using webdev please pass the --debug flag.\n' + 'Otherwise check the docs for the tool you are using.', ), ), ), @@ -478,22 +475,20 @@ class DevHandler { 'load in a different Chrome window than was launched by ' 'your development tool.'; var response = DevToolsResponse( - (b) => - b - ..success = false - ..promptExtension = false - ..error = error, + (b) => b + ..success = false + ..promptExtension = false + ..error = error, ); if (_extensionBackend != null) { response = response.rebuild( - (b) => - b - ..promptExtension = true - ..error = - '$error\n\n' - 'Your workflow alternatively supports debugging through the ' - 'Dart Debug Extension.\n\n' - 'Would you like to install the extension?', + (b) => b + ..promptExtension = true + ..error = + '$error\n\n' + 'Your workflow alternatively supports debugging through the ' + 'Dart Debug Extension.\n\n' + 'Would you like to install the extension?', ); } sseConnection.sink.add(jsonEncode(serializers.serialize(response))); @@ -508,13 +503,12 @@ class DevHandler { jsonEncode( serializers.serialize( DevToolsResponse( - (b) => - b - ..success = false - ..promptExtension = false - ..error = - 'This app is already being debugged in a different tab. ' - 'Please close that tab or switch to it.', + (b) => b + ..success = false + ..promptExtension = false + ..error = + 'This app is already being debugged in a different tab. ' + 'Please close that tab or switch to it.', ), ), ), @@ -526,10 +520,9 @@ class DevHandler { jsonEncode( serializers.serialize( DevToolsResponse( - (b) => - b - ..success = true - ..promptExtension = false, + (b) => b + ..success = true + ..promptExtension = false, ), ), ), @@ -826,16 +819,15 @@ class DevHandler { _injected.devHandlerPaths.listen((devHandlerPath) async { final uri = Uri.parse(devHandlerPath); if (!_sseHandlers.containsKey(uri.path)) { - final handler = - _useSseForInjectedClient - ? SseSocketHandler( - // We provide an essentially indefinite keep alive duration because - // the underlying connection could be lost while the application - // is paused. The connection will get re-established after a resume - // or cleaned up on a full page refresh. - SseHandler(uri, keepAlive: const Duration(days: 3000)), - ) - : WebSocketSocketHandler(); + final handler = _useSseForInjectedClient + ? SseSocketHandler( + // We provide an essentially indefinite keep alive duration because + // the underlying connection could be lost while the application + // is paused. The connection will get re-established after a resume + // or cleaned up on a full page refresh. + SseHandler(uri, keepAlive: const Duration(days: 3000)), + ) + : WebSocketSocketHandler(); _sseHandlers[uri.path] = handler; final injectedConnections = handler.connections; while (await injectedConnections.hasNext) { @@ -1105,10 +1097,9 @@ extension on Stream { /// Forwards events from the original stream until a period of at least [gap] /// occurs in between events, in which case the returned stream will end. Stream takeUntilGap(Duration gap) { - final controller = - isBroadcast - ? StreamController.broadcast(sync: true) - : StreamController(sync: true); + final controller = isBroadcast + ? StreamController.broadcast(sync: true) + : StreamController(sync: true); late StreamSubscription subscription; Timer? gapTimer; diff --git a/dwds/lib/src/handlers/injector.dart b/dwds/lib/src/handlers/injector.dart index 121c3628a..888714851 100644 --- a/dwds/lib/src/handlers/injector.dart +++ b/dwds/lib/src/handlers/injector.dart @@ -145,8 +145,9 @@ Future _injectClientAndHoistMain( var result = bodyLines.sublist(0, extensionIndex).join('\n'); // The line after the marker calls `main`. We prevent `main` from // being called and make it runnable through a global variable. - final mainFunction = - bodyLines[extensionIndex + 1].replaceAll('main();', 'main').trim(); + final mainFunction = bodyLines[extensionIndex + 1] + .replaceAll('main();', 'main') + .trim(); // We inject the client in the entry point module as the client expects the // application to be in a ready state, that is the main function is hoisted // and the Dart SDK is loaded. @@ -156,7 +157,8 @@ Future _injectClientAndHoistMain( entrypointPath, extensionUri, ); - result += ''' + result += + ''' // Injected by dwds for debugging support. if(!window.\$dwdsInitialized) { window.\$dwdsInitialized = true; diff --git a/dwds/lib/src/loaders/frontend_server_strategy_provider.dart b/dwds/lib/src/loaders/frontend_server_strategy_provider.dart index 80eb4fb9c..a042d1c38 100644 --- a/dwds/lib/src/loaders/frontend_server_strategy_provider.dart +++ b/dwds/lib/src/loaders/frontend_server_strategy_provider.dart @@ -38,10 +38,9 @@ abstract class FrontendServerStrategyProvider { return stripLeadingSlashes(stripped.substring(_basePath.length)); } - String _addBasePath(String serverPath) => - _basePath.isEmpty - ? stripLeadingSlashes(serverPath) - : '$_basePath/${stripLeadingSlashes(serverPath)}'; + String _addBasePath(String serverPath) => _basePath.isEmpty + ? stripLeadingSlashes(serverPath) + : '$_basePath/${stripLeadingSlashes(serverPath)}'; String _removeJsExtension(String path) => path.endsWith('.js') ? p.withoutExtension(path) : path; diff --git a/dwds/lib/src/loaders/require.dart b/dwds/lib/src/loaders/require.dart index f7d5a5961..a6e9aa778 100644 --- a/dwds/lib/src/loaders/require.dart +++ b/dwds/lib/src/loaders/require.dart @@ -185,7 +185,8 @@ class RequireStrategy extends LoadStrategy { /// /// Adds error handler code for require.js which requests a `.errors` file for /// any failed module, and logs it to the console. - String get _requireJsConfig => ''' + String get _requireJsConfig => + ''' $_baseUrlScript; require.config({ baseUrl: baseUrl, diff --git a/dwds/lib/src/readers/asset_reader.dart b/dwds/lib/src/readers/asset_reader.dart index b3210da6c..e85415b4f 100644 --- a/dwds/lib/src/readers/asset_reader.dart +++ b/dwds/lib/src/readers/asset_reader.dart @@ -81,10 +81,9 @@ class PackageUriMapper { final root = package.root; final relativeUrl = resolvedUri.toString().replaceFirst('$root', ''); final relativeRoot = _getRelativeRoot(root); - final ret = - relativeRoot == null - ? 'packages/$relativeUrl' - : 'packages/$relativeRoot/$relativeUrl'; + final ret = relativeRoot == null + ? 'packages/$relativeUrl' + : 'packages/$relativeRoot/$relativeUrl'; return ret; } _logger.severe('Expected package uri, but found $packageUri'); diff --git a/dwds/lib/src/readers/proxy_server_asset_reader.dart b/dwds/lib/src/readers/proxy_server_asset_reader.dart index 797374790..7ef30d89c 100644 --- a/dwds/lib/src/readers/proxy_server_asset_reader.dart +++ b/dwds/lib/src/readers/proxy_server_asset_reader.dart @@ -26,17 +26,13 @@ class ProxyServerAssetReader implements AssetReader { bool isHttps = false, }) { final scheme = isHttps ? 'https://' : 'http://'; - final inner = - HttpClient() - ..maxConnectionsPerHost = 200 - ..idleTimeout = const Duration(seconds: 30) - ..connectionTimeout = const Duration(seconds: 30); - _client = - isHttps - ? IOClient( - inner..badCertificateCallback = (cert, host, port) => true, - ) - : IOClient(inner); + final inner = HttpClient() + ..maxConnectionsPerHost = 200 + ..idleTimeout = const Duration(seconds: 30) + ..connectionTimeout = const Duration(seconds: 30); + _client = isHttps + ? IOClient(inner..badCertificateCallback = (cert, host, port) => true) + : IOClient(inner); var url = '$scheme$host:$assetServerPort/'; if (root.isNotEmpty) url += '$root/'; _handler = proxyHandler(url, client: _client); diff --git a/dwds/lib/src/servers/extension_debugger.dart b/dwds/lib/src/servers/extension_debugger.dart index df72a5ca2..11f9a32f6 100644 --- a/dwds/lib/src/servers/extension_debugger.dart +++ b/dwds/lib/src/servers/extension_debugger.dart @@ -142,10 +142,9 @@ class ExtensionDebugger implements RemoteDebugger { jsonEncode( serializers.serialize( ExtensionEvent( - (b) => - b - ..method = method - ..params = params, + (b) => b + ..method = method + ..params = params, ), ), ), @@ -167,11 +166,10 @@ class ExtensionDebugger implements RemoteDebugger { jsonEncode( serializers.serialize( ExtensionRequest( - (b) => - b - ..id = id - ..command = command - ..commandParams = jsonEncode(params ?? {}), + (b) => b + ..id = id + ..command = command + ..commandParams = jsonEncode(params ?? {}), ), ), ), @@ -196,16 +194,15 @@ class ExtensionDebugger implements RemoteDebugger { int newId() => _completerId++; @override - Future close() => - _closed ??= () { - _closeController.add({}); - return Future.wait([ - sseConnection.sink.close(), - _notificationController.close(), - _devToolsRequestController.close(), - _closeController.close(), - ]); - }(); + Future close() => _closed ??= () { + _closeController.add({}); + return Future.wait([ + sseConnection.sink.close(), + _notificationController.close(), + _devToolsRequestController.close(), + _closeController.close(), + ]); + }(); void closeWithError(Object? error) { _logger.shout( diff --git a/dwds/lib/src/services/batched_expression_evaluator.dart b/dwds/lib/src/services/batched_expression_evaluator.dart index 17a7382fe..af0bd31ca 100644 --- a/dwds/lib/src/services/batched_expression_evaluator.dart +++ b/dwds/lib/src/services/batched_expression_evaluator.dart @@ -158,9 +158,8 @@ class BatchedExpressionEvaluator extends ExpressionEvaluator { ); request.completer.complete(result); }), - onError: - (error, stackTrace) => - request.completer.completeError(error, stackTrace), + onError: (error, stackTrace) => + request.completer.completeError(error, stackTrace), ); } } diff --git a/dwds/lib/src/services/chrome_debug_exception.dart b/dwds/lib/src/services/chrome_debug_exception.dart index 2b3542dea..4f8e8b595 100644 --- a/dwds/lib/src/services/chrome_debug_exception.dart +++ b/dwds/lib/src/services/chrome_debug_exception.dart @@ -26,8 +26,8 @@ class ChromeDebugException extends ExceptionDetails implements Exception { @override String toString() { - final description = - StringBuffer()..writeln('Unexpected error from chrome devtools:'); + final description = StringBuffer() + ..writeln('Unexpected error from chrome devtools:'); description.writeln('text: $text'); if (exception != null) { description.writeln('exception:'); diff --git a/dwds/lib/src/services/chrome_proxy_service.dart b/dwds/lib/src/services/chrome_proxy_service.dart index 27080471c..3991e0057 100644 --- a/dwds/lib/src/services/chrome_proxy_service.dart +++ b/dwds/lib/src/services/chrome_proxy_service.dart @@ -299,17 +299,16 @@ class ChromeProxyService extends ProxyService { ); final compiler = _compiler; - _expressionEvaluator = - compiler == null - ? null - : BatchedExpressionEvaluator( - entrypoint, - inspector, - debugger, - _locations, - _modules, - compiler, - ); + _expressionEvaluator = compiler == null + ? null + : BatchedExpressionEvaluator( + entrypoint, + inspector, + debugger, + _locations, + _modules, + compiler, + ); safeUnawaited(_prewarmExpressionCompilerCache()); @@ -1481,24 +1480,21 @@ class ChromeProxyService extends ProxyService { // Always attempt to fetch the full properties instead of relying on // `RemoteObject.preview` which only has truncated log messages: // https://chromedevtools.github.io/devtools-protocol/tot/Runtime/#type-RemoteObject - final logParams = - objectId != null - ? await _fetchFullLogParams(objectId, logObject: logObject) - : _fetchAbbreviatedLogParams(logObject); + final logParams = objectId != null + ? await _fetchFullLogParams(objectId, logObject: logObject) + : _fetchAbbreviatedLogParams(logObject); final logRecord = LogRecord( message: await _instanceRef(logParams['message']), loggerName: await _instanceRef(logParams['name']), - level: - logParams['level'] != null - ? int.tryParse(logParams['level']!.value.toString()) - : 0, + level: logParams['level'] != null + ? int.tryParse(logParams['level']!.value.toString()) + : 0, error: await _instanceRef(logParams['error']), time: event.timestamp.toInt(), - sequenceNumber: - logParams['sequenceNumber'] != null - ? int.tryParse(logParams['sequenceNumber']!.value.toString()) - : 0, + sequenceNumber: logParams['sequenceNumber'] != null + ? int.tryParse(logParams['sequenceNumber']!.value.toString()) + : 0, stackTrace: await _instanceRef(logParams['stackTrace']), zone: await _instanceRef(logParams['zone']), ); diff --git a/dwds/lib/src/services/debug_service.dart b/dwds/lib/src/services/debug_service.dart index 17ab88150..4f79cb27c 100644 --- a/dwds/lib/src/services/debug_service.dart +++ b/dwds/lib/src/services/debug_service.dart @@ -177,11 +177,10 @@ class ChromeDebugService implements DebugService { ); @override - Future close() => - _closed ??= Future.wait([ - _server.close(), - if (_dds != null) _dds!.shutdown(), - ]); + Future close() => _closed ??= Future.wait([ + _server.close(), + if (_dds != null) _dds!.shutdown(), + ]); Future startDartDevelopmentService() async { // Note: DDS can handle both web socket and SSE connections with no @@ -206,11 +205,11 @@ class ChromeDebugService implements DebugService { } return (_useSse ? Uri( - scheme: 'sse', - host: hostname, - port: port, - path: '$authToken/\$debugHandler', - ) + scheme: 'sse', + host: hostname, + port: port, + path: '$authToken/\$debugHandler', + ) : Uri(scheme: 'ws', host: hostname, port: port, path: authToken)) .toString(); } @@ -360,11 +359,10 @@ class WebSocketDebugService implements DebugService { /// Closes the debug service and associated resources. @override - Future close() => - _closed ??= Future.wait([ - _server.close(), - if (_dds != null) _dds!.shutdown(), - ]); + Future close() => _closed ??= Future.wait([ + _server.close(), + if (_dds != null) _dds!.shutdown(), + ]); /// Starts DDS (Dart Development Service). Future startDartDevelopmentService({ diff --git a/dwds/lib/src/services/expression_evaluator.dart b/dwds/lib/src/services/expression_evaluator.dart index 528bf3682..1b6c38551 100644 --- a/dwds/lib/src/services/expression_evaluator.dart +++ b/dwds/lib/src/services/expression_evaluator.dart @@ -335,15 +335,9 @@ class ExpressionEvaluator { final jsCode = _maybeStripTryCatch(jsResult); // Send JS expression to chrome to evaluate. - var result = - scope.isEmpty - ? await _evaluateJsExpressionInFrame(frameIndex, jsCode) - : await _callJsFunctionInFrame( - frameIndex, - jsCode, - scope, - frameScope, - ); + var result = scope.isEmpty + ? await _evaluateJsExpressionInFrame(frameIndex, jsCode) + : await _callJsFunctionInFrame(frameIndex, jsCode, scope, frameScope); result = await _formatEvaluationError(result); _logger.finest('Evaluated "$expression" to "${result.json}"'); @@ -452,11 +446,12 @@ class ExpressionEvaluator { return createError(EvaluationErrorKind.type, error); } else if (error.startsWith('NetworkError: ')) { var modulePath = _loadModuleErrorRegex.firstMatch(error)?.group(1); - final module = - modulePath != null - ? await globalToolConfiguration.loadStrategy - .moduleForServerPath(_entrypoint, modulePath) - : 'unknown'; + final module = modulePath != null + ? await globalToolConfiguration.loadStrategy.moduleForServerPath( + _entrypoint, + modulePath, + ) + : 'unknown'; modulePath ??= 'unknown'; error = 'Module is not loaded : $module (path: $modulePath). ' @@ -532,8 +527,9 @@ class ExpressionEvaluator { if (lines.length > 5) { final tryLines = lines.getRange(0, 2).toList(); final bodyLines = lines.getRange(2, lines.length - 3); - final catchLines = - lines.getRange(lines.length - 3, lines.length).toList(); + final catchLines = lines + .getRange(lines.length - 3, lines.length) + .toList(); if (tryLines[0].isEmpty && tryLines[1] == 'try {' && catchLines[0] == '} catch (error) {' && diff --git a/dwds/lib/src/services/web_socket_proxy_service.dart b/dwds/lib/src/services/web_socket_proxy_service.dart index 4d5503e7c..70cadb876 100644 --- a/dwds/lib/src/services/web_socket_proxy_service.dart +++ b/dwds/lib/src/services/web_socket_proxy_service.dart @@ -573,8 +573,9 @@ class WebSocketProxyService extends ProxyService { final request = ServiceExtensionRequest.fromArgs( id: requestId, method: method, - args: - args != null ? Map.from(args) : {}, + args: args != null + ? Map.from(args) + : {}, ); // Send the request and get the number of connected clients diff --git a/dwds/lib/src/utilities/objects.dart b/dwds/lib/src/utilities/objects.dart index 60bcbd0be..86680aec1 100644 --- a/dwds/lib/src/utilities/objects.dart +++ b/dwds/lib/src/utilities/objects.dart @@ -46,10 +46,9 @@ class Property { if (_map == null) return null; if (rawName == null) return null; const prefix = 'Symbol('; - var nonSymbol = - (rawName!.startsWith(prefix)) - ? rawName!.substring(prefix.length, rawName!.length - 1) - : rawName!; + var nonSymbol = (rawName!.startsWith(prefix)) + ? rawName!.substring(prefix.length, rawName!.length - 1) + : rawName!; // Adjust names for late fields: // '_#MyTestClass#myselfField' -> 'myselfField' // TODO(annagrin): Use debug symbols to map from dart to JS symbols. diff --git a/dwds/lib/src/utilities/shared.dart b/dwds/lib/src/utilities/shared.dart index b8837cb26..1a55bdaf6 100644 --- a/dwds/lib/src/utilities/shared.dart +++ b/dwds/lib/src/utilities/shared.dart @@ -21,9 +21,8 @@ void safeUnawaited( Future future, { void Function(dynamic, StackTrace)? onError, }) { - onError ??= - (error, stackTrace) => - _logger.warning('Error in unawaited Future:', error, stackTrace); + onError ??= (error, stackTrace) => + _logger.warning('Error in unawaited Future:', error, stackTrace); unawaited(future.catchError(onError)); } diff --git a/dwds/pubspec.yaml b/dwds/pubspec.yaml index e394f75d2..59dd21d2d 100644 --- a/dwds/pubspec.yaml +++ b/dwds/pubspec.yaml @@ -7,7 +7,7 @@ description: >- service protocol. repository: https://github.com/dart-lang/webdev/tree/main/dwds environment: - sdk: ^3.7.0 + sdk: ^3.8.0 dependencies: async: ^2.9.0 diff --git a/dwds/test/common/chrome_proxy_service_common.dart b/dwds/test/common/chrome_proxy_service_common.dart index 17eb5a0a0..41595ccc3 100644 --- a/dwds/test/common/chrome_proxy_service_common.dart +++ b/dwds/test/common/chrome_proxy_service_common.dart @@ -787,8 +787,8 @@ void runTests({ // TODO: Figure out if we can encode the sript as utf8 and avoid this final body = (moduleFormat == ModuleFormat.ddc && canaryFeatures == true) - ? utf8.decode(result.body.codeUnits) - : result.body; + ? utf8.decode(result.body.codeUnits) + : result.body; expect(script.source, body); expect(scriptRef.uri, endsWith('.dart')); expect(script.tokenPosTable, isNotEmpty); @@ -1749,8 +1749,9 @@ void runTests({ }); test('break on exceptions with setIsolatePauseMode', () async { - final oldPauseMode = - (await service.getIsolate(isolateId!)).exceptionPauseMode; + final oldPauseMode = (await service.getIsolate( + isolateId!, + )).exceptionPauseMode; await service.setIsolatePauseMode( isolateId!, exceptionPauseMode: ExceptionPauseMode.kAll, diff --git a/dwds/test/dart_uri_file_uri_test.dart b/dwds/test/dart_uri_file_uri_test.dart index 7f223c8a4..d6f4cfbe5 100644 --- a/dwds/test/dart_uri_file_uri_test.dart +++ b/dwds/test/dart_uri_file_uri_test.dart @@ -34,20 +34,20 @@ void main() { group('Debugger module names: $useDebuggerModuleNames |', () { final appServerPath = compilationMode == CompilationMode.frontendServer - ? 'web/main.dart' - : 'main.dart'; + ? 'web/main.dart' + : 'main.dart'; final serverPath = compilationMode == CompilationMode.frontendServer && - useDebuggerModuleNames - ? 'packages/${testPackageProject.packageDirectory}/lib/test_library.dart' - : 'packages/${testPackageProject.packageName}/test_library.dart'; + useDebuggerModuleNames + ? 'packages/${testPackageProject.packageDirectory}/lib/test_library.dart' + : 'packages/${testPackageProject.packageName}/test_library.dart'; final anotherServerPath = compilationMode == CompilationMode.frontendServer && - useDebuggerModuleNames - ? 'packages/${testProject.packageDirectory}/lib/library.dart' - : 'packages/${testProject.packageName}/library.dart'; + useDebuggerModuleNames + ? 'packages/${testProject.packageDirectory}/lib/library.dart' + : 'packages/${testProject.packageName}/library.dart'; setUpAll(() async { await context.setUp( diff --git a/dwds/test/debug_extension_test.dart b/dwds/test/debug_extension_test.dart index 21129adcf..5ef09139a 100644 --- a/dwds/test/debug_extension_test.dart +++ b/dwds/test/debug_extension_test.dart @@ -233,11 +233,8 @@ void main() async { await context.setUp( debugSettings: TestDebugSettings.noDevTools().copyWith( enableDebugExtension: true, - urlEncoder: - (url) async => - url.endsWith(r'/$debug') - ? 'http://some-encoded-url:8081/' - : url, + urlEncoder: (url) async => + url.endsWith(r'/$debug') ? 'http://some-encoded-url:8081/' : url, ), ); }); diff --git a/dwds/test/debugger_test.dart b/dwds/test/debugger_test.dart index ec6fd766e..908b513bc 100644 --- a/dwds/test/debugger_test.dart +++ b/dwds/test/debugger_test.dart @@ -120,10 +120,9 @@ void main() async { [sampleSyncFrame], asyncStackTrace: StackTrace({ 'callFrames': [sampleAsyncFrame.json], - 'parent': - StackTrace({ - 'callFrames': [sampleAsyncFrame.json], - }).json, + 'parent': StackTrace({ + 'callFrames': [sampleAsyncFrame.json], + }).json, }), ); @@ -143,15 +142,13 @@ void main() async { [sampleSyncFrame], asyncStackTrace: StackTrace({ 'callFrames': [sampleAsyncFrame.json], - 'parent': - StackTrace({ - 'callFrames': [], - 'parent': - StackTrace({ - 'callFrames': [sampleAsyncFrame.json], - 'parent': StackTrace({'callFrames': []}).json, - }).json, - }).json, + 'parent': StackTrace({ + 'callFrames': [], + 'parent': StackTrace({ + 'callFrames': [sampleAsyncFrame.json], + 'parent': StackTrace({'callFrames': []}).json, + }).json, + }).json, }), ); diff --git a/dwds/test/execution_context_test.dart b/dwds/test/execution_context_test.dart index 9f8b59b5e..3a02c935c 100644 --- a/dwds/test/execution_context_test.dart +++ b/dwds/test/execution_context_test.dart @@ -235,10 +235,9 @@ class TestDebuggerConnection { /// context in the extension debugger. void sendContextsClearedEvent() { final extensionEvent = ExtensionEvent( - (b) => - b - ..method = jsonEncode('Runtime.executionContextsCleared') - ..params = jsonEncode({}), + (b) => b + ..method = jsonEncode('Runtime.executionContextsCleared') + ..params = jsonEncode({}), ); connection.controllerIncoming.sink.add( jsonEncode(serializers.serialize(extensionEvent)), @@ -249,12 +248,11 @@ class TestDebuggerConnection { /// context in the extension debugger. void sendContextCreatedEvent(TestContextId contextId) { final extensionEvent = ExtensionEvent( - (b) => - b - ..method = jsonEncode('Runtime.executionContextCreated') - ..params = jsonEncode({ - 'context': {'id': '${contextId.id}'}, - }), + (b) => b + ..method = jsonEncode('Runtime.executionContextCreated') + ..params = jsonEncode({ + 'context': {'id': '${contextId.id}'}, + }), ); connection.controllerIncoming.sink.add( jsonEncode(serializers.serialize(extensionEvent)), @@ -264,11 +262,10 @@ class TestDebuggerConnection { void _sendEvaluationResponse(Map response) { // Respond to the evaluate request. final extensionResponse = ExtensionResponse( - (b) => - b - ..result = jsonEncode(response) - ..id = _evaluateRequestId++ - ..success = true, + (b) => b + ..result = jsonEncode(response) + ..id = _evaluateRequestId++ + ..success = true, ); connection.controllerIncoming.sink.add( jsonEncode(serializers.serialize(extensionResponse)), @@ -277,11 +274,10 @@ class TestDebuggerConnection { void _sendDevToolsRequest({int? contextId}) { final devToolsRequest = DevToolsRequest( - (b) => - b - ..contextId = contextId - ..appId = 'app' - ..instanceId = '0', + (b) => b + ..contextId = contextId + ..appId = 'app' + ..instanceId = '0', ); connection.controllerIncoming.sink.add( jsonEncode(serializers.serialize(devToolsRequest)), diff --git a/dwds/test/expression_compiler_service_common.dart b/dwds/test/expression_compiler_service_common.dart index 2efe33a9b..e1e7f7c76 100644 --- a/dwds/test/expression_compiler_service_common.dart +++ b/dwds/test/expression_compiler_service_common.dart @@ -121,15 +121,16 @@ void testAll({required CompilerOptions compilerOptions}) { '--packages', packages.path, ]; - final process = await Process.start( - executable, - args, - workingDirectory: outputDir.path, - ).then((p) { - transformToLines(p.stdout).listen(output.add); - transformToLines(p.stderr).listen(output.add); - return p; - }); + final process = + await Process.start( + executable, + args, + workingDirectory: outputDir.path, + ).then((p) { + transformToLines(p.stdout).listen(output.add); + transformToLines(p.stderr).listen(output.add); + return p; + }); expect( await process.exitCode, 0, diff --git a/dwds/test/extension_debugger_test.dart b/dwds/test/extension_debugger_test.dart index 6ce40dff3..5c865b92d 100644 --- a/dwds/test/extension_debugger_test.dart +++ b/dwds/test/extension_debugger_test.dart @@ -35,13 +35,12 @@ void main() async { group('can receive', () { test('an ExtensionResponse', () async { final extensionResponse = ExtensionResponse( - (b) => - b - ..result = jsonEncode({ - 'result': {'value': 3.14}, - }) - ..id = 0 - ..success = true, + (b) => b + ..result = jsonEncode({ + 'result': {'value': 3.14}, + }) + ..id = 0 + ..success = true, ); final resultCompleter = Completer(); unawaited( @@ -58,10 +57,9 @@ void main() async { test('an ExtensionEvent', () async { final extensionEvent = ExtensionEvent( - (b) => - b - ..method = jsonEncode('Debugger.paused') - ..params = jsonEncode(frames1Json[0]), + (b) => b + ..method = jsonEncode('Debugger.paused') + ..params = jsonEncode(frames1Json[0]), ); connection.controllerIncoming.sink.add( jsonEncode(serializers.serialize(extensionEvent)), @@ -73,16 +71,14 @@ void main() async { test('a BatchedEvents', () async { final event1 = ExtensionEvent( - (b) => - b - ..method = jsonEncode('Debugger.scriptParsed') - ..params = jsonEncode(scriptParsedParams), + (b) => b + ..method = jsonEncode('Debugger.scriptParsed') + ..params = jsonEncode(scriptParsedParams), ); final event2 = ExtensionEvent( - (b) => - b - ..method = jsonEncode('Debugger.scriptParsed') - ..params = jsonEncode(scriptParsedParams), + (b) => b + ..method = jsonEncode('Debugger.scriptParsed') + ..params = jsonEncode(scriptParsedParams), ); final batch = BatchedEvents( (b) => b.events = ListBuilder([event1, event2]), @@ -97,11 +93,10 @@ void main() async { test('a DevToolsRequest', () async { final devToolsRequest = DevToolsRequest( - (b) => - b - ..tabUrl = 'pi/calculus' - ..appId = '3.14' - ..instanceId = '6.28', + (b) => b + ..tabUrl = 'pi/calculus' + ..appId = '3.14' + ..instanceId = '6.28', ); connection.controllerIncoming.sink.add( jsonEncode(serializers.serialize(devToolsRequest)), @@ -116,11 +111,10 @@ void main() async { group('can send', () { test('a request with empty params', () async { final extensionRequest = ExtensionRequest( - (b) => - b - ..id = 0 - ..command = 'Debugger.pause' - ..commandParams = jsonEncode({}), + (b) => b + ..id = 0 + ..command = 'Debugger.pause' + ..commandParams = jsonEncode({}), ); unawaited(extensionDebugger.pause()); final request = serializers.deserialize( @@ -134,11 +128,10 @@ void main() async { 'location': {'scriptId': '555', 'lineNumber': 28}, }; final extensionRequest = ExtensionRequest( - (b) => - b - ..id = 0 - ..command = 'Debugger.setBreakpoint' - ..commandParams = jsonEncode(params), + (b) => b + ..id = 0 + ..command = 'Debugger.setBreakpoint' + ..commandParams = jsonEncode(params), ); unawaited( extensionDebugger.sendCommand('Debugger.setBreakpoint', params: params), @@ -152,10 +145,9 @@ void main() async { group('when closed', () { test('DebugExtension.detached event closes the connection', () async { final extensionEvent = ExtensionEvent( - (b) => - b - ..method = jsonEncode('DebugExtension.detached') - ..params = jsonEncode({}), + (b) => b + ..method = jsonEncode('DebugExtension.detached') + ..params = jsonEncode({}), ); connection.controllerIncoming.sink.add( @@ -170,10 +162,9 @@ void main() async { () async { // Close the connection: final extensionEvent = ExtensionEvent( - (b) => - b - ..method = jsonEncode('DebugExtension.detached') - ..params = jsonEncode({}), + (b) => b + ..method = jsonEncode('DebugExtension.detached') + ..params = jsonEncode({}), ); connection.controllerIncoming.sink.add( jsonEncode(serializers.serialize(extensionEvent)), diff --git a/dwds/test/fixtures/context.dart b/dwds/test/fixtures/context.dart index 1f8686cbd..e4d103cda 100644 --- a/dwds/test/fixtures/context.dart +++ b/dwds/test/fixtures/context.dart @@ -181,17 +181,15 @@ class TestContext { ]); // On windows this takes a while to boot up, wait for the first line // of stdout as a signal that it is ready. - final stdOutLines = - chromeDriver.stdout - .transform(utf8.decoder) - .transform(const LineSplitter()) - .asBroadcastStream(); - - final stdErrLines = - chromeDriver.stderr - .transform(utf8.decoder) - .transform(const LineSplitter()) - .asBroadcastStream(); + final stdOutLines = chromeDriver.stdout + .transform(utf8.decoder) + .transform(const LineSplitter()) + .asBroadcastStream(); + + final stdErrLines = chromeDriver.stderr + .transform(utf8.decoder) + .transform(const LineSplitter()) + .asBroadcastStream(); stdOutLines.listen( (line) => _logger.finest('ChromeDriver stdout: $line'), @@ -244,8 +242,9 @@ class TestContext { options, (log) { final record = log.toLogRecord(); - final name = - record.loggerName == '' ? '' : '${record.loggerName}: '; + final name = record.loggerName == '' + ? '' + : '${record.loggerName}: '; _logger.log( record.level, '$name${record.message}', @@ -283,13 +282,12 @@ class TestContext { expressionCompiler = ddcService; } - loadStrategy = - BuildRunnerRequireStrategyProvider( - assetHandler, - testSettings.reloadConfiguration, - assetReader, - buildSettings, - ).strategy; + loadStrategy = BuildRunnerRequireStrategyProvider( + assetHandler, + testSettings.reloadConfiguration, + assetReader, + buildSettings, + ).strategy; buildResults = daemonClient.buildResults; } @@ -352,37 +350,35 @@ class TestContext { assetReader = webRunner.devFS!.assetServer; _assetHandler = webRunner.devFS!.assetServer.handleRequest; loadStrategy = switch (testSettings.moduleFormat) { - ModuleFormat.amd => - FrontendServerRequireStrategyProvider( - testSettings.reloadConfiguration, - assetReader, - packageUriMapper, - () async => {}, - buildSettings, - ).strategy, + ModuleFormat.amd => FrontendServerRequireStrategyProvider( + testSettings.reloadConfiguration, + assetReader, + packageUriMapper, + () async => {}, + buildSettings, + ).strategy, ModuleFormat.ddc => buildSettings.canaryFeatures ? FrontendServerDdcLibraryBundleStrategyProvider( - testSettings.reloadConfiguration, - assetReader, - packageUriMapper, - () async => {}, - buildSettings, - hotReloadSourcesUri: Uri.parse( - 'http://localhost:$port/${WebDevFS.reloadScriptsFileName}', - ), - ).strategy + testSettings.reloadConfiguration, + assetReader, + packageUriMapper, + () async => {}, + buildSettings, + hotReloadSourcesUri: Uri.parse( + 'http://localhost:$port/${WebDevFS.reloadScriptsFileName}', + ), + ).strategy : FrontendServerDdcStrategyProvider( - testSettings.reloadConfiguration, - assetReader, - packageUriMapper, - () async => {}, - buildSettings, - ).strategy, - _ => - throw Exception( - 'Unsupported DDC module format ${testSettings.moduleFormat.name}.', - ), + testSettings.reloadConfiguration, + assetReader, + packageUriMapper, + () async => {}, + buildSettings, + ).strategy, + _ => throw Exception( + 'Unsupported DDC module format ${testSettings.moduleFormat.name}.', + ), }; buildResults = const Stream.empty(); } @@ -402,20 +398,20 @@ class TestContext { if (enableDebugExtension) { await _buildDebugExtension(); } - final capabilities = - Capabilities.chrome..addAll({ - Capabilities.chromeOptions: { - 'args': [ - // --disable-gpu speeds up the tests that use ChromeDriver when - // they are run on GitHub Actions. - '--disable-gpu', - 'remote-debugging-port=$debugPort', - if (enableDebugExtension) - '--load-extension=debug_extension/prod_build', - if (headless) '--headless', - ], - }, - }); + final capabilities = Capabilities.chrome + ..addAll({ + Capabilities.chromeOptions: { + 'args': [ + // --disable-gpu speeds up the tests that use ChromeDriver when + // they are run on GitHub Actions. + '--disable-gpu', + 'remote-debugging-port=$debugPort', + if (enableDebugExtension) + '--load-extension=debug_extension/prod_build', + if (headless) '--headless', + ], + }, + }); _webDriver = await createDriver( spec: WebDriverSpec.JsonWire, desired: capabilities, @@ -464,10 +460,9 @@ class TestContext { } }); - _appUrl = - basePath.isEmpty - ? 'http://localhost:$port/$filePathToServe' - : 'http://localhost:$port/$basePath/$filePathToServe'; + _appUrl = basePath.isEmpty + ? 'http://localhost:$port/$filePathToServe' + : 'http://localhost:$port/$basePath/$filePathToServe'; if (testSettings.launchChrome) { await _webDriver?.get(appUrl); @@ -615,10 +610,9 @@ class TestContext { if (propagateToBrowser) { // Allow change to propagate to the browser. // Windows, or at least Travis on Windows, seems to need more time. - final delay = - Platform.isWindows - ? const Duration(seconds: 5) - : const Duration(seconds: 2); + final delay = Platform.isWindows + ? const Duration(seconds: 5) + : const Duration(seconds: 2); await Future.delayed(delay); } } diff --git a/dwds/test/fixtures/fakes.dart b/dwds/test/fixtures/fakes.dart index 2b021101d..e53c8e26c 100644 --- a/dwds/test/fixtures/fakes.dart +++ b/dwds/test/fixtures/fakes.dart @@ -348,10 +348,9 @@ class FakeStrategy extends LoadStrategy { @override shelf.Handler get handler => - (request) => - (request.url.path == 'someDummyPath') - ? shelf.Response.ok('some dummy response') - : shelf.Response.notFound('someDummyPath'); + (request) => (request.url.path == 'someDummyPath') + ? shelf.Response.ok('some dummy response') + : shelf.Response.notFound('someDummyPath'); @override BuildSettings get buildSettings => _buildSettings; diff --git a/dwds/test/fixtures/project.dart b/dwds/test/fixtures/project.dart index 85c921f2d..c822bb56f 100644 --- a/dwds/test/fixtures/project.dart +++ b/dwds/test/fixtures/project.dart @@ -65,8 +65,9 @@ class TestProject { packageDirectory: '_testPackageSound', webAssetsPath: 'web', dartEntryFileName: 'main.dart', - htmlEntryFileName: - baseMode == IndexBaseMode.base ? 'base_index.html' : 'index.html', + htmlEntryFileName: baseMode == IndexBaseMode.base + ? 'base_index.html' + : 'index.html', ); static final testCircular1 = TestProject._( @@ -83,8 +84,9 @@ class TestProject { packageDirectory: '_testCircular2Sound', webAssetsPath: 'web', dartEntryFileName: 'main.dart', - htmlEntryFileName: - baseMode == IndexBaseMode.base ? 'base_index.html' : 'index.html', + htmlEntryFileName: baseMode == IndexBaseMode.base + ? 'base_index.html' + : 'index.html', ); static final test = TestProject._( diff --git a/dwds/test/fixtures/server.dart b/dwds/test/fixtures/server.dart index 9bae91dd7..306271829 100644 --- a/dwds/test/fixtures/server.dart +++ b/dwds/test/fixtures/server.dart @@ -126,8 +126,9 @@ class TestServer { final watch = Stopwatch()..start(); try { final response = await innerHandler(request); - final logFn = - response.statusCode >= 500 ? _logger.warning : _logger.finest; + final logFn = response.statusCode >= 500 + ? _logger.warning + : _logger.finest; final msg = _requestLabel( response.statusCode, request.requestedUri, diff --git a/dwds/test/frontend_server_ddc_library_bundle_evaluate_test.dart b/dwds/test/frontend_server_ddc_library_bundle_evaluate_test.dart index 157ee82b1..fade6104f 100644 --- a/dwds/test/frontend_server_ddc_library_bundle_evaluate_test.dart +++ b/dwds/test/frontend_server_ddc_library_bundle_evaluate_test.dart @@ -43,10 +43,9 @@ void main() async { debug: debug, ); }, - skip: - indexBaseMode == IndexBaseMode.base && Platform.isWindows - ? 'Skipped on Windows when indexBaseMode is base. See issue: https://github.com/dart-lang/sdk/issues/49277' - : null, + skip: indexBaseMode == IndexBaseMode.base && Platform.isWindows + ? 'Skipped on Windows when indexBaseMode is base. See issue: https://github.com/dart-lang/sdk/issues/49277' + : null, ); } }); diff --git a/dwds/test/hot_reload_breakpoints_test.dart b/dwds/test/hot_reload_breakpoints_test.dart index 5b120d845..dd3910692 100644 --- a/dwds/test/hot_reload_breakpoints_test.dart +++ b/dwds/test/hot_reload_breakpoints_test.dart @@ -293,10 +293,9 @@ void main() { final newString = "log('$extraLog');\n$oldString"; await makeEditAndRecompile(mainFile, oldString, newString); - bp = - (await hotReloadAndHandlePausePost([ - (file: mainFile, breakpointMarker: callLogMarker, bp: bp), - ])).first; + bp = (await hotReloadAndHandlePausePost([ + (file: mainFile, breakpointMarker: callLogMarker, bp: bp), + ])).first; breakpointFuture = waitForBreakpoint(); @@ -355,7 +354,8 @@ void main() { final libValueMarker = 'libValue'; context.addLibraryFile( libFileName: libFile, - contents: '''String get libraryValue { + contents: + '''String get libraryValue { return '$libGenLog'; // Breakpoint: $libValueMarker }''', ); @@ -414,7 +414,8 @@ void main() { final libFile = 'library$i.dart'; context.addLibraryFile( libFileName: libFile, - contents: '''String get libraryValue$i { + contents: + '''String get libraryValue$i { return 'lib gen$i'; // Breakpoint: libValue$i }''', ); @@ -462,10 +463,9 @@ void main() { final newLog = "log('\${closure()}');"; await makeEditAndRecompile(mainFile, oldLog, newLog); - bp = - (await hotReloadAndHandlePausePost([ - (file: mainFile, breakpointMarker: capturedStringMarker, bp: bp), - ])).first; + bp = (await hotReloadAndHandlePausePost([ + (file: mainFile, breakpointMarker: capturedStringMarker, bp: bp), + ])).first; final breakpointFuture = waitForBreakpoint(); diff --git a/dwds/test/hot_restart_breakpoints_test.dart b/dwds/test/hot_restart_breakpoints_test.dart index c54bb3696..53c68b4ab 100644 --- a/dwds/test/hot_restart_breakpoints_test.dart +++ b/dwds/test/hot_restart_breakpoints_test.dart @@ -267,7 +267,8 @@ void main() { final libValueMarker = 'libValue'; context.addLibraryFile( libFileName: libFile, - contents: '''String get libraryValue { + contents: + '''String get libraryValue { return '$libGenLog'; // Breakpoint: $libValueMarker }''', ); diff --git a/dwds/test/inspector_test.dart b/dwds/test/inspector_test.dart index 0c3e646b0..cd52557f3 100644 --- a/dwds/test/inspector_test.dart +++ b/dwds/test/inspector_test.dart @@ -163,8 +163,10 @@ void main() { test('properties', () async { final remoteObject = await libraryPublicFinal(); final properties = await inspector.getProperties(remoteObject.objectId!); - final names = - properties.map((p) => p.name).where((x) => x != '__proto__').toList(); + final names = properties + .map((p) => p.name) + .where((x) => x != '__proto__') + .toList(); final expected = [ '_privateField', 'abstractField', diff --git a/dwds/test/instances/common/instance_common.dart b/dwds/test/instances/common/instance_common.dart index 079f33f18..099bdbe61 100644 --- a/dwds/test/instances/common/instance_common.dart +++ b/dwds/test/instances/common/instance_common.dart @@ -49,13 +49,14 @@ void runTypeSystemVerificationTests({ String libraryName(CompilationMode compilationMode) => compilationMode == CompilationMode.frontendServer - ? 'example/scopes/main.dart' - : 'example/scopes/main'; + ? 'example/scopes/main.dart' + : 'example/scopes/main'; String libraryVariableTypeExpression( String variable, CompilationMode compilationMode, - ) => ''' + ) => + ''' (function() { var dart = ${globalToolConfiguration.loadStrategy.loadModuleSnippet}('dart_sdk').dart; var libraryName = '${libraryName(compilationMode)}'; @@ -258,9 +259,9 @@ void runTests({ }, skip: provider.ddcModuleFormat == ModuleFormat.ddc && - canaryFeatures == true - ? unsupportedTestMsg - : null, + canaryFeatures == true + ? unsupportedTestMsg + : null, ); test( @@ -278,9 +279,9 @@ void runTests({ }, skip: provider.ddcModuleFormat == ModuleFormat.ddc && - canaryFeatures == true - ? unsupportedTestMsg - : null, + canaryFeatures == true + ? unsupportedTestMsg + : null, ); test( @@ -298,9 +299,9 @@ void runTests({ }, skip: provider.ddcModuleFormat == ModuleFormat.ddc && - canaryFeatures == true - ? unsupportedTestMsg - : null, + canaryFeatures == true + ? unsupportedTestMsg + : null, ); test( @@ -318,9 +319,9 @@ void runTests({ }, skip: provider.ddcModuleFormat == ModuleFormat.ddc && - canaryFeatures == true - ? unsupportedTestMsg - : null, + canaryFeatures == true + ? unsupportedTestMsg + : null, ); }); @@ -333,10 +334,9 @@ void runTests({ final classRef = instance.classRef!; expect(classRef, isNotNull); expect(classRef.name, 'MyTestClass'); - final boundFieldNames = - instance.fields! - .map((boundField) => boundField.decl!.name) - .toList(); + final boundFieldNames = instance.fields! + .map((boundField) => boundField.decl!.name) + .toList(); expect(boundFieldNames, [ '_privateField', 'abstractField', @@ -347,8 +347,9 @@ void runTests({ 'notFinal', 'tornOff', ]); - final fieldNames = - instance.fields!.map((boundField) => boundField.name).toList(); + final fieldNames = instance.fields! + .map((boundField) => boundField.name) + .toList(); expect(boundFieldNames, fieldNames); for (final field in instance.fields!) { expect(field.name, isNotNull); @@ -446,9 +447,9 @@ void runTests({ }, skip: provider.ddcModuleFormat == ModuleFormat.ddc && - canaryFeatures == true - ? unsupportedTestMsg - : null, + canaryFeatures == true + ? unsupportedTestMsg + : null, ); test( @@ -466,9 +467,9 @@ void runTests({ }, skip: provider.ddcModuleFormat == ModuleFormat.ddc && - canaryFeatures == true - ? unsupportedTestMsg - : null, + canaryFeatures == true + ? unsupportedTestMsg + : null, ); test( @@ -486,9 +487,9 @@ void runTests({ }, skip: provider.ddcModuleFormat == ModuleFormat.ddc && - canaryFeatures == true - ? unsupportedTestMsg - : null, + canaryFeatures == true + ? unsupportedTestMsg + : null, ); test( @@ -506,9 +507,9 @@ void runTests({ }, skip: provider.ddcModuleFormat == ModuleFormat.ddc && - canaryFeatures == true - ? unsupportedTestMsg - : null, + canaryFeatures == true + ? unsupportedTestMsg + : null, ); }); }); diff --git a/dwds/test/package_uri_mapper_test.dart b/dwds/test/package_uri_mapper_test.dart index 179e3a91a..2ad85d089 100644 --- a/dwds/test/package_uri_mapper_test.dart +++ b/dwds/test/package_uri_mapper_test.dart @@ -28,10 +28,9 @@ void main() { path: '${project.packageName}/test_library.dart', ); - final serverPath = - useDebuggerModuleNames - ? 'packages/${project.packageDirectory}/lib/test_library.dart' - : '/packages/${project.packageName}/test_library.dart'; + final serverPath = useDebuggerModuleNames + ? 'packages/${project.packageDirectory}/lib/test_library.dart' + : '/packages/${project.packageName}/test_library.dart'; final resolvedPath = '${project.packageDirectory}/lib/test_library.dart'; diff --git a/dwds/test/puppeteer/extension_common.dart b/dwds/test/puppeteer/extension_common.dart index ed545e79c..11b28962e 100644 --- a/dwds/test/puppeteer/extension_common.dart +++ b/dwds/test/puppeteer/extension_common.dart @@ -142,8 +142,9 @@ void testAll({required bool isMV3, required bool screenshotsEnabled}) { test('DevTools is opened with the correct query parameters', () async { final appUrl = context.appUrl; - final devToolsUrlFragment = - useSse ? 'debugger?uri=sse' : 'debugger?uri=ws'; + final devToolsUrlFragment = useSse + ? 'debugger?uri=sse' + : 'debugger?uri=ws'; // Navigate to the Dart app: final appTab = await navigateToPage( browser, @@ -178,8 +179,9 @@ void testAll({required bool isMV3, required bool screenshotsEnabled}) { 'navigating away from the Dart app while debugging closes DevTools', () async { final appUrl = context.appUrl; - final devToolsUrlFragment = - useSse ? 'debugger?uri=sse' : 'debugger?uri=ws'; + final devToolsUrlFragment = useSse + ? 'debugger?uri=sse' + : 'debugger?uri=ws'; // Navigate to the Dart app: final appTab = await navigateToPage( browser, @@ -212,8 +214,9 @@ void testAll({required bool isMV3, required bool screenshotsEnabled}) { test('closing the Dart app while debugging closes DevTools', () async { final appUrl = context.appUrl; - final devToolsUrlFragment = - useSse ? 'debugger?uri=sse' : 'debugger?uri=ws'; + final devToolsUrlFragment = useSse + ? 'debugger?uri=sse' + : 'debugger?uri=ws'; // Navigate to the Dart app: final appTab = await navigateToPage( browser, @@ -240,8 +243,9 @@ void testAll({required bool isMV3, required bool screenshotsEnabled}) { test('Clicking extension icon while debugging shows warning', () async { final appUrl = context.appUrl; - final devToolsUrlFragment = - useSse ? 'debugger?uri=sse' : 'debugger?uri=ws'; + final devToolsUrlFragment = useSse + ? 'debugger?uri=sse' + : 'debugger?uri=ws'; // Navigate to the Dart app: final appTab = await navigateToPage( browser, @@ -321,8 +325,9 @@ void testAll({required bool isMV3, required bool screenshotsEnabled}) { 'Refreshing the Dart app does not open a new Dart DevTools', () async { final appUrl = context.appUrl; - final devToolsUrlFragment = - useSse ? 'debugger?uri=sse' : 'debugger?uri=ws'; + final devToolsUrlFragment = useSse + ? 'debugger?uri=sse' + : 'debugger?uri=ws'; // Navigate to the Dart app: final appTab = await navigateToPage( browser, @@ -876,8 +881,9 @@ Future _clickLaunchButton(Browser browser, {required Panel panel}) async { } Future _getPanelPage(Browser browser, {required Panel panel}) async { - final panelName = - panel == Panel.inspector ? 'inspector_panel' : 'debugger_panel'; + final panelName = panel == Panel.inspector + ? 'inspector_panel' + : 'debugger_panel'; var panelTarget = browser.targets.firstWhereOrNull( (target) => target.url.contains(panelName), ); diff --git a/dwds/test/puppeteer/test_utils.dart b/dwds/test/puppeteer/test_utils.dart index 16a659c4c..dbb576c90 100644 --- a/dwds/test/puppeteer/test_utils.dart +++ b/dwds/test/puppeteer/test_utils.dart @@ -45,15 +45,14 @@ Future setUpExtensionTest( isInternalBuild: isInternalBuild, workspaceName: workspaceName, ), - debugSettings: - serveDevTools - ? TestDebugSettings.withDevTools( - context, - ).copyWith(enableDebugExtension: true, useSse: useSse) - : TestDebugSettings.noDevTools().copyWith( - enableDebugExtension: true, - useSse: useSse, - ), + debugSettings: serveDevTools + ? TestDebugSettings.withDevTools( + context, + ).copyWith(enableDebugExtension: true, useSse: useSse) + : TestDebugSettings.noDevTools().copyWith( + enableDebugExtension: true, + useSse: useSse, + ), ); return await puppeteer.launch( devTools: openChromeDevTools, @@ -170,8 +169,9 @@ Future navigateToPage( required String url, bool isNew = false, }) async { - final page = - isNew ? await browser.newPage() : await _getPageForUrl(browser, url: url); + final page = isNew + ? await browser.newPage() + : await _getPageForUrl(browser, url: url); if (isNew) { await page.goto(url, wait: Until.domContentLoaded); } @@ -239,7 +239,8 @@ Future _clearStorage({Worker? worker, Page? backgroundPage}) async { ).catchError((_) {}); } -String _clickIconJs({bool isMV3 = false}) => ''' +String _clickIconJs({bool isMV3 = false}) => + ''' async () => { const activeTabs = await chrome.tabs.query({ active: true }, (tabs) => { const tab = tabs[0]; @@ -248,7 +249,8 @@ String _clickIconJs({bool isMV3 = false}) => ''' } '''; -String _clearStorageJs({required bool isMV3}) => ''' +String _clearStorageJs({required bool isMV3}) => + ''' async () => { await chrome.storage.local.clear(); ${isMV3 ? 'await chrome.storage.session.clear();' : ''} diff --git a/dwds/test/variable_scope_test.dart b/dwds/test/variable_scope_test.dart index 22880ec8e..7f56319c3 100644 --- a/dwds/test/variable_scope_test.dart +++ b/dwds/test/variable_scope_test.dart @@ -200,8 +200,9 @@ void main() { await expectDartVariables(variables); final variableNames = variables.keys.toList()..sort(); - final variableValues = - variableNames.map((name) => variables[name]?.valueAsString).toList(); + final variableValues = variableNames + .map((name) => variables[name]?.valueAsString) + .toList(); expect(variableNames, containsAll(['myLocal', 'value'])); expect(variableValues, containsAll(['a local value', 'arg1'])); }); @@ -212,8 +213,9 @@ void main() { await expectDartVariables(variables); final variableNames = variables.keys.toList()..sort(); - final variableValues = - variableNames.map((name) => variables[name]?.valueAsString).toList(); + final variableValues = variableNames + .map((name) => variables[name]?.valueAsString) + .toList(); expect(variableNames, containsAll(['i', 'myLocal', 'value'])); // Ensure the loop variable, i, is captued correctly. The value from the // first iteration should be captured by the saved closure. diff --git a/dwds/web/client.dart b/dwds/web/client.dart index 2aefcdfd9..48764812c 100644 --- a/dwds/web/client.dart +++ b/dwds/web/client.dart @@ -49,12 +49,9 @@ Future? main() { final fixedPath = _fixProtocol(dwdsDevHandlerPath); final fixedUri = Uri.parse(fixedPath); - final client = - fixedUri.isScheme('ws') || fixedUri.isScheme('wss') - ? WebSocketClient(WebSocketChannel.connect(fixedUri)) - : SseSocketClient( - SseClient(fixedPath, debugKey: 'InjectedClient'), - ); + final client = fixedUri.isScheme('ws') || fixedUri.isScheme('wss') + ? WebSocketClient(WebSocketChannel.connect(fixedUri)) + : SseSocketClient(SseClient(fixedPath, debugKey: 'InjectedClient')); final restarter = switch (dartModuleStrategy) { 'require-js' => await RequireRestarter.create(), @@ -65,40 +62,36 @@ Future? main() { final manager = ReloadingManager(client, restarter); - hotReloadStartJs = - () { - return manager.hotReloadStart(hotReloadSourcesPath).toJS; - }.toJS; + hotReloadStartJs = () { + return manager.hotReloadStart(hotReloadSourcesPath).toJS; + }.toJS; - hotReloadEndJs = - () { - return manager.hotReloadEnd().toJS; - }.toJS; + hotReloadEndJs = () { + return manager.hotReloadEnd().toJS; + }.toJS; Completer? readyToRunMainCompleter; - hotRestartJs = - (String runId, [bool? pauseIsolatesOnStart]) { - if (pauseIsolatesOnStart ?? false) { - readyToRunMainCompleter = Completer(); - return manager - .hotRestart( - runId: runId, - readyToRunMain: readyToRunMainCompleter!.future, - ) - .toJS; - } else { - return manager.hotRestart(runId: runId).toJS; - } - }.toJS; + hotRestartJs = (String runId, [bool? pauseIsolatesOnStart]) { + if (pauseIsolatesOnStart ?? false) { + readyToRunMainCompleter = Completer(); + return manager + .hotRestart( + runId: runId, + readyToRunMain: readyToRunMainCompleter!.future, + ) + .toJS; + } else { + return manager.hotRestart(runId: runId).toJS; + } + }.toJS; - readyToRunMainJs = - () { - if (readyToRunMainCompleter == null) return; - if (readyToRunMainCompleter!.isCompleted) return; - readyToRunMainCompleter!.complete(); - readyToRunMainCompleter = null; - }.toJS; + readyToRunMainJs = () { + if (readyToRunMainCompleter == null) return; + if (readyToRunMainCompleter!.isCompleted) return; + readyToRunMainCompleter!.complete(); + readyToRunMainCompleter = null; + }.toJS; final debugEventController = BatchedStreamController( delay: _batchDelayMilliseconds, @@ -118,61 +111,55 @@ Future? main() { } }); - emitDebugEvent = - (String kind, String eventData) { - if (dartEmitDebugEvents) { - _trySendEvent( - debugEventController.sink, - DebugEvent( - (b) => - b - ..timestamp = (DateTime.now().millisecondsSinceEpoch) - ..kind = kind - ..eventData = eventData, - ), - ); - } - }.toJS; - - emitRegisterEvent = - (String eventData) { - _trySendEvent( - client.sink, - jsonEncode( - serializers.serialize( - RegisterEvent( - (b) => - b - ..timestamp = (DateTime.now().millisecondsSinceEpoch) - ..eventData = eventData, - ), - ), + emitDebugEvent = (String kind, String eventData) { + if (dartEmitDebugEvents) { + _trySendEvent( + debugEventController.sink, + DebugEvent( + (b) => b + ..timestamp = (DateTime.now().millisecondsSinceEpoch) + ..kind = kind + ..eventData = eventData, + ), + ); + } + }.toJS; + + emitRegisterEvent = (String eventData) { + _trySendEvent( + client.sink, + jsonEncode( + serializers.serialize( + RegisterEvent( + (b) => b + ..timestamp = (DateTime.now().millisecondsSinceEpoch) + ..eventData = eventData, ), - ); - }.toJS; - - launchDevToolsJs = - () { - if (!_isChromium) { - window.alert( - 'Dart DevTools is only supported on Chromium based browsers.', - ); - return; - } - _trySendEvent( - client.sink, - jsonEncode( - serializers.serialize( - DevToolsRequest( - (b) => - b - ..appId = dartAppId - ..instanceId = dartAppInstanceId, - ), - ), + ), + ), + ); + }.toJS; + + launchDevToolsJs = () { + if (!_isChromium) { + window.alert( + 'Dart DevTools is only supported on Chromium based browsers.', + ); + return; + } + _trySendEvent( + client.sink, + jsonEncode( + serializers.serialize( + DevToolsRequest( + (b) => b + ..appId = dartAppId + ..instanceId = dartAppInstanceId, ), - ); - }.toJS; + ), + ), + ); + }.toJS; client.stream.listen( (serialized) async { @@ -291,11 +278,10 @@ void _sendConnectRequest(StreamSink clientSink) { jsonEncode( serializers.serialize( ConnectRequest( - (b) => - b - ..appId = dartAppId - ..instanceId = dartAppInstanceId - ..entrypointPath = dartEntrypointPath, + (b) => b + ..appId = dartAppId + ..instanceId = dartAppInstanceId + ..entrypointPath = dartEntrypointPath, ), ), ), @@ -330,18 +316,17 @@ void _launchCommunicationWithDebugExtension() { final debugInfoJson = jsonEncode( serializers.serialize( DebugInfo( - (b) => - b - ..appEntrypointPath = dartEntrypointPath - ..appId = windowContext.$dartAppId - ..appInstanceId = dartAppInstanceId - ..appOrigin = window.location.origin - ..appUrl = window.location.href - ..authUrl = _authUrl - ..extensionUrl = windowContext.$dartExtensionUri - ..isInternalBuild = windowContext.$isInternalBuild - ..isFlutterApp = windowContext.$isFlutterApp - ..workspaceName = dartWorkspaceName, + (b) => b + ..appEntrypointPath = dartEntrypointPath + ..appId = windowContext.$dartAppId + ..appInstanceId = dartAppInstanceId + ..appOrigin = window.location.origin + ..appUrl = window.location.href + ..authUrl = _authUrl + ..extensionUrl = windowContext.$dartExtensionUri + ..isInternalBuild = windowContext.$isInternalBuild + ..isFlutterApp = windowContext.$isFlutterApp + ..workspaceName = dartWorkspaceName, ), ), ); diff --git a/dwds/web/reloader/ddc_library_bundle_restarter.dart b/dwds/web/reloader/ddc_library_bundle_restarter.dart index 0f4ee3021..b6f7ed325 100644 --- a/dwds/web/reloader/ddc_library_bundle_restarter.dart +++ b/dwds/web/reloader/ddc_library_bundle_restarter.dart @@ -81,11 +81,10 @@ class DdcLibraryBundleRestarter implements Restarter { @override Future restart({String? runId, Future? readyToRunMain}) async { await _dartDevEmbedder.debugger.maybeInvokeFlutterDisassemble(); - final mainHandler = - (JSFunction runMain) { - _dartDevEmbedder.config.capturedMainHandler = null; - safeUnawaited(_runMainWhenReady(readyToRunMain, runMain)); - }.toJS; + final mainHandler = (JSFunction runMain) { + _dartDevEmbedder.config.capturedMainHandler = null; + safeUnawaited(_runMainWhenReady(readyToRunMain, runMain)); + }.toJS; _dartDevEmbedder.config.capturedMainHandler = mainHandler; await _dartDevEmbedder.hotRestart().toDart; return true; @@ -96,14 +95,13 @@ class DdcLibraryBundleRestarter implements Restarter { final completer = Completer(); final xhr = _XMLHttpRequest(); xhr.withCredentials = true; - xhr.onreadystatechange = - () { - // If the request has completed and OK, or the response has not - // changed. - if (xhr.readyState == 4 && xhr.status == 200 || xhr.status == 304) { - completer.complete(xhr.responseText); - } - }.toJS; + xhr.onreadystatechange = () { + // If the request has completed and OK, or the response has not + // changed. + if (xhr.readyState == 4 && xhr.status == 200 || xhr.status == 304) { + completer.complete(xhr.responseText); + } + }.toJS; xhr.get(hotReloadSourcesPath, true); xhr.send(); final responseText = await completer.future; @@ -114,8 +112,8 @@ class DdcLibraryBundleRestarter implements Restarter { for (final srcModuleLibrary in srcModuleLibraries) { final srcModuleLibraryCast = srcModuleLibrary.cast(); final src = srcModuleLibraryCast['src'] as String; - final libraries = - (srcModuleLibraryCast['libraries'] as List).cast(); + final libraries = (srcModuleLibraryCast['libraries'] as List) + .cast(); filesToLoad.push(src.toJS); for (final library in libraries) { librariesToReload.push(library.toJS); @@ -146,16 +144,15 @@ class DdcLibraryBundleRestarter implements Restarter { await _dartDevEmbedder.debugger.maybeInvokeFlutterReassemble(); return {'status': 'reassemble invoked'}; } else if (method == 'getExtensionRpcs') { - final rpcs = - _dartDevEmbedder.debugger.extensionNames.toDart.cast(); + final rpcs = _dartDevEmbedder.debugger.extensionNames.toDart + .cast(); return {'rpcs': rpcs}; } else { // For other extension methods, delegate to the debugger final params = args.isNotEmpty ? jsonEncode(args) : '{}'; - final resultJson = - await _dartDevEmbedder.debugger - .invokeExtension(method, params) - .toDart; + final resultJson = await _dartDevEmbedder.debugger + .invokeExtension(method, params) + .toDart; return jsonDecode(resultJson.toDart) as Map; } } diff --git a/dwds/web/reloader/ddc_restarter.dart b/dwds/web/reloader/ddc_restarter.dart index ca324f540..227b70570 100644 --- a/dwds/web/reloader/ddc_restarter.dart +++ b/dwds/web/reloader/ddc_restarter.dart @@ -41,10 +41,9 @@ class DdcRestarter implements Restarter { } @override - Future hotReloadEnd() => - throw UnimplementedError( - 'Hot reload is not supported for the DDC module format.', - ); + Future hotReloadEnd() => throw UnimplementedError( + 'Hot reload is not supported for the DDC module format.', + ); @override Future> hotReloadStart(String hotReloadSourcesPath) => diff --git a/dwds/web/reloader/require_restarter.dart b/dwds/web/reloader/require_restarter.dart index 88cc5b98e..7cc295301 100644 --- a/dwds/web/reloader/require_restarter.dart +++ b/dwds/web/reloader/require_restarter.dart @@ -162,10 +162,9 @@ class RequireRestarter implements Restarter { } @override - Future hotReloadEnd() => - throw UnimplementedError( - 'Hot reload is not supported for the AMD module format.', - ); + Future hotReloadEnd() => throw UnimplementedError( + 'Hot reload is not supported for the AMD module format.', + ); @override Future> hotReloadStart(String hotReloadSourcesPath) => @@ -246,10 +245,9 @@ class RequireRestarter implements Restarter { // The bootstrap module is not reloaded but we need to update the // $dartRunMain reference to the newly loaded child module. // ignore: unnecessary_lambdas - dartRunMain = - () { - dart.getMainLibrary(previousModuleId).main(); - }.toJS; + dartRunMain = () { + dart.getMainLibrary(previousModuleId).main(); + }.toJS; } else { ++reloadedModules; await _reloadModule(moduleId); diff --git a/dwds/web/run_main.dart b/dwds/web/run_main.dart index 61c92a87b..70fcb5a09 100644 --- a/dwds/web/run_main.dart +++ b/dwds/web/run_main.dart @@ -25,26 +25,25 @@ String? _findNonce() { /// Creates a script that will run properly when strict CSP is enforced. /// /// More specifically, the script has the correct `nonce` value set. -final HTMLElement Function() _createScript = - (() { - final nonce = _findNonce(); +final HTMLElement Function() _createScript = (() { + final nonce = _findNonce(); - if (nonce == null) { - return () => document.createElement('script') as HTMLElement; - } - return () { - final scriptElement = document.createElement('script') as HTMLElement; - return scriptElement..setAttribute('nonce', nonce); - }; - })(); + if (nonce == null) { + return () => document.createElement('script') as HTMLElement; + } + return () { + final scriptElement = document.createElement('script') as HTMLElement; + return scriptElement..setAttribute('nonce', nonce); + }; +})(); /// Runs `window.$dartRunMain()` by injecting a script tag. /// /// We do this so that we don't see user exceptions bubble up in our own error /// handling zone. void runMain() { - final scriptElement = - _createScript()..innerHTML = r'window.$dartRunMain();'.toJS; + final scriptElement = _createScript() + ..innerHTML = r'window.$dartRunMain();'.toJS; document.body!.append(scriptElement.jsify()!); // External tear-offs are not allowed. // ignore: unnecessary_lambdas diff --git a/frontend_server_client/CHANGELOG.md b/frontend_server_client/CHANGELOG.md index 0530b11b4..c32f0b796 100644 --- a/frontend_server_client/CHANGELOG.md +++ b/frontend_server_client/CHANGELOG.md @@ -1,3 +1,7 @@ +## 4.0.1-wip + +- Update Dart SDK constraint to `^3.8.0`. + ## 4.0.0 - Update Dart SDK constraint to `^3.0.0`. diff --git a/frontend_server_client/example/vm_client.dart b/frontend_server_client/example/vm_client.dart index 303337da5..d10cd4db1 100644 --- a/frontend_server_client/example/vm_client.dart +++ b/frontend_server_client/example/vm_client.dart @@ -19,13 +19,14 @@ void main(List args) async { } final client = await FrontendServerClient.start( - 'org-dartlang-root:///$app', - outputDill, - p.join(sdkDir, 'lib', '_internal', 'vm_platform_strong.dill'), - target: 'vm', - fileSystemRoots: [p.url.current], - fileSystemScheme: 'org-dartlang-root', - verbose: true); + 'org-dartlang-root:///$app', + outputDill, + p.join(sdkDir, 'lib', '_internal', 'vm_platform_strong.dill'), + target: 'vm', + fileSystemRoots: [p.url.current], + fileSystemScheme: 'org-dartlang-root', + verbose: true, + ); _print('compiling $app'); var result = await client.compile(); client.accept(); @@ -33,30 +34,33 @@ void main(List args) async { Process appProcess; final vmServiceCompleter = Completer(); - appProcess = await Process.start(Platform.resolvedExecutable, - ['--enable-vm-service', result.dillOutput!]); + appProcess = await Process.start(Platform.resolvedExecutable, [ + '--enable-vm-service', + result.dillOutput!, + ]); final sawHelloWorld = Completer(); appProcess.stdout .transform(utf8.decoder) .transform(const LineSplitter()) .listen((line) { - stdout.writeln('APP -> $line'); - if (line == 'hello/world') { - sawHelloWorld.complete(); - } - if (line.startsWith( - 'The Dart DevTools debugger and profiler is available at:')) { - final observatoryUri = - '${line.split(' ').last.replaceFirst('http', 'ws')}ws'; - vmServiceCompleter.complete(vmServiceConnectUri(observatoryUri)); - } - }); + stdout.writeln('APP -> $line'); + if (line == 'hello/world') { + sawHelloWorld.complete(); + } + if (line.startsWith( + 'The Dart DevTools debugger and profiler is available at:', + )) { + final observatoryUri = + '${line.split(' ').last.replaceFirst('http', 'ws')}ws'; + vmServiceCompleter.complete(vmServiceConnectUri(observatoryUri)); + } + }); appProcess.stderr .transform(utf8.decoder) .transform(const LineSplitter()) .listen((line) { - stderr.writeln('APP -> $line'); - }); + stderr.writeln('APP -> $line'); + }); final vmService = await vmServiceCompleter.future; await sawHelloWorld.future; @@ -73,16 +77,21 @@ void main(List args) async { _print('done recompiling $app'); _print('reloading $app'); final vm = await vmService.getVM(); - await vmService.reloadSources(vm.isolates!.first.id!, - rootLibUri: result.dillOutput!); + await vmService.reloadSources( + vm.isolates!.first.id!, + rootLibUri: result.dillOutput!, + ); _print('restoring $app to original contents'); await appFile.writeAsString(originalContent); _print('exiting'); - await client.shutdown().timeout(const Duration(seconds: 1), onTimeout: () { - client.kill(); - return 1; - }); + await client.shutdown().timeout( + const Duration(seconds: 1), + onTimeout: () { + client.kill(); + return 1; + }, + ); } finally { Directory(p.join('.dart_tool', 'out')).deleteSync(recursive: true); } diff --git a/frontend_server_client/example/web_client.dart b/frontend_server_client/example/web_client.dart index 94e2b8142..c8cdedabf 100644 --- a/frontend_server_client/example/web_client.dart +++ b/frontend_server_client/example/web_client.dart @@ -33,19 +33,23 @@ void main(List args) async { p.url.join(sdkDir, sdkKernelPath), ]); if (sdkCompileResult.exitCode != 0) { - _print('Failed to compile the dart sdk to JS:\n' - '${sdkCompileResult.stdout}\n' - '${sdkCompileResult.stderr}'); + _print( + 'Failed to compile the dart sdk to JS:\n' + '${sdkCompileResult.stdout}\n' + '${sdkCompileResult.stderr}', + ); exit(sdkCompileResult.exitCode); } _print('starting frontend server'); final client = await DartDevcFrontendServerClient.start( - 'org-dartlang-root:///$app', outputDill, - fileSystemRoots: [p.current], - fileSystemScheme: 'org-dartlang-root', - platformKernel: p.toUri(sdkKernelPath).toString(), - verbose: true); + 'org-dartlang-root:///$app', + outputDill, + fileSystemRoots: [p.current], + fileSystemScheme: 'org-dartlang-root', + platformKernel: p.toUri(sdkKernelPath).toString(), + verbose: true, + ); _print('compiling $app'); await client.compile([]); @@ -57,13 +61,24 @@ void main(List args) async { .add(_clientHandler(client)) .add(createStaticHandler(p.current)) .add(createFileHandler(dartSdkJs, url: 'example/app/dart_sdk.js')) - .add(createFileHandler( - p.join(sdkDir, 'lib', 'dev_compiler', 'web', - 'dart_stack_trace_mapper.js'), - url: 'example/app/dart_stack_trace_mapper.js')) - .add(createFileHandler( + .add( + createFileHandler( + p.join( + sdkDir, + 'lib', + 'dev_compiler', + 'web', + 'dart_stack_trace_mapper.js', + ), + url: 'example/app/dart_stack_trace_mapper.js', + ), + ) + .add( + createFileHandler( p.join(sdkDir, 'lib', 'dev_compiler', 'amd', 'require.js'), - url: 'example/app/require.js')) + url: 'example/app/require.js', + ), + ) .add(packagesDirHandler()); final server = await shelf_io.serve(cascade.handler, 'localhost', 8080); _print('server ready'); @@ -73,11 +88,13 @@ void main(List args) async { final originalContent = await appFile.readAsString(); final appLines = const LineSplitter().convert(originalContent); final getterText = 'String get message =>'; - final messageLine = - appLines.indexWhere((line) => line.startsWith(getterText)); + final messageLine = appLines.indexWhere( + (line) => line.startsWith(getterText), + ); final stdinQueue = StreamQueue( - stdin.transform(utf8.decoder).transform(const LineSplitter())); + stdin.transform(utf8.decoder).transform(const LineSplitter()), + ); _prompt(); while (await stdinQueue.hasNext) { final newMessage = await stdinQueue.next; @@ -97,8 +114,9 @@ void main(List args) async { await appFile.writeAsString(newContent); _print('recompiling $app with edits'); - final result = - await client.compile([Uri.parse('org-dartlang-root:///$app')]); + final result = await client.compile([ + Uri.parse('org-dartlang-root:///$app'), + ]); if (result.errorCount > 0) { print('Compile errors: \n${result.compilerOutputLines.join('\n')}'); await client.reject(); @@ -137,8 +155,10 @@ Handler _clientHandler(DartDevcFrontendServerClient client) { } final assetBytes = client.assetBytes(path); if (assetBytes == null) return Response.notFound('path not found'); - return Response.ok(assetBytes, - headers: {HttpHeaders.contentTypeHeader: 'application/javascript'}); + return Response.ok( + assetBytes, + headers: {HttpHeaders.contentTypeHeader: 'application/javascript'}, + ); }; } @@ -147,7 +167,8 @@ void _print(String message) { } void _prompt() => stdout.write( - 'Enter a new message to print and recompile, or type `quit` to exit:'); + 'Enter a new message to print and recompile, or type `quit` to exit:', +); final app = 'example/app/main.dart'; final dartSdkJs = p.join('.dart_tool', 'out', 'dart_sdk.js'); diff --git a/frontend_server_client/lib/src/dartdevc_frontend_server_client.dart b/frontend_server_client/lib/src/dartdevc_frontend_server_client.dart index 15e78cd02..f87c85145 100644 --- a/frontend_server_client/lib/src/dartdevc_frontend_server_client.dart +++ b/frontend_server_client/lib/src/dartdevc_frontend_server_client.dart @@ -41,16 +41,19 @@ class DartDevcFrontendServerClient implements FrontendServerClient { final String? _mainModuleJs; DartDevcFrontendServerClient._( - this._frontendServerClient, this._entrypoint, String moduleFormat) - : _bootstrapJs = moduleFormat == 'amd' - ? generateAmdBootstrapScript( - requireUrl: 'require.js', - mapperUrl: 'dart_stack_trace_mapper.js', - entrypoint: _entrypoint) - : null, - _mainModuleJs = moduleFormat == 'amd' - ? generateAmdMainModule(entrypoint: _entrypoint) - : null { + this._frontendServerClient, + this._entrypoint, + String moduleFormat, + ) : _bootstrapJs = moduleFormat == 'amd' + ? generateAmdBootstrapScript( + requireUrl: 'require.js', + mapperUrl: 'dart_stack_trace_mapper.js', + entrypoint: _entrypoint, + ) + : null, + _mainModuleJs = moduleFormat == 'amd' + ? generateAmdMainModule(entrypoint: _entrypoint) + : null { _resetAssets(); } @@ -86,7 +89,10 @@ class DartDevcFrontendServerClient implements FrontendServerClient { verbose: verbose, ); return DartDevcFrontendServerClient._( - feServer, Uri.parse(entrypoint).path, dartdevcModuleFormat); + feServer, + Uri.parse(entrypoint).path, + dartdevcModuleFormat, + ); } /// Returns the current bytes for the asset at [path]. @@ -121,11 +127,15 @@ class DartDevcFrontendServerClient implements FrontendServerClient { for (final entry in manifest.entries) { final metadata = entry.value as Map; final sourceOffsets = metadata['code'] as List; - _assets[entry.key] = - sourceBytes.sublist(sourceOffsets[0] as int, sourceOffsets[1] as int); + _assets[entry.key] = sourceBytes.sublist( + sourceOffsets[0] as int, + sourceOffsets[1] as int, + ); final sourceMapOffsets = metadata['sourcemap'] as List; _assets['${entry.key}.map'] = sourceMapBytes.sublist( - sourceMapOffsets[0] as int, sourceMapOffsets[1] as int); + sourceMapOffsets[0] as int, + sourceMapOffsets[1] as int, + ); } } @@ -142,9 +152,9 @@ class DartDevcFrontendServerClient implements FrontendServerClient { required String klass, required String libraryUri, required List typeDefinitions, - }) => - throw UnsupportedError( - 'Use `compileExpressionToJs` for dartdevc based clients'); + }) => throw UnsupportedError( + 'Use `compileExpressionToJs` for dartdevc based clients', + ); @override Future compileExpressionToJs({ @@ -155,15 +165,15 @@ class DartDevcFrontendServerClient implements FrontendServerClient { required String libraryUri, required int line, required String moduleName, - }) => - _frontendServerClient.compileExpressionToJs( - expression: expression, - column: column, - jsFrameValues: jsFrameValues, - jsModules: jsModules, - libraryUri: libraryUri, - line: line, - moduleName: moduleName); + }) => _frontendServerClient.compileExpressionToJs( + expression: expression, + column: column, + jsFrameValues: jsFrameValues, + jsModules: jsModules, + libraryUri: libraryUri, + line: line, + moduleName: moduleName, + ); @override void accept() { @@ -201,11 +211,13 @@ class DartDevcFrontendServerClient implements FrontendServerClient { } final mainModuleJs = _mainModuleJs; if (mainModuleJs != null) { - _assets['$_entrypoint.bootstrap.js'] = - Uint8List.fromList(utf8.encode(mainModuleJs)); + _assets['$_entrypoint.bootstrap.js'] = Uint8List.fromList( + utf8.encode(mainModuleJs), + ); } } } -final _dartdevcPlatformKernel = - p.toUri(p.join(sdkDir, 'lib', '_internal', 'ddc_sdk.dill')).toString(); +final _dartdevcPlatformKernel = p + .toUri(p.join(sdkDir, 'lib', '_internal', 'ddc_sdk.dill')) + .toString(); diff --git a/frontend_server_client/lib/src/frontend_server_client.dart b/frontend_server_client/lib/src/frontend_server_client.dart index f53ada854..a2dbd7247 100644 --- a/frontend_server_client/lib/src/frontend_server_client.dart +++ b/frontend_server_client/lib/src/frontend_server_client.dart @@ -21,10 +21,12 @@ class FrontendServerClient { _ClientState _state; FrontendServerClient._( - this._entrypoint, this._feServer, this._feServerStdoutLines, - {bool? verbose}) - : _verbose = verbose ?? false, - _state = _ClientState.waitingForFirstCompile { + this._entrypoint, + this._feServer, + this._feServerStdoutLines, { + bool? verbose, + }) : _verbose = verbose ?? false, + _state = _ClientState.waitingForFirstCompile { _feServer.stderr.transform(utf8.decoder).listen(stderr.write); } @@ -89,49 +91,39 @@ class FrontendServerClient { if (enabledExperiments != null) for (final experiment in enabledExperiments) '--enable-experiment=$experiment', - for (final source in additionalSources) ...[ - '--source', - source, - ], - if (nativeAssets != null) ...[ - '--native-assets', - nativeAssets, - ], + for (final source in additionalSources) ...['--source', source], + if (nativeAssets != null) ...['--native-assets', nativeAssets], ]; late final Process feServer; if (frontendServerPath != null) { - feServer = await Process.start( - Platform.resolvedExecutable, - [ - if (debug) '--observe', - frontendServerPath, - ...commonArguments, - ], - ); + feServer = await Process.start(Platform.resolvedExecutable, [ + if (debug) '--observe', + frontendServerPath, + ...commonArguments, + ]); } else if (File(_feServerAotSnapshotPath).existsSync()) { if (debug) { - throw ArgumentError('The debug argument cannot be set to true when the ' - 'frontendServerPath argument is omitted.'); + throw ArgumentError( + 'The debug argument cannot be set to true when the ' + 'frontendServerPath argument is omitted.', + ); } - feServer = await Process.start( - _dartAotRuntimePath, - [_feServerAotSnapshotPath, ...commonArguments], - ); + feServer = await Process.start(_dartAotRuntimePath, [ + _feServerAotSnapshotPath, + ...commonArguments, + ]); } else { // AOT snapshots cannot be generated on IA32, so we need this fallback // branch until support for IA32 is dropped (https://dartbug.com/49969). - feServer = await Process.start( - Platform.resolvedExecutable, - [ - if (debug) '--observe', - _feServerAppJitSnapshotPath, - ...commonArguments, - ], - ); + feServer = await Process.start(Platform.resolvedExecutable, [ + if (debug) '--observe', + _feServerAppJitSnapshotPath, + ...commonArguments, + ]); } - final feServerStdoutLines = StreamQueue(feServer.stdout - .transform(utf8.decoder) - .transform(const LineSplitter())); + final feServerStdoutLines = StreamQueue( + feServer.stdout.transform(utf8.decoder).transform(const LineSplitter()), + ); // The frontend_server doesn't appear to recursively create files, so we // need to make sure the output dir already exists. @@ -162,16 +154,20 @@ class FrontendServerClient { break; case _ClientState.waitingForAcceptOrReject: throw StateError( - 'Previous `CompileResult` must be accepted or rejected by ' - 'calling `accept` or `reject`.'); + 'Previous `CompileResult` must be accepted or rejected by ' + 'calling `accept` or `reject`.', + ); case _ClientState.compiling: throw StateError( - 'App is already being compiled, you must wait for that to ' - 'complete and `accept` or `reject` the result before compiling ' - 'again.'); + 'App is already being compiled, you must wait for that to ' + 'complete and `accept` or `reject` the result before compiling ' + 'again.', + ); case _ClientState.rejecting: - throw StateError('Still waiting for previous `reject` call to finish. ' - 'You must await that before compiling again.'); + throw StateError( + 'Still waiting for previous `reject` call to finish. ' + 'You must await that before compiling again.', + ); } _state = _ClientState.compiling; @@ -180,8 +176,9 @@ class FrontendServerClient { if (action == 'recompile') { if (invalidatedUris == null || invalidatedUris.isEmpty) { throw StateError( - 'Subsequent compile invocations must provide a non-empty list ' - 'of invalidated uris.'); + 'Subsequent compile invocations must provide a non-empty list ' + 'of invalidated uris.', + ); } final boundaryKey = generateUuidV4(); command.writeln(' $boundaryKey'); @@ -199,8 +196,8 @@ class FrontendServerClient { final compilerOutputLines = []; var errorCount = 0; String? outputDillPath; - while ( - state != _CompileState.done && await _feServerStdoutLines.hasNext) { + while (state != _CompileState.done && + await _feServerStdoutLines.hasNext) { final line = await _nextInputLine(); switch (state) { case _CompileState.started: @@ -230,7 +227,8 @@ class FrontendServerClient { removedSources.add(diffUri); } else { throw StateError( - 'unrecognized diff line, should start with a + or - but got: $line'); + 'unrecognized diff line, should start with a + or - but got: $line', + ); } continue; case _CompileState.done: @@ -239,11 +237,12 @@ class FrontendServerClient { } return CompileResult._( - dillOutput: outputDillPath, - errorCount: errorCount, - newSources: newSources, - removedSources: removedSources, - compilerOutputLines: compilerOutputLines); + dillOutput: outputDillPath, + errorCount: errorCount, + newSources: newSources, + removedSources: removedSources, + compilerOutputLines: compilerOutputLines, + ); } finally { _state = _ClientState.waitingForAcceptOrReject; } @@ -257,8 +256,7 @@ class FrontendServerClient { required String klass, required String libraryUri, required List typeDefinitions, - }) => - throw UnimplementedError(); + }) => throw UnimplementedError(); /// TODO: Document Future compileExpressionToJs({ @@ -269,8 +267,7 @@ class FrontendServerClient { required String libraryUri, required int line, required String moduleName, - }) => - throw UnimplementedError(); + }) => throw UnimplementedError(); /// Should be invoked when results of compilation are accepted by the client. /// @@ -278,7 +275,8 @@ class FrontendServerClient { void accept() { if (_state != _ClientState.waitingForAcceptOrReject) { throw StateError( - 'Called `accept` but there was no previous compile to accept.'); + 'Called `accept` but there was no previous compile to accept.', + ); } _sendCommand('accept'); _state = _ClientState.waitingForRecompile; @@ -293,7 +291,8 @@ class FrontendServerClient { Future reject() async { if (_state != _ClientState.waitingForAcceptOrReject) { throw StateError( - 'Called `reject` but there was no previous compile to reject.'); + 'Called `reject` but there was no previous compile to reject.', + ); } _state = _ClientState.rejecting; _sendCommand('reject'); @@ -306,8 +305,9 @@ class FrontendServerClient { case _RejectState.started: if (!line.startsWith('result')) { throw StateError( - 'Expected a line like `result ` after a `reject` ' - 'command, but got:\n$line'); + 'Expected a line like `result ` after a `reject` ' + 'command, but got:\n$line', + ); } boundaryKey = line.split(' ').last; rejectState = _RejectState.waitingForKey; @@ -331,8 +331,9 @@ class FrontendServerClient { void reset() { if (_state == _ClientState.compiling) { throw StateError( - 'Called `reset` during an active compile, you must wait for that to ' - 'complete first.'); + 'Called `reset` during an active compile, you must wait for that to ' + 'complete first.', + ); } _sendCommand('reset'); _state = _ClientState.waitingForRecompile; @@ -376,12 +377,13 @@ class FrontendServerClient { /// The result of a compile call. class CompileResult { - const CompileResult._( - {required this.dillOutput, - required this.compilerOutputLines, - required this.errorCount, - required this.newSources, - required this.removedSources}); + const CompileResult._({ + required this.dillOutput, + required this.compilerOutputLines, + required this.errorCount, + required this.newSources, + required this.removedSources, + }); /// The produced dill output file, this will either be a full dill file, an /// incremental dill file, or `null` if no file was produced. @@ -431,24 +433,23 @@ enum _ClientState { } /// Frontend server interaction states for a `compile` call. -enum _CompileState { - started, - waitingForKey, - gettingSourceDiffs, - done, -} +enum _CompileState { started, waitingForKey, gettingSourceDiffs, done } /// Frontend server interaction states for a `reject` call. -enum _RejectState { - started, - waitingForKey, - done, -} +enum _RejectState { started, waitingForKey, done } final _dartAotRuntimePath = p.join(sdkDir, 'bin', 'dartaotruntime'); -final _feServerAppJitSnapshotPath = - p.join(sdkDir, 'bin', 'snapshots', 'frontend_server.dart.snapshot'); - -final _feServerAotSnapshotPath = - p.join(sdkDir, 'bin', 'snapshots', 'frontend_server_aot.dart.snapshot'); +final _feServerAppJitSnapshotPath = p.join( + sdkDir, + 'bin', + 'snapshots', + 'frontend_server.dart.snapshot', +); + +final _feServerAotSnapshotPath = p.join( + sdkDir, + 'bin', + 'snapshots', + 'frontend_server_aot.dart.snapshot', +); diff --git a/frontend_server_client/pubspec.yaml b/frontend_server_client/pubspec.yaml index 030187f81..95ad25f8a 100644 --- a/frontend_server_client/pubspec.yaml +++ b/frontend_server_client/pubspec.yaml @@ -1,12 +1,12 @@ name: frontend_server_client -version: 4.0.0 +version: 4.0.1-wip description: >- Client code to start and interact with the frontend_server compiler from the Dart SDK. repository: https://github.com/dart-lang/webdev/tree/main/frontend_server_client environment: - sdk: ^3.1.0 + sdk: ^3.8.0 dependencies: async: ^2.5.0 diff --git a/frontend_server_client/test/example/vm_client_test.dart b/frontend_server_client/test/example/vm_client_test.dart index 324011c47..110553391 100644 --- a/frontend_server_client/test/example/vm_client_test.dart +++ b/frontend_server_client/test/example/vm_client_test.dart @@ -13,16 +13,26 @@ import 'package:test_process/test_process.dart'; void main() { test('vm client example can build and rebuild an app', () async { - final process = await TestProcess.start( - Platform.resolvedExecutable, ['run', 'example/vm_client.dart']); - await expectLater(process.stdout, - emitsThrough(contains('done compiling example/app/main.dart'))); + final process = await TestProcess.start(Platform.resolvedExecutable, [ + 'run', + 'example/vm_client.dart', + ]); await expectLater( - process.stdout, emitsThrough(contains('APP -> hello/world'))); - await expectLater(process.stdout, - emitsThrough(contains('done recompiling example/app/main.dart'))); + process.stdout, + emitsThrough(contains('done compiling example/app/main.dart')), + ); await expectLater( - process.stdout, emitsThrough(contains('APP -> goodbye/world'))); + process.stdout, + emitsThrough(contains('APP -> hello/world')), + ); + await expectLater( + process.stdout, + emitsThrough(contains('done recompiling example/app/main.dart')), + ); + await expectLater( + process.stdout, + emitsThrough(contains('APP -> goodbye/world')), + ); expect(await process.exitCode, 0); }); } diff --git a/frontend_server_client/test/example/web_client_test.dart b/frontend_server_client/test/example/web_client_test.dart index d285fb089..3d4589d7f 100644 --- a/frontend_server_client/test/example/web_client_test.dart +++ b/frontend_server_client/test/example/web_client_test.dart @@ -13,15 +13,19 @@ import 'package:test_process/test_process.dart'; void main() { test('web client example can build and rebuild an app', () async { - final process = await TestProcess.start( - Platform.resolvedExecutable, ['run', 'example/web_client.dart']); - await expectLater(process.stdout, - emitsThrough(contains('done compiling example/app/main.dart'))); + final process = await TestProcess.start(Platform.resolvedExecutable, [ + 'run', + 'example/web_client.dart', + ]); + await expectLater( + process.stdout, + emitsThrough(contains('done compiling example/app/main.dart')), + ); process.stdin.writeln('new message'); await expectLater( - process.stdout, - emitsThrough( - contains('Recompile succeeded for example/app/main.dart'))); + process.stdout, + emitsThrough(contains('Recompile succeeded for example/app/main.dart')), + ); process.stdin.writeln('quit'); expect(await process.exitCode, 0); }); diff --git a/frontend_server_client/test/frontend_server_client_test.dart b/frontend_server_client/test/frontend_server_client_test.dart index 7a9c7016b..08befc79e 100644 --- a/frontend_server_client/test/frontend_server_client_test.dart +++ b/frontend_server_client/test/frontend_server_client_test.dart @@ -47,12 +47,14 @@ void main() async { String get message => p.join('hello', 'world'); -''') +'''), ]), ]).create(); packageRoot = p.join(d.sandbox, 'a'); - await Process.run(Platform.resolvedExecutable, ['pub', 'get'], - workingDirectory: packageRoot); + await Process.run(Platform.resolvedExecutable, [ + 'pub', + 'get', + ], workingDirectory: packageRoot); packageConfig = (await findPackageConfig(Directory(packageRoot)))!; }); @@ -60,151 +62,161 @@ String get message => p.join('hello', 'world'); await client.shutdown(); }); - test( - 'can compile, recompile, and hot reload a vm app', - () async { - final entrypoint = p.join(packageRoot, 'bin', 'main.dart'); - client = await FrontendServerClient.start( - entrypoint, p.join(packageRoot, 'out.dill'), vmPlatformDill); - var result = await client.compile(); - client.accept(); - expect(result.compilerOutputLines, isEmpty); - expect(result.errorCount, 0); - expect( - result.newSources, - containsAll([ - File(entrypoint).uri, - packageConfig.resolve(Uri.parse('package:path/path.dart')), - ])); - expect(result.removedSources, isEmpty); - expect(result.dillOutput, isNotNull); - expect(File(result.dillOutput!).existsSync(), true); - final process = await Process.start(Platform.resolvedExecutable, [ - '--observe', - '--no-pause-isolates-on-exit', - '--pause-isolates-on-start', - result.dillOutput! - ]); - addTearDown(process.kill); - final stdoutLines = StreamQueue(process.stdout - .transform(utf8.decoder) - .transform(const LineSplitter())); - - final observatoryLine = await stdoutLines.next; - final observatoryUri = - '${observatoryLine.split(' ').last.replaceFirst('http', 'ws')}ws'; - final vmService = await vmServiceConnectUri(observatoryUri); - final isolate = await waitForIsolatesAndResume(vmService); - - await expectLater(stdoutLines, emitsThrough(p.join('hello', 'world'))); - - final appFile = File(entrypoint); - final originalContent = await appFile.readAsString(); - final newContent = originalContent.replaceFirst('hello', 'goodbye'); - await appFile.writeAsString(newContent); - - result = await client.compile([File(entrypoint).uri]); - - client.accept(); - expect(result.newSources, isEmpty); - expect(result.removedSources, isEmpty); - expect(result.compilerOutputLines, isEmpty); - expect(result.errorCount, 0); - expect(result.dillOutput, endsWith('.incremental.dill')); - - await vmService.reloadSources(isolate.id!, rootLibUri: result.dillOutput); - - expect(await stdoutLines.next, p.join('goodbye', 'world')); - expect(await process.exitCode, 0); - }, - ); - - test( - 'can handle compile errors and reload fixes', - () async { - final entrypoint = p.join(packageRoot, 'bin', 'main.dart'); - final entrypointFile = File(entrypoint); - final originalContent = await entrypointFile.readAsString(); - // append two compile errors to the bottom - await entrypointFile - .writeAsString('$originalContent\nint foo = 1.0;\nString bar = 4;'); - - client = await FrontendServerClient.start( - entrypoint, p.join(packageRoot, 'out.dill'), vmPlatformDill); - var result = await client.compile(); - - client.accept(); - expect(result.errorCount, 2); - expect(result.compilerOutputLines, - allOf(contains('int foo = 1.0;'), contains('String bar = 4;'))); - expect( - result.newSources, - containsAll([ - File(entrypoint).uri, - packageConfig.resolve(Uri.parse('package:path/path.dart')), - ])); - expect(result.removedSources, isEmpty); - expect(result.dillOutput, isNotNull); - expect(File(result.dillOutput!).existsSync(), true); - - final process = await Process.start(Platform.resolvedExecutable, [ - '--observe', - '--no-pause-isolates-on-exit', - '--pause-isolates-on-start', - result.dillOutput! - ]); - addTearDown(process.kill); - final stdoutLines = StreamQueue(process.stdout - .transform(utf8.decoder) - .transform(const LineSplitter())); - - final observatoryLine = await stdoutLines.next; - final observatoryUri = - '${observatoryLine.split(' ').last.replaceFirst('http', 'ws')}ws'; - final vmService = await vmServiceConnectUri(observatoryUri); - final isolate = await waitForIsolatesAndResume(vmService); - - // The program actually runs regardless of the errors, as they don't affect - // the runtime behavior. - await expectLater(stdoutLines, emitsThrough(p.join('hello', 'world'))); - - await entrypointFile - .writeAsString(originalContent.replaceFirst('hello', 'goodbye')); - result = await client.compile([entrypointFile.uri]); - client.accept(); - expect(result.errorCount, 0); - expect(result.compilerOutputLines, isEmpty); - expect(result.newSources, isEmpty); - expect(result.removedSources, isEmpty); - expect(result.dillOutput, isNotNull); - expect(File(result.dillOutput!).existsSync(), true); - - await vmService.reloadSources(isolate.id!, rootLibUri: result.dillOutput); - - expect(await stdoutLines.next, p.join('goodbye', 'world')); - expect(await process.exitCode, 0); - }, - ); + test('can compile, recompile, and hot reload a vm app', () async { + final entrypoint = p.join(packageRoot, 'bin', 'main.dart'); + client = await FrontendServerClient.start( + entrypoint, + p.join(packageRoot, 'out.dill'), + vmPlatformDill, + ); + var result = await client.compile(); + client.accept(); + expect(result.compilerOutputLines, isEmpty); + expect(result.errorCount, 0); + expect( + result.newSources, + containsAll([ + File(entrypoint).uri, + packageConfig.resolve(Uri.parse('package:path/path.dart')), + ]), + ); + expect(result.removedSources, isEmpty); + expect(result.dillOutput, isNotNull); + expect(File(result.dillOutput!).existsSync(), true); + final process = await Process.start(Platform.resolvedExecutable, [ + '--observe', + '--no-pause-isolates-on-exit', + '--pause-isolates-on-start', + result.dillOutput!, + ]); + addTearDown(process.kill); + final stdoutLines = StreamQueue( + process.stdout.transform(utf8.decoder).transform(const LineSplitter()), + ); + + final observatoryLine = await stdoutLines.next; + final observatoryUri = + '${observatoryLine.split(' ').last.replaceFirst('http', 'ws')}ws'; + final vmService = await vmServiceConnectUri(observatoryUri); + final isolate = await waitForIsolatesAndResume(vmService); + + await expectLater(stdoutLines, emitsThrough(p.join('hello', 'world'))); + + final appFile = File(entrypoint); + final originalContent = await appFile.readAsString(); + final newContent = originalContent.replaceFirst('hello', 'goodbye'); + await appFile.writeAsString(newContent); + + result = await client.compile([File(entrypoint).uri]); + + client.accept(); + expect(result.newSources, isEmpty); + expect(result.removedSources, isEmpty); + expect(result.compilerOutputLines, isEmpty); + expect(result.errorCount, 0); + expect(result.dillOutput, endsWith('.incremental.dill')); + + await vmService.reloadSources(isolate.id!, rootLibUri: result.dillOutput); + + expect(await stdoutLines.next, p.join('goodbye', 'world')); + expect(await process.exitCode, 0); + }); + + test('can handle compile errors and reload fixes', () async { + final entrypoint = p.join(packageRoot, 'bin', 'main.dart'); + final entrypointFile = File(entrypoint); + final originalContent = await entrypointFile.readAsString(); + // append two compile errors to the bottom + await entrypointFile.writeAsString( + '$originalContent\nint foo = 1.0;\nString bar = 4;', + ); + + client = await FrontendServerClient.start( + entrypoint, + p.join(packageRoot, 'out.dill'), + vmPlatformDill, + ); + var result = await client.compile(); + + client.accept(); + expect(result.errorCount, 2); + expect( + result.compilerOutputLines, + allOf(contains('int foo = 1.0;'), contains('String bar = 4;')), + ); + expect( + result.newSources, + containsAll([ + File(entrypoint).uri, + packageConfig.resolve(Uri.parse('package:path/path.dart')), + ]), + ); + expect(result.removedSources, isEmpty); + expect(result.dillOutput, isNotNull); + expect(File(result.dillOutput!).existsSync(), true); + + final process = await Process.start(Platform.resolvedExecutable, [ + '--observe', + '--no-pause-isolates-on-exit', + '--pause-isolates-on-start', + result.dillOutput!, + ]); + addTearDown(process.kill); + final stdoutLines = StreamQueue( + process.stdout.transform(utf8.decoder).transform(const LineSplitter()), + ); + + final observatoryLine = await stdoutLines.next; + final observatoryUri = + '${observatoryLine.split(' ').last.replaceFirst('http', 'ws')}ws'; + final vmService = await vmServiceConnectUri(observatoryUri); + final isolate = await waitForIsolatesAndResume(vmService); + + // The program actually runs regardless of the errors, as they don't affect + // the runtime behavior. + await expectLater(stdoutLines, emitsThrough(p.join('hello', 'world'))); + + await entrypointFile.writeAsString( + originalContent.replaceFirst('hello', 'goodbye'), + ); + result = await client.compile([entrypointFile.uri]); + client.accept(); + expect(result.errorCount, 0); + expect(result.compilerOutputLines, isEmpty); + expect(result.newSources, isEmpty); + expect(result.removedSources, isEmpty); + expect(result.dillOutput, isNotNull); + expect(File(result.dillOutput!).existsSync(), true); + + await vmService.reloadSources(isolate.id!, rootLibUri: result.dillOutput); + + expect(await stdoutLines.next, p.join('goodbye', 'world')); + expect(await process.exitCode, 0); + }); test('can compile and recompile a dartdevc app', () async { - final entrypoint = - p.toUri(p.join(packageRoot, 'bin', 'main.dart')).toString(); + final entrypoint = p + .toUri(p.join(packageRoot, 'bin', 'main.dart')) + .toString(); final dartDevcClient = client = await DartDevcFrontendServerClient.start( - entrypoint, p.join(packageRoot, 'out.dill'), - platformKernel: p - .toUri(p.join(sdkDir, 'lib', '_internal', 'ddc_platform.dill')) - .toString()); + entrypoint, + p.join(packageRoot, 'out.dill'), + platformKernel: p + .toUri(p.join(sdkDir, 'lib', '_internal', 'ddc_platform.dill')) + .toString(), + ); var result = await client.compile(); client.accept(); expect(result.compilerOutputLines, isEmpty); expect(result.errorCount, 0); expect( - result.newSources, - containsAll([ - Uri.parse(entrypoint), - packageConfig.resolve(Uri.parse('package:path/path.dart')), - ])); + result.newSources, + containsAll([ + Uri.parse(entrypoint), + packageConfig.resolve(Uri.parse('package:path/path.dart')), + ]), + ); expect(result.removedSources, isEmpty); expect(result.dillOutput, isNotNull); @@ -214,8 +226,9 @@ String get message => p.join('hello', 'world'); final entrypointUri = Uri.parse(entrypoint); expect( - utf8.decode(dartDevcClient.assetBytes('${entrypointUri.path}.lib.js')!), - contains('hello')); + utf8.decode(dartDevcClient.assetBytes('${entrypointUri.path}.lib.js')!), + contains('hello'), + ); final appFile = File(entrypointUri.toFilePath()); final originalContent = await appFile.readAsString(); @@ -231,8 +244,9 @@ String get message => p.join('hello', 'world'); expect(result.jsManifestOutput, endsWith('.incremental.dill.json')); expect( - utf8.decode(dartDevcClient.assetBytes('${entrypointUri.path}.lib.js')!), - contains('goodbye')); + utf8.decode(dartDevcClient.assetBytes('${entrypointUri.path}.lib.js')!), + contains('goodbye'), + ); }); test('can enable experiments', () async { @@ -246,13 +260,16 @@ int x; void main() { print(x); } -''') - ]) +'''), + ]), ]).create(); final entrypoint = p.join(packageRoot, 'bin', 'nnbd.dart'); client = await FrontendServerClient.start( - entrypoint, p.join(packageRoot, 'out.dill'), vmPlatformDill, - enabledExperiments: ['non-nullable']); + entrypoint, + p.join(packageRoot, 'out.dill'), + vmPlatformDill, + enabledExperiments: ['non-nullable'], + ); final result = await client.compile(); client.accept(); expect(result.errorCount, 1); @@ -266,27 +283,27 @@ void main() { void main() { print('hello world'); } -''') +'''), ]), ]).create(); final entrypoint = p.join(packageRoot, 'bin', 'main with spaces.dart'); - client = await FrontendServerClient.start(entrypoint, - p.join(packageRoot, 'out with spaces.dill'), vmPlatformDill); + client = await FrontendServerClient.start( + entrypoint, + p.join(packageRoot, 'out with spaces.dill'), + vmPlatformDill, + ); var result = await client.compile(); client.accept(); expect(result.compilerOutputLines, isEmpty); expect(result.errorCount, 0); - expect( - result.newSources, - containsAll([ - File(entrypoint).uri, - ])); + expect(result.newSources, containsAll([File(entrypoint).uri])); expect(result.removedSources, isEmpty); expect(result.dillOutput, isNotNull); expect(File(result.dillOutput!).existsSync(), true); - var processResult = - await Process.run(Platform.resolvedExecutable, [result.dillOutput!]); + var processResult = await Process.run(Platform.resolvedExecutable, [ + result.dillOutput!, + ]); expect(processResult.stdout, startsWith('hello world')); expect(processResult.exitCode, 0); @@ -301,8 +318,9 @@ void main() { expect(result.newSources, isEmpty); expect(result.removedSources, isEmpty); - processResult = - await Process.run(Platform.resolvedExecutable, [result.dillOutput!]); + processResult = await Process.run(Platform.resolvedExecutable, [ + result.dillOutput!, + ]); expect(processResult.stdout, startsWith('goodbye world')); expect(processResult.exitCode, 0); }); diff --git a/frontend_server_common/CHANGELOG.md b/frontend_server_common/CHANGELOG.md index d1c229c14..cc6d0bedc 100644 --- a/frontend_server_common/CHANGELOG.md +++ b/frontend_server_common/CHANGELOG.md @@ -1,5 +1,6 @@ ## 0.2.3-wip +- Update minimum SDK constraint to 3.8.0. - Add bootstrapping code for DDC library bundle format. ## 0.2.2 diff --git a/frontend_server_common/lib/src/asset_server.dart b/frontend_server_common/lib/src/asset_server.dart index f8060b661..72d2b2d47 100644 --- a/frontend_server_common/lib/src/asset_server.dart +++ b/frontend_server_common/lib/src/asset_server.dart @@ -78,8 +78,15 @@ class TestAssetServer implements AssetReader { final address = (await InternetAddress.lookup(hostname)).first; final httpServer = await HttpServer.bind(address, port); final sdkLayout = TestSdkLayout.createDefault(sdkDirectory); - final server = TestAssetServer(index, httpServer, packageUriMapper, address, - projectDirectory, fileSystem, sdkLayout); + final server = TestAssetServer( + index, + httpServer, + packageUriMapper, + address, + projectDirectory, + fileSystem, + sdkLayout, + ); return server; } @@ -100,8 +107,9 @@ class TestAssetServer implements AssetReader { final indexFile = _fileSystem.file(_projectDirectory.resolve(index)); if (indexFile.existsSync()) { headers[HttpHeaders.contentTypeHeader] = 'text/html'; - headers[HttpHeaders.contentLengthHeader] = - indexFile.lengthSync().toString(); + headers[HttpHeaders.contentLengthHeader] = indexFile + .lengthSync() + .toString(); return shelf.Response.ok(indexFile.openRead(), headers: headers); } return shelf.Response.notFound(''); @@ -169,20 +177,25 @@ class TestAssetServer implements AssetReader { /// /// Returns a list of updated modules. List write( - File codeFile, File manifestFile, File sourcemapFile, File metadataFile) { + File codeFile, + File manifestFile, + File sourcemapFile, + File metadataFile, + ) { final modules = []; final codeBytes = codeFile.readAsBytesSync(); final sourcemapBytes = sourcemapFile.readAsBytesSync(); final metadataBytes = metadataFile.readAsBytesSync(); - final manifest = - _castStringKeyedMap(json.decode(manifestFile.readAsStringSync())); + final manifest = _castStringKeyedMap( + json.decode(manifestFile.readAsStringSync()), + ); for (final filePath in manifest.keys) { final offsets = _castStringKeyedMap(manifest[filePath]); final codeOffsets = (offsets['code'] as List).cast(); - final sourcemapOffsets = - (offsets['sourcemap'] as List).cast(); - final metadataOffsets = - (offsets['metadata'] as List).cast(); + final sourcemapOffsets = (offsets['sourcemap'] as List) + .cast(); + final metadataOffsets = (offsets['metadata'] as List) + .cast(); if (codeOffsets.length != 2 || sourcemapOffsets.length != 2 || metadataOffsets.length != 2) { @@ -202,8 +215,9 @@ class TestAssetServer implements AssetReader { codeEnd - codeStart, ); - final fileName = - filePath.startsWith('/') ? filePath.substring(1) : filePath; + final fileName = filePath.startsWith('/') + ? filePath.substring(1) + : filePath; _files[fileName] = byteView; final sourcemapStart = sourcemapOffsets[0]; @@ -271,7 +285,8 @@ class TestAssetServer implements AssetReader { // Otherwise it must be a Dart SDK source. final dartSdkParent = _fileSystem.directory(_sdkLayout.sdkDirectory).parent; final dartSdkFile = _fileSystem.file( - _fileSystem.path.joinAll([dartSdkParent.path, ...segments])); + _fileSystem.path.joinAll([dartSdkParent.path, ...segments]), + ); return dartSdkFile; } diff --git a/frontend_server_common/lib/src/bootstrap.dart b/frontend_server_common/lib/src/bootstrap.dart index 8f1073278..67000351a 100644 --- a/frontend_server_common/lib/src/bootstrap.dart +++ b/frontend_server_common/lib/src/bootstrap.dart @@ -356,8 +356,10 @@ $_simpleLoaderScript '''; } -String generateDDCMainModule( - {required String entrypoint, String? exportedMain}) { +String generateDDCMainModule({ + required String entrypoint, + String? exportedMain, +}) { final exportedMainName = exportedMain ?? entrypoint.split('.')[0]; return '''/* ENTRYPOINT_EXTENTION_MARKER */ diff --git a/frontend_server_common/lib/src/devfs.dart b/frontend_server_common/lib/src/devfs.dart index b6caf471d..d3b7fa8a3 100644 --- a/frontend_server_common/lib/src/devfs.dart +++ b/frontend_server_common/lib/src/devfs.dart @@ -84,7 +84,8 @@ class WebDevFS { }) async { final mainPath = mainUri.toFilePath(); final outputDirectory = fileSystem.directory( - fileSystem.file(projectDirectory.resolve(mainPath)).parent.path); + fileSystem.file(projectDirectory.resolve(mainPath)).parent.path, + ); final entryPoint = mainUri.toString(); var prefix = ''; @@ -103,10 +104,9 @@ class WebDevFS { final bootstrap = '${prefix}main_module.bootstrap.js'; assetServer.writeFile( - entryPoint, - fileSystem - .file(projectDirectory.resolve(mainPath)) - .readAsStringSync()); + entryPoint, + fileSystem.file(projectDirectory.resolve(mainPath)).readAsStringSync(), + ); assetServer.writeFile(stackMapper, stackTraceMapper.readAsStringSync()); switch (ddcModuleFormat) { @@ -122,27 +122,32 @@ class WebDevFS { ); assetServer.writeFile( bootstrap, - generateMainModule( - entrypoint: entryPoint, - ), + generateMainModule(entrypoint: entryPoint), ); break; case ModuleFormat.ddc: assetServer.writeFile( - ddcModuleLoader, ddcModuleLoaderJS.readAsStringSync()); + ddcModuleLoader, + ddcModuleLoaderJS.readAsStringSync(), + ); String bootstrapper; String mainModule; if (compilerOptions.canaryFeatures) { bootstrapper = generateDDCLibraryBundleBootstrapScript( - ddcModuleLoaderUrl: ddcModuleLoader, - mapperUrl: stackMapper, - entrypoint: entryPoint, - bootstrapUrl: bootstrap); + ddcModuleLoaderUrl: ddcModuleLoader, + mapperUrl: stackMapper, + entrypoint: entryPoint, + bootstrapUrl: bootstrap, + ); const onLoadEndBootstrap = 'on_load_end_bootstrap.js'; - assetServer.writeFile(onLoadEndBootstrap, - generateDDCLibraryBundleOnLoadEndBootstrap()); + assetServer.writeFile( + onLoadEndBootstrap, + generateDDCLibraryBundleOnLoadEndBootstrap(), + ); mainModule = generateDDCLibraryBundleMainModule( - entrypoint: entryPoint, onLoadEndBootstrap: onLoadEndBootstrap); + entrypoint: entryPoint, + onLoadEndBootstrap: onLoadEndBootstrap, + ); } else { bootstrapper = generateDDCBootstrapScript( ddcModuleLoaderUrl: ddcModuleLoader, @@ -156,19 +161,16 @@ class WebDevFS { // removed, and special path elements like '/', '\', and '..' are // replaced with // '__'. - final exportedMainName = - pathToJSIdentifier(entryPoint.split('.')[0]); + final exportedMainName = pathToJSIdentifier( + entryPoint.split('.')[0], + ); mainModule = generateDDCMainModule( - entrypoint: entryPoint, exportedMain: exportedMainName); + entrypoint: entryPoint, + exportedMain: exportedMainName, + ); } - assetServer.writeFile( - main, - bootstrapper, - ); - assetServer.writeFile( - bootstrap, - mainModule, - ); + assetServer.writeFile(main, bootstrapper); + assetServer.writeFile(bootstrap, mainModule); break; default: throw Exception('Unsupported DDC module format $ddcModuleFormat.'); @@ -202,16 +204,24 @@ class WebDevFS { File metadataFile; List modules; try { - codeFile = - outputDirectory.childFile('${compilerOutput.outputFilename}.sources'); - manifestFile = - outputDirectory.childFile('${compilerOutput.outputFilename}.json'); - sourcemapFile = - outputDirectory.childFile('${compilerOutput.outputFilename}.map'); - metadataFile = outputDirectory - .childFile('${compilerOutput.outputFilename}.metadata'); + codeFile = outputDirectory.childFile( + '${compilerOutput.outputFilename}.sources', + ); + manifestFile = outputDirectory.childFile( + '${compilerOutput.outputFilename}.json', + ); + sourcemapFile = outputDirectory.childFile( + '${compilerOutput.outputFilename}.map', + ); + metadataFile = outputDirectory.childFile( + '${compilerOutput.outputFilename}.metadata', + ); modules = assetServer.write( - codeFile, manifestFile, sourcemapFile, metadataFile); + codeFile, + manifestFile, + sourcemapFile, + metadataFile, + ); } on FileSystemException catch (err) { throw Exception('Failed to load recompiled sources:\n$err'); } @@ -280,19 +290,23 @@ class WebDevFS { /// [entrypointDirectory] is used to make the module paths relative to the /// entrypoint, which is needed in order to load `src`s correctly. void performReload( - List modules, String entrypointDirectory, Uri fileServerUri) { + List modules, + String entrypointDirectory, + Uri fileServerUri, + ) { final moduleToLibrary = >[]; for (final module in modules) { final metadata = ModuleMetadata.fromJson( - json.decode(utf8 - .decode(assetServer.getMetadata('$module.metadata').toList())) + json.decode( + utf8.decode(assetServer.getMetadata('$module.metadata').toList()), + ) as Map, ); final libraries = metadata.libraries.keys.toList(); moduleToLibrary.add({ 'src': '$fileServerUri/$module', 'module': metadata.name, - 'libraries': libraries + 'libraries': libraries, }); } assetServer.writeFile(reloadScriptsFileName, json.encode(moduleToLibrary)); @@ -302,15 +316,15 @@ class WebDevFS { fileSystem.file(sdkLayout.ddcModuleLoaderJsPath); File get requireJS => fileSystem.file(sdkLayout.requireJsPath); File get dartSdk => fileSystem.file(switch (ddcModuleFormat) { - ModuleFormat.amd => sdkLayout.amdJsPath, - ModuleFormat.ddc => sdkLayout.ddcJsPath, - _ => throw Exception('Unsupported DDC module format $ddcModuleFormat.') - }); + ModuleFormat.amd => sdkLayout.amdJsPath, + ModuleFormat.ddc => sdkLayout.ddcJsPath, + _ => throw Exception('Unsupported DDC module format $ddcModuleFormat.'), + }); File get dartSdkSourcemap => fileSystem.file(switch (ddcModuleFormat) { - ModuleFormat.amd => sdkLayout.amdJsMapPath, - ModuleFormat.ddc => sdkLayout.ddcJsMapPath, - _ => throw Exception('Unsupported DDC module format $ddcModuleFormat.') - }); + ModuleFormat.amd => sdkLayout.amdJsMapPath, + ModuleFormat.ddc => sdkLayout.ddcJsMapPath, + _ => throw Exception('Unsupported DDC module format $ddcModuleFormat.'), + }); File get stackTraceMapper => fileSystem.file(sdkLayout.stackTraceMapperPath); ModuleFormat get ddcModuleFormat => compilerOptions.moduleFormat; } @@ -324,9 +338,9 @@ class UpdateFSReport { bool success = false, int invalidatedSourcesCount = 0, int syncedBytes = 0, - }) : _success = success, - _invalidatedSourcesCount = invalidatedSourcesCount, - _syncedBytes = syncedBytes; + }) : _success = success, + _invalidatedSourcesCount = invalidatedSourcesCount, + _syncedBytes = syncedBytes; bool get success => _success; int get invalidatedSourcesCount => _invalidatedSourcesCount; @@ -350,7 +364,7 @@ class InvalidationResult { /// application to determine when they are dirty. class ProjectFileInvalidator { ProjectFileInvalidator({required FileSystem fileSystem}) - : _fileSystem = fileSystem; + : _fileSystem = fileSystem; final FileSystem _fileSystem; @@ -380,8 +394,8 @@ class ProjectFileInvalidator { final updatedAt = uri.hasScheme && uri.scheme != 'file' ? _fileSystem.file(uri).statSync().modified : _fileSystem - .statSync(uri.toFilePath(windows: Platform.isWindows)) - .modified; + .statSync(uri.toFilePath(windows: Platform.isWindows)) + .modified; if (updatedAt.isAfter(lastCompiled)) { invalidatedFiles.add(uri); } diff --git a/frontend_server_common/lib/src/frontend_server_client.dart b/frontend_server_common/lib/src/frontend_server_client.dart index 3c3ae3c1d..9940d0b9b 100644 --- a/frontend_server_common/lib/src/frontend_server_client.dart +++ b/frontend_server_common/lib/src/frontend_server_client.dart @@ -21,11 +21,11 @@ Logger _serverLogger = Logger('FrontendServer'); void defaultConsumer(String message, {StackTrace? stackTrace}) => stackTrace == null - ? _serverLogger.info(message) - : _serverLogger.severe(message, null, stackTrace); + ? _serverLogger.info(message) + : _serverLogger.severe(message, null, stackTrace); -typedef CompilerMessageConsumer = void Function(String message, - {StackTrace stackTrace}); +typedef CompilerMessageConsumer = + void Function(String message, {StackTrace stackTrace}); class CompilerOutput { const CompilerOutput(this.outputFilename, this.errorCount, this.sources); @@ -79,17 +79,18 @@ class StdoutHandler { // the stream. Instead use completeError so that the error is returned // from the awaited future that the compiler consumers are expecting. compilerOutput.completeError( - 'Frontend server tests encountered an internal problem. ' - 'This can be caused by printing to stdout into the stream that is ' - 'used for communication between frontend server (in sdk) or ' - 'frontend server client (in dwds tests).' - '\n\n' - 'Additional debugging information:\n' - ' StdoutState: $_state\n' - ' compilerMessageReceived: $_compilerMessageReceived\n' - ' message: $message\n' - ' _expectSources: $_expectSources\n' - ' sources: $_sources\n'); + 'Frontend server tests encountered an internal problem. ' + 'This can be caused by printing to stdout into the stream that is ' + 'used for communication between frontend server (in sdk) or ' + 'frontend server client (in dwds tests).' + '\n\n' + 'Additional debugging information:\n' + ' StdoutState: $_state\n' + ' compilerMessageReceived: $_compilerMessageReceived\n' + ' message: $message\n' + ' _expectSources: $_expectSources\n' + ' sources: $_sources\n', + ); // There are several event turns before the tool actually exits from a // tool exception. Normally, the stream should be cancelled to prevent // more events from entering the bad state, but because the error @@ -112,10 +113,13 @@ class StdoutHandler { return; } final spaceDelimiter = message.lastIndexOf(' '); - compilerOutput.complete(CompilerOutput( + compilerOutput.complete( + CompilerOutput( message.substring(boundaryKey.length + 1, spaceDelimiter), int.parse(message.substring(spaceDelimiter + 1).trim()), - _sources)); + _sources, + ), + ); return; } if (_state == StdoutState.collectDiagnostic) { @@ -143,8 +147,10 @@ class StdoutHandler { // This is needed to get ready to process next compilation result output, // with its own boundary key and new completer. - void reset( - {bool suppressCompilerMessages = false, bool expectSources = true}) { + void reset({ + bool suppressCompilerMessages = false, + bool expectSources = true, + }) { _boundaryKey = null; _compilerMessageReceived = false; compilerOutput = Completer(); @@ -213,14 +219,15 @@ class _CompileExpressionRequest extends _CompilationRequest { class _CompileExpressionToJsRequest extends _CompilationRequest { _CompileExpressionToJsRequest( - super.completer, - this.libraryUri, - this.line, - this.column, - this.jsModules, - this.jsFrameValues, - this.moduleName, - this.expression); + super.completer, + this.libraryUri, + this.line, + this.column, + this.jsModules, + this.jsFrameValues, + this.moduleName, + this.expression, + ); String libraryUri; int line; @@ -304,18 +311,24 @@ class ResidentCompiler { } final completer = Completer(); - _controller.add(_RecompileRequest( - completer, mainUri, invalidatedFiles, outputPath, packageConfig, - recompileRestart: recompileRestart)); + _controller.add( + _RecompileRequest( + completer, + mainUri, + invalidatedFiles, + outputPath, + packageConfig, + recompileRestart: recompileRestart, + ), + ); return completer.future; } Future _recompile(_RecompileRequest request) async { _stdoutHandler.reset(); - final mainUri = request.packageConfig - .toPackageUri(request.mainUri) - ?.toString() ?? + final mainUri = + request.packageConfig.toPackageUri(request.mainUri)?.toString() ?? _toMultiRootPath(request.mainUri, fileSystemScheme, fileSystemRoots); _compileRequestNeedsConfirmation = true; @@ -326,8 +339,9 @@ class ResidentCompiler { final server = _server!; final inputKey = generateV4UUID(); - final instruction = - request.recompileRestart ? 'recompile-restart' : 'recompile'; + final instruction = request.recompileRestart + ? 'recompile-restart' + : 'recompile'; server.stdin.writeln('$instruction $mainUri $inputKey'); _logger.info('<- $instruction $mainUri $inputKey'); for (final fileUri in request.invalidatedFiles) { @@ -335,7 +349,8 @@ class ResidentCompiler { if (fileUri.scheme == 'package') { message = fileUri.toString(); } else { - message = request.packageConfig.toPackageUri(fileUri)?.toString() ?? + message = + request.packageConfig.toPackageUri(fileUri)?.toString() ?? _toMultiRootPath(fileUri, fileSystemScheme, fileSystemRoots); } server.stdin.writeln(message); @@ -365,7 +380,9 @@ class ResidentCompiler { } Future _compile( - String scriptUri, String outputFilePath) async { + String scriptUri, + String outputFilePath, + ) async { final frontendServer = sdkLayout.frontendServerSnapshotPath; final args = [ frontendServer, @@ -376,22 +393,13 @@ class ResidentCompiler { '-Ddart.developer.causal_async_stacks=true', '--output-dill', outputFilePath, - ...[ - '--packages', - '$packageConfigFile', - ], + ...['--packages', '$packageConfigFile'], for (final root in fileSystemRoots) ...[ '--filesystem-root', '$root', ], - ...[ - '--filesystem-scheme', - fileSystemScheme, - ], - ...[ - '--platform', - platformDill, - ], + ...['--filesystem-scheme', fileSystemScheme], + ...['--platform', platformDill], if (useDebuggerModuleNames) '--debugger-module-names', '--experimental-emit-debug-metadata', '--sound-null-safety', @@ -400,36 +408,44 @@ class ResidentCompiler { if (compilerOptions.canaryFeatures) '--dartdevc-canary', if (verbose) '--verbose', if (compilerOptions.moduleFormat == ModuleFormat.ddc) - '--dartdevc-module-format=ddc' + '--dartdevc-module-format=ddc', ]; _logger.info(args.join(' ')); final workingDirectory = projectDirectory.toFilePath(); - _server = await Process.start(sdkLayout.dartAotRuntimePath, args, - workingDirectory: workingDirectory); + _server = await Process.start( + sdkLayout.dartAotRuntimePath, + args, + workingDirectory: workingDirectory, + ); final server = _server!; server.stdout .transform(utf8.decoder) .transform(const LineSplitter()) - .listen(_stdoutHandler.handler, onDone: () { - // when outputFilename future is not completed, but stdout is closed - // process has died unexpectedly. - if (!_stdoutHandler.compilerOutput.isCompleted) { - _stdoutHandler.compilerOutput.complete(null); - throw Exception('the Dart compiler exited unexpectedly.'); - } - }); + .listen( + _stdoutHandler.handler, + onDone: () { + // when outputFilename future is not completed, but stdout is closed + // process has died unexpectedly. + if (!_stdoutHandler.compilerOutput.isCompleted) { + _stdoutHandler.compilerOutput.complete(null); + throw Exception('the Dart compiler exited unexpectedly.'); + } + }, + ); server.stderr .transform(utf8.decoder) .transform(const LineSplitter()) .listen(_logger.info); - unawaited(server.exitCode.then((int code) { - if (code != 0) { - throw Exception('the Dart compiler exited unexpectedly.'); - } - })); + unawaited( + server.exitCode.then((int code) { + if (code != 0) { + throw Exception('the Dart compiler exited unexpectedly.'); + } + }), + ); server.stdin.writeln('compile $scriptUri'); _logger.info('<- compile $scriptUri'); @@ -451,13 +467,23 @@ class ResidentCompiler { } final completer = Completer(); - _controller.add(_CompileExpressionRequest(completer, expression, - definitions, typeDefinitions, libraryUri, klass, isStatic)); + _controller.add( + _CompileExpressionRequest( + completer, + expression, + definitions, + typeDefinitions, + libraryUri, + klass, + isStatic, + ), + ); return completer.future; } Future _compileExpression( - _CompileExpressionRequest request) async { + _CompileExpressionRequest request, + ) async { _stdoutHandler.reset(suppressCompilerMessages: true, expectSources: false); // 'compile-expression' should be invoked after compiler has been started, @@ -483,27 +509,41 @@ class ResidentCompiler { /// Compiles dart expression to JavaScript. Future compileExpressionToJs( - String libraryUri, - int line, - int column, - Map jsModules, - Map jsFrameValues, - String moduleName, - String expression) { + String libraryUri, + int line, + int column, + Map jsModules, + Map jsFrameValues, + String moduleName, + String expression, + ) { if (!_controller.hasListener) { _controller.stream.listen(_handleCompilationRequest); } final completer = Completer(); - _controller.add(_CompileExpressionToJsRequest(completer, libraryUri, line, - column, jsModules, jsFrameValues, moduleName, expression)); + _controller.add( + _CompileExpressionToJsRequest( + completer, + libraryUri, + line, + column, + jsModules, + jsFrameValues, + moduleName, + expression, + ), + ); return completer.future; } Future _compileExpressionToJs( - _CompileExpressionToJsRequest request) async { + _CompileExpressionToJsRequest request, + ) async { _stdoutHandler.reset( - suppressCompilerMessages: !verbose, expectSources: false); + suppressCompilerMessages: !verbose, + expectSources: false, + ); // 'compile-expression-to-js' should be invoked after compiler has been started, // program was compiled. @@ -615,23 +655,33 @@ class TestExpressionCompiler implements ExpressionCompiler { @override Future compileExpressionToJs( - String isolateId, - String libraryUri, - int line, - int column, - Map jsModules, - Map jsFrameValues, - String moduleName, - String expression) async { - final compilerOutput = await _generator.compileExpressionToJs(libraryUri, - line, column, jsModules, jsFrameValues, moduleName, expression); + String isolateId, + String libraryUri, + int line, + int column, + Map jsModules, + Map jsFrameValues, + String moduleName, + String expression, + ) async { + final compilerOutput = await _generator.compileExpressionToJs( + libraryUri, + line, + column, + jsModules, + jsFrameValues, + moduleName, + expression, + ); if (compilerOutput != null) { - final content = utf8.decode(localFileSystem - .file(compilerOutput.outputFilename) - .readAsBytesSync()); + final content = utf8.decode( + localFileSystem.file(compilerOutput.outputFilename).readAsBytesSync(), + ); return ExpressionCompilationResult( - content, compilerOutput.errorCount > 0); + content, + compilerOutput.errorCount > 0, + ); } throw Exception('Failed to compile $expression'); @@ -648,7 +698,10 @@ class TestExpressionCompiler implements ExpressionCompiler { /// Convert a file URI into a multi-root scheme URI if provided, otherwise /// return unmodified. String _toMultiRootPath( - Uri fileUri, String? scheme, List fileSystemRoots) { + Uri fileUri, + String? scheme, + List fileSystemRoots, +) { if (scheme == null || fileSystemRoots.isEmpty || fileUri.scheme != 'file') { return fileUri.toString(); } diff --git a/frontend_server_common/lib/src/resident_runner.dart b/frontend_server_common/lib/src/resident_runner.dart index 6802a3689..9ac21e98e 100644 --- a/frontend_server_common/lib/src/resident_runner.dart +++ b/frontend_server_common/lib/src/resident_runner.dart @@ -88,7 +88,10 @@ class ResidentWebRunner { uri ??= await devFS!.create(); final report = await _updateDevFS( - initialCompile: true, fullRestart: false, fileServerUri: null); + initialCompile: true, + fullRestart: false, + fileServerUri: null, + ); if (!report.success) { _logger.severe('Failed to compile application.'); return 1; @@ -98,16 +101,18 @@ class ResidentWebRunner { return 0; } - Future rerun( - {required bool fullRestart, - // The uri of the `HttpServer` that handles file requests. - // TODO(srujzs): This should be the same as the uri of the AssetServer to - // align with Flutter tools, but currently is not. Delete when that's fixed. - required Uri fileServerUri}) async { + Future rerun({ + required bool fullRestart, + // The uri of the `HttpServer` that handles file requests. + // TODO(srujzs): This should be the same as the uri of the AssetServer to + // align with Flutter tools, but currently is not. Delete when that's fixed. + required Uri fileServerUri, + }) async { final report = await _updateDevFS( - initialCompile: false, - fullRestart: fullRestart, - fileServerUri: fileServerUri); + initialCompile: false, + fullRestart: fullRestart, + fileServerUri: fileServerUri, + ); if (!report.success) { _logger.severe('Failed to compile application.'); return 1; @@ -131,13 +136,14 @@ class ResidentWebRunner { packagesPath: packageConfigFile.toFilePath(), ); final report = await devFS!.update( - mainUri: mainUri, - dillOutputPath: outputPath, - generator: generator, - invalidatedFiles: invalidationResult.uris!, - initialCompile: initialCompile, - fullRestart: fullRestart, - fileServerUri: fileServerUri); + mainUri: mainUri, + dillOutputPath: outputPath, + generator: generator, + invalidatedFiles: invalidationResult.uris!, + initialCompile: initialCompile, + fullRestart: fullRestart, + fileServerUri: fileServerUri, + ); return report; } diff --git a/frontend_server_common/pubspec.yaml b/frontend_server_common/pubspec.yaml index cba711520..b9b601179 100644 --- a/frontend_server_common/pubspec.yaml +++ b/frontend_server_common/pubspec.yaml @@ -3,7 +3,7 @@ publish_to: none description: >- Frontend server integration code to use for dwds tests. Mimics flutter code. environment: - sdk: ^3.2.0 + sdk: ^3.8.0 dependencies: dwds: any diff --git a/test_common/lib/logging.dart b/test_common/lib/logging.dart index e729e361e..1d870b085 100644 --- a/test_common/lib/logging.dart +++ b/test_common/lib/logging.dart @@ -7,8 +7,14 @@ import 'dart:async'; import 'package:logging/logging.dart'; import 'package:test/test.dart'; -typedef LogWriter = void Function(Level level, String message, - {String? error, String? loggerName, String? stackTrace}); +typedef LogWriter = + void Function( + Level level, + String message, { + String? error, + String? loggerName, + String? stackTrace, + }); StreamSubscription? _loggerSub; @@ -52,10 +58,13 @@ void configureLogWriter({LogWriter? customLogWriter}) { Logger.root.level = Level.ALL; _loggerSub?.cancel(); _loggerSub = Logger.root.onRecord.listen((event) { - logWriter(event.level, event.message, - error: event.error?.toString(), - loggerName: event.loggerName, - stackTrace: event.stackTrace?.toString()); + logWriter( + event.level, + event.message, + error: event.error?.toString(), + loggerName: event.loggerName, + stackTrace: event.stackTrace?.toString(), + ); }); } @@ -71,9 +80,11 @@ LogWriter createLogWriter({bool debug = false}) => final printFn = debug ? print : printOnFailure; final errorMessage = error == null ? '' : ':\n$error'; final stackMessage = stackTrace == null ? '' : ':\n$stackTrace'; - printFn('[$level] $loggerName: $message' - '$errorMessage' - '$stackMessage'); + printFn( + '[$level] $loggerName: $message' + '$errorMessage' + '$stackMessage', + ); }; LogWriter get logWriter => _logWriter; diff --git a/test_common/lib/sdk_asset_generator.dart b/test_common/lib/sdk_asset_generator.dart index 341556ef2..e5768752d 100644 --- a/test_common/lib/sdk_asset_generator.dart +++ b/test_common/lib/sdk_asset_generator.dart @@ -124,17 +124,17 @@ class SdkAssetGenerator { .transform(utf8.decoder) .transform(const LineSplitter()) .listen((line) { - _logger.fine(line); - output.add(line); - }); + _logger.fine(line); + output.add(line); + }); process.stderr .transform(utf8.decoder) .transform(const LineSplitter()) .listen((line) { - _logger.warning(line); - output.add(line); - }); + _logger.warning(line); + output.add(line); + }); await process.exitCode.then((int code) { if (code != 0) { diff --git a/test_common/lib/test_sdk_configuration.dart b/test_common/lib/test_sdk_configuration.dart index 407ecde60..98fa9b5e2 100644 --- a/test_common/lib/test_sdk_configuration.dart +++ b/test_common/lib/test_sdk_configuration.dart @@ -51,7 +51,9 @@ class TestSdkConfigurationProvider extends SdkConfigurationProvider { Future _create() async { try { await copyDirectory( - TestSdkLayout.defaultSdkDirectory, _sdkDirectory.path); + TestSdkLayout.defaultSdkDirectory, + _sdkDirectory.path, + ); } catch (e, s) { _logger.severe('Failed to create SDK directory copy', e, s); dispose(); diff --git a/test_common/lib/test_sdk_layout.dart b/test_common/lib/test_sdk_layout.dart index f9d57596f..c44b08e33 100644 --- a/test_common/lib/test_sdk_layout.dart +++ b/test_common/lib/test_sdk_layout.dart @@ -14,15 +14,18 @@ import 'package:path/path.dart' as p; class TestSdkLayout { static final defaultSdkDirectory = SdkLayout.defaultSdkDirectory; - static TestSdkLayout defaultSdkLayout = - TestSdkLayout.createDefault(defaultSdkDirectory); + static TestSdkLayout defaultSdkLayout = TestSdkLayout.createDefault( + defaultSdkDirectory, + ); - static SdkConfiguration defaultSdkConfiguration = - createConfiguration(defaultSdkLayout); + static SdkConfiguration defaultSdkConfiguration = createConfiguration( + defaultSdkLayout, + ); factory TestSdkLayout.createDefault(String sdkDirectory) => TestSdkLayout.createDefaultFromSdkLayout( - SdkLayout.createDefault(sdkDirectory)); + SdkLayout.createDefault(sdkDirectory), + ); factory TestSdkLayout.createDefaultFromSdkLayout(SdkLayout sdkLayout) => TestSdkLayout( diff --git a/test_common/pubspec.yaml b/test_common/pubspec.yaml index 0b16e6124..35496c296 100644 --- a/test_common/pubspec.yaml +++ b/test_common/pubspec.yaml @@ -3,7 +3,7 @@ publish_to: none description: >- Common test functionality. environment: - sdk: ^3.1.0 + sdk: ^3.8.0 dependencies: dwds: any diff --git a/test_common/test/proper_release_test.dart b/test_common/test/proper_release_test.dart index e5da401a4..8726e131f 100644 --- a/test_common/test/proper_release_test.dart +++ b/test_common/test/proper_release_test.dart @@ -17,19 +17,28 @@ import 'package:test_common/utilities.dart'; void main() { for (final package in ['dwds', 'webdev']) { test('$package is following proper release procedure', () async { - final pubspecPath = - absolutePath(pathFromWebdev: p.join(package, 'pubspec.yaml')); + final pubspecPath = absolutePath( + pathFromWebdev: p.join(package, 'pubspec.yaml'), + ); final pubspec = Pubspec.parse(File(pubspecPath).readAsStringSync()); final version = pubspec.version!; final isWip = version.toString().contains('wip'); if (!isWip) { - final wasReleased = - await _versionWasReleased(package, version: version); - expect(wasReleased, isTrue, - reason: _versionNotReleasedReason(package, version: version)); + final wasReleased = await _versionWasReleased( + package, + version: version, + ); + expect( + wasReleased, + isTrue, + reason: _versionNotReleasedReason(package, version: version), + ); } - expect(isWip, isTrue, - reason: _noWipVersionReason(package, version: version)); + expect( + isWip, + isTrue, + reason: _noWipVersionReason(package, version: version), + ); }); } } @@ -37,13 +46,18 @@ void main() { String _releaseTagName(String package, {required Version version}) => '$package-v$version'; -Future _versionWasReleased(String package, - {required Version version}) async { +Future _versionWasReleased( + String package, { + required Version version, +}) async { final releaseTagName = _releaseTagName(package, version: version); - final gitProcess = await Process.run( - 'git', - ['tag', '-l', '|', 'grep', releaseTagName], - ); + final gitProcess = await Process.run('git', [ + 'tag', + '-l', + '|', + 'grep', + releaseTagName, + ]); final stdout = gitProcess.stdout as String; return stdout.contains(releaseTagName); } diff --git a/test_common/test/sdk_asset_generator_test.dart b/test_common/test/sdk_asset_generator_test.dart index 02b408065..2f586ae23 100644 --- a/test_common/test/sdk_asset_generator_test.dart +++ b/test_common/test/sdk_asset_generator_test.dart @@ -57,102 +57,109 @@ void main() { }); test( - 'Can generate missing SDK assets and validate SDK configuration for the AMD module system', - () async { - final sdkLayout = TestSdkLayout.createDefault(sdkDirectory); - final configuration = TestSdkLayout.createConfiguration(sdkLayout); - - final assetGenerator = SdkAssetGenerator( - sdkLayout: sdkLayout, - verbose: true, - canaryFeatures: false, - ddcModuleFormat: ModuleFormat.amd, - ); - await assetGenerator.generateSdkAssets(); - - // Make sure SDK configuration and asset generator agree on the file paths. - expect(configuration.sdkDirectory, equals(sdkDirectory)); - expect(configuration.compilerWorkerPath, equals(compilerWorkerPath)); - - expect(sdkLayout.amdJsPath, equals(amdSdkJsPath)); - expect(sdkLayout.amdJsMapPath, equals(amdSdkJsMapPath)); - - // Validate that configuration files exist. - configuration.validateSdkDir(); - configuration.validate(); - - // Validate all assets exist. - expect(sdkLayout.amdJsPath, _exists); - expect(sdkLayout.amdJsMapPath, _exists); - }); + 'Can generate missing SDK assets and validate SDK configuration for the AMD module system', + () async { + final sdkLayout = TestSdkLayout.createDefault(sdkDirectory); + final configuration = TestSdkLayout.createConfiguration(sdkLayout); + + final assetGenerator = SdkAssetGenerator( + sdkLayout: sdkLayout, + verbose: true, + canaryFeatures: false, + ddcModuleFormat: ModuleFormat.amd, + ); + await assetGenerator.generateSdkAssets(); + + // Make sure SDK configuration and asset generator agree on the file paths. + expect(configuration.sdkDirectory, equals(sdkDirectory)); + expect(configuration.compilerWorkerPath, equals(compilerWorkerPath)); + + expect(sdkLayout.amdJsPath, equals(amdSdkJsPath)); + expect(sdkLayout.amdJsMapPath, equals(amdSdkJsMapPath)); + + // Validate that configuration files exist. + configuration.validateSdkDir(); + configuration.validate(); + + // Validate all assets exist. + expect(sdkLayout.amdJsPath, _exists); + expect(sdkLayout.amdJsMapPath, _exists); + }, + ); test( - 'Can generate missing SDK assets and validate SDK configuration for the DDC module system', - () async { - final sdkLayout = TestSdkLayout.createDefault(sdkDirectory); - final configuration = TestSdkLayout.createConfiguration(sdkLayout); - - final assetGenerator = SdkAssetGenerator( - sdkLayout: sdkLayout, - verbose: true, - canaryFeatures: false, - ddcModuleFormat: ModuleFormat.ddc, - ); - await assetGenerator.generateSdkAssets(); - - // Make sure SDK configuration and asset generator agree on the file paths. - expect(configuration.sdkDirectory, equals(sdkDirectory)); - expect(configuration.compilerWorkerPath, equals(compilerWorkerPath)); - - expect(sdkLayout.ddcJsPath, equals(ddcSdkJsPath)); - expect(sdkLayout.ddcJsMapPath, equals(ddcSdkJsMapPath)); - - // Validate that configuration files exist. - configuration.validateSdkDir(); - configuration.validate(); - - // Validate all assets exist. - expect(sdkLayout.ddcJsPath, _exists); - expect(sdkLayout.ddcJsMapPath, _exists); - }); - - test('Can generate missing SDK assets with canary features enabled', - () async { - final sdkLayout = TestSdkLayout.createDefault(sdkDirectory); - - final assetGenerator = SdkAssetGenerator( - sdkLayout: sdkLayout, - verbose: true, - canaryFeatures: true, - ddcModuleFormat: ModuleFormat.amd, - ); - await assetGenerator.generateSdkAssets(); + 'Can generate missing SDK assets and validate SDK configuration for the DDC module system', + () async { + final sdkLayout = TestSdkLayout.createDefault(sdkDirectory); + final configuration = TestSdkLayout.createConfiguration(sdkLayout); + + final assetGenerator = SdkAssetGenerator( + sdkLayout: sdkLayout, + verbose: true, + canaryFeatures: false, + ddcModuleFormat: ModuleFormat.ddc, + ); + await assetGenerator.generateSdkAssets(); + + // Make sure SDK configuration and asset generator agree on the file paths. + expect(configuration.sdkDirectory, equals(sdkDirectory)); + expect(configuration.compilerWorkerPath, equals(compilerWorkerPath)); + + expect(sdkLayout.ddcJsPath, equals(ddcSdkJsPath)); + expect(sdkLayout.ddcJsMapPath, equals(ddcSdkJsMapPath)); + + // Validate that configuration files exist. + configuration.validateSdkDir(); + configuration.validate(); + + // Validate all assets exist. + expect(sdkLayout.ddcJsPath, _exists); + expect(sdkLayout.ddcJsMapPath, _exists); + }, + ); - final sdk = File(amdSdkJsPath).readAsStringSync(); - expect(sdk, contains('canary')); - }); + test( + 'Can generate missing SDK assets with canary features enabled', + () async { + final sdkLayout = TestSdkLayout.createDefault(sdkDirectory); + + final assetGenerator = SdkAssetGenerator( + sdkLayout: sdkLayout, + verbose: true, + canaryFeatures: true, + ddcModuleFormat: ModuleFormat.amd, + ); + await assetGenerator.generateSdkAssets(); + + final sdk = File(amdSdkJsPath).readAsStringSync(); + expect(sdk, contains('canary')); + }, + ); test( - 'Can generate missing SDK assets with canary features enabled for the DDC module system', - () async { - final sdkLayout = TestSdkLayout.createDefault(sdkDirectory); - - final assetGenerator = SdkAssetGenerator( - sdkLayout: sdkLayout, - verbose: true, - canaryFeatures: true, - ddcModuleFormat: ModuleFormat.ddc, - ); - await assetGenerator.generateSdkAssets(); - - final sdk = File(ddcSdkJsPath).readAsStringSync(); - expect(sdk, contains('canary')); - }); + 'Can generate missing SDK assets with canary features enabled for the DDC module system', + () async { + final sdkLayout = TestSdkLayout.createDefault(sdkDirectory); + + final assetGenerator = SdkAssetGenerator( + sdkLayout: sdkLayout, + verbose: true, + canaryFeatures: true, + ddcModuleFormat: ModuleFormat.ddc, + ); + await assetGenerator.generateSdkAssets(); + + final sdk = File(ddcSdkJsPath).readAsStringSync(); + expect(sdk, contains('canary')); + }, + ); }); } -Matcher _exists = - predicate((String path) => File(path).existsSync(), 'File exists'); +Matcher _exists = predicate( + (String path) => File(path).existsSync(), + 'File exists', +); void _deleteIfExists(String path) { final file = File(path); diff --git a/test_common/test/test_sdk_configuration_test.dart b/test_common/test/test_sdk_configuration_test.dart index f061d58b3..9f1a086dd 100644 --- a/test_common/test/test_sdk_configuration_test.dart +++ b/test_common/test/test_sdk_configuration_test.dart @@ -26,18 +26,30 @@ void main() { final sdkDirectory = provider.sdkLayout.sdkDirectory; final sdkSummary = provider.sdkLayout.summaryPath; try { - expect(sdkDirectory, _directoryExists, - reason: 'SDK directory should be created'); - expect(sdkSummary, isNot(_fileExists), - reason: 'SDK summary should not be generated yet.'); + expect( + sdkDirectory, + _directoryExists, + reason: 'SDK directory should be created', + ); + expect( + sdkSummary, + isNot(_fileExists), + reason: 'SDK summary should not be generated yet.', + ); await provider.configuration; - expect(sdkSummary, _fileExists, - reason: 'SDK summary should be generated'); + expect( + sdkSummary, + _fileExists, + reason: 'SDK summary should be generated', + ); } finally { provider.dispose(); - expect(sdkDirectory, isNot(_directoryExists), - reason: 'SDK directory copy should be deleted on dispose'); + expect( + sdkDirectory, + isNot(_directoryExists), + reason: 'SDK directory copy should be deleted on dispose', + ); } }); }); @@ -45,7 +57,9 @@ void main() { group('Test SDK configuration | DDC with DDC modules |', () { setCurrentLogWriter(debug: debug); final provider = TestSdkConfigurationProvider( - verbose: debug, ddcModuleFormat: ModuleFormat.ddc); + verbose: debug, + ddcModuleFormat: ModuleFormat.ddc, + ); tearDownAll(provider.dispose); test('Can validate configuration with generated assets', () async { @@ -109,8 +123,12 @@ void main() { }); } -Matcher _fileExists = - predicate((String path) => File(path).existsSync(), 'File exists'); +Matcher _fileExists = predicate( + (String path) => File(path).existsSync(), + 'File exists', +); Matcher _directoryExists = predicate( - (String path) => Directory(path).existsSync(), 'Directory exists'); + (String path) => Directory(path).existsSync(), + 'Directory exists', +); diff --git a/tool/pubspec.yaml b/tool/pubspec.yaml index bb3967c34..c0eeb6f3e 100644 --- a/tool/pubspec.yaml +++ b/tool/pubspec.yaml @@ -3,7 +3,7 @@ publish_to: none description: >- Common tools for the mono-repo. environment: - sdk: ^3.1.0 + sdk: ^3.8.0 dev_dependencies: args: ^2.4.0 diff --git a/tool/release.dart b/tool/release.dart index 25b7aa9d2..d117429dc 100644 --- a/tool/release.dart +++ b/tool/release.dart @@ -27,14 +27,7 @@ const _skipStableCheckFlag = 'skipStableCheck'; void main(List arguments) async { final parser = ArgParser() - ..addOption( - _packageOption, - abbr: 'p', - allowed: [ - 'webdev', - 'dwds', - ], - ) + ..addOption(_packageOption, abbr: 'p', allowed: ['webdev', 'dwds']) ..addOption(_versionOption, abbr: 'v') ..addFlag(_resetFlag, abbr: 'r') ..addFlag(_skipStableCheckFlag, abbr: 's'); @@ -52,10 +45,7 @@ void main(List arguments) async { int exitCode; if (isReset == true) { - exitCode = await runReset( - package: package, - newVersion: newVersion, - ); + exitCode = await runReset(package: package, newVersion: newVersion); } else { exitCode = await runRelease( package: package, @@ -68,19 +58,14 @@ void main(List arguments) async { } } -Future runReset({ - required String package, - String? newVersion, -}) { +Future runReset({required String package, String? newVersion}) { // Check that a new wip version has been provided. final currentVersion = _readVersionFile(package); if (newVersion == null || !newVersion.contains('wip')) { - _logInfo( - ''' + _logInfo(''' Please provide the next wip version for $package, e.g. -v 3.0.1-wip Current version is $currentVersion. - ''', - ); + '''); return Future.value(1); } @@ -110,13 +95,11 @@ Future runRelease({ final checkVersionProcess = await Process.run('dart', ['--version']); final versionInfo = checkVersionProcess.stdout as String; if (!versionInfo.contains('stable')) { - _logWarning( - ''' + _logWarning(''' Expected to be on stable version of Dart, instead on: $versionInfo To skip this check, re-run with --skipStableCheck - ''', - ); + '''); return checkVersionProcess.exitCode; } } @@ -146,14 +129,10 @@ Future runRelease({ '../test_common', ]) { _logInfo('Upgrading pub packages for $packagePath'); - final pubUpgradeProcess = await Process.run( - 'dart', - [ - 'pub', - 'upgrade', - ], - workingDirectory: packagePath, - ); + final pubUpgradeProcess = await Process.run('dart', [ + 'pub', + 'upgrade', + ], workingDirectory: packagePath); final upgradeErrors = pubUpgradeProcess.stderr as String; if (upgradeErrors.isNotEmpty) { _logWarning(upgradeErrors); @@ -177,11 +156,11 @@ Future runRelease({ Future _buildPackage(String package) async { _logInfo('Building $package'); - final buildProcess = await Process.run( - 'dart', - ['run', 'build_runner', 'build'], - workingDirectory: '../$package', - ); + final buildProcess = await Process.run('dart', [ + 'run', + 'build_runner', + 'build', + ], workingDirectory: '../$package'); final buildErrors = buildProcess.stderr as String; if (buildErrors.isNotEmpty) { @@ -190,10 +169,7 @@ Future _buildPackage(String package) async { return buildProcess.exitCode; } -void _updateOverrides( - String package, { - required bool includeOverrides, -}) { +void _updateOverrides(String package, {required bool includeOverrides}) { final overridesFilePath = '../$package/pubspec_overrides.yaml'; final noOverridesFilePath = '../$package/ignore_pubspec_overrides.yaml'; if (includeOverrides) { @@ -231,11 +207,7 @@ void _updateVersionStrings( } } -void _addNewLine( - File file, { - required String newLine, - int insertAt = 0, -}) { +void _addNewLine(File file, {required String newLine, int insertAt = 0}) { final currentLines = file.readAsLinesSync(); final linesBefore = currentLines.sublist(0, insertAt); final linesAfter = currentLines.sublist(insertAt); @@ -290,25 +262,24 @@ String _removeWip(String wipVersion) { /// Returns the new pinned DWDS version on success. Future _updateDwdsPin(String package) async { - final pubOutdatedProcess = await Process.run( - 'dart', - [ - 'pub', - 'outdated', - '--no-dependency-overrides', - ], - workingDirectory: '../$package', - ); + final pubOutdatedProcess = await Process.run('dart', [ + 'pub', + 'outdated', + '--no-dependency-overrides', + ], workingDirectory: '../$package'); final lines = pubOutdatedProcess.stdout.split('\n') as List; String? nextDwdsVersion; String? currentDwdsVersion; for (final line in lines) { if (line.trim().startsWith('dwds')) { - final segments = - line.trim().split(' ').where((segment) => segment != ' '); + final segments = line + .trim() + .split(' ') + .where((segment) => segment != ' '); nextDwdsVersion = segments.last; - currentDwdsVersion = - segments.lastWhere((segment) => segment.startsWith('*')).substring(1); + currentDwdsVersion = segments + .lastWhere((segment) => segment.startsWith('*')) + .substring(1); break; } } diff --git a/webdev/CHANGELOG.md b/webdev/CHANGELOG.md index 47a6f1ef7..60296c806 100644 --- a/webdev/CHANGELOG.md +++ b/webdev/CHANGELOG.md @@ -1,5 +1,7 @@ ## 3.8.0-wip +- Bump minimum SDK constraint to 3.8.0 + ## 3.7.2 - Fixed duplicate app logs on page refresh by preventing multiple stdout listeners for the same appId. diff --git a/webdev/bin/webdev.dart b/webdev/bin/webdev.dart index 4c2905d64..b78e8698a 100644 --- a/webdev/bin/webdev.dart +++ b/webdev/bin/webdev.dart @@ -28,10 +28,12 @@ Future main(List args) async { } exitCode = ExitCode.config.code; } on PackageException catch (e) { - final withUnsupportedArg = - e.unsupportedArgument != null ? ' with --${e.unsupportedArgument}' : ''; - print(red - .wrap('$_boldApp could not run$withUnsupportedArg for this project.')); + final withUnsupportedArg = e.unsupportedArgument != null + ? ' with --${e.unsupportedArgument}' + : ''; + print( + red.wrap('$_boldApp could not run$withUnsupportedArg for this project.'), + ); for (final detail in e.details) { print(yellow.wrap(detail.error)); if (detail.description != null) { diff --git a/webdev/lib/src/command/build_command.dart b/webdev/lib/src/command/build_command.dart index 08e45936d..7b68ffbf4 100644 --- a/webdev/lib/src/command/build_command.dart +++ b/webdev/lib/src/command/build_command.dart @@ -41,12 +41,14 @@ class BuildCommand extends Command { final unsupported = extraArgs.where((arg) => !arg.startsWith('-')).toList(); if (unsupported.isNotEmpty) { throw UsageException( - 'Arguments were provided that are not supported: ' - '"${unsupported.join(' ')}".', - argParser.usage); + 'Arguments were provided that are not supported: ' + '"${unsupported.join(' ')}".', + argParser.usage, + ); } - final validExtraArgs = - extraArgs.where((arg) => arg.startsWith('-')).toList(); + final validExtraArgs = extraArgs + .where((arg) => arg.startsWith('-')) + .toList(); final configuration = Configuration.fromArgs(argResults); configureLogWriter(configuration.verbose); @@ -56,40 +58,51 @@ class BuildCommand extends Command { await validatePubspecLock(configuration); arguments = buildRunnerArgs(configuration)..addAll(validExtraArgs); } on PackageException catch (e) { - logWriter(logging.Level.SEVERE, 'Pubspec errors: ', - error: '${e.details}'); + logWriter( + logging.Level.SEVERE, + 'Pubspec errors: ', + error: '${e.details}', + ); rethrow; } try { logWriter(logging.Level.INFO, 'Connecting to the build daemon...'); - final client = await connectClient( - Directory.current.path, - arguments, - (serverLog) { - logWriter(toLoggingLevel(serverLog.level), serverLog.message, - error: serverLog.error, - loggerName: serverLog.loggerName, - stackTrace: serverLog.stackTrace); - }, - ); + final client = await connectClient(Directory.current.path, arguments, ( + serverLog, + ) { + logWriter( + toLoggingLevel(serverLog.level), + serverLog.message, + error: serverLog.error, + loggerName: serverLog.loggerName, + stackTrace: serverLog.stackTrace, + ); + }); OutputLocation? outputLocation; final outputInput = configuration.outputInput; if (configuration.outputPath != null) { - outputLocation = OutputLocation((b) => b - ..output = configuration.outputPath - ..useSymlinks = false - ..hoist = outputInput != null && outputInput.isNotEmpty); + outputLocation = OutputLocation( + (b) => b + ..output = configuration.outputPath + ..useSymlinks = false + ..hoist = outputInput != null && outputInput.isNotEmpty, + ); } - client.registerBuildTarget(DefaultBuildTarget((b) => b - ..target = configuration.outputInput - ..outputLocation = outputLocation?.toBuilder())); + client.registerBuildTarget( + DefaultBuildTarget( + (b) => b + ..target = configuration.outputInput + ..outputLocation = outputLocation?.toBuilder(), + ), + ); client.startBuild(); var exitCode = 0; var gotBuildStart = false; await for (final result in client.buildResults) { final targetResult = result.results.firstWhereOrNull( - (buildResult) => buildResult.target == configuration.outputInput); + (buildResult) => buildResult.target == configuration.outputInput, + ); if (targetResult == null) continue; // We ignore any builds that happen before we get a `started` event, // because those could be stale (from some other client). @@ -114,10 +127,11 @@ class BuildCommand extends Command { return exitCode; } on OptionsSkew catch (_) { logWriter( - logging.Level.SEVERE, - 'Incompatible options with current running build daemon.\n\n' - 'Please stop other WebDev instances running in this directory ' - 'before starting a new instance with these options.\n\n'); + logging.Level.SEVERE, + 'Incompatible options with current running build daemon.\n\n' + 'Please stop other WebDev instances running in this directory ' + 'before starting a new instance with these options.\n\n', + ); return 1; } } diff --git a/webdev/lib/src/command/configuration.dart b/webdev/lib/src/command/configuration.dart index 07f532261..27b67d6b9 100644 --- a/webdev/lib/src/command/configuration.dart +++ b/webdev/lib/src/command/configuration.dart @@ -49,14 +49,16 @@ ReloadConfiguration _parseReloadConfiguration(ArgResults argResults) { argResults.wasParsed(flag) && (argResults[flag] as bool? ?? false)) { logWriter( - Level.WARNING, - '--$flag is deprecated please use --auto=$autoFallback instead ' - '(this has been automatically selected).'); + Level.WARNING, + '--$flag is deprecated please use --auto=$autoFallback instead ' + '(this has been automatically selected).', + ); if (auto != null) { logWriter( - Level.WARNING, - 'Only one --auto option is allowed, got $flag which corresponds ' - 'to --auto=$autoFallback, but already got --auto=$auto'); + Level.WARNING, + 'Only one --auto option is allowed, got $flag which corresponds ' + 'to --auto=$autoFallback, but already got --auto=$auto', + ); } else { auto = autoFallback; } @@ -70,9 +72,10 @@ ReloadConfiguration _parseReloadConfiguration(ArgResults argResults) { switch (auto) { case 'reload': logWriter( - Level.WARNING, - 'Hot reload is not yet supported for web projects. ' - 'Please try --auto=restart instead.'); + Level.WARNING, + 'Hot reload is not yet supported for web projects. ' + 'Please try --auto=restart instead.', + ); return ReloadConfiguration.none; case 'restart': return ReloadConfiguration.hotRestart; @@ -136,29 +139,29 @@ class Configuration { List? experiments, bool? canaryFeatures, bool? offline, - }) : _autoRun = autoRun, - _chromeDebugPort = chromeDebugPort, - _debugExtension = debugExtension, - _debug = debug, - _enableInjectedClient = enableInjectedClient, - _hostname = hostname, - _tlsCertChain = tlsCertChain, - _tlsCertKey = tlsCertKey, - _launchApps = launchApps, - _launchInChrome = launchInChrome, - _userDataDir = userDataDir, - _logRequests = logRequests, - _output = output, - _release = release, - _reload = reload, - _requireBuildWebCompilers = requireBuildWebCompilers, - _disableDds = disableDds, - _enableExpressionEvaluation = enableExpressionEvaluation, - _verbose = verbose, - _nullSafety = nullSafety, - _experiments = experiments, - _canaryFeatures = canaryFeatures, - _offline = offline { + }) : _autoRun = autoRun, + _chromeDebugPort = chromeDebugPort, + _debugExtension = debugExtension, + _debug = debug, + _enableInjectedClient = enableInjectedClient, + _hostname = hostname, + _tlsCertChain = tlsCertChain, + _tlsCertKey = tlsCertKey, + _launchApps = launchApps, + _launchInChrome = launchInChrome, + _userDataDir = userDataDir, + _logRequests = logRequests, + _output = output, + _release = release, + _reload = reload, + _requireBuildWebCompilers = requireBuildWebCompilers, + _disableDds = disableDds, + _enableExpressionEvaluation = enableExpressionEvaluation, + _verbose = verbose, + _nullSafety = nullSafety, + _experiments = experiments, + _canaryFeatures = canaryFeatures, + _offline = offline { _validateConfiguration(); } @@ -170,12 +173,14 @@ class Configuration { if ((tlsCertKey != null && tlsCertChain == null) || (tlsCertKey == null && tlsCertChain != null)) { throw InvalidConfiguration( - 'Must use --$tlsCertKey with --$tlsCertChain.'); + 'Must use --$tlsCertKey with --$tlsCertChain.', + ); } if (debug && chromeDebugPort == 0 && !launchInChrome) { throw InvalidConfiguration( - 'Must either use --$chromeDebugPortFlag or --$launchInChromeFlag ' - 'with --$debugFlag.'); + 'Must either use --$chromeDebugPortFlag or --$launchInChromeFlag ' + 'with --$debugFlag.', + ); } // Check that no debugging options were passed if the injected client is @@ -183,58 +188,65 @@ class Configuration { if (!enableInjectedClient) { if (debug) { throw InvalidConfiguration( - '--$debugFlag cannot be used with --no-$enableInjectedClientFlag'); + '--$debugFlag cannot be used with --no-$enableInjectedClientFlag', + ); } if (debugExtension) { - throw InvalidConfiguration('--$debugExtensionFlag cannot be used with ' - '--no-$enableInjectedClientFlag'); + throw InvalidConfiguration( + '--$debugExtensionFlag cannot be used with ' + '--no-$enableInjectedClientFlag', + ); } if (chromeDebugPort != 0) { - throw InvalidConfiguration('--$chromeDebugPortFlag cannot be used ' - 'with --no-$enableInjectedClientFlag'); + throw InvalidConfiguration( + '--$chromeDebugPortFlag cannot be used ' + 'with --no-$enableInjectedClientFlag', + ); } } if (launchApps.isNotEmpty && !launchInChrome) { throw InvalidConfiguration( - '--$launchAppOption can only be used with --$launchInChromeFlag'); + '--$launchAppOption can only be used with --$launchInChromeFlag', + ); } if (userDataDir != null && !launchInChrome) { throw InvalidConfiguration( - '--$userDataDir can only be used with --$launchInChromeFlag'); + '--$userDataDir can only be used with --$launchInChromeFlag', + ); } } /// Creates a new [Configuration] with all non-null fields from /// [other] overriding the values of `this`. Configuration _override(Configuration other) => Configuration( - autoRun: other._autoRun ?? _autoRun, - chromeDebugPort: other._chromeDebugPort ?? _chromeDebugPort, - debugExtension: other._debugExtension ?? _debugExtension, - debug: other._debug ?? _debug, - enableInjectedClient: - other._enableInjectedClient ?? _enableInjectedClient, - hostname: other._hostname ?? _hostname, - tlsCertChain: other._tlsCertChain ?? _tlsCertChain, - tlsCertKey: other._tlsCertKey ?? _tlsCertKey, - launchApps: other._launchApps ?? _launchApps, - launchInChrome: other._launchInChrome ?? _launchInChrome, - userDataDir: other._userDataDir ?? _userDataDir, - logRequests: other._logRequests ?? _logRequests, - output: other._output ?? _output, - release: other._release ?? _release, - reload: other._reload ?? _reload, - requireBuildWebCompilers: - other._requireBuildWebCompilers ?? _requireBuildWebCompilers, - disableDds: other._disableDds ?? _disableDds, - enableExpressionEvaluation: - other._enableExpressionEvaluation ?? _enableExpressionEvaluation, - verbose: other._verbose ?? _verbose, - nullSafety: other._nullSafety ?? _nullSafety, - experiments: other._experiments ?? _experiments, - canaryFeatures: other._canaryFeatures ?? _canaryFeatures, - offline: other._offline ?? _offline); + autoRun: other._autoRun ?? _autoRun, + chromeDebugPort: other._chromeDebugPort ?? _chromeDebugPort, + debugExtension: other._debugExtension ?? _debugExtension, + debug: other._debug ?? _debug, + enableInjectedClient: other._enableInjectedClient ?? _enableInjectedClient, + hostname: other._hostname ?? _hostname, + tlsCertChain: other._tlsCertChain ?? _tlsCertChain, + tlsCertKey: other._tlsCertKey ?? _tlsCertKey, + launchApps: other._launchApps ?? _launchApps, + launchInChrome: other._launchInChrome ?? _launchInChrome, + userDataDir: other._userDataDir ?? _userDataDir, + logRequests: other._logRequests ?? _logRequests, + output: other._output ?? _output, + release: other._release ?? _release, + reload: other._reload ?? _reload, + requireBuildWebCompilers: + other._requireBuildWebCompilers ?? _requireBuildWebCompilers, + disableDds: other._disableDds ?? _disableDds, + enableExpressionEvaluation: + other._enableExpressionEvaluation ?? _enableExpressionEvaluation, + verbose: other._verbose ?? _verbose, + nullSafety: other._nullSafety ?? _nullSafety, + experiments: other._experiments ?? _experiments, + canaryFeatures: other._canaryFeatures ?? _canaryFeatures, + offline: other._offline ?? _offline, + ); factory Configuration.noInjectedClientDefaults() => Configuration(autoRun: false, debug: false, debugExtension: false); @@ -292,23 +304,26 @@ class Configuration { bool get offline => _offline ?? false; /// Returns a new configuration with values updated from the parsed args. - static Configuration fromArgs(ArgResults? argResults, - {Configuration? defaultConfiguration}) { + static Configuration fromArgs( + ArgResults? argResults, { + Configuration? defaultConfiguration, + }) { defaultConfiguration ??= Configuration(); if (argResults == null) return defaultConfiguration; final enableInjectedClient = argResults.options.contains(enableInjectedClientFlag) - ? (argResults[enableInjectedClientFlag] as bool) - : defaultConfiguration.enableInjectedClient; + ? (argResults[enableInjectedClientFlag] as bool) + : defaultConfiguration.enableInjectedClient; // Change the defaults when we have no injected client to disable all // debugging features. // // After parsing we check these defaults weren't overridden as well. if (!enableInjectedClient) { - defaultConfiguration = defaultConfiguration - ._override(Configuration.noInjectedClientDefaults()); + defaultConfiguration = defaultConfiguration._override( + Configuration.noInjectedClientDefaults(), + ); } final chromeDebugPort = argResults.options.contains(chromeDebugPortFlag) @@ -335,21 +350,23 @@ class Configuration { ? argResults[tlsCertKeyFlag] as String? : defaultConfiguration.tlsCertKey; - final launchApps = argResults.options.contains(launchAppOption) && + final launchApps = + argResults.options.contains(launchAppOption) && argResults.wasParsed(launchAppOption) ? argResults[launchAppOption] as List? : defaultConfiguration.launchApps; - final launchInChrome = argResults.options.contains(launchInChromeFlag) && + final launchInChrome = + argResults.options.contains(launchInChromeFlag) && argResults.wasParsed(launchInChromeFlag) ? argResults[launchInChromeFlag] as bool? // We want to default to launch chrome if the user provides just --debug // and not --chrome-debug-port. : debug! && - !(argResults.options.contains(launchInChromeFlag) && - argResults.wasParsed(chromeDebugPortFlag)) - ? true - : defaultConfiguration.launchInChrome; + !(argResults.options.contains(launchInChromeFlag) && + argResults.wasParsed(chromeDebugPortFlag)) + ? true + : defaultConfiguration.launchInChrome; final userDataDir = argResults.options.contains(userDataDirFlag) ? argResults[userDataDirFlag] as String? @@ -386,13 +403,13 @@ class Configuration { final requireBuildWebCompilers = argResults.options.contains(requireBuildWebCompilersFlag) - ? argResults[requireBuildWebCompilersFlag] as bool? - : defaultConfiguration.requireBuildWebCompilers; + ? argResults[requireBuildWebCompilersFlag] as bool? + : defaultConfiguration.requireBuildWebCompilers; final enableExpressionEvaluation = argResults.options.contains(enableExpressionEvaluationFlag) - ? argResults[enableExpressionEvaluationFlag] as bool? - : defaultConfiguration.enableExpressionEvaluation; + ? argResults[enableExpressionEvaluationFlag] as bool? + : defaultConfiguration.enableExpressionEvaluation; final verbose = argResults.options.contains(verboseFlag) ? argResults[verboseFlag] as bool? @@ -406,7 +423,8 @@ class Configuration { ? argResults[disableDdsFlag] as bool? : defaultConfiguration.disableDds; - final experiments = argResults.options.contains(enableExperimentOption) && + final experiments = + argResults.options.contains(enableExperimentOption) && argResults.wasParsed(enableExperimentOption) ? argResults[enableExperimentOption] as List? : defaultConfiguration.experiments; diff --git a/webdev/lib/src/command/daemon_command.dart b/webdev/lib/src/command/daemon_command.dart index 72651a195..e3159c9d8 100644 --- a/webdev/lib/src/command/daemon_command.dart +++ b/webdev/lib/src/command/daemon_command.dart @@ -22,10 +22,10 @@ import 'configuration.dart'; import 'shared.dart'; Stream> get _stdinCommandStream => stdin - .transform(utf8.decoder) - .transform(const LineSplitter()) - .where((String line) => line.startsWith('[{') && line.endsWith('}]')) - .map>((String line) { + .transform(utf8.decoder) + .transform(const LineSplitter()) + .where((String line) => line.startsWith('[{') && line.endsWith('}]')) + .map>((String line) { line = line.substring(1, line.length - 1); return json.decode(line) as Map; }); @@ -61,9 +61,15 @@ class DaemonCommand extends Command { @override Future run() async { - final configuration = Configuration.fromArgs(argResults, - defaultConfiguration: Configuration( - launchInChrome: true, debug: true, autoRun: false, release: false)); + final configuration = Configuration.fromArgs( + argResults, + defaultConfiguration: Configuration( + launchInChrome: true, + debug: true, + autoRun: false, + release: false, + ), + ); configureLogWriter(configuration.verbose); // Validate the pubspec first to ensure we are in a Dart project. try { @@ -76,43 +82,55 @@ class DaemonCommand extends Command { Daemon? daemon; DevWorkflow? workflow; var cancelCount = 0; - final cancelSub = StreamGroup.merge([ - ProcessSignal.sigint.watch(), - // SIGTERM is not supported on Windows. - Platform.isWindows ? const Stream.empty() : ProcessSignal.sigterm.watch() - ]).listen((signal) async { - cancelCount++; - daemon?.shutdown(); - if (cancelCount > 1) exit(1); - }); + final cancelSub = + StreamGroup.merge([ + ProcessSignal.sigint.watch(), + // SIGTERM is not supported on Windows. + Platform.isWindows + ? const Stream.empty() + : ProcessSignal.sigterm.watch(), + ]).listen((signal) async { + cancelCount++; + daemon?.shutdown(); + if (cancelCount > 1) exit(1); + }); try { daemon = Daemon(_stdinCommandStream, _stdoutCommandResponse); final daemonDomain = DaemonDomain(daemon); - configureLogWriter(configuration.verbose, customLogWriter: - (level, message, {loggerName, error, stackTrace, verbose}) { - if (configuration.verbose || level >= Level.INFO) { - daemonDomain.sendEvent('daemon.log', { - 'log': formatLog( - level, - message, - loggerName: loggerName, - error: error, - stackTrace: stackTrace, - ) - }); - } - }); + configureLogWriter( + configuration.verbose, + customLogWriter: + (level, message, {loggerName, error, stackTrace, verbose}) { + if (configuration.verbose || level >= Level.INFO) { + daemonDomain.sendEvent('daemon.log', { + 'log': formatLog( + level, + message, + loggerName: loggerName, + error: error, + stackTrace: stackTrace, + ), + }); + } + }, + ); daemon.registerDomain(daemonDomain); final buildOptions = buildRunnerArgs(configuration); final extraArgs = argResults?.rest ?? []; - final directoryArgs = - extraArgs.where((arg) => !arg.startsWith('-')).toList(); - final targetPorts = - parseDirectoryArgs(directoryArgs, basePort: await findUnusedPort()); + final directoryArgs = extraArgs + .where((arg) => !arg.startsWith('-')) + .toList(); + final targetPorts = parseDirectoryArgs( + directoryArgs, + basePort: await findUnusedPort(), + ); validateLaunchApps(configuration.launchApps, targetPorts.keys); - workflow = - await DevWorkflow.start(configuration, buildOptions, targetPorts); + workflow = await DevWorkflow.start( + configuration, + buildOptions, + targetPorts, + ); daemon.registerDomain(AppDomain(daemon, workflow.serverManager)); await daemon.onExit; exitCode = 0; diff --git a/webdev/lib/src/command/serve_command.dart b/webdev/lib/src/command/serve_command.dart index 3c32817e8..b85cf3c30 100644 --- a/webdev/lib/src/command/serve_command.dart +++ b/webdev/lib/src/command/serve_command.dart @@ -20,68 +20,107 @@ class ServeCommand extends Command { final name = 'serve'; @override - final description = 'Run a local web development server and a file system' + final description = + 'Run a local web development server and a file system' ' watcher that rebuilds on changes.'; @override final argParser = ArgParser(usageLineLength: lineLength) - ..addOption(autoOption, help: ''' + ..addOption( + autoOption, + help: ''' Automatically performs an action after each build: restart: Reload modules and re-invoke main (loses current state) refresh: Performs a full page refresh. -''', allowed: ['restart', 'refresh']) - ..addFlag(debugFlag, - help: 'Enable the launching of DevTools (Alt + D / Option + D). ' - 'This also enables --$launchInChromeFlag.') - ..addFlag(debugExtensionFlag, - help: 'Enable the backend for the Dart Debug Extension. ' - 'Learn more at dart.dev/to/web-debug-extension.') - ..addFlag(enableInjectedClientFlag, - help: 'Whether or not to inject the client.js script in web apps. This ' - 'is required for all debugging related features, but may interact ' - 'poorly with proxy servers or other environments.', - defaultsTo: true) +''', + allowed: ['restart', 'refresh'], + ) + ..addFlag( + debugFlag, + help: + 'Enable the launching of DevTools (Alt + D / Option + D). ' + 'This also enables --$launchInChromeFlag.', + ) + ..addFlag( + debugExtensionFlag, + help: + 'Enable the backend for the Dart Debug Extension. ' + 'Learn more at dart.dev/to/web-debug-extension.', + ) + ..addFlag( + enableInjectedClientFlag, + help: + 'Whether or not to inject the client.js script in web apps. This ' + 'is required for all debugging related features, but may interact ' + 'poorly with proxy servers or other environments.', + defaultsTo: true, + ) ..addSeparator('Advanced:') - ..addOption(chromeDebugPortFlag, - help: 'Specify which port the Chrome debugger is listening on. ' - 'If used with $launchInChromeFlag Chrome will be started with the' - ' debugger listening on this port.') - ..addOption(hostnameFlag, - help: 'Specify the hostname to serve on.', defaultsTo: 'localhost') - ..addFlag(hotRestartFlag, - negatable: false, - help: 'Automatically reloads changed modules after each build ' - 'and restarts your application.\n' - "Can't be used with $liveReloadFlag.", - hide: true) + ..addOption( + chromeDebugPortFlag, + help: + 'Specify which port the Chrome debugger is listening on. ' + 'If used with $launchInChromeFlag Chrome will be started with the' + ' debugger listening on this port.', + ) + ..addOption( + hostnameFlag, + help: 'Specify the hostname to serve on.', + defaultsTo: 'localhost', + ) + ..addFlag( + hotRestartFlag, + negatable: false, + help: + 'Automatically reloads changed modules after each build ' + 'and restarts your application.\n' + "Can't be used with $liveReloadFlag.", + hide: true, + ) ..addFlag(hotReloadFlag, negatable: false, hide: true) - ..addFlag(launchInChromeFlag, - help: 'Automatically launches your application in Chrome with the ' - 'debug port open. Use $chromeDebugPortFlag to specify a specific ' - 'port to attach to an already running chrome instance instead.') - ..addOption(userDataDirFlag, - defaultsTo: null, - help: 'Use with $launchInChromeFlag to specify user data directory ' - 'to pass to chrome. Will start chrome window logged into default ' - 'profile with enabled extensions. Use `auto` as a value to infer ' - 'the default directory for the current OS. ' - 'Note: only supported for Mac OS X and linux platforms.') - ..addFlag(liveReloadFlag, - negatable: false, - help: 'Automatically refreshes the page after each successful build.\n' - "Can't be used with $hotRestartFlag.", - hide: true) - ..addFlag(logRequestsFlag, - negatable: false, - help: 'Enables logging for each request to the server.') - ..addOption(tlsCertChainFlag, - help: - 'The file location to a TLS Certificate to create an HTTPs server.\n' - 'Must be used with $tlsCertKeyFlag.') - ..addOption(tlsCertKeyFlag, - help: 'The file location to a TLS Key to create an HTTPs server.\n' - 'Must be used with $tlsCertChainFlag.') + ..addFlag( + launchInChromeFlag, + help: + 'Automatically launches your application in Chrome with the ' + 'debug port open. Use $chromeDebugPortFlag to specify a specific ' + 'port to attach to an already running chrome instance instead.', + ) + ..addOption( + userDataDirFlag, + defaultsTo: null, + help: + 'Use with $launchInChromeFlag to specify user data directory ' + 'to pass to chrome. Will start chrome window logged into default ' + 'profile with enabled extensions. Use `auto` as a value to infer ' + 'the default directory for the current OS. ' + 'Note: only supported for Mac OS X and linux platforms.', + ) + ..addFlag( + liveReloadFlag, + negatable: false, + help: + 'Automatically refreshes the page after each successful build.\n' + "Can't be used with $hotRestartFlag.", + hide: true, + ) + ..addFlag( + logRequestsFlag, + negatable: false, + help: 'Enables logging for each request to the server.', + ) + ..addOption( + tlsCertChainFlag, + help: + 'The file location to a TLS Certificate to create an HTTPs server.\n' + 'Must be used with $tlsCertKeyFlag.', + ) + ..addOption( + tlsCertKeyFlag, + help: + 'The file location to a TLS Key to create an HTTPs server.\n' + 'Must be used with $tlsCertChainFlag.', + ) ..addSeparator('Common:'); ServeCommand() { @@ -107,13 +146,17 @@ refresh: Performs a full page refresh. final buildOptions = buildRunnerArgs(configuration) ..addAll(argResults!.rest.where((arg) => arg.startsWith('-')).toList()); final extraArgs = argResults?.rest ?? []; - final directoryArgs = - extraArgs.where((arg) => !arg.startsWith('-')).toList(); + final directoryArgs = extraArgs + .where((arg) => !arg.startsWith('-')) + .toList(); final targetPorts = parseDirectoryArgs(directoryArgs); validateLaunchApps(configuration.launchApps, targetPorts.keys); - final workflow = - await DevWorkflow.start(configuration, buildOptions, targetPorts); + final workflow = await DevWorkflow.start( + configuration, + buildOptions, + targetPorts, + ); await workflow.done; return 0; } diff --git a/webdev/lib/src/command/shared.dart b/webdev/lib/src/command/shared.dart index 097a893c9..b6c9f9f4d 100644 --- a/webdev/lib/src/command/shared.dart +++ b/webdev/lib/src/command/shared.dart @@ -13,8 +13,11 @@ import 'configuration.dart'; final lineLength = stdout.hasTerminal ? stdout.terminalColumns : 80; -void addSharedArgs(ArgParser argParser, - {String? outputDefault, bool? releaseDefault}) { +void addSharedArgs( + ArgParser argParser, { + String? outputDefault, + bool? releaseDefault, +}) { outputDefault ??= outputNone; releaseDefault ??= true; argParser @@ -22,63 +25,83 @@ void addSharedArgs(ArgParser argParser, outputFlag, abbr: 'o', defaultsTo: outputDefault, - help: 'A directory to write the result of a build to. Or a mapping ' + help: + 'A directory to write the result of a build to. Or a mapping ' 'from a top-level directory in the package to the directory to ' 'write a filtered build output to. For example "web:deploy".\n' 'A value of "NONE" indicates that no "--output" value should be ' 'passed to `build_runner`.', ) - ..addOption(nullSafetyFlag, - abbr: 'n', - defaultsTo: nullSafetyAuto, - allowed: [nullSafetySound, nullSafetyUnsound, nullSafetyAuto], - help: - 'DEPRECATED: If "sound", `package:build_web_compilers` will be run ' - 'with sound null safety support. ' - 'If "unsound", `package:build_web_compilers` will be run without ' - 'sound null safety support. ' - 'If "auto", the default `package:build_web_compilers` ' - 'behavior is used.', - hide: true) - ..addFlag(releaseFlag, - abbr: 'r', - defaultsTo: releaseDefault, - negatable: true, - help: 'Build with release mode defaults for builders.') - ..addFlag(requireBuildWebCompilersFlag, - defaultsTo: true, - negatable: true, - help: 'If a dependency on `build_web_compilers` is required to run.') - ..addFlag(disableDdsFlag, - negatable: false, - help: 'Disable the Dart Development Service (DDS). Disabling DDS may ' - 'result in a degraded developer experience in some tools.', - hide: true) - ..addFlag(enableExpressionEvaluationFlag, - abbr: 'e', - defaultsTo: true, - negatable: true, - help: 'Enable expression evaluation features in the debugger.') - ..addMultiOption(enableExperimentOption, - abbr: 'x', - defaultsTo: null, - hide: true, - help: 'Enable experiment features in the debugger.') - ..addFlag(canaryFeaturesFlag, - abbr: 'c', - defaultsTo: false, - negatable: true, - hide: true, - help: 'Enables DDC canary features.') - ..addFlag(verboseFlag, - abbr: 'v', - defaultsTo: false, - negatable: false, - help: 'Enables verbose logging.') - ..addFlag(offlineFlag, - defaultsTo: false, - negatable: false, - help: 'Disable fetching from pub.dev.'); + ..addOption( + nullSafetyFlag, + abbr: 'n', + defaultsTo: nullSafetyAuto, + allowed: [nullSafetySound, nullSafetyUnsound, nullSafetyAuto], + help: + 'DEPRECATED: If "sound", `package:build_web_compilers` will be run ' + 'with sound null safety support. ' + 'If "unsound", `package:build_web_compilers` will be run without ' + 'sound null safety support. ' + 'If "auto", the default `package:build_web_compilers` ' + 'behavior is used.', + hide: true, + ) + ..addFlag( + releaseFlag, + abbr: 'r', + defaultsTo: releaseDefault, + negatable: true, + help: 'Build with release mode defaults for builders.', + ) + ..addFlag( + requireBuildWebCompilersFlag, + defaultsTo: true, + negatable: true, + help: 'If a dependency on `build_web_compilers` is required to run.', + ) + ..addFlag( + disableDdsFlag, + negatable: false, + help: + 'Disable the Dart Development Service (DDS). Disabling DDS may ' + 'result in a degraded developer experience in some tools.', + hide: true, + ) + ..addFlag( + enableExpressionEvaluationFlag, + abbr: 'e', + defaultsTo: true, + negatable: true, + help: 'Enable expression evaluation features in the debugger.', + ) + ..addMultiOption( + enableExperimentOption, + abbr: 'x', + defaultsTo: null, + hide: true, + help: 'Enable experiment features in the debugger.', + ) + ..addFlag( + canaryFeaturesFlag, + abbr: 'c', + defaultsTo: false, + negatable: true, + hide: true, + help: 'Enables DDC canary features.', + ) + ..addFlag( + verboseFlag, + abbr: 'v', + defaultsTo: false, + negatable: false, + help: 'Enables verbose logging.', + ) + ..addFlag( + offlineFlag, + defaultsTo: false, + negatable: false, + help: 'Disable fetching from pub.dev.', + ); } /// Parses the provided [Configuration] to return a list of @@ -108,8 +131,10 @@ List buildRunnerArgs(Configuration configuration) { Future validatePubspecLock(Configuration configuration) async { final pubspecLock = await PubspecLock.read(offline: configuration.offline); - await checkPubspecLock(pubspecLock, - requireBuildWebCompilers: configuration.requireBuildWebCompilers); + await checkPubspecLock( + pubspecLock, + requireBuildWebCompilers: configuration.requireBuildWebCompilers, + ); } /// Checks that the normalized form of [path] is a top level directory under @@ -124,8 +149,9 @@ void ensureIsTopLevelDir(String path) { path.contains(r'\') || path.contains(r'/')) { throw InvalidConfiguration( - 'Only top level directories under the package can be built or served ' - '(such as `web` or `test`), but was given `$path`.'); + 'Only top level directories under the package can be built or served ' + '(such as `web` or `test`), but was given `$path`.', + ); } } @@ -173,9 +199,10 @@ void validateLaunchApps(List launchApps, Iterable serveDirs) { final dir = p.url.split(app).first; if (!serveDirs.contains(dir)) { throw InvalidConfiguration( - 'Unable to launch app `$app` since its top level dir (`$dir`) ' - 'is not being served. The currently directories being served are: ' - '${serveDirs.toList()}'); + 'Unable to launch app `$app` since its top level dir (`$dir`) ' + 'is not being served. The currently directories being served are: ' + '${serveDirs.toList()}', + ); } } } diff --git a/webdev/lib/src/daemon/app_domain.dart b/webdev/lib/src/daemon/app_domain.dart index 8d750e50e..ec24f8010 100644 --- a/webdev/lib/src/daemon/app_domain.dart +++ b/webdev/lib/src/daemon/app_domain.dart @@ -83,7 +83,7 @@ class AppDomain extends Domain { 'appId': appId, 'directory': Directory.current.path, 'deviceId': 'chrome', - 'launchMode': 'run' + 'launchMode': 'run', }); // Set up VM service listeners for this appId @@ -96,31 +96,30 @@ class AppDomain extends Domain { 'wsUri': debugConnection.uri, }); // ignore: cancel_subscriptions - final resultSub = - server.buildResults.listen((r) => _handleBuildResult(r, appId)); + final resultSub = server.buildResults.listen( + (r) => _handleBuildResult(r, appId), + ); final appState = _AppState(debugConnection, resultSub, stdOutSub); _appStates[appId] = appState; - sendEvent('app.started', { - 'appId': appId, - }); + sendEvent('app.started', {'appId': appId}); appConnection.runMain(); // Handle connection termination - send events first, then cleanup - unawaited(debugConnection.onDone.whenComplete(() { - sendEvent('app.log', { - 'appId': appId, - 'log': 'Lost connection to device.', - }); - sendEvent('app.stop', { - 'appId': appId, - }); - daemon.shutdown(); - - // Clean up app resources - _cleanupAppConnection(appId, appState); - })); + unawaited( + debugConnection.onDone.whenComplete(() { + sendEvent('app.log', { + 'appId': appId, + 'log': 'Lost connection to device.', + }); + sendEvent('app.stop', {'appId': appId}); + daemon.shutdown(); + + // Clean up app resources + _cleanupAppConnection(appId, appState); + }), + ); } // Shutdown could have been triggered while awaiting above. @@ -148,7 +147,8 @@ class AppDomain extends Domain { } Future?> _callServiceExtension( - Map args) async { + Map args, + ) async { final appId = getStringArg(args, 'appId', required: true); final appState = _appStates[appId]; if (appState == null) { @@ -158,8 +158,10 @@ class AppDomain extends Domain { final params = args['params'] != null ? (args['params'] as Map) : {}; - final response = await appState.vmService! - .callServiceExtension(methodName, args: params); + final response = await appState.vmService!.callServiceExtension( + methodName, + args: params, + ); return response.json; } @@ -171,10 +173,7 @@ class AppDomain extends Domain { } final fullRestart = getBoolArg(args, 'fullRestart') ?? false; if (!fullRestart) { - return { - 'code': 1, - 'message': 'hot reload not yet supported by webdev', - }; + return {'code': 1, 'message': 'hot reload not yet supported by webdev'}; } // TODO(grouma) - Support pauseAfterRestart. // var pauseAfterRestart = getBoolArg(args, 'pause') ?? false; @@ -188,8 +187,9 @@ class AppDomain extends Domain { }); final restartMethod = _registeredMethodsForService['hotRestart'] ?? 'hotRestart'; - final response = - await appState.vmService!.callServiceExtension(restartMethod); + final response = await appState.vmService!.callServiceExtension( + restartMethod, + ); sendEvent('app.progress', { 'appId': appId, 'id': '$_progressEventId', @@ -198,11 +198,11 @@ class AppDomain extends Domain { }); sendEvent('app.log', { 'appId': appId, - 'log': 'Restarted application in ${stopwatch.elapsedMilliseconds}ms' + 'log': 'Restarted application in ${stopwatch.elapsedMilliseconds}ms', }); return { 'code': response.type == 'Success' ? 0 : 1, - 'message': response.toString() + 'message': response.toString(), }; } @@ -223,7 +223,9 @@ class AppDomain extends Domain { /// Sets up VM service listeners for the given appId. /// Returns the stdout subscription. Future> _setupVmServiceListeners( - String appId, VmService vmService) async { + String appId, + VmService vmService, + ) async { try { vmService.onServiceEvent.listen(_onServiceEvent); await vmService.streamListen(EventStreams.kService); diff --git a/webdev/lib/src/daemon/daemon.dart b/webdev/lib/src/daemon/daemon.dart index 6fa6cf68d..ebe37475a 100644 --- a/webdev/lib/src/daemon/daemon.dart +++ b/webdev/lib/src/daemon/daemon.dart @@ -13,10 +13,7 @@ import 'utilites.dart'; /// Listens for commands, routes them to the corresponding domain and provides /// the result. class Daemon { - Daemon( - Stream> commandStream, - this._sendCommand, - ) { + Daemon(Stream> commandStream, this._sendCommand) { _commandSubscription = commandStream.listen( _handleRequest, onDone: () { @@ -66,7 +63,10 @@ class Daemon { } domainValue.handleCommand( - name, id, request['params'] as Map? ?? {}); + name, + id, + request['params'] as Map? ?? {}, + ); } catch (error, trace) { send({ 'id': id, diff --git a/webdev/lib/src/daemon/daemon_domain.dart b/webdev/lib/src/daemon/daemon_domain.dart index df1bd8675..c5e75a4fd 100644 --- a/webdev/lib/src/daemon/daemon_domain.dart +++ b/webdev/lib/src/daemon/daemon_domain.dart @@ -16,13 +16,7 @@ class DaemonDomain extends Domain { registerHandler('version', _version); registerHandler('shutdown', _shutdown); - sendEvent( - 'daemon.connected', - { - 'version': protocolVersion, - 'pid': pid, - }, - ); + sendEvent('daemon.connected', {'version': protocolVersion, 'pid': pid}); } Future _version(Map args) { diff --git a/webdev/lib/src/daemon/domain.dart b/webdev/lib/src/daemon/domain.dart index f54f58dac..a4607cd7e 100644 --- a/webdev/lib/src/daemon/domain.dart +++ b/webdev/lib/src/daemon/domain.dart @@ -24,21 +24,23 @@ abstract class Domain { void handleCommand(String command, dynamic id, Map args) { Future.sync(() { - if (_handlers.containsKey(command)) return _handlers[command]!(args); - throw ArgumentError('command not understood: $name.$command'); - }).then((dynamic result) { - if (result == null) { - _send({'id': id}); - } else { - _send({'id': id, 'result': toJsonable(result)}); - } - }).catchError((dynamic error, dynamic trace) { - _send({ - 'id': id, - 'error': toJsonable(error), - 'trace': '$trace', - }); - }); + if (_handlers.containsKey(command)) return _handlers[command]!(args); + throw ArgumentError('command not understood: $name.$command'); + }) + .then((dynamic result) { + if (result == null) { + _send({'id': id}); + } else { + _send({'id': id, 'result': toJsonable(result)}); + } + }) + .catchError((dynamic error, dynamic trace) { + _send({ + 'id': id, + 'error': toJsonable(error), + 'trace': '$trace', + }); + }); } void sendEvent(String name, [dynamic args]) { diff --git a/webdev/lib/src/daemon/utilites.dart b/webdev/lib/src/daemon/utilites.dart index 6cbdcc479..31f414a1b 100644 --- a/webdev/lib/src/daemon/utilites.dart +++ b/webdev/lib/src/daemon/utilites.dart @@ -14,8 +14,11 @@ dynamic toJsonable(dynamic obj) { return '$obj'; } -String? getStringArg(Map args, String name, - {bool required = false}) { +String? getStringArg( + Map args, + String name, { + bool required = false, +}) { if (required && !args.containsKey(name)) { throw ArgumentError('$name is required'); } @@ -26,8 +29,11 @@ String? getStringArg(Map args, String name, return val as String?; } -bool? getBoolArg(Map args, String name, - {bool required = false}) { +bool? getBoolArg( + Map args, + String name, { + bool required = false, +}) { if (required && !args.containsKey(name)) { throw ArgumentError('$name is required'); } @@ -36,8 +42,11 @@ bool? getBoolArg(Map args, String name, return val as bool?; } -int? getIntArg(Map args, String name, - {bool required = false}) { +int? getIntArg( + Map args, + String name, { + bool required = false, +}) { if (required && !args.containsKey(name)) { throw ArgumentError('$name is required'); } diff --git a/webdev/lib/src/daemon_client.dart b/webdev/lib/src/daemon_client.dart index a986ddf38..c0be0ea71 100644 --- a/webdev/lib/src/daemon_client.dart +++ b/webdev/lib/src/daemon_client.dart @@ -12,11 +12,17 @@ import 'package:build_daemon/data/server_log.dart'; import 'util.dart'; /// Connects to the `build_runner` daemon. -Future connectClient(String workingDirectory, - List options, Function(ServerLog) logHandler) => - BuildDaemonClient.connect(workingDirectory, - [dartPath, 'run', 'build_runner', 'daemon', ...options], - logHandler: logHandler); +Future connectClient( + String workingDirectory, + List options, + Function(ServerLog) logHandler, +) => BuildDaemonClient.connect(workingDirectory, [ + dartPath, + 'run', + 'build_runner', + 'daemon', + ...options, +], logHandler: logHandler); /// Returns the port of the daemon asset server. int daemonPort(String workingDirectory) { diff --git a/webdev/lib/src/logging.dart b/webdev/lib/src/logging.dart index f00ca6333..6e65dff6d 100644 --- a/webdev/lib/src/logging.dart +++ b/webdev/lib/src/logging.dart @@ -8,8 +8,14 @@ import 'dart:io'; import 'package:io/ansi.dart'; import 'package:logging/logging.dart'; -typedef LogWriter = void Function(Level level, String message, - {String? error, String? loggerName, String? stackTrace}); +typedef LogWriter = + void Function( + Level level, + String message, { + String? error, + String? loggerName, + String? stackTrace, + }); var _verbose = false; StreamSubscription? _subscription; @@ -19,40 +25,52 @@ void configureLogWriter(bool verbose, {LogWriter? customLogWriter}) { _logWriter = customLogWriter ?? _logWriter; Logger.root.level = verbose ? Level.ALL : Level.INFO; _subscription ??= Logger.root.onRecord.listen((event) { - logWriter(event.level, event.message, - error: event.error?.toString(), - loggerName: event.loggerName, - stackTrace: event.stackTrace?.toString()); + logWriter( + event.level, + event.message, + error: event.error?.toString(), + loggerName: event.loggerName, + stackTrace: event.stackTrace?.toString(), + ); }); } // ignore: prefer_function_declarations_over_variables LogWriter _logWriter = (level, message, {String? error, String? loggerName, String? stackTrace}) { - // Erases the previous line - if (!_verbose) stdout.write('\x1b[2K\r'); - final log = formatLog(level, message, - error: error, - loggerName: loggerName, - stackTrace: stackTrace, - withColors: true); + // Erases the previous line + if (!_verbose) stdout.write('\x1b[2K\r'); + final log = formatLog( + level, + message, + error: error, + loggerName: loggerName, + stackTrace: stackTrace, + withColors: true, + ); - if (level >= Level.INFO || _verbose) { - stdout.write(log); - // Prevent multiline logs and > info messages from being erased. - if (level > Level.INFO || - _verbose || - (log.contains('\n') && !log.endsWith('\n'))) { - stdout.writeln(''); - } - } -}; + if (level >= Level.INFO || _verbose) { + stdout.write(log); + // Prevent multiline logs and > info messages from being erased. + if (level > Level.INFO || + _verbose || + (log.contains('\n') && !log.endsWith('\n'))) { + stdout.writeln(''); + } + } + }; LogWriter get logWriter => _logWriter; /// Colors the message and writes it to stdout. -String formatLog(Level level, String message, - {bool? withColors, String? error, String? loggerName, String? stackTrace}) { +String formatLog( + Level level, + String message, { + bool? withColors, + String? error, + String? loggerName, + String? stackTrace, +}) { withColors ??= false; final buffer = StringBuffer(message); if (error != null) { @@ -78,7 +96,7 @@ String formatLog(Level level, String message, final loggerNameOutput = (loggerName != null && (_verbose || loggerName.contains(' '))) - ? ' $loggerName:' - : ''; + ? ' $loggerName:' + : ''; return '$formattedLevel$loggerNameOutput $buffer'; } diff --git a/webdev/lib/src/pubspec.dart b/webdev/lib/src/pubspec.dart index 9dc7b4e39..93400bc97 100644 --- a/webdev/lib/src/pubspec.dart +++ b/webdev/lib/src/pubspec.dart @@ -28,19 +28,23 @@ class PackageExceptionDetails { final String? description; final bool _missingDependency; - const PackageExceptionDetails._(this.error, - {this.description, bool missingDependency = false}) - : _missingDependency = missingDependency; + const PackageExceptionDetails._( + this.error, { + this.description, + bool missingDependency = false, + }) : _missingDependency = missingDependency; static PackageExceptionDetails missingDep( - String pkgName, VersionConstraint constraint) => - PackageExceptionDetails._( - 'You must have a dependency on `$pkgName` in `pubspec.yaml`.', - description: ''' + String pkgName, + VersionConstraint constraint, + ) => PackageExceptionDetails._( + 'You must have a dependency on `$pkgName` in `pubspec.yaml`.', + description: ''' # pubspec.yaml dev_dependencies: $pkgName: $constraint''', - missingDependency: true); + missingDependency: true, + ); @override String toString() => [error, description].join('\n'); @@ -50,16 +54,18 @@ Future _runPubDeps() async { final result = Process.runSync(dartPath, ['pub', 'deps']); if (result.exitCode == 65 || result.exitCode == 66) { - throw PackageException( - [PackageExceptionDetails._((result.stderr as String).trim())]); + throw PackageException([ + PackageExceptionDetails._((result.stderr as String).trim()), + ]); } if (result.exitCode != 0) { throw ProcessException( - dartPath, - ['pub', 'deps'], - '***OUT***\n${result.stdout}\n***ERR***\n${result.stderr}\n***', - exitCode); + dartPath, + ['pub', 'deps'], + '***OUT***\n${result.stdout}\n***ERR***\n${result.stderr}\n***', + exitCode, + ); } } @@ -74,11 +80,7 @@ class PubspecLock { } var dir = p.absolute(p.current); while (true) { - final candidate = p.join( - dir, - '.dart_tool', - 'package_config.json', - ); + final candidate = p.join(dir, '.dart_tool', 'package_config.json'); if (File(candidate).existsSync()) break; final next = p.dirname(dir); if (next == dir) { @@ -89,23 +91,32 @@ class PubspecLock { dir = next; } - final pubspecLock = loadYaml( - await File(p.relative(p.join(dir, 'pubspec.lock'))).readAsString()) - as YamlMap; + final pubspecLock = + loadYaml( + await File( + p.relative(p.join(dir, 'pubspec.lock')), + ).readAsString(), + ) + as YamlMap; final packages = pubspecLock['packages'] as YamlMap?; return PubspecLock(packages); } List checkPackage( - String pkgName, VersionConstraint constraint, - {String? forArgument}) { + String pkgName, + VersionConstraint constraint, { + String? forArgument, + }) { final issues = []; - final missingDetails = - PackageExceptionDetails.missingDep(pkgName, constraint); - - final pkgDataMap = - (_packages == null) ? null : _packages[pkgName] as YamlMap?; + final missingDetails = PackageExceptionDetails.missingDep( + pkgName, + constraint, + ); + + final pkgDataMap = (_packages == null) + ? null + : _packages[pkgName] as YamlMap?; if (pkgDataMap == null) { issues.add(missingDetails); } else { @@ -118,7 +129,8 @@ class PubspecLock { final version = pkgDataMap['version'] as String; final pkgVersion = Version.parse(version); if (!constraint.allows(pkgVersion)) { - final error = 'The `$pkgName` version – $pkgVersion – is not ' + final error = + 'The `$pkgName` version – $pkgVersion – is not ' 'within the allowed constraint – $constraint.'; issues.add(PackageExceptionDetails._(error)); } @@ -132,7 +144,8 @@ class PubspecLock { } Future> _validateBuildDaemonVersion( - PubspecLock pubspecLock) async { + PubspecLock pubspecLock, +) async { final buildDaemonConstraint = '^4.0.0'; final issues = []; @@ -154,13 +167,21 @@ Future> _validateBuildDaemonVersion( pubspecLock .checkPackage('build_daemon', info.buildDaemonConstraint) .isEmpty) { - issues.add(PackageExceptionDetails._('$issuePreamble\n' + issues.add( + PackageExceptionDetails._( + '$issuePreamble\n' 'A newer version of webdev is available which supports ' - 'your version of the `build_daemon`. Please update.')); + 'your version of the `build_daemon`. Please update.', + ), + ); } else { - issues.add(PackageExceptionDetails._('$issuePreamble\n' + issues.add( + PackageExceptionDetails._( + '$issuePreamble\n' 'Please add a dev dependency on `build_daemon` with constraint: ' - '$buildDaemonConstraint')); + '$buildDaemonConstraint', + ), + ); } } return issues; @@ -171,17 +192,25 @@ final buildWebCompilersConstraint = VersionConstraint.parse('^4.0.4'); // Note the minimum versions should never be dev versions as users will not // get them by default. -Future checkPubspecLock(PubspecLock pubspecLock, - {required bool requireBuildWebCompilers}) async { +Future checkPubspecLock( + PubspecLock pubspecLock, { + required bool requireBuildWebCompilers, +}) async { final issues = []; - final buildRunnerIssues = - pubspecLock.checkPackage('build_runner', buildRunnerConstraint); + final buildRunnerIssues = pubspecLock.checkPackage( + 'build_runner', + buildRunnerConstraint, + ); issues.addAll(buildRunnerIssues); if (requireBuildWebCompilers) { - issues.addAll(pubspecLock.checkPackage( - 'build_web_compilers', buildWebCompilersConstraint)); + issues.addAll( + pubspecLock.checkPackage( + 'build_web_compilers', + buildWebCompilersConstraint, + ), + ); } if (buildRunnerIssues.isEmpty) { @@ -202,11 +231,14 @@ class _PackageInfo { /// Returns the package info for the latest webdev release. Future<_PackageInfo> _latestPackageInfo() async { - final response = await get(Uri.parse('https://pub.dev/api/packages/webdev'), - headers: {HttpHeaders.userAgentHeader: 'webdev $packageVersion'}); + final response = await get( + Uri.parse('https://pub.dev/api/packages/webdev'), + headers: {HttpHeaders.userAgentHeader: 'webdev $packageVersion'}, + ); final responseObj = json.decode(response.body); final pubspec = Pubspec.fromJson( - responseObj['latest']['pubspec'] as Map); + responseObj['latest']['pubspec'] as Map, + ); final buildDaemonDependency = pubspec.dependencies['build_daemon']; // This should never be satisfied. var buildDaemonConstraint = VersionConstraint.parse('0.0.0'); diff --git a/webdev/lib/src/serve/chrome.dart b/webdev/lib/src/serve/chrome.dart index 033816ed2..3abf13982 100644 --- a/webdev/lib/src/serve/chrome.dart +++ b/webdev/lib/src/serve/chrome.dart @@ -22,10 +22,8 @@ class Chrome { final browser_launcher.Chrome _chrome; final ChromeConnection chromeConnection; - Chrome._( - this.debugPort, - this._chrome, - ) : chromeConnection = _chrome.chromeConnection; + Chrome._(this.debugPort, this._chrome) + : chromeConnection = _chrome.chromeConnection; Future close() async { if (_currentCompleter.isCompleted) _currentCompleter = Completer(); @@ -34,7 +32,8 @@ class Chrome { /// Connects to an instance of Chrome with an open debug port. static Future fromExisting(int port) async => _connect( - Chrome._(port, await browser_launcher.Chrome.fromExisting(port))); + Chrome._(port, await browser_launcher.Chrome.fromExisting(port)), + ); static Future get connectedInstance => _currentCompleter.future; @@ -45,18 +44,29 @@ class Chrome { /// Uses a copy of [userDataDir] to sign into the default /// user profile, or starts a new session without sign in, /// if not specified. - static Future start(List urls, - {required int port, String? userDataDir}) async { + static Future start( + List urls, { + required int port, + String? userDataDir, + }) async { var signIn = false; String? dir; // Re-using the directory causes flakiness on Windows, so on that platform // pass null to have it create a directory. // Issue: https://github.com/dart-lang/webdev/issues/1545 if (!Platform.isWindows) { - final userDataTemp = path.join(Directory.current.absolute.path, - '.dart_tool', 'webdev', 'chrome_user_data'); - final userDataCopy = path.join(Directory.current.absolute.path, - '.dart_tool', 'webdev', 'chrome_user_data_copy'); + final userDataTemp = path.join( + Directory.current.absolute.path, + '.dart_tool', + 'webdev', + 'chrome_user_data', + ); + final userDataCopy = path.join( + Directory.current.absolute.path, + '.dart_tool', + 'webdev', + 'chrome_user_data_copy', + ); if (userDataDir != null) { signIn = true; @@ -65,16 +75,20 @@ class Chrome { try { _logger.info('Copying user data directory...'); _logger.warning( - 'Copying user data directory might take >12s on the first ' - 'use of --$userDataDirFlag, and ~2-3s on subsequent runs. ' - 'Run without --$userDataDirFlag to improve performance.'); + 'Copying user data directory might take >12s on the first ' + 'use of --$userDataDirFlag, and ~2-3s on subsequent runs. ' + 'Run without --$userDataDirFlag to improve performance.', + ); Directory(dir).createSync(recursive: true); await updatePath( - path.join(userDataDir, 'Default'), path.join(dir, 'Default')); + path.join(userDataDir, 'Default'), + path.join(dir, 'Default'), + ); _logger.info( - 'Copied user data directory in ${stopwatch.elapsedMilliseconds} ms'); + 'Copied user data directory in ${stopwatch.elapsedMilliseconds} ms', + ); } catch (e, s) { dir = userDataTemp; signIn = false; @@ -94,8 +108,12 @@ class Chrome { } _logger.info('Starting chrome with user data directory: $dir'); - final chrome = await browser_launcher.Chrome.startWithDebugPort(urls, - debugPort: port, userDataDir: dir, signIn: signIn); + final chrome = await browser_launcher.Chrome.startWithDebugPort( + urls, + debugPort: port, + userDataDir: dir, + signIn: signIn, + ); return _connect(Chrome._(chrome.debugPort, chrome)); } @@ -110,7 +128,8 @@ class Chrome { } catch (e) { await chrome.close(); throw ChromeError( - 'Unable to connect to Chrome debug port: ${chrome.debugPort}\n $e'); + 'Unable to connect to Chrome debug port: ${chrome.debugPort}\n $e', + ); } _currentCompleter.complete(chrome); return chrome; @@ -132,12 +151,15 @@ String? autoDetectChromeUserDataDirectory() { final home = Platform.environment['HOME'] ?? ''; if (Platform.isMacOS) { directory = Directory( - path.join(home, 'Library', 'Application Support', 'Google', 'Chrome')); + path.join(home, 'Library', 'Application Support', 'Google', 'Chrome'), + ); } else if (Platform.isLinux) { directory = Directory(path.join(home, '.config', 'google-chrome')); } else { - _logger.warning('Auto detecting chrome user data directory option is not ' - 'supported for ${Platform.operatingSystem}'); + _logger.warning( + 'Auto detecting chrome user data directory option is not ' + 'supported for ${Platform.operatingSystem}', + ); return null; } @@ -146,8 +168,10 @@ String? autoDetectChromeUserDataDirectory() { return directory.path; } - _logger.warning('Cannot automatically detect chrome user data directory. ' - 'Directory does not exist: ${directory.path}'); + _logger.warning( + 'Cannot automatically detect chrome user data directory. ' + 'Directory does not exist: ${directory.path}', + ); return null; } diff --git a/webdev/lib/src/serve/dev_workflow.dart b/webdev/lib/src/serve/dev_workflow.dart index f22294fba..e950620f3 100644 --- a/webdev/lib/src/serve/dev_workflow.dart +++ b/webdev/lib/src/serve/dev_workflow.dart @@ -20,39 +20,42 @@ import 'server_manager.dart'; import 'webdev_server.dart'; Future _startBuildDaemon( - String workingDirectory, List buildOptions) async { + String workingDirectory, + List buildOptions, +) async { try { logWriter(logging.Level.INFO, 'Connecting to the build daemon...'); - return await connectClient( - workingDirectory, - buildOptions, - (serverLog) { - logWriter(toLoggingLevel(serverLog.level), serverLog.message, - loggerName: serverLog.loggerName, - error: serverLog.error, - stackTrace: serverLog.stackTrace); - }, - ); + return await connectClient(workingDirectory, buildOptions, (serverLog) { + logWriter( + toLoggingLevel(serverLog.level), + serverLog.message, + loggerName: serverLog.loggerName, + error: serverLog.error, + stackTrace: serverLog.stackTrace, + ); + }); } on OptionsSkew { // TODO(grouma) - Give an option to kill the running daemon. throw StateError( - 'Incompatible options with current running build daemon.\n\n' - 'Please stop other WebDev instances running in this directory ' - 'before starting a new instance with these options.'); + 'Incompatible options with current running build daemon.\n\n' + 'Please stop other WebDev instances running in this directory ' + 'before starting a new instance with these options.', + ); } } String _uriForLaunchApp(String launchApp, ServerManager serverManager) { final parts = p.url.split(launchApp); final dir = parts.first; - final server = - serverManager.servers.firstWhere((server) => server.target == dir); + final server = serverManager.servers.firstWhere( + (server) => server.target == dir, + ); return Uri( - scheme: 'http', - host: server.host, - port: server.port, - pathSegments: parts.skip(1)) - .toString(); + scheme: 'http', + host: server.host, + port: server.port, + pathSegments: parts.skip(1), + ).toString(); } Future _startChrome( @@ -66,15 +69,18 @@ Future _startChrome( Uri(scheme: 'http', host: s.host, port: s.port).toString() else for (final app in configuration.launchApps) - _uriForLaunchApp(app, serverManager) + _uriForLaunchApp(app, serverManager), ]; try { if (configuration.launchInChrome) { final userDataDir = configuration.userDataDir == autoOption ? autoDetectChromeUserDataDirectory() : configuration.userDataDir; - return await Chrome.start(uris, - port: configuration.chromeDebugPort, userDataDir: userDataDir); + return await Chrome.start( + uris, + port: configuration.chromeDebugPort, + userDataDir: userDataDir, + ); } else if (configuration.chromeDebugPort != 0) { return await Chrome.fromExisting(configuration.chromeDebugPort); } @@ -95,22 +101,22 @@ Future _startServerManager( final assetPort = daemonPort(workingDirectory); final serverOptions = {}; for (final target in targetPorts.keys) { - serverOptions.add(ServerOptions( - configuration, - targetPorts[target]!, - target, - assetPort, - )); + serverOptions.add( + ServerOptions(configuration, targetPorts[target]!, target, assetPort), + ); } logWriter(logging.Level.INFO, 'Starting resource servers...'); - final serverManager = - await ServerManager.start(serverOptions, client.buildResults); + final serverManager = await ServerManager.start( + serverOptions, + client.buildResults, + ); for (final server in serverManager.servers) { logWriter( - logging.Level.INFO, - 'Serving `${server.target}` on ' - '${Uri(scheme: server.protocol, host: server.host, port: server.port)}\n'); + logging.Level.INFO, + 'Serving `${server.target}` on ' + '${Uri(scheme: server.protocol, host: server.host, port: server.port)}\n', + ); } return serverManager; @@ -127,25 +133,37 @@ void _registerBuildTargets( if (configuration.outputPath != null && (configuration.outputInput == null || target == configuration.outputInput)) { - outputLocation = OutputLocation((b) => b - ..output = configuration.outputPath - ..useSymlinks = true - ..hoist = true); + outputLocation = OutputLocation( + (b) => b + ..output = configuration.outputPath + ..useSymlinks = true + ..hoist = true, + ); } - client.registerBuildTarget(DefaultBuildTarget((b) => b - ..target = target - ..outputLocation = outputLocation?.toBuilder())); + client.registerBuildTarget( + DefaultBuildTarget( + (b) => b + ..target = target + ..outputLocation = outputLocation?.toBuilder(), + ), + ); } // Empty string indicates we should build everything, register a corresponding // target. if (configuration.outputInput == '' && configuration.outputPath != null) { - final outputLocation = OutputLocation((b) => b - ..output = configuration.outputPath - ..useSymlinks = true - ..hoist = false); - client.registerBuildTarget(DefaultBuildTarget((b) => b - ..target = '' - ..outputLocation = outputLocation.toBuilder())); + final outputLocation = OutputLocation( + (b) => b + ..output = configuration.outputPath + ..useSymlinks = true + ..hoist = false, + ); + client.registerBuildTarget( + DefaultBuildTarget( + (b) => b + ..target = '' + ..outputLocation = outputLocation.toBuilder(), + ), + ); } } @@ -163,15 +181,13 @@ class DevWorkflow { final _wrapWidth = stdout.hasTerminal ? stdout.terminalColumns - 8 : 72; - DevWorkflow._( - this._client, - this._chrome, - this.serverManager, - ) { + DevWorkflow._(this._client, this._chrome, this.serverManager) { _resultsSub = _client.buildResults.listen((data) { - if (data.results.any((result) => - result.status == BuildStatus.failed || - result.status == BuildStatus.succeeded)) { + if (data.results.any( + (result) => + result.status == BuildStatus.failed || + result.status == BuildStatus.succeeded, + )) { logWriter(logging.Level.INFO, '${'-' * _wrapWidth}\n'); } }); @@ -198,7 +214,11 @@ class DevWorkflow { logWriter(logging.Level.INFO, 'Starting initial build...'); client.startBuild(); final serverManager = await _startServerManager( - configuration, targetPorts, workingDirectory, client); + configuration, + targetPorts, + workingDirectory, + client, + ); final chrome = await _startChrome(configuration, serverManager, client); return DevWorkflow._(client, chrome, serverManager); } diff --git a/webdev/lib/src/serve/handlers/favicon_handler.dart b/webdev/lib/src/serve/handlers/favicon_handler.dart index 72ab38658..c1c8c0580 100644 --- a/webdev/lib/src/serve/handlers/favicon_handler.dart +++ b/webdev/lib/src/serve/handlers/favicon_handler.dart @@ -21,7 +21,8 @@ Handler interceptFavicon(Handler handler) { }; } -final _icon = gzip.decode(base64.decode( +final _icon = gzip.decode( + base64.decode( 'H4sIAAAAAAAAE+3aTUgUYRgH8DGK0lN06BBBBkGG7Ye7JnrKPiAIjQ6GJX6trQtBRubOul' 'bQHLNbiYcgEO2SsusmgiiIH4fsw2Z3O4hEdTUPBYoQKyRPM7PO9rKuOuvOvM+7o//l2cPw' 'sju/h2fnZZbhuBzpVV7OSe/5XMFljjvKcVyBVNIhTuDix7ECMzdyIeIOQ9QD1CrccAkNTA' @@ -38,4 +39,6 @@ final _icon = gzip.decode(base64.decode( 'pOHVT9SxNV6MaNdQ7GOisNsauRPvveyqc2GHpcyoC3GN4+LIFh4TyMPr0Kk121MNdX0WGU' 'Xc6w4MybffMIprrrle/DrunuOgj31sPCqAv+zjZcM9KuRnneN9rUgv58L1lio2Ezz3wfEO' 'zM9AHZToZ6Hxiyk6HSB0btZAzrQxbYyejahyyzk8m4D1lsJ7OjPpjETkZTHyKeX/DF5cA+' - 'V6MDUVc1RNz9EGn+JtUiRN1BEF1XsM9rL3vZi/nzD71EuTA+RAAA')); + 'V6MDUVc1RNz9EGn+JtUiRN1BEF1XsM9rL3vZi/nzD71EuTA+RAAA', + ), +); diff --git a/webdev/lib/src/serve/utils.dart b/webdev/lib/src/serve/utils.dart index 7c3361987..e6e062a67 100644 --- a/webdev/lib/src/serve/utils.dart +++ b/webdev/lib/src/serve/utils.dart @@ -89,8 +89,9 @@ String? findPackageConfigFilePath() { var candidateDir = Directory(p.current).absolute; while (true) { - final candidatePackageConfigFile = - File(p.join(candidateDir.path, '.dart_tool', 'package_config.json')); + final candidatePackageConfigFile = File( + p.join(candidateDir.path, '.dart_tool', 'package_config.json'), + ); if (candidatePackageConfigFile.existsSync()) { return candidatePackageConfigFile.path; diff --git a/webdev/lib/src/serve/webdev_server.dart b/webdev/lib/src/serve/webdev_server.dart index e166503f6..b1604d96c 100644 --- a/webdev/lib/src/serve/webdev_server.dart +++ b/webdev/lib/src/serve/webdev_server.dart @@ -31,12 +31,7 @@ class ServerOptions { final String target; final int daemonPort; - ServerOptions( - this.configuration, - this.port, - this.target, - this.daemonPort, - ); + ServerOptions(this.configuration, this.port, this.target, this.daemonPort); } class WebDevServer { @@ -82,7 +77,9 @@ class WebDevServer { } static Future start( - ServerOptions options, Stream buildResults) async { + ServerOptions options, + Stream buildResults, + ) async { var pipeline = const Pipeline(); if (options.configuration.logRequests) { @@ -93,8 +90,9 @@ class WebDevServer { // Only provide relevant build results final filteredBuildResults = buildResults.asyncMap((results) { - final result = results.results - .firstWhere((result) => result.target == options.target); + final result = results.results.firstWhere( + (result) => result.target == options.target, + ); switch (result.status) { case daemon.BuildStatus.started: return BuildResult((b) => b.status = BuildStatus.started); @@ -109,13 +107,16 @@ class WebDevServer { }); var cascade = Cascade(); - final client = IOClient(HttpClient() - ..maxConnectionsPerHost = 200 - ..idleTimeout = const Duration(seconds: 30) - ..connectionTimeout = const Duration(seconds: 30)); + final client = IOClient( + HttpClient() + ..maxConnectionsPerHost = 200 + ..idleTimeout = const Duration(seconds: 30) + ..connectionTimeout = const Duration(seconds: 30), + ); final assetHandler = proxyHandler( - 'http://localhost:${options.daemonPort}/${options.target}/', - client: client); + 'http://localhost:${options.daemonPort}/${options.target}/', + client: client, + ); Dwds? dwds; ExpressionCompilerService? ddcService; @@ -130,8 +131,9 @@ class WebDevServer { // Can we save build metadata in build_web_compilers and and read it in // the load strategy? final buildSettings = BuildSettings( - appEntrypoint: - Uri.parse('org-dartlang-app:///${options.target}/main.dart'), + appEntrypoint: Uri.parse( + 'org-dartlang-app:///${options.target}/main.dart', + ), canaryFeatures: options.configuration.canaryFeatures, isFlutterApp: false, experiments: options.configuration.experiments, @@ -173,14 +175,13 @@ class WebDevServer { : null, ); - final appMetadata = AppMetadata( - hostname: options.configuration.hostname, - ); + final appMetadata = AppMetadata(hostname: options.configuration.hostname); final toolConfiguration = ToolConfiguration( - loadStrategy: loadStrategy, - debugSettings: debugSettings, - appMetadata: appMetadata); + loadStrategy: loadStrategy, + debugSettings: debugSettings, + appMetadata: appMetadata, + ); dwds = await Dwds.start( toolConfiguration: toolConfiguration, assetReader: assetReader, @@ -200,14 +201,18 @@ class WebDevServer { final tlsCertKey = options.configuration.tlsCertKey ?? ''; HttpServer server; - final protocol = - (tlsCertChain.isNotEmpty && tlsCertKey.isNotEmpty) ? 'https' : 'http'; + final protocol = (tlsCertChain.isNotEmpty && tlsCertKey.isNotEmpty) + ? 'https' + : 'http'; if (protocol == 'https') { final serverContext = SecurityContext() ..useCertificateChain(tlsCertChain) ..usePrivateKey(tlsCertKey); server = await HttpMultiServer.bindSecure( - hostname, options.port, serverContext); + hostname, + options.port, + serverContext, + ); } else { server = await HttpMultiServer.bind(hostname, options.port); } diff --git a/webdev/lib/src/util.dart b/webdev/lib/src/util.dart index 62170896f..7d943988b 100644 --- a/webdev/lib/src/util.dart +++ b/webdev/lib/src/util.dart @@ -16,8 +16,11 @@ const appName = 'webdev'; /// /// Captures all sync and async stack error traces and passes /// them to the [onError] handler. -void serveHttpRequests(Stream requests, Handler handler, - void Function(Object, StackTrace) onError) { +void serveHttpRequests( + Stream requests, + Handler handler, + void Function(Object, StackTrace) onError, +) { return Chain.capture(() { serveRequests(requests, handler); }, onError: onError); diff --git a/webdev/lib/src/webdev_command_runner.dart b/webdev/lib/src/webdev_command_runner.dart index 2f5af323f..c0144bb50 100644 --- a/webdev/lib/src/webdev_command_runner.dart +++ b/webdev/lib/src/webdev_command_runner.dart @@ -20,8 +20,11 @@ Future run(List args) async => (await _CommandRunner().run(args))!; class _CommandRunner extends CommandRunner { _CommandRunner() : super(appName, 'A tool to develop Dart web projects.') { - argParser.addFlag('version', - negatable: false, help: 'Prints the version of webdev.'); + argParser.addFlag( + 'version', + negatable: false, + help: 'Prints the version of webdev.', + ); addCommand(BuildCommand()); addCommand(ServeCommand()); addCommand(DaemonCommand()); diff --git a/webdev/pubspec.yaml b/webdev/pubspec.yaml index d8730c128..f5f339aa1 100644 --- a/webdev/pubspec.yaml +++ b/webdev/pubspec.yaml @@ -8,7 +8,7 @@ description: >- features for users and tools to build and deploy web applications with Dart. repository: https://github.com/dart-lang/webdev/tree/main/webdev environment: - sdk: ^3.2.0 + sdk: ^3.8.0 dependencies: args: ^2.3.1 diff --git a/webdev/test/build/ensure_build_test.dart b/webdev/test/build/ensure_build_test.dart index 01e102a15..90c4ad6ec 100644 --- a/webdev/test/build/ensure_build_test.dart +++ b/webdev/test/build/ensure_build_test.dart @@ -3,9 +3,7 @@ // BSD-style license that can be found in the LICENSE file. @TestOn('vm') -@OnPlatform({ - 'windows': Skip('https://github.com/dart-lang/webdev/issues/711'), -}) +@OnPlatform({'windows': Skip('https://github.com/dart-lang/webdev/issues/711')}) library; import 'package:build_verify/build_verify.dart'; diff --git a/webdev/test/build/min_sdk_test.dart b/webdev/test/build/min_sdk_test.dart index 84afbed1a..eb1ed8bc4 100644 --- a/webdev/test/build/min_sdk_test.dart +++ b/webdev/test/build/min_sdk_test.dart @@ -20,11 +20,14 @@ void main() { final sdkConstraint = VersionConstraint.compatibleWith(sdkVersion); final pubspecSdkConstraint = pubspec.environment['sdk']!; - expect(sdkConstraint.allowsAll(pubspecSdkConstraint), true, - reason: - 'Min sdk constraint is outdated. Please update SDK constraint in ' - 'pubspec to allow latest stable and backwards compatible versions.' - '\n Current stable: $sdkVersion, ' - '\n Webdev pubspec constraint: $pubspecSdkConstraint'); + expect( + sdkConstraint.allowsAll(pubspecSdkConstraint), + true, + reason: + 'Min sdk constraint is outdated. Please update SDK constraint in ' + 'pubspec to allow latest stable and backwards compatible versions.' + '\n Current stable: $sdkVersion, ' + '\n Webdev pubspec constraint: $pubspecSdkConstraint', + ); }); } diff --git a/webdev/test/chrome_test.dart b/webdev/test/chrome_test.dart index 9dbb20e6a..f2940016f 100644 --- a/webdev/test/chrome_test.dart +++ b/webdev/test/chrome_test.dart @@ -18,8 +18,11 @@ void main() { Chrome? chrome; Future launchChrome({int? port, String? userDataDir}) async { - chrome = await Chrome.start([_googleUrl], - port: port ?? 0, userDataDir: userDataDir); + chrome = await Chrome.start( + [_googleUrl], + port: port ?? 0, + userDataDir: userDataDir, + ); } Future openTab(String url) => @@ -30,8 +33,9 @@ void main() { Future connectToTab(String url) async { final tab = await chrome!.chromeConnection.getTab( - (t) => t.url.contains(url), - retryFor: const Duration(milliseconds: 60)); + (t) => t.url.contains(url), + retryFor: const Duration(milliseconds: 60), + ); expect(tab, isNotNull); return tab!.connect(); } @@ -57,9 +61,15 @@ void main() { await launchChrome(); final tabs = await chrome!.chromeConnection.getTabs(); expect( - tabs, - contains(const TypeMatcher() - .having((t) => t.url, 'url', _googleUrl))); + tabs, + contains( + const TypeMatcher().having( + (t) => t.url, + 'url', + _googleUrl, + ), + ), + ); }); test('uses open debug port if provided port is 0', () async { @@ -67,22 +77,28 @@ void main() { expect(chrome!.debugPort, isNot(equals(0))); }); - test('has correct profile path', () async { - await launchChrome(); - await openTab(_chromeVersionUrl); - - final wipConnection = await connectToTab(_chromeVersionUrl); - final result = await _evaluateExpression(wipConnection.page, - "document.getElementById('profile_path').textContent"); - - if (Platform.isWindows) { - // --user-data-dir is not supported on Windows yet - // Issue: https://github.com/dart-lang/webdev/issues/1545 - expect(result, isNot(contains('chrome_user_data'))); - } else { - expect(result, contains('chrome_user_data')); - } - }, skip: 'https://github.com/dart-lang/webdev/issues/2030'); + test( + 'has correct profile path', + () async { + await launchChrome(); + await openTab(_chromeVersionUrl); + + final wipConnection = await connectToTab(_chromeVersionUrl); + final result = await _evaluateExpression( + wipConnection.page, + "document.getElementById('profile_path').textContent", + ); + + if (Platform.isWindows) { + // --user-data-dir is not supported on Windows yet + // Issue: https://github.com/dart-lang/webdev/issues/1545 + expect(result, isNot(contains('chrome_user_data'))); + } else { + expect(result, contains('chrome_user_data')); + } + }, + skip: 'https://github.com/dart-lang/webdev/issues/2030', + ); }); group('chrome with user data dir', () { @@ -94,8 +110,13 @@ void main() { logController = StreamController(); logStream = logController.stream; - void logWriter(Level level, String message, - {String? error, String? loggerName, String? stackTrace}) { + void logWriter( + Level level, + String message, { + String? error, + String? loggerName, + String? stackTrace, + }) { if (level >= Level.INFO) { logController.add('[$level] $loggerName: $message'); } @@ -118,9 +139,14 @@ void main() { // Issue: https://github.com/dart-lang/webdev/issues/1545 if (!Platform.isWindows) { expect( - logStream, - emitsThrough(matches('Starting chrome with user data directory:' - '.*chrome_user_data_copy'))); + logStream, + emitsThrough( + matches( + 'Starting chrome with user data directory:' + '.*chrome_user_data_copy', + ), + ), + ); await logController.close(); } dataDir.deleteSync(recursive: true); @@ -136,53 +162,78 @@ void main() { final tabs = await chrome!.chromeConnection.getTabs(); expect( - tabs, - contains(const TypeMatcher() - .having((t) => t.url, 'url', _googleUrl))); + tabs, + contains( + const TypeMatcher().having( + (t) => t.url, + 'url', + _googleUrl, + ), + ), + ); }); - test('has correct profile path', () async { - await launchChrome(userDataDir: dataDir.path); - await openTab(_chromeVersionUrl); - - final wipConnection = await connectToTab(_chromeVersionUrl); - final result = await _evaluateExpression(wipConnection.page, - "document.getElementById('profile_path').textContent"); - - if (Platform.isWindows) { - // --user-data-dir is not supported on Windows yet - // Issue: https://github.com/dart-lang/webdev/issues/1545 - expect(result, isNot(contains('chrome_user_data_copy'))); - } else { - expect(result, contains('chrome_user_data_copy')); - } - }, skip: 'https://github.com/dart-lang/webdev/issues/2030'); + test( + 'has correct profile path', + () async { + await launchChrome(userDataDir: dataDir.path); + await openTab(_chromeVersionUrl); + + final wipConnection = await connectToTab(_chromeVersionUrl); + final result = await _evaluateExpression( + wipConnection.page, + "document.getElementById('profile_path').textContent", + ); + + if (Platform.isWindows) { + // --user-data-dir is not supported on Windows yet + // Issue: https://github.com/dart-lang/webdev/issues/1545 + expect(result, isNot(contains('chrome_user_data_copy'))); + } else { + expect(result, contains('chrome_user_data_copy')); + } + }, + skip: 'https://github.com/dart-lang/webdev/issues/2030', + ); - test('can auto detect default chrome directory', () async { - final userDataDir = autoDetectChromeUserDataDirectory(); - expect(userDataDir, isNotNull); + test( + 'can auto detect default chrome directory', + () async { + final userDataDir = autoDetectChromeUserDataDirectory(); + expect(userDataDir, isNotNull); - expect(Directory(userDataDir!).existsSync(), isTrue); + expect(Directory(userDataDir!).existsSync(), isTrue); - await launchChrome(userDataDir: userDataDir); - await openTab(_chromeVersionUrl); + await launchChrome(userDataDir: userDataDir); + await openTab(_chromeVersionUrl); - final wipConnection = await connectToTab(_chromeVersionUrl); - final result = await _evaluateExpression(wipConnection.page, - "document.getElementById('profile_path').textContent"); + final wipConnection = await connectToTab(_chromeVersionUrl); + final result = await _evaluateExpression( + wipConnection.page, + "document.getElementById('profile_path').textContent", + ); - expect(result, contains('chrome_user_data_copy')); - }, onPlatform: { - 'windows': const Skip('https://github.com/dart-lang/webdev/issues/1545') - }, skip: 'https://github.com/dart-lang/webdev/issues/2030'); + expect(result, contains('chrome_user_data_copy')); + }, + onPlatform: { + 'windows': const Skip( + 'https://github.com/dart-lang/webdev/issues/1545', + ), + }, + skip: 'https://github.com/dart-lang/webdev/issues/2030', + ); - test('cannot auto detect default chrome directory on windows', () async { - final userDataDir = autoDetectChromeUserDataDirectory(); - expect(userDataDir, isNull); - }, onPlatform: { - 'linux': const Skip('https://github.com/dart-lang/webdev/issues/1545'), - 'mac-os': const Skip('https://github.com/dart-lang/webdev/issues/1545'), - }); + test( + 'cannot auto detect default chrome directory on windows', + () async { + final userDataDir = autoDetectChromeUserDataDirectory(); + expect(userDataDir, isNull); + }, + onPlatform: { + 'linux': const Skip('https://github.com/dart-lang/webdev/issues/1545'), + 'mac-os': const Skip('https://github.com/dart-lang/webdev/issues/1545'), + }, + ); }); } diff --git a/webdev/test/configuration_test.dart b/webdev/test/configuration_test.dart index 5fccfd2d0..8c8e6000b 100644 --- a/webdev/test/configuration_test.dart +++ b/webdev/test/configuration_test.dart @@ -30,15 +30,21 @@ void main() { }); test('tlsCertKey and tlsCertChain must be provided together', () { - expect(() => Configuration(tlsCertKey: 'blah'), - throwsA(isA())); - expect(() => Configuration(tlsCertChain: 'blah'), - throwsA(isA())); + expect( + () => Configuration(tlsCertKey: 'blah'), + throwsA(isA()), + ); + expect( + () => Configuration(tlsCertChain: 'blah'), + throwsA(isA()), + ); }); test('must provide a debug port when launchInChrome is false ', () { - expect(() => Configuration(debug: true, launchInChrome: false), - throwsA(isA())); + expect( + () => Configuration(debug: true, launchInChrome: false), + throwsA(isA()), + ); }); test('user data directory defaults to null ', () { @@ -48,27 +54,35 @@ void main() { }); test('can read user data dir from args ', () { - final argResults = - argParser.parse(['--launch-in-chrome', '--user-data-dir=tempdir']); + final argResults = argParser.parse([ + '--launch-in-chrome', + '--user-data-dir=tempdir', + ]); final configuration = Configuration.fromArgs(argResults); expect(configuration.userDataDir, equals('tempdir')); }); test('can set user data directory with launchInChrome ', () { - final configuration = - Configuration(launchInChrome: true, userDataDir: 'temp'); + final configuration = Configuration( + launchInChrome: true, + userDataDir: 'temp', + ); expect(configuration.userDataDir, equals('temp')); }); test('can set user data directory to auto with launchInChrome ', () { - final configuration = - Configuration(launchInChrome: true, userDataDir: 'auto'); + final configuration = Configuration( + launchInChrome: true, + userDataDir: 'auto', + ); expect(configuration.userDataDir, equals('auto')); }); test('must set launchInChrome is to true if using user data directory ', () { - expect(() => Configuration(launchInChrome: false, userDataDir: 'temp'), - throwsA(isA())); + expect( + () => Configuration(launchInChrome: false, userDataDir: 'temp'), + throwsA(isA()), + ); }); test('nullSafety defaults to auto', () { @@ -77,36 +91,48 @@ void main() { expect(defaultConfiguration.nullSafety, equals(nullSafetyAuto)); }); - test( - 'must not provide debug related configuration when enableInjectedClient ' + test('must not provide debug related configuration when enableInjectedClient ' 'is false', () { - expect(() => Configuration(enableInjectedClient: false, debug: true), - throwsA(isA())); expect( - () => Configuration(enableInjectedClient: false, debugExtension: true), - throwsA(isA())); + () => Configuration(enableInjectedClient: false, debug: true), + throwsA(isA()), + ); + expect( + () => Configuration(enableInjectedClient: false, debugExtension: true), + throwsA(isA()), + ); expect( - () => Configuration(enableInjectedClient: false, chromeDebugPort: 8080), - throwsA(isA())); + () => Configuration(enableInjectedClient: false, chromeDebugPort: 8080), + throwsA(isA()), + ); }); - test( - 'only top level directories or an empty target are allowed for ' + test('only top level directories or an empty target are allowed for ' 'outputInput', () { // Valid expect(() => Configuration(outputInput: ''), returnsNormally); expect(() => Configuration(outputInput: 'foo/'), returnsNormally); // Invalid - expect(() => Configuration(outputInput: '.'), - throwsA(isA())); - expect(() => Configuration(outputInput: '../'), - throwsA(isA())); - expect(() => Configuration(outputInput: '../foo'), - throwsA(isA())); - expect(() => Configuration(outputInput: 'foo/bar'), - throwsA(isA())); - expect(() => Configuration(outputInput: 'foo/../'), - throwsA(isA())); + expect( + () => Configuration(outputInput: '.'), + throwsA(isA()), + ); + expect( + () => Configuration(outputInput: '../'), + throwsA(isA()), + ); + expect( + () => Configuration(outputInput: '../foo'), + throwsA(isA()), + ); + expect( + () => Configuration(outputInput: 'foo/bar'), + throwsA(isA()), + ); + expect( + () => Configuration(outputInput: 'foo/../'), + throwsA(isA()), + ); }); } diff --git a/webdev/test/daemon/app_domain_test.dart b/webdev/test/daemon/app_domain_test.dart index d361031a9..dc09c9fbc 100644 --- a/webdev/test/daemon/app_domain_test.dart +++ b/webdev/test/daemon/app_domain_test.dart @@ -27,139 +27,153 @@ void main() { group('AppDomain', () { group('Events', () { test('.start', () async { - final webdev = await testRunner - .runWebDev(['daemon'], workingDirectory: exampleDirectory); + final webdev = await testRunner.runWebDev([ + 'daemon', + ], workingDirectory: exampleDirectory); await expectLater( - webdev.stdout, emitsThrough(startsWith('[{"event":"app.start"'))); + webdev.stdout, + emitsThrough(startsWith('[{"event":"app.start"')), + ); await exitWebdev(webdev); }); test('.started', () async { - final webdev = await testRunner - .runWebDev(['daemon'], workingDirectory: exampleDirectory); + final webdev = await testRunner.runWebDev([ + 'daemon', + ], workingDirectory: exampleDirectory); await expectLater( - webdev.stdout, emitsThrough(startsWith('[{"event":"app.started"'))); + webdev.stdout, + emitsThrough(startsWith('[{"event":"app.started"')), + ); await exitWebdev(webdev); }); test('.debugPort', () async { - final webdev = await testRunner - .runWebDev(['daemon'], workingDirectory: exampleDirectory); - await expectLater(webdev.stdout, - emitsThrough(startsWith('[{"event":"app.debugPort"'))); + final webdev = await testRunner.runWebDev([ + 'daemon', + ], workingDirectory: exampleDirectory); + await expectLater( + webdev.stdout, + emitsThrough(startsWith('[{"event":"app.debugPort"')), + ); await exitWebdev(webdev); }); test('.log', () async { - final webdev = await testRunner - .runWebDev(['daemon'], workingDirectory: exampleDirectory); + final webdev = await testRunner.runWebDev([ + 'daemon', + ], workingDirectory: exampleDirectory); final appId = await waitForAppId(webdev); // The example app does an initial print. await expectLater( - webdev.stdout, - emitsThrough( - startsWith('[{"event":"app.log","params":{"appId":"$appId",' - '"log":"Initial Print\\n"}}'))); + webdev.stdout, + emitsThrough( + startsWith( + '[{"event":"app.log","params":{"appId":"$appId",' + '"log":"Initial Print\\n"}}', + ), + ), + ); await exitWebdev(webdev); }); }); group('Methods', () { - test( - '.callServiceExtension', - () async { - final webdev = await testRunner - .runWebDev(['daemon'], workingDirectory: exampleDirectory); - final appId = await waitForAppId(webdev); - if (Platform.isWindows) { - // Windows takes a bit longer to run the application and register - // the service extension. - await Future.delayed(const Duration(seconds: 5)); - } - final extensionCall = '[{"method":"app.callServiceExtension","id":0,' - '"params" : { "appId" : "$appId", "methodName" : "ext.print"}}]'; - webdev.stdin.add(utf8.encode('$extensionCall\n')); - // The example app sets up a service extension for printing. - await expectLater( - webdev.stdout, - emitsThrough( - startsWith('[{"event":"app.log","params":{"appId":"$appId",' - '"log":"Hello World\\n"}}'))); - await exitWebdev(webdev); - }, - timeout: const Timeout( - Duration(minutes: 2), - ), - ); + test('.callServiceExtension', () async { + final webdev = await testRunner.runWebDev([ + 'daemon', + ], workingDirectory: exampleDirectory); + final appId = await waitForAppId(webdev); + if (Platform.isWindows) { + // Windows takes a bit longer to run the application and register + // the service extension. + await Future.delayed(const Duration(seconds: 5)); + } + final extensionCall = + '[{"method":"app.callServiceExtension","id":0,' + '"params" : { "appId" : "$appId", "methodName" : "ext.print"}}]'; + webdev.stdin.add(utf8.encode('$extensionCall\n')); + // The example app sets up a service extension for printing. + await expectLater( + webdev.stdout, + emitsThrough( + startsWith( + '[{"event":"app.log","params":{"appId":"$appId",' + '"log":"Hello World\\n"}}', + ), + ), + ); + await exitWebdev(webdev); + }, timeout: const Timeout(Duration(minutes: 2))); - test( - '.reload', - () async { - final webdev = await testRunner - .runWebDev(['daemon'], workingDirectory: exampleDirectory); - final appId = await waitForAppId(webdev); - final extensionCall = '[{"method":"app.restart","id":0,' - '"params" : { "appId" : "$appId", "fullRestart" : false}}]'; - webdev.stdin.add(utf8.encode('$extensionCall\n')); - await expectLater( - webdev.stdout, - emitsThrough(startsWith( + test('.reload', () async { + final webdev = await testRunner.runWebDev([ + 'daemon', + ], workingDirectory: exampleDirectory); + final appId = await waitForAppId(webdev); + final extensionCall = + '[{"method":"app.restart","id":0,' + '"params" : { "appId" : "$appId", "fullRestart" : false}}]'; + webdev.stdin.add(utf8.encode('$extensionCall\n')); + await expectLater( + webdev.stdout, + emitsThrough( + startsWith( '[{"id":0,"result":{"code":1,"message":"hot reload not yet supported', - )), - ); - await exitWebdev(webdev); - }, - timeout: const Timeout( - Duration(minutes: 2), - ), - ); + ), + ), + ); + await exitWebdev(webdev); + }, timeout: const Timeout(Duration(minutes: 2))); - test( - '.restart', - () async { - final webdev = await testRunner - .runWebDev(['daemon'], workingDirectory: exampleDirectory); - final appId = await waitForAppId(webdev); - final extensionCall = '[{"method":"app.restart","id":0,' - '"params" : { "appId" : "$appId", "fullRestart" : true}}]'; - webdev.stdin.add(utf8.encode('$extensionCall\n')); - await expectLater( - webdev.stdout, - emitsThrough(startsWith( - '[{"event":"app.progress","params":{"appId":"$appId","id":"1",' - '"message":"Performing hot restart..."'))); - await expectLater( - webdev.stdout, - emitsThrough(startsWith( - '[{"event":"app.progress","params":{"appId":"$appId","id":"1",' - '"finished":true'))); - await exitWebdev(webdev); - }, - timeout: const Timeout( - Duration(minutes: 2), - ), - ); + test('.restart', () async { + final webdev = await testRunner.runWebDev([ + 'daemon', + ], workingDirectory: exampleDirectory); + final appId = await waitForAppId(webdev); + final extensionCall = + '[{"method":"app.restart","id":0,' + '"params" : { "appId" : "$appId", "fullRestart" : true}}]'; + webdev.stdin.add(utf8.encode('$extensionCall\n')); + await expectLater( + webdev.stdout, + emitsThrough( + startsWith( + '[{"event":"app.progress","params":{"appId":"$appId","id":"1",' + '"message":"Performing hot restart..."', + ), + ), + ); + await expectLater( + webdev.stdout, + emitsThrough( + startsWith( + '[{"event":"app.progress","params":{"appId":"$appId","id":"1",' + '"finished":true', + ), + ), + ); + await exitWebdev(webdev); + }, timeout: const Timeout(Duration(minutes: 2))); - test( - '.stop', - () async { - final webdev = await testRunner - .runWebDev(['daemon'], workingDirectory: exampleDirectory); - final appId = await waitForAppId(webdev); - final stopCall = '[{"method":"app.stop","id":0,' - '"params" : { "appId" : "$appId"}}]'; - webdev.stdin.add(utf8.encode('$stopCall\n')); - await expectLater( - webdev.stdout, - emitsThrough(startsWith( - '[{"event":"app.stop","params":{"appId":"$appId"}}'))); - // This should cause webdev to exit. - expect(await webdev.exitCode, equals(0)); - }, - timeout: const Timeout( - Duration(minutes: 2), - ), - ); + test('.stop', () async { + final webdev = await testRunner.runWebDev([ + 'daemon', + ], workingDirectory: exampleDirectory); + final appId = await waitForAppId(webdev); + final stopCall = + '[{"method":"app.stop","id":0,' + '"params" : { "appId" : "$appId"}}]'; + webdev.stdin.add(utf8.encode('$stopCall\n')); + await expectLater( + webdev.stdout, + emitsThrough( + startsWith('[{"event":"app.stop","params":{"appId":"$appId"}}'), + ), + ); + // This should cause webdev to exit. + expect(await webdev.exitCode, equals(0)); + }, timeout: const Timeout(Duration(minutes: 2))); }); }); } diff --git a/webdev/test/daemon/daemon_domain_test.dart b/webdev/test/daemon/daemon_domain_test.dart index b2e37c5fc..1d94e3538 100644 --- a/webdev/test/daemon/daemon_domain_test.dart +++ b/webdev/test/daemon/daemon_domain_test.dart @@ -26,29 +26,37 @@ void main() { group('Daemon', () { group('Events', () { test('.connected', () async { - final webdev = await testRunner - .runWebDev(['daemon'], workingDirectory: exampleDirectory); + final webdev = await testRunner.runWebDev([ + 'daemon', + ], workingDirectory: exampleDirectory); await expectLater( - webdev.stdout, emits(startsWith('[{"event":"daemon.connected"'))); + webdev.stdout, + emits(startsWith('[{"event":"daemon.connected"')), + ); await exitWebdev(webdev); }); }); group('Methods', () { test('.version', () async { - final webdev = await testRunner - .runWebDev(['daemon'], workingDirectory: exampleDirectory); + final webdev = await testRunner.runWebDev([ + 'daemon', + ], workingDirectory: exampleDirectory); webdev.stdin.add(utf8.encode('[{"method":"daemon.version","id":0}]\n')); await expectLater( - webdev.stdout, emitsThrough(equals('[{"id":0,"result":"0.4.2"}]'))); + webdev.stdout, + emitsThrough(equals('[{"id":0,"result":"0.4.2"}]')), + ); await exitWebdev(webdev); }); test('.shutdown', () async { - final webdev = await testRunner - .runWebDev(['daemon'], workingDirectory: exampleDirectory); - webdev.stdin - .add(utf8.encode('[{"method":"daemon.shutdown","id":0}]\n')); + final webdev = await testRunner.runWebDev([ + 'daemon', + ], workingDirectory: exampleDirectory); + webdev.stdin.add( + utf8.encode('[{"method":"daemon.shutdown","id":0}]\n'), + ); await expectLater(webdev.stdout, emitsThrough(equals('[{"id":0}]'))); expect(await webdev.exitCode, equals(0)); }); diff --git a/webdev/test/daemon/launch_app_test.dart b/webdev/test/daemon/launch_app_test.dart index 4e3c83f57..c2c3c63b4 100644 --- a/webdev/test/daemon/launch_app_test.dart +++ b/webdev/test/daemon/launch_app_test.dart @@ -22,17 +22,22 @@ void main() { tearDownAll(testRunner.tearDownAll); test('--launch-app launches the specified app', () async { - final webdev = await testRunner.runWebDev( - ['daemon', '--launch-app=web/scopes.html'], - workingDirectory: exampleDirectory); + final webdev = await testRunner.runWebDev([ + 'daemon', + '--launch-app=web/scopes.html', + ], workingDirectory: exampleDirectory); final appId = await waitForAppId(webdev); // The example app does an initial print. await expectLater( - webdev.stdout, - emitsThrough( - startsWith('[{"event":"app.log","params":{"appId":"$appId",' - '"log":"Initial print from scopes app\\n"}}'))); + webdev.stdout, + emitsThrough( + startsWith( + '[{"event":"app.log","params":{"appId":"$appId",' + '"log":"Initial print from scopes app\\n"}}', + ), + ), + ); await exitWebdev(webdev); }); } diff --git a/webdev/test/daemon/utils.dart b/webdev/test/daemon/utils.dart index 30fa1b4fa..b760eabc4 100644 --- a/webdev/test/daemon/utils.dart +++ b/webdev/test/daemon/utils.dart @@ -43,15 +43,22 @@ String? getDebugServiceUri(String line) { return null; } -Future findBreakpointLine(VmService vmService, String breakpointId, - String isolateId, ScriptRef scriptRef) async { +Future findBreakpointLine( + VmService vmService, + String breakpointId, + String isolateId, + ScriptRef scriptRef, +) async { final script = await vmService.getObject(isolateId, scriptRef.id!) as Script; final lines = LineSplitter.split(script.source!).toList(); - final lineNumber = - lines.indexWhere((l) => l.endsWith('// Breakpoint: $breakpointId')); + final lineNumber = lines.indexWhere( + (l) => l.endsWith('// Breakpoint: $breakpointId'), + ); if (lineNumber == -1) { - throw StateError('Unable to find breakpoint in ${scriptRef.uri} with id ' - '$breakpointId'); + throw StateError( + 'Unable to find breakpoint in ${scriptRef.uri} with id ' + '$breakpointId', + ); } return lineNumber + 1; } diff --git a/webdev/test/e2e_test.dart b/webdev/test/e2e_test.dart index 87c07f74d..39f0b714f 100644 --- a/webdev/test/e2e_test.dart +++ b/webdev/test/e2e_test.dart @@ -45,12 +45,16 @@ void main() { setUpAll(() async { configureLogWriter(debug); await testRunner.setUpAll(); - soundExampleDirectory = - p.absolute(p.join(p.current, '..', 'fixtures', '_webdevSoundSmoke')); + soundExampleDirectory = p.absolute( + p.join(p.current, '..', 'fixtures', '_webdevSoundSmoke'), + ); - final process = await TestProcess.start(dartPath, ['pub', 'upgrade'], - workingDirectory: soundExampleDirectory, - environment: getPubEnvironment()); + final process = await TestProcess.start( + dartPath, + ['pub', 'upgrade'], + workingDirectory: soundExampleDirectory, + environment: getPubEnvironment(), + ); await process.shouldExit(0); @@ -63,19 +67,27 @@ void main() { tearDownAll(testRunner.tearDownAll); test('smoke test is configured properly', () async { - final smokeYaml = loadYaml( - await File('$soundExampleDirectory/pubspec.yaml').readAsString()) - as YamlMap; + final smokeYaml = + loadYaml( + await File('$soundExampleDirectory/pubspec.yaml').readAsString(), + ) + as YamlMap; final webdevYaml = loadYaml(await File('pubspec.yaml').readAsString()) as YamlMap; - expect(smokeYaml['environment']['sdk'], - equals(webdevYaml['environment']['sdk'])); expect( - buildRunnerConstraint.allowsAny(VersionConstraint.parse( - smokeYaml['dev_dependencies']['build_runner'])), - true); - expect(smokeYaml['dev_dependencies']['build_web_compilers'], - equals(buildWebCompilersConstraint.toString())); + smokeYaml['environment']['sdk'], + equals(webdevYaml['environment']['sdk']), + ); + expect( + buildRunnerConstraint.allowsAny( + VersionConstraint.parse(smokeYaml['dev_dependencies']['build_runner']), + ), + true, + ); + expect( + smokeYaml['dev_dependencies']['build_web_compilers'], + equals(buildWebCompilersConstraint.toString()), + ); }); test('build should fail if targeting an existing directory', () async { @@ -83,19 +95,24 @@ void main() { final args = ['build', '-o', 'web:${d.sandbox}']; - final process = await testRunner.runWebDev(args, - workingDirectory: soundExampleDirectory); + final process = await testRunner.runWebDev( + args, + workingDirectory: soundExampleDirectory, + ); // NOTE: We'd like this to be more useful // See https://github.com/dart-lang/build/issues/1283 await expectLater( - process.stdout, - emitsThrough(contains( + process.stdout, + emitsThrough( + contains( 'Unable to create merged directory ${d.sandbox}. ' 'Choose a different directory or delete the contents of that ' 'directory.', - ))); + ), + ), + ); await process.shouldExit(isNot(0)); }); @@ -108,11 +125,13 @@ void main() { '-o', 'web:${d.sandbox}', '--', - '--delete-conflicting-outputs' + '--delete-conflicting-outputs', ]; - final process = await testRunner.runWebDev(args, - workingDirectory: soundExampleDirectory); + final process = await testRunner.runWebDev( + args, + workingDirectory: soundExampleDirectory, + ); await checkProcessStdout(process, ['Built with build_runner']); await process.shouldExit(0); @@ -131,8 +150,10 @@ void main() { args.add('--no-release'); } - final process = await testRunner.runWebDev(args, - workingDirectory: soundExampleDirectory); + final process = await testRunner.runWebDev( + args, + workingDirectory: soundExampleDirectory, + ); final expectedItems = ['Built with build_runner']; @@ -161,11 +182,13 @@ void main() { '-o', 'web:${d.sandbox}', '--no-release', - '--null-safety=sound' + '--null-safety=sound', ]; - final process = await testRunner.runWebDev(args, - workingDirectory: soundExampleDirectory); + final process = await testRunner.runWebDev( + args, + workingDirectory: soundExampleDirectory, + ); final expectedItems = ['Built with build_runner']; @@ -187,8 +210,10 @@ void main() { args.add('--no-release'); } - final process = await testRunner.runWebDev(args, - workingDirectory: soundExampleDirectory); + final process = await testRunner.runWebDev( + args, + workingDirectory: soundExampleDirectory, + ); final expectedItems = ['Built with build_runner']; @@ -210,14 +235,18 @@ void main() { args.add('--release'); } - final process = await testRunner.runWebDev(args, - workingDirectory: soundExampleDirectory); + final process = await testRunner.runWebDev( + args, + workingDirectory: soundExampleDirectory, + ); final hostUrl = 'http://localhost:$openPort'; // Wait for the initial build to finish. await expectLater( - process.stdout, emitsThrough(contains('Built with build_runner'))); + process.stdout, + emitsThrough(contains('Built with build_runner')), + ); final client = HttpClient(); @@ -230,8 +259,11 @@ void main() { final shouldExist = (entry.value ?? withDDC) == withDDC; - expect(response.statusCode, shouldExist ? 200 : 404, - reason: 'Expecting "$url"? $shouldExist'); + expect( + response.statusCode, + shouldExist ? 200 : 404, + reason: 'Expecting "$url"? $shouldExist', + ); } } finally { client.close(force: true); @@ -250,16 +282,22 @@ void main() { test('cannot $command directory: `$dir`', () async { final args = [ command, - if (command == 'build') '--output=$dir:foo' else dir + if (command == 'build') '--output=$dir:foo' else dir, ]; - final process = await testRunner.runWebDev(args, - workingDirectory: soundExampleDirectory); + final process = await testRunner.runWebDev( + args, + workingDirectory: soundExampleDirectory, + ); await expectLater( - process.stdout, - emitsThrough(contains( - 'Invalid configuration: Only top level directories under the ' - 'package can be built'))); + process.stdout, + emitsThrough( + contains( + 'Invalid configuration: Only top level directories under the ' + 'package can be built', + ), + ), + ); await expectLater(process.exitCode, completion(ExitCode.config.code)); }); } @@ -284,8 +322,10 @@ void main() { '--null-safety=sound', '--verbose', ]; - final process = await testRunner.runWebDev(args, - workingDirectory: soundExampleDirectory); + final process = await testRunner.runWebDev( + args, + workingDirectory: soundExampleDirectory, + ); VmService? vmService; process.stdoutStream().listen(Logger.root.fine); @@ -294,10 +334,13 @@ void main() { try { // Wait for debug service Uri String? wsUri; - await expectLater(process.stdout, emitsThrough((message) { - wsUri = getDebugServiceUri(message as String); - return wsUri != null; - })); + await expectLater( + process.stdout, + emitsThrough((message) { + wsUri = getDebugServiceUri(message as String); + return wsUri != null; + }), + ); Logger.root.fine('vm service uri: $wsUri'); expect(wsUri, isNotNull); @@ -309,30 +352,44 @@ void main() { await vmService.streamListen('Debug'); final stream = vmService.onEvent('Debug'); - final mainScript = scripts.scripts! - .firstWhere((each) => each.uri!.contains('main.dart')); + final mainScript = scripts.scripts!.firstWhere( + (each) => each.uri!.contains('main.dart'), + ); final bpLine = await findBreakpointLine( - vmService, 'printCounter', isolateId, mainScript); + vmService, + 'printCounter', + isolateId, + mainScript, + ); final bp = await vmService.addBreakpointWithScriptUri( - isolateId, mainScript.uri!, bpLine); + isolateId, + mainScript.uri!, + bpLine, + ); expect(bp, isNotNull); await stream.firstWhere( - (Event event) => event.kind == EventKind.kPauseBreakpoint); + (Event event) => event.kind == EventKind.kPauseBreakpoint, + ); final isNullSafetyEnabled = '() { const sound = !([] is List); return sound; } ()'; final result = await vmService.evaluateInFrame( - isolateId, 0, isNullSafetyEnabled); + isolateId, + 0, + isNullSafetyEnabled, + ); expect( - result, - const TypeMatcher().having( - (instance) => instance.valueAsString, - 'valueAsString', - 'true')); + result, + const TypeMatcher().having( + (instance) => instance.valueAsString, + 'valueAsString', + 'true', + ), + ); } finally { await vmService?.dispose(); await exitWebdev(process); @@ -349,8 +406,10 @@ void main() { '--enable-expression-evaluation', '--verbose', ]; - final process = await testRunner.runWebDev(args, - workingDirectory: soundExampleDirectory); + final process = await testRunner.runWebDev( + args, + workingDirectory: soundExampleDirectory, + ); process.stdoutStream().listen(Logger.root.fine); process.stderrStream().listen(Logger.root.warning); @@ -360,10 +419,13 @@ void main() { try { // Wait for debug service Uri String? wsUri; - await expectLater(process.stdout, emitsThrough((message) { - wsUri = getDebugServiceUri(message as String); - return wsUri != null; - })); + await expectLater( + process.stdout, + emitsThrough((message) { + wsUri = getDebugServiceUri(message as String); + return wsUri != null; + }), + ); expect(wsUri, isNotNull); vmService = await vmServiceConnectUri(wsUri!); @@ -374,25 +436,35 @@ void main() { await vmService.streamListen('Debug'); - var result = await vmService.evaluate(isolateId, libraryId, - '(document?.body?.children?.first as SpanElement)?.text'); + var result = await vmService.evaluate( + isolateId, + libraryId, + '(document?.body?.children?.first as SpanElement)?.text', + ); expect( - result, - const TypeMatcher().having( - (instance) => instance.valueAsString, - 'valueAsString', - 'Hello World!!')); + result, + const TypeMatcher().having( + (instance) => instance.valueAsString, + 'valueAsString', + 'Hello World!!', + ), + ); result = await vmService.evaluate( - isolateId, libraryId, 'topLevelMethod()'); + isolateId, + libraryId, + 'topLevelMethod()', + ); expect( - result, - const TypeMatcher().having( - (instance) => instance.valueAsString, - 'valueAsString', - equals('verify this!'))); + result, + const TypeMatcher().having( + (instance) => instance.valueAsString, + 'valueAsString', + equals('verify this!'), + ), + ); } finally { await vmService?.dispose(); await exitWebdev(process); @@ -409,8 +481,10 @@ void main() { '--enable-expression-evaluation', '--verbose', ]; - final process = await testRunner.runWebDev(args, - workingDirectory: soundExampleDirectory); + final process = await testRunner.runWebDev( + args, + workingDirectory: soundExampleDirectory, + ); process.stdoutStream().listen(Logger.root.fine); process.stderrStream().listen(Logger.root.warning); @@ -420,10 +494,13 @@ void main() { try { // Wait for debug service Uri String? wsUri; - await expectLater(process.stdout, emitsThrough((message) { - wsUri = getDebugServiceUri(message as String); - return wsUri != null; - })); + await expectLater( + process.stdout, + emitsThrough((message) { + wsUri = getDebugServiceUri(message as String); + return wsUri != null; + }), + ); expect(wsUri, isNotNull); vmService = await vmServiceConnectUri(wsUri!); @@ -434,34 +511,47 @@ void main() { await vmService.streamListen('Debug'); - final result = - await vmService.evaluate(isolateId, libraryId, '[true, false]'); + final result = await vmService.evaluate( + isolateId, + libraryId, + '[true, false]', + ); expect( - result, - const TypeMatcher().having( - (instance) => instance.classRef?.name, - 'class name', - dartSdkIsAtLeast('3.3.0-242.0.dev') - ? 'JSArray' - : 'List')); + result, + const TypeMatcher().having( + (instance) => instance.classRef?.name, + 'class name', + dartSdkIsAtLeast('3.3.0-242.0.dev') + ? 'JSArray' + : 'List', + ), + ); final instanceRef = result as InstanceRef; final list = await vmService.getObject(isolateId, instanceRef.id!); expect( - list, - const TypeMatcher().having( - (instance) => instance.classRef?.name, - 'class name', - dartSdkIsAtLeast('3.3.0-242.0.dev') - ? 'JSArray' - : 'List')); + list, + const TypeMatcher().having( + (instance) => instance.classRef?.name, + 'class name', + dartSdkIsAtLeast('3.3.0-242.0.dev') + ? 'JSArray' + : 'List', + ), + ); final elements = (list as Instance).elements; expect(elements, [ - const TypeMatcher() - .having((instance) => instance.valueAsString, 'value', 'true'), - const TypeMatcher() - .having((instance) => instance.valueAsString, 'value', 'false'), + const TypeMatcher().having( + (instance) => instance.valueAsString, + 'value', + 'true', + ), + const TypeMatcher().having( + (instance) => instance.valueAsString, + 'value', + 'false', + ), ]); } finally { await vmService?.dispose(); @@ -480,17 +570,22 @@ void main() { '--no-enable-expression-evaluation', '--verbose', ]; - final process = await testRunner.runWebDev(args, - workingDirectory: soundExampleDirectory); + final process = await testRunner.runWebDev( + args, + workingDirectory: soundExampleDirectory, + ); VmService? vmService; try { // Wait for debug service Uri String? wsUri; - await expectLater(process.stdout, emitsThrough((message) { - wsUri = getDebugServiceUri(message as String); - return wsUri != null; - })); + await expectLater( + process.stdout, + emitsThrough((message) { + wsUri = getDebugServiceUri(message as String); + return wsUri != null; + }), + ); expect(wsUri, isNotNull); vmService = await vmServiceConnectUri(wsUri!); @@ -501,23 +596,36 @@ void main() { await vmService.streamListen('Debug'); final stream = vmService.onEvent('Debug'); - final mainScript = scripts.scripts! - .firstWhere((each) => each.uri!.contains('main.dart')); + final mainScript = scripts.scripts!.firstWhere( + (each) => each.uri!.contains('main.dart'), + ); final bpLine = await findBreakpointLine( - vmService, 'printCounter', isolateId, mainScript); + vmService, + 'printCounter', + isolateId, + mainScript, + ); final bp = await vmService.addBreakpointWithScriptUri( - isolateId, mainScript.uri!, bpLine); + isolateId, + mainScript.uri!, + bpLine, + ); expect(bp, isNotNull); final event = await stream.firstWhere( - (Event event) => event.kind == EventKind.kPauseBreakpoint); + (Event event) => event.kind == EventKind.kPauseBreakpoint, + ); expect( - () => vmService! - .evaluateInFrame(isolateId, event.topFrame!.index!, 'true'), - throwsRPCError); + () => vmService!.evaluateInFrame( + isolateId, + event.topFrame!.index!, + 'true', + ), + throwsRPCError, + ); } finally { await vmService?.dispose(); await exitWebdev(process); @@ -534,17 +642,22 @@ void main() { '--no-enable-expression-evaluation', '--verbose', ]; - final process = await testRunner.runWebDev(args, - workingDirectory: soundExampleDirectory); + final process = await testRunner.runWebDev( + args, + workingDirectory: soundExampleDirectory, + ); VmService? vmService; try { // Wait for debug service Uri String? wsUri; - await expectLater(process.stdout, emitsThrough((message) { - wsUri = getDebugServiceUri(message as String); - return wsUri != null; - })); + await expectLater( + process.stdout, + emitsThrough((message) { + wsUri = getDebugServiceUri(message as String); + return wsUri != null; + }), + ); expect(wsUri, isNotNull); vmService = await vmServiceConnectUri(wsUri!); @@ -556,9 +669,9 @@ void main() { await vmService.streamListen('Debug'); expect( - () => - vmService!.evaluate(isolateId, libraryId, 'topLevelMethod()'), - throwsRPCError); + () => vmService!.evaluate(isolateId, libraryId, 'topLevelMethod()'), + throwsRPCError, + ); } finally { await vmService?.dispose(); await exitWebdev(process); diff --git a/webdev/test/installation_test.dart b/webdev/test/installation_test.dart index e06d1ffde..cc6023278 100644 --- a/webdev/test/installation_test.dart +++ b/webdev/test/installation_test.dart @@ -17,10 +17,7 @@ import 'package:test/test.dart'; // Webdev can be activated and serve a web app. It is intended to catch any // regressions due to changes in the Dart SDK. -enum StreamType { - stdout, - stderr, -} +enum StreamType { stdout, stderr } const processTimeout = Duration(minutes: 1); @@ -30,16 +27,23 @@ void main() { Process? serveProcess; Directory? tempDir0; - final testScript = - File(p.join(p.dirname(Platform.script.toFilePath()), 'test.dart')) - .readAsStringSync(); - final thisScript = File.fromUri(Uri.parse(testScript.substring( - testScript.lastIndexOf('import', testScript.indexOf('as test;')) + 8, - testScript.indexOf('as test;') - 2))); + final testScript = File( + p.join(p.dirname(Platform.script.toFilePath()), 'test.dart'), + ).readAsStringSync(); + final thisScript = File.fromUri( + Uri.parse( + testScript.substring( + testScript.lastIndexOf('import', testScript.indexOf('as test;')) + 8, + testScript.indexOf('as test;') - 2, + ), + ), + ); final packageDir = p.dirname(p.dirname(thisScript.path)); - Future expectStdoutAndCleanExit(Process process, - {required String expectedStdout}) async { + Future expectStdoutAndCleanExit( + Process process, { + required String expectedStdout, + }) async { final stdoutCompleter = _captureOutput( process, streamType: StreamType.stdout, @@ -60,18 +64,14 @@ void main() { // cleanly: reason: 'stderr: $stderrLogs, stdout: $stdoutLogs', ); - expect( - stderrLogs, - isEmpty, - ); - expect( - stdoutLogs, - contains(expectedStdout), - ); + expect(stderrLogs, isEmpty); + expect(stdoutLogs, contains(expectedStdout)); } - Future expectStdoutThenExit(Process process, - {required String expectedStdout}) async { + Future expectStdoutThenExit( + Process process, { + required String expectedStdout, + }) async { final expectedStdoutCompleter = _waitForStdoutOrTimeout( process, expectedStdout: expectedStdout, @@ -84,7 +84,8 @@ void main() { final stdoutLogs = await expectedStdoutCompleter.future; final stderrLogs = await stderrCompleter.future; expect( - stdoutLogs, contains(expectedStdout), + stdoutLogs, + contains(expectedStdout), // Also include the stderr if the stdout is not expected. reason: 'stderr: $stderrLogs', ); @@ -93,10 +94,7 @@ void main() { setUp(() async { tempDir0 = Directory.systemTemp.createTempSync('installation_test'); - await Process.run( - 'dart', - ['pub', 'global', 'deactivate', 'webdev'], - ); + await Process.run('dart', ['pub', 'global', 'deactivate', 'webdev']); }); tearDown(() async { @@ -120,11 +118,12 @@ void main() { final tempPath = tempDir.path; // Verify that we can create a new Dart app: - createProcess = await Process.start( - 'dart', - ['create', '--template', 'web', 'temp_app'], - workingDirectory: tempPath, - ); + createProcess = await Process.start('dart', [ + 'create', + '--template', + 'web', + 'temp_app', + ], workingDirectory: tempPath); await expectStdoutAndCleanExit( createProcess!, expectedStdout: 'Created project temp_app in temp_app!', @@ -133,21 +132,29 @@ void main() { expect(await Directory(appPath).exists(), isTrue); // Verify that `dart pub global activate` works: - activateProcess = await Process.start( - 'dart', - ['pub', 'global', 'activate', 'webdev'], - ); + activateProcess = await Process.start('dart', [ + 'pub', + 'global', + 'activate', + 'webdev', + ]); await expectStdoutAndCleanExit( activateProcess!, expectedStdout: 'Activated webdev', ); // Verify that `webdev serve` works for our new app: - serveProcess = await Process.start( - 'dart', ['pub', 'global', 'run', 'webdev', 'serve'], - workingDirectory: appPath); - await expectStdoutThenExit(serveProcess!, - expectedStdout: 'Serving `web` on'); + serveProcess = await Process.start('dart', [ + 'pub', + 'global', + 'run', + 'webdev', + 'serve', + ], workingDirectory: appPath); + await expectStdoutThenExit( + serveProcess!, + expectedStdout: 'Serving `web` on', + ); }); test('activate and serve webdev fails with offline', () async { @@ -155,11 +162,13 @@ void main() { final tempPath = tempDir.path; // Verify that we can create a new Dart app: - createProcess = await Process.start( - 'dart', - ['create', '--no-pub', '--template', 'web', 'temp_app'], - workingDirectory: tempPath, - ); + createProcess = await Process.start('dart', [ + 'create', + '--no-pub', + '--template', + 'web', + 'temp_app', + ], workingDirectory: tempPath); await expectStdoutAndCleanExit( createProcess!, expectedStdout: 'Created project temp_app in temp_app!', @@ -168,21 +177,33 @@ void main() { expect(await Directory(appPath).exists(), isTrue); // Verify that `dart pub global activate` works: - activateProcess = await Process.start( - 'dart', - ['pub', 'global', 'activate', '--source', 'path', packageDir], - ); + activateProcess = await Process.start('dart', [ + 'pub', + 'global', + 'activate', + '--source', + 'path', + packageDir, + ]); await expectStdoutAndCleanExit( activateProcess!, expectedStdout: 'Activated webdev', ); // Verify that `webdev serve` works for our new app: - serveProcess = await Process.start('dart', - ['pub', 'global', 'run', 'webdev', 'serve', '--offline', 'web:8081'], - workingDirectory: appPath); - await expectStdoutThenExit(serveProcess!, - expectedStdout: 'Cannot open file\n pubspec.lock\n'); + serveProcess = await Process.start('dart', [ + 'pub', + 'global', + 'run', + 'webdev', + 'serve', + '--offline', + 'web:8081', + ], workingDirectory: appPath); + await expectStdoutThenExit( + serveProcess!, + expectedStdout: 'Cannot open file\n pubspec.lock\n', + ); }); } @@ -196,8 +217,10 @@ Future _waitForExitOrTimeout(Process process) { /// Returns the stdout for the [process] once the [expectedStdout] is found. /// /// Otherwise returns all the stdout up to the [processTimeout]. -Completer _waitForStdoutOrTimeout(Process process, - {required String expectedStdout}) { +Completer _waitForStdoutOrTimeout( + Process process, { + required String expectedStdout, +}) { var output = ''; final completer = Completer(); @@ -225,8 +248,9 @@ Completer _captureOutput( required StreamType streamType, required Future stopCaptureFuture, }) { - final stream = - streamType == StreamType.stdout ? process.stdout : process.stderr; + final stream = streamType == StreamType.stdout + ? process.stdout + : process.stderr; final completer = Completer(); var output = ''; stream.transform(utf8.decoder).listen((line) { @@ -238,10 +262,12 @@ Completer _captureOutput( } } }); - unawaited(stopCaptureFuture.then((_) { - if (!completer.isCompleted) { - completer.complete(output); - } - })); + unawaited( + stopCaptureFuture.then((_) { + if (!completer.isCompleted) { + completer.complete(output); + } + }), + ); return completer; } diff --git a/webdev/test/integration_test.dart b/webdev/test/integration_test.dart index 44b79275f..8b14850c4 100644 --- a/webdev/test/integration_test.dart +++ b/webdev/test/integration_test.dart @@ -15,10 +15,7 @@ import 'package:test_descriptor/test_descriptor.dart' as d; import 'test_utils.dart'; -enum StreamType { - stdout, - stderr, -} +enum StreamType { stdout, stderr } const processTimeout = Duration(minutes: 1); @@ -27,8 +24,10 @@ void main() { setUpAll(testRunner.setUpAll); tearDownAll(testRunner.tearDownAll); - Future expectStdoutAndCleanExit(Process process, - {required String expectedStdout}) async { + Future expectStdoutAndCleanExit( + Process process, { + required String expectedStdout, + }) async { final stdoutCompleter = _captureOutput( process, streamType: StreamType.stdout, @@ -49,21 +48,17 @@ void main() { // cleanly: reason: 'stderr: $stderrLogs, stdout: $stdoutLogs', ); - expect( - stderrLogs, - isEmpty, - ); - expect( - stdoutLogs, - contains(expectedStdout), - ); + expect(stderrLogs, isEmpty); + expect(stdoutLogs, contains(expectedStdout)); } test('non-existent commands create errors', () async { final process = await testRunner.runWebDev(['monkey']); await expectLater( - process.stdout, emits('Could not find a command named "monkey".')); + process.stdout, + emits('Could not find a command named "monkey".'), + ); await process.shouldExit(64); }); @@ -71,37 +66,40 @@ void main() { test('passing extra args to build fails with bad usage', () async { final process = await testRunner.runWebDev(['build', 'extra', 'args']); - await expectLater(process.stdout, - emits('Arguments were provided that are not supported: "extra args".')); + await expectLater( + process.stdout, + emits('Arguments were provided that are not supported: "extra args".'), + ); await process.shouldExit(64); }); - test('Errors with `build_runner` should not surface `build_daemon` issues', - () async { - await d.file('pubspec.yaml', _pubspecYaml).create(); + test( + 'Errors with `build_runner` should not surface `build_daemon` issues', + () async { + await d.file('pubspec.yaml', _pubspecYaml).create(); - await d - .file( + await d + .file( 'pubspec.lock', - _pubspecLock( - runnerVersion: '1.2.8', - daemonVersion: '0.4.0', - )) - .create(); + _pubspecLock(runnerVersion: '1.2.8', daemonVersion: '0.4.0'), + ) + .create(); - await d.dir('.dart_tool', [d.file('package_config.json', '')]).create(); - await d.file('.dart_tool/package_config.json', '').create(); + await d.dir('.dart_tool', [d.file('package_config.json', '')]).create(); + await d.file('.dart_tool/package_config.json', '').create(); - final process = - await testRunner.runWebDev(['serve'], workingDirectory: d.sandbox); + final process = await testRunner.runWebDev([ + 'serve', + ], workingDirectory: d.sandbox); - final output = await process.stdout.rest.toList(); + final output = await process.stdout.rest.toList(); - expect(output, isNot(contains(contains('`build_daemon`')))); + expect(output, isNot(contains(contains('`build_daemon`')))); - await process.shouldExit(78); - }); + await process.shouldExit(78); + }, + ); final invalidRanges = >{ 'build_runner': ['0.8.9', '3.0.0'], @@ -119,12 +117,14 @@ void main() { .file('pubspec.lock', _pubspecLock(runnerVersion: null)) .create(); - await d - .dir('.dart_tool', [d.file('package_config.json', '')]).create(); + await d.dir('.dart_tool', [ + d.file('package_config.json', ''), + ]).create(); await d.file('.dart_tool/package_config.json', '').create(); - final process = await testRunner - .runWebDev([command], workingDirectory: d.sandbox); + final process = await testRunner.runWebDev([ + command, + ], workingDirectory: d.sandbox); await checkProcessStdout(process, ['webdev could not run']); await process.shouldExit(78); @@ -137,19 +137,20 @@ void main() { .file('pubspec.lock', _pubspecLock(webCompilersVersion: null)) .create(); - await d - .dir('.dart_tool', [d.file('package_config.json', '')]).create(); + await d.dir('.dart_tool', [ + d.file('package_config.json', ''), + ]).create(); await d.file('.dart_tool/package_config.json', '').create(); - final process = await testRunner - .runWebDev(['serve'], workingDirectory: d.sandbox); + final process = await testRunner.runWebDev([ + 'serve', + ], workingDirectory: d.sandbox); await checkProcessStdout(process, ['webdev could not run']); await process.shouldExit(78); }); - test( - '`build_web_compilers` should be ignored with ' + test('`build_web_compilers` should be ignored with ' '--no-build-web-compilers', () async { await d.file('pubspec.yaml', _pubspecYaml).create(); @@ -157,16 +158,18 @@ void main() { .file('pubspec.lock', _pubspecLock(webCompilersVersion: null)) .create(); - await d - .dir('.dart_tool', [d.file('package_config.json', '')]).create(); + await d.dir('.dart_tool', [ + d.file('package_config.json', ''), + ]).create(); await d.file('.dart_tool/package_config.json', '').create(); // Required for webdev to not complain about nothing to serve. await d.dir('web').create(); - final process = await testRunner.runWebDev( - ['serve', '--no-build-web-compilers'], - workingDirectory: d.sandbox); + final process = await testRunner.runWebDev([ + 'serve', + '--no-build-web-compilers', + ], workingDirectory: d.sandbox); await process.shouldExit(); }); @@ -195,19 +198,23 @@ void main() { await d .file( - 'pubspec.lock', - _pubspecLock( - runnerVersion: buildRunnerVersion, - webCompilersVersion: webCompilersVersion, - daemonVersion: buildDaemonVersion)) + 'pubspec.lock', + _pubspecLock( + runnerVersion: buildRunnerVersion, + webCompilersVersion: webCompilersVersion, + daemonVersion: buildDaemonVersion, + ), + ) .create(); - await d.dir( - '.dart_tool', [d.file('package_config.json', '')]).create(); + await d.dir('.dart_tool', [ + d.file('package_config.json', ''), + ]).create(); await d.file('.dart_tool/package_config.json', '').create(); - final process = await testRunner - .runWebDev(['serve'], workingDirectory: d.sandbox); + final process = await testRunner.runWebDev([ + 'serve', + ], workingDirectory: d.sandbox); await checkProcessStdout(process, ['webdev could not run']); @@ -218,25 +225,24 @@ void main() { } test('no pubspec.yaml', () async { - final process = - await testRunner.runWebDev(['serve'], workingDirectory: d.sandbox); + final process = await testRunner.runWebDev([ + 'serve', + ], workingDirectory: d.sandbox); await checkProcessStdout(process, ['webdev could not run']); await process.shouldExit(78); }); - test( - 'pubspec.yaml, no pubspec.lock', - () async { - await d.file('pubspec.yaml', _pubspecYaml).create(); + test('pubspec.yaml, no pubspec.lock', () async { + await d.file('pubspec.yaml', _pubspecYaml).create(); - final process = await testRunner - .runWebDev(['serve'], workingDirectory: d.sandbox); + final process = await testRunner.runWebDev([ + 'serve', + ], workingDirectory: d.sandbox); - await checkProcessStdout(process, ['webdev could not run']); - await process.shouldExit(78); - }, - ); + await checkProcessStdout(process, ['webdev could not run']); + await process.shouldExit(78); + }); test('should fail if there has been a dependency change', () async { await d.file('pubspec.lock', _pubspecLock()).create(); @@ -253,8 +259,9 @@ dependencies: args: ^1.0.0 ''').create(); - final process = - await testRunner.runWebDev(['serve'], workingDirectory: d.sandbox); + final process = await testRunner.runWebDev([ + 'serve', + ], workingDirectory: d.sandbox); await checkProcessStdout(process, ['webdev could not run']); await process.shouldExit(78); @@ -262,18 +269,24 @@ dependencies: if (command != 'daemon') { test('failure with offline and unresolved dependencies', () async { - final createProcess = await Process.start( - 'dart', - ['create', '--no-pub', '--template', 'web', 'temp_app'], - workingDirectory: d.sandbox, + final createProcess = await Process.start('dart', [ + 'create', + '--no-pub', + '--template', + 'web', + 'temp_app', + ], workingDirectory: d.sandbox); + await expectStdoutAndCleanExit( + createProcess, + expectedStdout: 'Created project temp_app', ); - await expectStdoutAndCleanExit(createProcess, - expectedStdout: 'Created project temp_app'); final appPath = p.join(d.sandbox, 'temp_app'); - final process = await testRunner - .runWebDev([command, '--offline'], workingDirectory: appPath); + final process = await testRunner.runWebDev([ + command, + '--offline', + ], workingDirectory: appPath); await checkProcessStdout(process, ['webdev could not run']); await process.shouldExit(78); @@ -291,11 +304,12 @@ String _pubspecYaml = ''' name: sample '''; -String _pubspecLock( - {String? runnerVersion = _supportedBuildRunnerVersion, - String? webCompilersVersion = _supportedWebCompilersVersion, - String? daemonVersion = _supportedBuildDaemonVersion, - List extraPkgs = const []}) { +String _pubspecLock({ + String? runnerVersion = _supportedBuildRunnerVersion, + String? webCompilersVersion = _supportedWebCompilersVersion, + String? daemonVersion = _supportedBuildDaemonVersion, + List extraPkgs = const [], +}) { final buffer = StringBuffer(''' # Copy-pasted from a valid run packages: @@ -364,8 +378,9 @@ Completer _captureOutput( required StreamType streamType, required Future stopCaptureFuture, }) { - final stream = - streamType == StreamType.stdout ? process.stdout : process.stderr; + final stream = streamType == StreamType.stdout + ? process.stdout + : process.stderr; final completer = Completer(); var output = ''; stream.transform(utf8.decoder).listen((line) { @@ -377,10 +392,12 @@ Completer _captureOutput( } } }); - unawaited(stopCaptureFuture.then((_) { - if (!completer.isCompleted) { - completer.complete(output); - } - })); + unawaited( + stopCaptureFuture.then((_) { + if (!completer.isCompleted) { + completer.complete(output); + } + }), + ); return completer; } diff --git a/webdev/test/readme_test.dart b/webdev/test/readme_test.dart index 4a5795f69..b2ed30b36 100644 --- a/webdev/test/readme_test.dart +++ b/webdev/test/readme_test.dart @@ -3,9 +3,7 @@ // BSD-style license that can be found in the LICENSE file. @TestOn('vm') -@OnPlatform({ - 'windows': Skip('https://github.com/dart-lang/webdev/issues/711'), -}) +@OnPlatform({'windows': Skip('https://github.com/dart-lang/webdev/issues/711')}) library; import 'dart:async'; @@ -34,16 +32,14 @@ Future _readmeCheck(TestRunner testRunner, List args) async { .trim(); await process.shouldExit(0); - final firstLineStart = - _readmeContents.indexOf(LineSplitter.split(output).first); + final firstLineStart = _readmeContents.indexOf( + LineSplitter.split(output).first, + ); expect(firstLineStart, greaterThanOrEqualTo(0)); final sectionEnd = _readmeContents.indexOf('```', firstLineStart); expect(sectionEnd, greaterThan(firstLineStart)); - expect( - _readmeContents.substring(firstLineStart, sectionEnd).trim(), - output, - ); + expect(_readmeContents.substring(firstLineStart, sectionEnd).trim(), output); } diff --git a/webdev/test/test_utils.dart b/webdev/test/test_utils.dart index 5f5f64af2..1ab7a17ac 100644 --- a/webdev/test/test_utils.dart +++ b/webdev/test/test_utils.dart @@ -36,21 +36,30 @@ class TestRunner { sdkConfigurationProvider.dispose(); } - Future runWebDev(List args, - {String? workingDirectory}) async { + Future runWebDev( + List args, { + String? workingDirectory, + }) async { final fullArgs = [_webdevBin, ...args]; - return TestProcess.start(sdkLayout.dartPath, fullArgs, - workingDirectory: workingDirectory); + return TestProcess.start( + sdkLayout.dartPath, + fullArgs, + workingDirectory: workingDirectory, + ); } Future prepareWorkspace() async { - final exampleDirectory = - p.absolute(p.join(p.current, '..', 'fixtures', '_webdevSoundSmoke')); + final exampleDirectory = p.absolute( + p.join(p.current, '..', 'fixtures', '_webdevSoundSmoke'), + ); final process = await TestProcess.start( - sdkLayout.dartPath, ['pub', 'upgrade'], - workingDirectory: exampleDirectory, environment: getPubEnvironment()); + sdkLayout.dartPath, + ['pub', 'upgrade'], + workingDirectory: exampleDirectory, + environment: getPubEnvironment(), + ); await process.shouldExit(0); return exampleDirectory; diff --git a/webdev/test/tls_test.dart b/webdev/test/tls_test.dart index 1b580c65d..46bc78ec9 100644 --- a/webdev/test/tls_test.dart +++ b/webdev/test/tls_test.dart @@ -27,8 +27,9 @@ void main() { setUpAll(() async { configureLogWriter(debug); await testRunner.setUpAll(); - exampleDirectory = - p.absolute(p.join(p.current, '..', 'fixtures', '_webdevSoundSmoke')); + exampleDirectory = p.absolute( + p.join(p.current, '..', 'fixtures', '_webdevSoundSmoke'), + ); final process = await TestProcess.start( 'dart', @@ -55,16 +56,21 @@ void main() { '--tls-cert-key=localhost+2-key.pem', ]; - final process = - await testRunner.runWebDev(args, workingDirectory: exampleDirectory); + final process = await testRunner.runWebDev( + args, + workingDirectory: exampleDirectory, + ); await expectLater( - process.stdout, emitsThrough(contains('Built with build_runner'))); + process.stdout, + emitsThrough(contains('Built with build_runner')), + ); final client = HttpClient() ..badCertificateCallback = (_, __, ___) => true; try { - final request = - await client.getUrl(Uri.parse('https://localhost:$port')); + final request = await client.getUrl( + Uri.parse('https://localhost:$port'), + ); final response = await request.close(); expect(response.statusCode, equals(200)); } finally { @@ -86,10 +92,14 @@ void main() { '--enable-experiment=dot-shorthands', ]; - final process = - await testRunner.runWebDev(args, workingDirectory: exampleDirectory); + final process = await testRunner.runWebDev( + args, + workingDirectory: exampleDirectory, + ); await expectLater( - process.stdout, emitsThrough(contains('Built with build_runner'))); + process.stdout, + emitsThrough(contains('Built with build_runner')), + ); final interfaces = await NetworkInterface.list( type: InternetAddressType.IPv4, @@ -99,13 +109,15 @@ void main() { if (nonLoopback == null) { Logger.root.info( - 'No non-loopback IPv4 address available, skipping hostname test.'); + 'No non-loopback IPv4 address available, skipping hostname test.', + ); } else { final client = HttpClient() ..badCertificateCallback = (_, __, ___) => true; try { - final request = await client - .getUrl(Uri.parse('https://${nonLoopback.address}:$port')); + final request = await client.getUrl( + Uri.parse('https://${nonLoopback.address}:$port'), + ); final response = await request.close(); expect(response.statusCode, equals(200)); } finally { diff --git a/webdev/test/utils_test.dart b/webdev/test/utils_test.dart index 6f52ebf5a..03e37d957 100644 --- a/webdev/test/utils_test.dart +++ b/webdev/test/utils_test.dart @@ -76,8 +76,9 @@ void main() { subDirFrom.createSync(); subDirTo.createSync(); - final listFrom = - from.listSync().map((e) => p.relative(e.path, from: from.path)); + final listFrom = from.listSync().map( + (e) => p.relative(e.path, from: from.path), + ); await updatePath(from.path, to.path); final listTo = to.listSync().map((e) => p.relative(e.path, from: to.path)); @@ -91,8 +92,9 @@ void main() { fileFrom.createSync(); fileTo.createSync(); - final listFrom = - from.listSync().map((e) => p.relative(e.path, from: from.path)); + final listFrom = from.listSync().map( + (e) => p.relative(e.path, from: from.path), + ); await updatePath(from.path, to.path); final listTo = to.listSync().map((e) => p.relative(e.path, from: to.path));