Unverified Commit 2efeeb47 authored by Jackson Gardner's avatar Jackson Gardner Committed by GitHub

Revert Dual Web Compile changes (#143175)

Dual Web Compile has had some issues where `flutter test` is not respecting the `--web-renderer` flag for some reason. I haven't gotten entirely to the bottom of the issue, but for now we need to rever these changes while I investigate. This reverts the following PRs:

https://github.com/flutter/flutter/pull/143128
https://github.com/flutter/flutter/pull/141396

While doing this revert, I had a few merge conflicts with https://github.com/flutter/flutter/pull/142760, and I tried to resolve the merge conflicts within the spirit of that PR's change, but @chingjun I might need your input on whether the imports I have modified are okay with regards to the change you were making.
parent 8d3c7b6f
...@@ -6,12 +6,8 @@ found in the LICENSE file. --> ...@@ -6,12 +6,8 @@ found in the LICENSE file. -->
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8">
<title>Web Benchmarks</title> <title>Web Benchmarks</title>
<script src="flutter.js"></script>
</head> </head>
<body> <body>
<script> <script src="main.dart.js" type="application/javascript"></script>
{{flutter_build_config}}
_flutter.loader.load();
</script>
</body> </body>
</html> </html>
...@@ -39,7 +39,7 @@ Future<TaskResult> runWebBenchmark(WebBenchmarkOptions benchmarkOptions) async { ...@@ -39,7 +39,7 @@ Future<TaskResult> runWebBenchmark(WebBenchmarkOptions benchmarkOptions) async {
'--omit-type-checks', '--omit-type-checks',
], ],
'--dart-define=FLUTTER_WEB_ENABLE_PROFILING=true', '--dart-define=FLUTTER_WEB_ENABLE_PROFILING=true',
if (!benchmarkOptions.useWasm) '--web-renderer=${benchmarkOptions.webRenderer}', '--web-renderer=${benchmarkOptions.webRenderer}',
'--profile', '--profile',
'--no-web-resources-cdn', '--no-web-resources-cdn',
'-t', '-t',
...@@ -125,7 +125,7 @@ Future<TaskResult> runWebBenchmark(WebBenchmarkOptions benchmarkOptions) async { ...@@ -125,7 +125,7 @@ Future<TaskResult> runWebBenchmark(WebBenchmarkOptions benchmarkOptions) async {
return Response.internalServerError(body: '$error'); return Response.internalServerError(body: '$error');
} }
}).add(createBuildDirectoryHandler( }).add(createBuildDirectoryHandler(
path.join(macrobenchmarksDirectory, 'build', 'web'), path.join(macrobenchmarksDirectory, 'build', benchmarkOptions.useWasm ? 'web_wasm' : 'web'),
)); ));
server = await io.HttpServer.bind('localhost', benchmarkServerPort); server = await io.HttpServer.bind('localhost', benchmarkServerPort);
......
...@@ -5,17 +5,14 @@ found in the LICENSE file. --> ...@@ -5,17 +5,14 @@ found in the LICENSE file. -->
<html> <html>
<head> <head>
<title>Web Integration Tests</title> <title>Web Integration Tests</title>
<script src="flutter.js"></script> <script>
// Use the local CanvasKit bundle instead of the CDN to reduce test flakiness.
window.flutterConfiguration = {
canvasKitBaseUrl: "/canvaskit/"
};
</script>
</head> </head>
<body> <body>
<script> <script src="main.dart.js"></script>
{{flutter_build_config}}
_flutter.loader.load({
config: {
// Use the local CanvasKit bundle instead of the CDN to reduce test flakiness.
canvasKitBaseUrl: "/canvaskit/",
},
});
</script>
</body> </body>
</html> </html>
...@@ -12,6 +12,7 @@ import 'base/os.dart'; ...@@ -12,6 +12,7 @@ import 'base/os.dart';
import 'base/utils.dart'; import 'base/utils.dart';
import 'convert.dart'; import 'convert.dart';
import 'globals.dart' as globals; import 'globals.dart' as globals;
import 'web/compile.dart';
/// Whether icon font subsetting is enabled by default. /// Whether icon font subsetting is enabled by default.
const bool kIconTreeShakerEnabledDefault = true; const bool kIconTreeShakerEnabledDefault = true;
...@@ -35,6 +36,7 @@ class BuildInfo { ...@@ -35,6 +36,7 @@ class BuildInfo {
List<String>? dartDefines, List<String>? dartDefines,
this.bundleSkSLPath, this.bundleSkSLPath,
List<String>? dartExperiments, List<String>? dartExperiments,
this.webRenderer = WebRendererMode.auto,
required this.treeShakeIcons, required this.treeShakeIcons,
this.performanceMeasurementFile, this.performanceMeasurementFile,
this.packagesPath = '.dart_tool/package_config.json', // TODO(zanderso): make this required and remove the default. this.packagesPath = '.dart_tool/package_config.json', // TODO(zanderso): make this required and remove the default.
...@@ -128,6 +130,9 @@ class BuildInfo { ...@@ -128,6 +130,9 @@ class BuildInfo {
/// A list of Dart experiments. /// A list of Dart experiments.
final List<String> dartExperiments; final List<String> dartExperiments;
/// When compiling to web, which web renderer mode we are using (html, canvaskit, auto)
final WebRendererMode webRenderer;
/// The name of a file where flutter assemble will output performance /// The name of a file where flutter assemble will output performance
/// information in a JSON format. /// information in a JSON format.
/// ///
...@@ -793,6 +798,10 @@ HostPlatform getCurrentHostPlatform() { ...@@ -793,6 +798,10 @@ HostPlatform getCurrentHostPlatform() {
return HostPlatform.linux_x64; return HostPlatform.linux_x64;
} }
FileSystemEntity getWebPlatformBinariesDirectory(Artifacts artifacts, WebRendererMode webRenderer) {
return artifacts.getHostArtifact(HostArtifact.webPlatformKernelFolder);
}
/// Returns the top-level build output directory. /// Returns the top-level build output directory.
String getBuildDirectory([Config? config, FileSystem? fileSystem]) { String getBuildDirectory([Config? config, FileSystem? fileSystem]) {
// TODO(johnmccutchan): Stop calling this function as part of setting // TODO(johnmccutchan): Stop calling this function as part of setting
...@@ -835,8 +844,8 @@ String getMacOSBuildDirectory() { ...@@ -835,8 +844,8 @@ String getMacOSBuildDirectory() {
} }
/// Returns the web build output directory. /// Returns the web build output directory.
String getWebBuildDirectory() { String getWebBuildDirectory([bool isWasm = false]) {
return globals.fs.path.join(getBuildDirectory(), 'web'); return globals.fs.path.join(getBuildDirectory(), isWasm ? 'web_wasm' : 'web');
} }
/// Returns the Linux build output directory. /// Returns the Linux build output directory.
......
...@@ -136,15 +136,6 @@ abstract class Target { ...@@ -136,15 +136,6 @@ abstract class Target {
/// A list of zero or more depfiles, located directly under {BUILD_DIR}. /// A list of zero or more depfiles, located directly under {BUILD_DIR}.
List<String> get depfiles => const <String>[]; List<String> get depfiles => const <String>[];
/// A string that differentiates different build variants from each other
/// with regards to build flags or settings on the target. This string should
/// represent each build variant as a different unique value. If this value
/// changes between builds, the target will be invalidated and rebuilt.
///
/// By default, this returns null, which indicates there is only one build
/// variant, and the target won't invalidate or rebuild due to this property.
String? get buildKey => null;
/// Whether this target can be executed with the given [environment]. /// Whether this target can be executed with the given [environment].
/// ///
/// Returning `true` will cause [build] to be skipped. This is equivalent /// Returning `true` will cause [build] to be skipped. This is equivalent
...@@ -165,7 +156,6 @@ abstract class Target { ...@@ -165,7 +156,6 @@ abstract class Target {
<Node>[ <Node>[
for (final Target target in dependencies) target._toNode(environment), for (final Target target in dependencies) target._toNode(environment),
], ],
buildKey,
environment, environment,
inputsFiles.containsNewDepfile, inputsFiles.containsNewDepfile,
); );
...@@ -191,11 +181,9 @@ abstract class Target { ...@@ -191,11 +181,9 @@ abstract class Target {
for (final File output in outputs) { for (final File output in outputs) {
outputPaths.add(output.path); outputPaths.add(output.path);
} }
final String? key = buildKey;
final Map<String, Object> result = <String, Object>{ final Map<String, Object> result = <String, Object>{
'inputs': inputPaths, 'inputs': inputPaths,
'outputs': outputPaths, 'outputs': outputPaths,
if (key != null) 'buildKey': key,
}; };
if (!stamp.existsSync()) { if (!stamp.existsSync()) {
stamp.createSync(); stamp.createSync();
...@@ -230,7 +218,6 @@ abstract class Target { ...@@ -230,7 +218,6 @@ abstract class Target {
/// This requires constants from the [Environment] to resolve the paths of /// This requires constants from the [Environment] to resolve the paths of
/// inputs and the output stamp. /// inputs and the output stamp.
Map<String, Object> toJson(Environment environment) { Map<String, Object> toJson(Environment environment) {
final String? key = buildKey;
return <String, Object>{ return <String, Object>{
'name': name, 'name': name,
'dependencies': <String>[ 'dependencies': <String>[
...@@ -242,7 +229,6 @@ abstract class Target { ...@@ -242,7 +229,6 @@ abstract class Target {
'outputs': <String>[ 'outputs': <String>[
for (final File file in resolveOutputs(environment).sources) file.path, for (final File file in resolveOutputs(environment).sources) file.path,
], ],
if (key != null) 'buildKey': key,
'stamp': _findStampFile(environment).absolute.path, 'stamp': _findStampFile(environment).absolute.path,
}; };
} }
...@@ -994,85 +980,49 @@ void verifyOutputDirectories(List<File> outputs, Environment environment, Target ...@@ -994,85 +980,49 @@ void verifyOutputDirectories(List<File> outputs, Environment environment, Target
/// A node in the build graph. /// A node in the build graph.
class Node { class Node {
factory Node( Node(
Target target, this.target,
List<File> inputs, this.inputs,
List<File> outputs, this.outputs,
List<Node> dependencies, this.dependencies,
String? buildKey,
Environment environment, Environment environment,
bool missingDepfile, this.missingDepfile,
) { ) {
final File stamp = target._findStampFile(environment); final File stamp = target._findStampFile(environment);
Map<String, Object?>? stampValues;
// If the stamp file doesn't exist, we haven't run this step before and // If the stamp file doesn't exist, we haven't run this step before and
// all inputs were added. // all inputs were added.
if (stamp.existsSync()) { if (!stamp.existsSync()) {
final String content = stamp.readAsStringSync(); // No stamp file, not safe to skip.
if (content.isEmpty) { _dirty = true;
stamp.deleteSync(); return;
} else {
try {
stampValues = castStringKeyedMap(json.decode(content));
} on FormatException {
// The json is malformed in some way.
}
}
} }
if (stampValues != null) { final String content = stamp.readAsStringSync();
final String? previousBuildKey = stampValues['buildKey'] as String?; // Something went wrong writing the stamp file.
final Object? stampInputs = stampValues['inputs']; if (content.isEmpty) {
final Object? stampOutputs = stampValues['outputs']; stamp.deleteSync();
if (stampInputs is List<Object?> && stampOutputs is List<Object?>) { // Malformed stamp file, not safe to skip.
final Set<String> previousInputs = stampInputs.whereType<String>().toSet(); _dirty = true;
final Set<String> previousOutputs = stampOutputs.whereType<String>().toSet(); return;
return Node.withStamp(
target,
inputs,
previousInputs,
outputs,
previousOutputs,
dependencies,
buildKey,
previousBuildKey,
missingDepfile,
);
}
} }
return Node.withNoStamp( Map<String, Object?>? values;
target, try {
inputs, values = castStringKeyedMap(json.decode(content));
outputs, } on FormatException {
dependencies, // The json is malformed in some way.
buildKey,
missingDepfile,
);
}
Node.withNoStamp(
this.target,
this.inputs,
this.outputs,
this.dependencies,
this.buildKey,
this.missingDepfile,
) : previousInputs = <String>{},
previousOutputs = <String>{},
previousBuildKey = null,
_dirty = true; _dirty = true;
return;
Node.withStamp( }
this.target, final Object? inputs = values?['inputs'];
this.inputs, final Object? outputs = values?['outputs'];
this.previousInputs, if (inputs is List<Object?> && outputs is List<Object?>) {
this.outputs, inputs.cast<String?>().whereType<String>().forEach(previousInputs.add);
this.previousOutputs, outputs.cast<String?>().whereType<String>().forEach(previousOutputs.add);
this.dependencies, } else {
this.buildKey, // The json is malformed in some way.
this.previousBuildKey, _dirty = true;
this.missingDepfile, }
) : _dirty = false; }
/// The resolved input files. /// The resolved input files.
/// ///
...@@ -1084,11 +1034,6 @@ class Node { ...@@ -1084,11 +1034,6 @@ class Node {
/// These files may not yet exist if the target hasn't run yet. /// These files may not yet exist if the target hasn't run yet.
final List<File> outputs; final List<File> outputs;
/// The current build key of the target
///
/// See `buildKey` in the `Target` class for more information.
final String? buildKey;
/// Whether this node is missing a depfile. /// Whether this node is missing a depfile.
/// ///
/// This requires an additional pass of source resolution after the target /// This requires an additional pass of source resolution after the target
...@@ -1102,15 +1047,10 @@ class Node { ...@@ -1102,15 +1047,10 @@ class Node {
final List<Node> dependencies; final List<Node> dependencies;
/// Output file paths from the previous invocation of this build node. /// Output file paths from the previous invocation of this build node.
final Set<String> previousOutputs; final Set<String> previousOutputs = <String>{};
/// Input file paths from the previous invocation of this build node. /// Input file paths from the previous invocation of this build node.
final Set<String> previousInputs; final Set<String> previousInputs = <String>{};
/// The buildKey from the previous invocation of this build node.
///
/// See `buildKey` in the `Target` class for more information.
final String? previousBuildKey;
/// One or more reasons why a task was invalidated. /// One or more reasons why a task was invalidated.
/// ///
...@@ -1134,10 +1074,6 @@ class Node { ...@@ -1134,10 +1074,6 @@ class Node {
FileSystem fileSystem, FileSystem fileSystem,
Logger logger, Logger logger,
) { ) {
if (buildKey != previousBuildKey) {
_invalidate(InvalidatedReasonKind.buildKeyChanged);
_dirty = true;
}
final Set<String> currentOutputPaths = <String>{ final Set<String> currentOutputPaths = <String>{
for (final File file in outputs) file.path, for (final File file in outputs) file.path,
}; };
...@@ -1237,8 +1173,7 @@ class InvalidatedReason { ...@@ -1237,8 +1173,7 @@ class InvalidatedReason {
InvalidatedReasonKind.inputChanged => 'The following inputs have updated contents: ${data.join(',')}', InvalidatedReasonKind.inputChanged => 'The following inputs have updated contents: ${data.join(',')}',
InvalidatedReasonKind.outputChanged => 'The following outputs have updated contents: ${data.join(',')}', InvalidatedReasonKind.outputChanged => 'The following outputs have updated contents: ${data.join(',')}',
InvalidatedReasonKind.outputMissing => 'The following outputs were missing: ${data.join(',')}', InvalidatedReasonKind.outputMissing => 'The following outputs were missing: ${data.join(',')}',
InvalidatedReasonKind.outputSetChanged => 'The following outputs were removed from the output set: ${data.join(',')}', InvalidatedReasonKind.outputSetChanged => 'The following outputs were removed from the output set: ${data.join(',')}'
InvalidatedReasonKind.buildKeyChanged => 'The target build key changed.',
}; };
} }
} }
...@@ -1260,7 +1195,4 @@ enum InvalidatedReasonKind { ...@@ -1260,7 +1195,4 @@ enum InvalidatedReasonKind {
/// The set of expected output files changed. /// The set of expected output files changed.
outputSetChanged, outputSetChanged,
/// The build key changed
buildKeyChanged,
} }
...@@ -3,7 +3,7 @@ ...@@ -3,7 +3,7 @@
// found in the LICENSE file. // found in the LICENSE file.
import '../base/file_system.dart'; import '../base/file_system.dart';
import '../web/compiler_config.dart'; import '../web/compile.dart';
import './build_system.dart'; import './build_system.dart';
/// Commonly used build [Target]s. /// Commonly used build [Target]s.
...@@ -14,7 +14,11 @@ abstract class BuildTargets { ...@@ -14,7 +14,11 @@ abstract class BuildTargets {
Target get releaseCopyFlutterBundle; Target get releaseCopyFlutterBundle;
Target get generateLocalizationsTarget; Target get generateLocalizationsTarget;
Target get dartPluginRegistrantTarget; Target get dartPluginRegistrantTarget;
Target webServiceWorker(FileSystem fileSystem, List<WebCompilerConfig> compileConfigs); Target webServiceWorker(
FileSystem fileSystem, {
required WebRendererMode webRenderer,
required bool isWasm
});
} }
/// BuildTargets that return NoOpTarget for every action. /// BuildTargets that return NoOpTarget for every action.
...@@ -34,7 +38,11 @@ class NoOpBuildTargets extends BuildTargets { ...@@ -34,7 +38,11 @@ class NoOpBuildTargets extends BuildTargets {
Target get dartPluginRegistrantTarget => const _NoOpTarget(); Target get dartPluginRegistrantTarget => const _NoOpTarget();
@override @override
Target webServiceWorker(FileSystem fileSystem, List<WebCompilerConfig> compileConfigs) => const _NoOpTarget(); Target webServiceWorker(
FileSystem fileSystem, {
required WebRendererMode webRenderer,
required bool isWasm,
}) => const _NoOpTarget();
} }
/// A [Target] that does nothing. /// A [Target] that does nothing.
......
...@@ -138,50 +138,24 @@ class BuildWebCommand extends BuildSubCommand { ...@@ -138,50 +138,24 @@ class BuildWebCommand extends BuildSubCommand {
throwToolExit('"build web" is not currently supported. To enable, run "flutter config --enable-web".'); throwToolExit('"build web" is not currently supported. To enable, run "flutter config --enable-web".');
} }
final List<WebCompilerConfig> compilerConfigs; final WebCompilerConfig compilerConfig;
if (boolArg('wasm')) { if (boolArg('wasm')) {
if (!featureFlags.isFlutterWebWasmEnabled) { if (!featureFlags.isFlutterWebWasmEnabled) {
throwToolExit('Compiling to WebAssembly (wasm) is only available on the master channel.'); throwToolExit('Compiling to WebAssembly (wasm) is only available on the master channel.');
} }
if (stringArg(FlutterOptions.kWebRendererFlag) != argParser.defaultFor(FlutterOptions.kWebRendererFlag)) { compilerConfig = WasmCompilerConfig(
throwToolExit('"--${FlutterOptions.kWebRendererFlag}" cannot be combined with "--${FlutterOptions.kWebWasmFlag}"'); omitTypeChecks: boolArg('omit-type-checks'),
} wasmOpt: WasmOptLevel.values.byName(stringArg('wasm-opt')!),
globals.logger.printBox(
title: 'Experimental feature',
'''
WebAssembly compilation is experimental.
$kWasmMoreInfo''',
); );
compilerConfigs = <WebCompilerConfig>[
WasmCompilerConfig(
omitTypeChecks: boolArg('omit-type-checks'),
wasmOpt: WasmOptLevel.values.byName(stringArg('wasm-opt')!),
renderer: WebRendererMode.skwasm,
),
JsCompilerConfig(
csp: boolArg('csp'),
optimizationLevel: stringArg('dart2js-optimization') ?? JsCompilerConfig.kDart2jsDefaultOptimizationLevel,
dumpInfo: boolArg('dump-info'),
nativeNullAssertions: boolArg('native-null-assertions'),
noFrequencyBasedMinification: boolArg('no-frequency-based-minification'),
sourceMaps: boolArg('source-maps'),
renderer: WebRendererMode.canvaskit,
)];
} else { } else {
WebRendererMode webRenderer = WebRendererMode.auto; compilerConfig = JsCompilerConfig(
if (argParser.options.containsKey(FlutterOptions.kWebRendererFlag)) {
webRenderer = WebRendererMode.values.byName(stringArg(FlutterOptions.kWebRendererFlag)!);
}
compilerConfigs = <WebCompilerConfig>[JsCompilerConfig(
csp: boolArg('csp'), csp: boolArg('csp'),
optimizationLevel: stringArg('dart2js-optimization') ?? JsCompilerConfig.kDart2jsDefaultOptimizationLevel, optimizationLevel: stringArg('dart2js-optimization') ?? JsCompilerConfig.kDart2jsDefaultOptimizationLevel,
dumpInfo: boolArg('dump-info'), dumpInfo: boolArg('dump-info'),
nativeNullAssertions: boolArg('native-null-assertions'), nativeNullAssertions: boolArg('native-null-assertions'),
noFrequencyBasedMinification: boolArg('no-frequency-based-minification'), noFrequencyBasedMinification: boolArg('no-frequency-based-minification'),
sourceMaps: boolArg('source-maps'), sourceMaps: boolArg('source-maps'),
renderer: webRenderer, );
)];
} }
final FlutterProject flutterProject = FlutterProject.current(); final FlutterProject flutterProject = FlutterProject.current();
...@@ -231,7 +205,7 @@ class BuildWebCommand extends BuildSubCommand { ...@@ -231,7 +205,7 @@ class BuildWebCommand extends BuildSubCommand {
target, target,
buildInfo, buildInfo,
ServiceWorkerStrategy.fromCliName(stringArg('pwa-strategy')), ServiceWorkerStrategy.fromCliName(stringArg('pwa-strategy')),
compilerConfigs: compilerConfigs, compilerConfig: compilerConfig,
baseHref: baseHref, baseHref: baseHref,
outputDirectoryPath: outputDirectoryPath, outputDirectoryPath: outputDirectoryPath,
); );
......
...@@ -29,7 +29,6 @@ import '../runner/flutter_command.dart'; ...@@ -29,7 +29,6 @@ import '../runner/flutter_command.dart';
import '../runner/flutter_command_runner.dart'; import '../runner/flutter_command_runner.dart';
import '../tracing.dart'; import '../tracing.dart';
import '../vmservice.dart'; import '../vmservice.dart';
import '../web/compile.dart';
import '../web/web_runner.dart'; import '../web/web_runner.dart';
import 'daemon.dart'; import 'daemon.dart';
...@@ -242,10 +241,6 @@ abstract class RunCommandBase extends FlutterCommand with DeviceBasedDevelopment ...@@ -242,10 +241,6 @@ abstract class RunCommandBase extends FlutterCommand with DeviceBasedDevelopment
final Map<String, String> webHeaders = featureFlags.isWebEnabled final Map<String, String> webHeaders = featureFlags.isWebEnabled
? extractWebHeaders() ? extractWebHeaders()
: const <String, String>{}; : const <String, String>{};
final String? webRendererString = stringArg('web-renderer');
final WebRendererMode webRenderer = (webRendererString != null)
? WebRendererMode.values.byName(webRendererString)
: WebRendererMode.auto;
if (buildInfo.mode.isRelease) { if (buildInfo.mode.isRelease) {
return DebuggingOptions.disabled( return DebuggingOptions.disabled(
...@@ -263,7 +258,6 @@ abstract class RunCommandBase extends FlutterCommand with DeviceBasedDevelopment ...@@ -263,7 +258,6 @@ abstract class RunCommandBase extends FlutterCommand with DeviceBasedDevelopment
webBrowserDebugPort: webBrowserDebugPort, webBrowserDebugPort: webBrowserDebugPort,
webBrowserFlags: webBrowserFlags, webBrowserFlags: webBrowserFlags,
webHeaders: webHeaders, webHeaders: webHeaders,
webRenderer: webRenderer,
enableImpeller: enableImpeller, enableImpeller: enableImpeller,
enableVulkanValidation: enableVulkanValidation, enableVulkanValidation: enableVulkanValidation,
uninstallFirst: uninstallFirst, uninstallFirst: uninstallFirst,
...@@ -313,7 +307,6 @@ abstract class RunCommandBase extends FlutterCommand with DeviceBasedDevelopment ...@@ -313,7 +307,6 @@ abstract class RunCommandBase extends FlutterCommand with DeviceBasedDevelopment
webEnableExpressionEvaluation: featureFlags.isWebEnabled && boolArg('web-enable-expression-evaluation'), webEnableExpressionEvaluation: featureFlags.isWebEnabled && boolArg('web-enable-expression-evaluation'),
webLaunchUrl: featureFlags.isWebEnabled ? stringArg('web-launch-url') : null, webLaunchUrl: featureFlags.isWebEnabled ? stringArg('web-launch-url') : null,
webHeaders: webHeaders, webHeaders: webHeaders,
webRenderer: webRenderer,
vmserviceOutFile: stringArg('vmservice-out-file'), vmserviceOutFile: stringArg('vmservice-out-file'),
fastStart: argParser.options.containsKey('fast-start') fastStart: argParser.options.containsKey('fast-start')
&& boolArg('fast-start') && boolArg('fast-start')
......
...@@ -22,7 +22,6 @@ import '../test/runner.dart'; ...@@ -22,7 +22,6 @@ import '../test/runner.dart';
import '../test/test_time_recorder.dart'; import '../test/test_time_recorder.dart';
import '../test/test_wrapper.dart'; import '../test/test_wrapper.dart';
import '../test/watcher.dart'; import '../test/watcher.dart';
import '../web/compile.dart';
/// The name of the directory where Integration Tests are placed. /// The name of the directory where Integration Tests are placed.
/// ///
...@@ -358,10 +357,6 @@ class TestCommand extends FlutterCommand with DeviceBasedDevelopmentArtifacts { ...@@ -358,10 +357,6 @@ class TestCommand extends FlutterCommand with DeviceBasedDevelopmentArtifacts {
); );
} }
final String? webRendererString = stringArg('web-renderer');
final WebRendererMode webRenderer = (webRendererString != null)
? WebRendererMode.values.byName(webRendererString)
: WebRendererMode.auto;
final DebuggingOptions debuggingOptions = DebuggingOptions.enabled( final DebuggingOptions debuggingOptions = DebuggingOptions.enabled(
buildInfo, buildInfo,
startPaused: startPaused, startPaused: startPaused,
...@@ -374,7 +369,6 @@ class TestCommand extends FlutterCommand with DeviceBasedDevelopmentArtifacts { ...@@ -374,7 +369,6 @@ class TestCommand extends FlutterCommand with DeviceBasedDevelopmentArtifacts {
usingCISystem: usingCISystem, usingCISystem: usingCISystem,
enableImpeller: ImpellerStatus.fromBool(argResults!['enable-impeller'] as bool?), enableImpeller: ImpellerStatus.fromBool(argResults!['enable-impeller'] as bool?),
debugLogsDirectoryPath: debugLogsDirectoryPath, debugLogsDirectoryPath: debugLogsDirectoryPath,
webRenderer: webRenderer,
); );
String? testAssetDirectory; String? testAssetDirectory;
......
...@@ -18,7 +18,6 @@ import 'devfs.dart'; ...@@ -18,7 +18,6 @@ import 'devfs.dart';
import 'device_port_forwarder.dart'; import 'device_port_forwarder.dart';
import 'project.dart'; import 'project.dart';
import 'vmservice.dart'; import 'vmservice.dart';
import 'web/compile.dart';
DeviceManager? get deviceManager => context.get<DeviceManager>(); DeviceManager? get deviceManager => context.get<DeviceManager>();
...@@ -953,7 +952,6 @@ class DebuggingOptions { ...@@ -953,7 +952,6 @@ class DebuggingOptions {
this.webEnableExpressionEvaluation = false, this.webEnableExpressionEvaluation = false,
this.webHeaders = const <String, String>{}, this.webHeaders = const <String, String>{},
this.webLaunchUrl, this.webLaunchUrl,
this.webRenderer = WebRendererMode.auto,
this.vmserviceOutFile, this.vmserviceOutFile,
this.fastStart = false, this.fastStart = false,
this.nullAssertions = false, this.nullAssertions = false,
...@@ -983,7 +981,6 @@ class DebuggingOptions { ...@@ -983,7 +981,6 @@ class DebuggingOptions {
this.webBrowserFlags = const <String>[], this.webBrowserFlags = const <String>[],
this.webLaunchUrl, this.webLaunchUrl,
this.webHeaders = const <String, String>{}, this.webHeaders = const <String, String>{},
this.webRenderer = WebRendererMode.auto,
this.cacheSkSL = false, this.cacheSkSL = false,
this.traceAllowlist, this.traceAllowlist,
this.enableImpeller = ImpellerStatus.platformDefault, this.enableImpeller = ImpellerStatus.platformDefault,
...@@ -1063,7 +1060,6 @@ class DebuggingOptions { ...@@ -1063,7 +1060,6 @@ class DebuggingOptions {
required this.webEnableExpressionEvaluation, required this.webEnableExpressionEvaluation,
required this.webHeaders, required this.webHeaders,
required this.webLaunchUrl, required this.webLaunchUrl,
required this.webRenderer,
required this.vmserviceOutFile, required this.vmserviceOutFile,
required this.fastStart, required this.fastStart,
required this.nullAssertions, required this.nullAssertions,
...@@ -1148,9 +1144,6 @@ class DebuggingOptions { ...@@ -1148,9 +1144,6 @@ class DebuggingOptions {
/// Allow developers to add custom headers to web server /// Allow developers to add custom headers to web server
final Map<String, String> webHeaders; final Map<String, String> webHeaders;
/// Which web renderer to use for the debugging session
final WebRendererMode webRenderer;
/// A file where the VM Service URL should be written after the application is started. /// A file where the VM Service URL should be written after the application is started.
final String? vmserviceOutFile; final String? vmserviceOutFile;
final bool fastStart; final bool fastStart;
...@@ -1259,7 +1252,6 @@ class DebuggingOptions { ...@@ -1259,7 +1252,6 @@ class DebuggingOptions {
'webEnableExpressionEvaluation': webEnableExpressionEvaluation, 'webEnableExpressionEvaluation': webEnableExpressionEvaluation,
'webLaunchUrl': webLaunchUrl, 'webLaunchUrl': webLaunchUrl,
'webHeaders': webHeaders, 'webHeaders': webHeaders,
'webRenderer': webRenderer.name,
'vmserviceOutFile': vmserviceOutFile, 'vmserviceOutFile': vmserviceOutFile,
'fastStart': fastStart, 'fastStart': fastStart,
'nullAssertions': nullAssertions, 'nullAssertions': nullAssertions,
...@@ -1315,7 +1307,6 @@ class DebuggingOptions { ...@@ -1315,7 +1307,6 @@ class DebuggingOptions {
webEnableExpressionEvaluation: json['webEnableExpressionEvaluation']! as bool, webEnableExpressionEvaluation: json['webEnableExpressionEvaluation']! as bool,
webHeaders: (json['webHeaders']! as Map<dynamic, dynamic>).cast<String, String>(), webHeaders: (json['webHeaders']! as Map<dynamic, dynamic>).cast<String, String>(),
webLaunchUrl: json['webLaunchUrl'] as String?, webLaunchUrl: json['webLaunchUrl'] as String?,
webRenderer: WebRendererMode.values.byName(json['webRenderer']! as String),
vmserviceOutFile: json['vmserviceOutFile'] as String?, vmserviceOutFile: json['vmserviceOutFile'] as String?,
fastStart: json['fastStart']! as bool, fastStart: json['fastStart']! as bool,
nullAssertions: json['nullAssertions']! as bool, nullAssertions: json['nullAssertions']! as bool,
......
...@@ -78,14 +78,12 @@ class WebDriverService extends DriverService { ...@@ -78,14 +78,12 @@ class WebDriverService extends DriverService {
buildInfo, buildInfo,
port: debuggingOptions.port, port: debuggingOptions.port,
hostname: debuggingOptions.hostname, hostname: debuggingOptions.hostname,
webRenderer: debuggingOptions.webRenderer,
) )
: DebuggingOptions.enabled( : DebuggingOptions.enabled(
buildInfo, buildInfo,
port: debuggingOptions.port, port: debuggingOptions.port,
hostname: debuggingOptions.hostname, hostname: debuggingOptions.hostname,
disablePortPublication: debuggingOptions.disablePortPublication, disablePortPublication: debuggingOptions.disablePortPublication,
webRenderer: debuggingOptions.webRenderer,
), ),
stayResident: true, stayResident: true,
flutterProject: FlutterProject.current(), flutterProject: FlutterProject.current(),
......
...@@ -62,7 +62,6 @@ class IndexHtml { ...@@ -62,7 +62,6 @@ class IndexHtml {
void applySubstitutions({ void applySubstitutions({
required String baseHref, required String baseHref,
required String? serviceWorkerVersion, required String? serviceWorkerVersion,
String? buildConfig,
}) { }) {
if (_content.contains(kBaseHrefPlaceholder)) { if (_content.contains(kBaseHrefPlaceholder)) {
_content = _content.replaceAll(kBaseHrefPlaceholder, baseHref); _content = _content.replaceAll(kBaseHrefPlaceholder, baseHref);
...@@ -82,12 +81,6 @@ class IndexHtml { ...@@ -82,12 +81,6 @@ class IndexHtml {
"navigator.serviceWorker.register('flutter_service_worker.js?v=$serviceWorkerVersion')", "navigator.serviceWorker.register('flutter_service_worker.js?v=$serviceWorkerVersion')",
); );
} }
if (buildConfig != null) {
_content = _content.replaceFirst(
'{{flutter_build_config}}',
buildConfig,
);
}
} }
} }
......
...@@ -9,7 +9,7 @@ import '../build_system/targets/common.dart'; ...@@ -9,7 +9,7 @@ import '../build_system/targets/common.dart';
import '../build_system/targets/dart_plugin_registrant.dart'; import '../build_system/targets/dart_plugin_registrant.dart';
import '../build_system/targets/localizations.dart'; import '../build_system/targets/localizations.dart';
import '../build_system/targets/web.dart'; import '../build_system/targets/web.dart';
import '../web/compiler_config.dart'; import '../web/compile.dart';
class BuildTargetsImpl extends BuildTargets { class BuildTargetsImpl extends BuildTargets {
const BuildTargetsImpl(); const BuildTargetsImpl();
...@@ -27,6 +27,9 @@ class BuildTargetsImpl extends BuildTargets { ...@@ -27,6 +27,9 @@ class BuildTargetsImpl extends BuildTargets {
Target get dartPluginRegistrantTarget => const DartPluginRegistrantTarget(); Target get dartPluginRegistrantTarget => const DartPluginRegistrantTarget();
@override @override
Target webServiceWorker(FileSystem fileSystem, List<WebCompilerConfig> compileConfigs) => Target webServiceWorker(
WebServiceWorker(fileSystem, compileConfigs); FileSystem fileSystem, {
required WebRendererMode webRenderer,
required bool isWasm,
}) => WebServiceWorker(fileSystem, webRenderer, isWasm: isWasm);
} }
...@@ -117,9 +117,8 @@ class WebAssetServer implements AssetReader { ...@@ -117,9 +117,8 @@ class WebAssetServer implements AssetReader {
this.internetAddress, this.internetAddress,
this._modules, this._modules,
this._digests, this._digests,
this._nullSafetyMode, { this._nullSafetyMode,
required this.webRenderer, ) : basePath = _getIndexHtml().getBaseHref();
}) : basePath = _getIndexHtml().getBaseHref();
// Fallback to "application/octet-stream" on null which // Fallback to "application/octet-stream" on null which
// makes no claims as to the structure of the data. // makes no claims as to the structure of the data.
...@@ -178,7 +177,6 @@ class WebAssetServer implements AssetReader { ...@@ -178,7 +177,6 @@ class WebAssetServer implements AssetReader {
ExpressionCompiler? expressionCompiler, ExpressionCompiler? expressionCompiler,
Map<String, String> extraHeaders, Map<String, String> extraHeaders,
NullSafetyMode nullSafetyMode, { NullSafetyMode nullSafetyMode, {
required WebRendererMode webRenderer,
bool testMode = false, bool testMode = false,
DwdsLauncher dwdsLauncher = Dwds.start, DwdsLauncher dwdsLauncher = Dwds.start,
}) async { }) async {
...@@ -227,7 +225,6 @@ class WebAssetServer implements AssetReader { ...@@ -227,7 +225,6 @@ class WebAssetServer implements AssetReader {
modules, modules,
digests, digests,
nullSafetyMode, nullSafetyMode,
webRenderer: webRenderer,
); );
if (testMode) { if (testMode) {
return server; return server;
...@@ -507,29 +504,16 @@ class WebAssetServer implements AssetReader { ...@@ -507,29 +504,16 @@ class WebAssetServer implements AssetReader {
} }
/// Determines what rendering backed to use. /// Determines what rendering backed to use.
final WebRendererMode webRenderer; WebRendererMode webRenderer = WebRendererMode.html;
shelf.Response _serveIndex() { shelf.Response _serveIndex() {
final IndexHtml indexHtml = _getIndexHtml(); final IndexHtml indexHtml = _getIndexHtml();
final Map<String, dynamic> buildConfig = <String, dynamic>{
'engineRevision': globals.flutterVersion.engineRevision,
'builds': <dynamic>[
<String, dynamic>{
'compileTarget': 'dartdevc',
'renderer': webRenderer.name,
'mainJsPath': 'main.dart.js',
},
],
};
final String buildConfigString = '_flutter.buildConfig = ${jsonEncode(buildConfig)};';
indexHtml.applySubstitutions( indexHtml.applySubstitutions(
// Currently, we don't support --base-href for the "run" command. // Currently, we don't support --base-href for the "run" command.
baseHref: '/', baseHref: '/',
serviceWorkerVersion: null, serviceWorkerVersion: null,
buildConfig: buildConfigString,
); );
final Map<String, String> headers = <String, String>{ final Map<String, String> headers = <String, String>{
...@@ -679,7 +663,6 @@ class WebDevFS implements DevFS { ...@@ -679,7 +663,6 @@ class WebDevFS implements DevFS {
required this.nullAssertions, required this.nullAssertions,
required this.nativeNullAssertions, required this.nativeNullAssertions,
required this.nullSafetyMode, required this.nullSafetyMode,
required this.webRenderer,
this.testMode = false, this.testMode = false,
}) : _port = port; }) : _port = port;
...@@ -703,7 +686,6 @@ class WebDevFS implements DevFS { ...@@ -703,7 +686,6 @@ class WebDevFS implements DevFS {
final NullSafetyMode nullSafetyMode; final NullSafetyMode nullSafetyMode;
final String? tlsCertPath; final String? tlsCertPath;
final String? tlsCertKeyPath; final String? tlsCertKeyPath;
final WebRendererMode webRenderer;
late WebAssetServer webAssetServer; late WebAssetServer webAssetServer;
...@@ -803,11 +785,15 @@ class WebDevFS implements DevFS { ...@@ -803,11 +785,15 @@ class WebDevFS implements DevFS {
expressionCompiler, expressionCompiler,
extraHeaders, extraHeaders,
nullSafetyMode, nullSafetyMode,
webRenderer: webRenderer,
testMode: testMode, testMode: testMode,
); );
final int selectedPort = webAssetServer.selectedPort; final int selectedPort = webAssetServer.selectedPort;
if (buildInfo.dartDefines.contains('FLUTTER_WEB_AUTO_DETECT=true')) {
webAssetServer.webRenderer = WebRendererMode.auto;
} else if (buildInfo.dartDefines.contains('FLUTTER_WEB_USE_SKIA=true')) {
webAssetServer.webRenderer = WebRendererMode.canvaskit;
}
String url = '$hostname:$selectedPort'; String url = '$hostname:$selectedPort';
if (hostname == 'any') { if (hostname == 'any') {
url ='localhost:$selectedPort'; url ='localhost:$selectedPort';
......
...@@ -309,7 +309,6 @@ Please provide a valid TCP port (an integer between 0 and 65535, inclusive). ...@@ -309,7 +309,6 @@ Please provide a valid TCP port (an integer between 0 and 65535, inclusive).
nullAssertions: debuggingOptions.nullAssertions, nullAssertions: debuggingOptions.nullAssertions,
nullSafetyMode: debuggingOptions.buildInfo.nullSafetyMode, nullSafetyMode: debuggingOptions.buildInfo.nullSafetyMode,
nativeNullAssertions: debuggingOptions.nativeNullAssertions, nativeNullAssertions: debuggingOptions.nativeNullAssertions,
webRenderer: debuggingOptions.webRenderer,
); );
Uri url = await device!.devFS!.create(); Uri url = await device!.devFS!.create();
if (debuggingOptions.tlsCertKeyPath != null && debuggingOptions.tlsCertPath != null) { if (debuggingOptions.tlsCertKeyPath != null && debuggingOptions.tlsCertPath != null) {
...@@ -340,12 +339,7 @@ Please provide a valid TCP port (an integer between 0 and 65535, inclusive). ...@@ -340,12 +339,7 @@ Please provide a valid TCP port (an integer between 0 and 65535, inclusive).
target, target,
debuggingOptions.buildInfo, debuggingOptions.buildInfo,
ServiceWorkerStrategy.none, ServiceWorkerStrategy.none,
compilerConfigs: <WebCompilerConfig>[ compilerConfig: JsCompilerConfig.run(nativeNullAssertions: debuggingOptions.nativeNullAssertions)
JsCompilerConfig.run(
nativeNullAssertions: debuggingOptions.nativeNullAssertions,
renderer: debuggingOptions.webRenderer,
)
]
); );
} }
await device!.device!.startApp( await device!.device!.startApp(
...@@ -424,12 +418,7 @@ Please provide a valid TCP port (an integer between 0 and 65535, inclusive). ...@@ -424,12 +418,7 @@ Please provide a valid TCP port (an integer between 0 and 65535, inclusive).
target, target,
debuggingOptions.buildInfo, debuggingOptions.buildInfo,
ServiceWorkerStrategy.none, ServiceWorkerStrategy.none,
compilerConfigs: <WebCompilerConfig>[ compilerConfig: JsCompilerConfig.run(nativeNullAssertions: debuggingOptions.nativeNullAssertions),
JsCompilerConfig.run(
nativeNullAssertions: debuggingOptions.nativeNullAssertions,
renderer: debuggingOptions.webRenderer,
)
],
); );
} on ToolExit { } on ToolExit {
return OperationResult(1, 'Failed to recompile application.'); return OperationResult(1, 'Failed to recompile application.');
......
...@@ -135,7 +135,7 @@ class FlutterDevice { ...@@ -135,7 +135,7 @@ class FlutterDevice {
} }
final String platformDillPath = globals.fs.path.join( final String platformDillPath = globals.fs.path.join(
globals.artifacts!.getHostArtifact(HostArtifact.webPlatformKernelFolder).path, getWebPlatformBinariesDirectory(globals.artifacts!, buildInfo.webRenderer).path,
platformDillName, platformDillName,
); );
......
...@@ -1263,7 +1263,13 @@ abstract class FlutterCommand extends Command<void> { ...@@ -1263,7 +1263,13 @@ abstract class FlutterCommand extends Command<void> {
: null; : null;
final Map<String, Object?> defineConfigJsonMap = extractDartDefineConfigJsonMap(); final Map<String, Object?> defineConfigJsonMap = extractDartDefineConfigJsonMap();
final List<String> dartDefines = extractDartDefines(defineConfigJsonMap: defineConfigJsonMap); List<String> dartDefines = extractDartDefines(defineConfigJsonMap: defineConfigJsonMap);
WebRendererMode webRenderer = WebRendererMode.auto;
if (argParser.options.containsKey(FlutterOptions.kWebRendererFlag)) {
webRenderer = WebRendererMode.values.byName(stringArg(FlutterOptions.kWebRendererFlag)!);
dartDefines = updateDartDefines(dartDefines, webRenderer);
}
if (argParser.options.containsKey(FlutterOptions.kWebResourcesCdnFlag)) { if (argParser.options.containsKey(FlutterOptions.kWebResourcesCdnFlag)) {
final bool hasLocalWebSdk = argParser.options.containsKey('local-web-sdk') && stringArg('local-web-sdk') != null; final bool hasLocalWebSdk = argParser.options.containsKey('local-web-sdk') && stringArg('local-web-sdk') != null;
...@@ -1311,6 +1317,7 @@ abstract class FlutterCommand extends Command<void> { ...@@ -1311,6 +1317,7 @@ abstract class FlutterCommand extends Command<void> {
dartDefines: dartDefines, dartDefines: dartDefines,
bundleSkSLPath: bundleSkSLPath, bundleSkSLPath: bundleSkSLPath,
dartExperiments: experiments, dartExperiments: experiments,
webRenderer: webRenderer,
performanceMeasurementFile: performanceMeasurementFile, performanceMeasurementFile: performanceMeasurementFile,
packagesPath: packagesPath ?? globals.fs.path.absolute('.dart_tool', 'package_config.json'), packagesPath: packagesPath ?? globals.fs.path.absolute('.dart_tool', 'package_config.json'),
nullSafetyMode: nullSafetyMode, nullSafetyMode: nullSafetyMode,
...@@ -1548,6 +1555,19 @@ abstract class FlutterCommand extends Command<void> { ...@@ -1548,6 +1555,19 @@ abstract class FlutterCommand extends Command<void> {
return jsonEncode(propertyMap); return jsonEncode(propertyMap);
} }
/// Updates dart-defines based on [webRenderer].
@visibleForTesting
static List<String> updateDartDefines(List<String> dartDefines, WebRendererMode webRenderer) {
final Set<String> dartDefinesSet = dartDefines.toSet();
if (!dartDefines.any((String d) => d.startsWith('FLUTTER_WEB_AUTO_DETECT='))
&& dartDefines.any((String d) => d.startsWith('FLUTTER_WEB_USE_SKIA='))) {
dartDefinesSet.removeWhere((String d) => d.startsWith('FLUTTER_WEB_USE_SKIA='));
}
dartDefinesSet.addAll(webRenderer.dartDefines);
return dartDefinesSet.toList();
}
Map<String, String> extractWebHeaders() { Map<String, String> extractWebHeaders() {
final Map<String, String> webHeaders = <String, String>{}; final Map<String, String> webHeaders = <String, String>{};
......
...@@ -69,7 +69,7 @@ class WebTestCompiler { ...@@ -69,7 +69,7 @@ class WebTestCompiler {
} }
final String platformDillPath = _fileSystem.path.join( final String platformDillPath = _fileSystem.path.join(
_artifacts.getHostArtifact(HostArtifact.webPlatformKernelFolder).path, getWebPlatformBinariesDirectory(_artifacts, buildInfo.webRenderer).path,
platformDillName platformDillName
); );
......
...@@ -24,6 +24,7 @@ import '../version.dart'; ...@@ -24,6 +24,7 @@ import '../version.dart';
import 'compiler_config.dart'; import 'compiler_config.dart';
import 'file_generators/flutter_service_worker_js.dart'; import 'file_generators/flutter_service_worker_js.dart';
import 'migrations/scrub_generated_plugin_registrant.dart'; import 'migrations/scrub_generated_plugin_registrant.dart';
import 'web_constants.dart';
export 'compiler_config.dart'; export 'compiler_config.dart';
...@@ -66,14 +67,23 @@ class WebBuilder { ...@@ -66,14 +67,23 @@ class WebBuilder {
String target, String target,
BuildInfo buildInfo, BuildInfo buildInfo,
ServiceWorkerStrategy serviceWorkerStrategy, { ServiceWorkerStrategy serviceWorkerStrategy, {
required List<WebCompilerConfig> compilerConfigs, required WebCompilerConfig compilerConfig,
String? baseHref, String? baseHref,
String? outputDirectoryPath, String? outputDirectoryPath,
}) async { }) async {
if (compilerConfig.isWasm) {
globals.logger.printBox(
title: 'Experimental feature',
'''
WebAssembly compilation is experimental.
$kWasmMoreInfo''',
);
}
final bool hasWebPlugins = final bool hasWebPlugins =
(await findPlugins(flutterProject)).any((Plugin p) => p.platforms.containsKey(WebPlugin.kConfigKey)); (await findPlugins(flutterProject)).any((Plugin p) => p.platforms.containsKey(WebPlugin.kConfigKey));
final Directory outputDirectory = outputDirectoryPath == null final Directory outputDirectory = outputDirectoryPath == null
? _fileSystem.directory(getWebBuildDirectory()) ? _fileSystem.directory(getWebBuildDirectory(compilerConfig.isWasm))
: _fileSystem.directory(outputDirectoryPath); : _fileSystem.directory(outputDirectoryPath);
outputDirectory.createSync(recursive: true); outputDirectory.createSync(recursive: true);
...@@ -89,7 +99,11 @@ class WebBuilder { ...@@ -89,7 +99,11 @@ class WebBuilder {
final Stopwatch sw = Stopwatch()..start(); final Stopwatch sw = Stopwatch()..start();
try { try {
final BuildResult result = await _buildSystem.build( final BuildResult result = await _buildSystem.build(
globals.buildTargets.webServiceWorker(_fileSystem, compilerConfigs), globals.buildTargets.webServiceWorker(
_fileSystem,
webRenderer: buildInfo.webRenderer,
isWasm: compilerConfig.isWasm,
),
Environment( Environment(
projectDir: _fileSystem.currentDirectory, projectDir: _fileSystem.currentDirectory,
outputDir: outputDirectory, outputDir: outputDirectory,
...@@ -99,6 +113,7 @@ class WebBuilder { ...@@ -99,6 +113,7 @@ class WebBuilder {
kHasWebPlugins: hasWebPlugins.toString(), kHasWebPlugins: hasWebPlugins.toString(),
if (baseHref != null) kBaseHref: baseHref, if (baseHref != null) kBaseHref: baseHref,
kServiceWorkerStrategy: serviceWorkerStrategy.cliName, kServiceWorkerStrategy: serviceWorkerStrategy.cliName,
...compilerConfig.toBuildSystemEnvironment(),
...buildInfo.toBuildSystemEnvironment(), ...buildInfo.toBuildSystemEnvironment(),
}, },
artifacts: globals.artifacts!, artifacts: globals.artifacts!,
...@@ -131,7 +146,8 @@ class WebBuilder { ...@@ -131,7 +146,8 @@ class WebBuilder {
} }
final String buildSettingsString = _buildEventAnalyticsSettings( final String buildSettingsString = _buildEventAnalyticsSettings(
configs: compilerConfigs, config: compilerConfig,
buildInfo: buildInfo,
); );
BuildEvent( BuildEvent(
...@@ -147,15 +163,14 @@ class WebBuilder { ...@@ -147,15 +163,14 @@ class WebBuilder {
)); ));
final Duration elapsedDuration = sw.elapsed; final Duration elapsedDuration = sw.elapsed;
final String variableName = compilerConfigs.length > 1 ? 'dual-compile' : 'dart2js';
_flutterUsage.sendTiming( _flutterUsage.sendTiming(
'build', 'build',
variableName, compilerConfig.isWasm ? 'dart2wasm' : 'dart2js',
elapsedDuration, elapsedDuration,
); );
_analytics.send(Event.timing( _analytics.send(Event.timing(
workflow: 'build', workflow: 'build',
variableName: variableName, variableName: compilerConfig.isWasm ? 'dart2wasm' : 'dart2js',
elapsedMilliseconds: elapsedDuration.inMilliseconds, elapsedMilliseconds: elapsedDuration.inMilliseconds,
)); ));
} }
...@@ -242,18 +257,13 @@ const Map<WebRendererMode, Map<NullSafetyMode, HostArtifact>> kDartSdkJsMapArtif ...@@ -242,18 +257,13 @@ const Map<WebRendererMode, Map<NullSafetyMode, HostArtifact>> kDartSdkJsMapArtif
}; };
String _buildEventAnalyticsSettings({ String _buildEventAnalyticsSettings({
required List<WebCompilerConfig> configs, required WebCompilerConfig config,
required BuildInfo buildInfo,
}) { }) {
final Map<String, Object> values = <String, Object>{}; final Map<String, Object> values = <String, Object>{
final List<String> renderers = <String>[]; ...config.buildEventAnalyticsValues,
final List<String> targets = <String>[]; 'web-renderer': buildInfo.webRenderer.cliName,
for (final WebCompilerConfig config in configs) { };
values.addAll(config.buildEventAnalyticsValues);
renderers.add(config.renderer.name);
targets.add(config.compileTarget.name);
}
values['web-renderer'] = renderers.join(',');
values['web-target'] = targets.join(',');
final List<String> sortedList = values.entries final List<String> sortedList = values.entries
.map((MapEntry<String, Object> e) => '${e.key}: ${e.value};') .map((MapEntry<String, Object> e) => '${e.key}: ${e.value};')
......
...@@ -3,48 +3,58 @@ ...@@ -3,48 +3,58 @@
// found in the LICENSE file. // found in the LICENSE file.
import '../base/utils.dart'; import '../base/utils.dart';
import '../convert.dart';
import 'compile.dart';
enum CompileTarget { abstract class WebCompilerConfig {
js, const WebCompilerConfig();
wasm,
}
sealed class WebCompilerConfig {
const WebCompilerConfig({required this.renderer});
/// Returns which target this compiler outputs (js or wasm) /// Returns `true` if `this` represents configuration for the Wasm compiler.
CompileTarget get compileTarget; ///
final WebRendererMode renderer; /// Otherwise, `false`–represents the JavaScript compiler.
bool get isWasm;
String get buildKey; Map<String, String> toBuildSystemEnvironment();
Map<String, Object> get buildEventAnalyticsValues => <String, Object>{}; Map<String, Object> get buildEventAnalyticsValues => <String, Object>{
'wasm-compile': isWasm,
};
} }
/// Configuration for the Dart-to-Javascript compiler (dart2js). /// Configuration for the Dart-to-Javascript compiler (dart2js).
class JsCompilerConfig extends WebCompilerConfig { class JsCompilerConfig extends WebCompilerConfig {
const JsCompilerConfig({ const JsCompilerConfig({
this.csp = false, required this.csp,
this.dumpInfo = false, required this.dumpInfo,
this.nativeNullAssertions = false, required this.nativeNullAssertions,
this.optimizationLevel = kDart2jsDefaultOptimizationLevel, required this.optimizationLevel,
this.noFrequencyBasedMinification = false, required this.noFrequencyBasedMinification,
this.sourceMaps = true, required this.sourceMaps,
super.renderer = WebRendererMode.auto,
}); });
/// Instantiates [JsCompilerConfig] suitable for the `flutter run` command. /// Instantiates [JsCompilerConfig] suitable for the `flutter run` command.
const JsCompilerConfig.run({ const JsCompilerConfig.run({required bool nativeNullAssertions})
required bool nativeNullAssertions, : this(
required WebRendererMode renderer, csp: false,
}) : this( dumpInfo: false,
nativeNullAssertions: nativeNullAssertions, nativeNullAssertions: nativeNullAssertions,
noFrequencyBasedMinification: false,
optimizationLevel: kDart2jsDefaultOptimizationLevel, optimizationLevel: kDart2jsDefaultOptimizationLevel,
renderer: renderer, sourceMaps: true,
); );
/// Creates a new [JsCompilerConfig] from build system environment values.
///
/// Should correspond exactly with [toBuildSystemEnvironment].
factory JsCompilerConfig.fromBuildSystemEnvironment(
Map<String, String> defines) =>
JsCompilerConfig(
csp: defines[kCspMode] == 'true',
dumpInfo: defines[kDart2jsDumpInfo] == 'true',
nativeNullAssertions: defines[kNativeNullAssertions] == 'true',
optimizationLevel: defines[kDart2jsOptimization] ?? kDart2jsDefaultOptimizationLevel,
noFrequencyBasedMinification: defines[kDart2jsNoFrequencyBasedMinification] == 'true',
sourceMaps: defines[kSourceMapsEnabled] == 'true',
);
/// The default optimization level for dart2js. /// The default optimization level for dart2js.
/// ///
/// Maps to [kDart2jsOptimization]. /// Maps to [kDart2jsOptimization].
...@@ -92,7 +102,17 @@ class JsCompilerConfig extends WebCompilerConfig { ...@@ -92,7 +102,17 @@ class JsCompilerConfig extends WebCompilerConfig {
final bool sourceMaps; final bool sourceMaps;
@override @override
CompileTarget get compileTarget => CompileTarget.js; bool get isWasm => false;
@override
Map<String, String> toBuildSystemEnvironment() => <String, String>{
kCspMode: csp.toString(),
kDart2jsDumpInfo: dumpInfo.toString(),
kNativeNullAssertions: nativeNullAssertions.toString(),
kDart2jsNoFrequencyBasedMinification: noFrequencyBasedMinification.toString(),
kDart2jsOptimization: optimizationLevel,
kSourceMapsEnabled: sourceMaps.toString(),
};
/// Arguments to use in both phases: full JS compile and CFE-only. /// Arguments to use in both phases: full JS compile and CFE-only.
List<String> toSharedCommandOptions() => <String>[ List<String> toSharedCommandOptions() => <String>[
...@@ -110,29 +130,25 @@ class JsCompilerConfig extends WebCompilerConfig { ...@@ -110,29 +130,25 @@ class JsCompilerConfig extends WebCompilerConfig {
if (noFrequencyBasedMinification) '--no-frequency-based-minification', if (noFrequencyBasedMinification) '--no-frequency-based-minification',
if (csp) '--csp', if (csp) '--csp',
]; ];
@override
String get buildKey {
final Map<String, dynamic> settings = <String, dynamic>{
'csp': csp,
'dumpInfo': dumpInfo,
'nativeNullAssertions': nativeNullAssertions,
'noFrequencyBasedMinification': noFrequencyBasedMinification,
'optimizationLevel': optimizationLevel,
'sourceMaps': sourceMaps,
};
return jsonEncode(settings);
}
} }
/// Configuration for the Wasm compiler. /// Configuration for the Wasm compiler.
class WasmCompilerConfig extends WebCompilerConfig { class WasmCompilerConfig extends WebCompilerConfig {
const WasmCompilerConfig({ const WasmCompilerConfig({
this.omitTypeChecks = false, required this.omitTypeChecks,
this.wasmOpt = WasmOptLevel.defaultValue, required this.wasmOpt,
super.renderer = WebRendererMode.auto,
}); });
/// Creates a new [WasmCompilerConfig] from build system environment values.
///
/// Should correspond exactly with [toBuildSystemEnvironment].
factory WasmCompilerConfig.fromBuildSystemEnvironment(
Map<String, String> defines) =>
WasmCompilerConfig(
omitTypeChecks: defines[kOmitTypeChecks] == 'true',
wasmOpt: WasmOptLevel.values.byName(defines[kRunWasmOpt]!),
);
/// Build environment for [omitTypeChecks]. /// Build environment for [omitTypeChecks].
static const String kOmitTypeChecks = 'WasmOmitTypeChecks'; static const String kOmitTypeChecks = 'WasmOmitTypeChecks';
...@@ -146,31 +162,25 @@ class WasmCompilerConfig extends WebCompilerConfig { ...@@ -146,31 +162,25 @@ class WasmCompilerConfig extends WebCompilerConfig {
final WasmOptLevel wasmOpt; final WasmOptLevel wasmOpt;
@override @override
CompileTarget get compileTarget => CompileTarget.wasm; bool get isWasm => true;
bool get runWasmOpt => bool get runWasmOpt => wasmOpt == WasmOptLevel.full || wasmOpt == WasmOptLevel.debug;
wasmOpt == WasmOptLevel.full || wasmOpt == WasmOptLevel.debug;
@override
Map<String, String> toBuildSystemEnvironment() => <String, String>{
kOmitTypeChecks: omitTypeChecks.toString(),
kRunWasmOpt: wasmOpt.name,
};
List<String> toCommandOptions() => <String>[ List<String> toCommandOptions() => <String>[
if (omitTypeChecks) '--omit-type-checks', if (omitTypeChecks) '--omit-type-checks',
]; ];
@override @override
Map<String, Object> get buildEventAnalyticsValues => <String, Object>{ Map<String, Object> get buildEventAnalyticsValues => <String, Object>{
...super.buildEventAnalyticsValues, ...super.buildEventAnalyticsValues,
kOmitTypeChecks: omitTypeChecks.toString(), ...toBuildSystemEnvironment(),
kRunWasmOpt: wasmOpt.name, };
};
@override
String get buildKey {
final Map<String, dynamic> settings = <String, dynamic>{
'omitTypeChecks': omitTypeChecks,
'wasmOpt': wasmOpt.name,
};
return jsonEncode(settings);
}
} }
enum WasmOptLevel implements CliEnum { enum WasmOptLevel implements CliEnum {
...@@ -185,11 +195,8 @@ enum WasmOptLevel implements CliEnum { ...@@ -185,11 +195,8 @@ enum WasmOptLevel implements CliEnum {
@override @override
String get helpText => switch (this) { String get helpText => switch (this) {
WasmOptLevel.none => WasmOptLevel.none => 'wasm-opt is not run. Fastest build; bigger, slower output.',
'wasm-opt is not run. Fastest build; bigger, slower output.', WasmOptLevel.debug => 'Similar to `${WasmOptLevel.full.name}`, but member names are preserved. Debugging is easier, but size is a bit bigger.',
WasmOptLevel.debug => WasmOptLevel.full => 'wasm-opt is run. Build time is slower, but output is smaller and faster.',
'Similar to `${WasmOptLevel.full.name}`, but member names are preserved. Debugging is easier, but size is a bit bigger.', };
WasmOptLevel.full =>
'wasm-opt is run. Build time is slower, but output is smaller and faster.',
};
} }
...@@ -11,13 +11,11 @@ import 'package:flutter_tools/src/base/platform.dart'; ...@@ -11,13 +11,11 @@ import 'package:flutter_tools/src/base/platform.dart';
import 'package:flutter_tools/src/base/process.dart'; import 'package:flutter_tools/src/base/process.dart';
import 'package:flutter_tools/src/build_info.dart'; import 'package:flutter_tools/src/build_info.dart';
import 'package:flutter_tools/src/build_system/build_system.dart'; import 'package:flutter_tools/src/build_system/build_system.dart';
import 'package:flutter_tools/src/build_system/targets/web.dart';
import 'package:flutter_tools/src/cache.dart'; import 'package:flutter_tools/src/cache.dart';
import 'package:flutter_tools/src/commands/build.dart'; import 'package:flutter_tools/src/commands/build.dart';
import 'package:flutter_tools/src/commands/build_web.dart'; import 'package:flutter_tools/src/commands/build_web.dart';
import 'package:flutter_tools/src/features.dart'; import 'package:flutter_tools/src/features.dart';
import 'package:flutter_tools/src/runner/flutter_command.dart'; import 'package:flutter_tools/src/runner/flutter_command.dart';
import 'package:flutter_tools/src/web/compile.dart';
import '../../src/common.dart'; import '../../src/common.dart';
import '../../src/context.dart'; import '../../src/context.dart';
...@@ -149,9 +147,15 @@ void main() { ...@@ -149,9 +147,15 @@ void main() {
expect(environment.defines, <String, String>{ expect(environment.defines, <String, String>{
'TargetFile': 'lib/main.dart', 'TargetFile': 'lib/main.dart',
'HasWebPlugins': 'true', 'HasWebPlugins': 'true',
'cspMode': 'false',
'SourceMaps': 'false',
'NativeNullAssertions': 'true',
'ServiceWorkerStrategy': 'offline-first', 'ServiceWorkerStrategy': 'offline-first',
'Dart2jsDumpInfo': 'false',
'Dart2jsNoFrequencyBasedMinification': 'false',
'Dart2jsOptimization': 'O3',
'BuildMode': 'release', 'BuildMode': 'release',
'DartDefines': 'Zm9vPWE=', 'DartDefines': 'Zm9vPWE=,RkxVVFRFUl9XRUJfQVVUT19ERVRFQ1Q9dHJ1ZQ==',
'DartObfuscation': 'false', 'DartObfuscation': 'false',
'TrackWidgetCreation': 'false', 'TrackWidgetCreation': 'false',
'TreeShakeIcons': 'true', 'TreeShakeIcons': 'true',
...@@ -245,8 +249,15 @@ void main() { ...@@ -245,8 +249,15 @@ void main() {
expect(environment.defines, <String, String>{ expect(environment.defines, <String, String>{
'TargetFile': 'lib/main.dart', 'TargetFile': 'lib/main.dart',
'HasWebPlugins': 'true', 'HasWebPlugins': 'true',
'cspMode': 'false',
'SourceMaps': 'false',
'NativeNullAssertions': 'true',
'ServiceWorkerStrategy': 'offline-first', 'ServiceWorkerStrategy': 'offline-first',
'Dart2jsDumpInfo': 'false',
'Dart2jsNoFrequencyBasedMinification': 'false',
'Dart2jsOptimization': 'O4',
'BuildMode': 'release', 'BuildMode': 'release',
'DartDefines': 'RkxVVFRFUl9XRUJfQVVUT19ERVRFQ1Q9dHJ1ZQ==',
'DartObfuscation': 'false', 'DartObfuscation': 'false',
'TrackWidgetCreation': 'false', 'TrackWidgetCreation': 'false',
'TreeShakeIcons': 'true', 'TreeShakeIcons': 'true',
...@@ -277,17 +288,15 @@ void main() { ...@@ -277,17 +288,15 @@ void main() {
final CommandRunner<void> runner = createTestCommandRunner(buildCommand); final CommandRunner<void> runner = createTestCommandRunner(buildCommand);
setupFileSystemForEndToEndTest(fileSystem); setupFileSystemForEndToEndTest(fileSystem);
await runner.run(<String>['build', 'web', '--no-pub']); await runner.run(<String>['build', 'web', '--no-pub']);
final BuildInfo buildInfo =
await buildCommand.webCommand.getBuildInfo(forcedBuildMode: BuildMode.debug);
expect(buildInfo.dartDefines, contains('FLUTTER_WEB_AUTO_DETECT=true'));
}, overrides: <Type, Generator>{ }, overrides: <Type, Generator>{
Platform: () => fakePlatform, Platform: () => fakePlatform,
FileSystem: () => fileSystem, FileSystem: () => fileSystem,
FeatureFlags: () => TestFeatureFlags(isWebEnabled: true), FeatureFlags: () => TestFeatureFlags(isWebEnabled: true),
ProcessManager: () => processManager, ProcessManager: () => processManager,
BuildSystem: () => TestBuildSystem.all(BuildResult(success: true), (Target target, Environment environment) { BuildSystem: () => TestBuildSystem.all(BuildResult(success: true)),
expect(target, isA<WebServiceWorker>());
final List<WebCompilerConfig> configs = (target as WebServiceWorker).compileConfigs;
expect(configs.length, 1);
expect(configs.first.renderer, WebRendererMode.auto);
}),
}); });
testUsingContext('Web build supports build-name and build-number', () async { testUsingContext('Web build supports build-name and build-number', () async {
......
...@@ -32,6 +32,7 @@ import 'package:flutter_tools/src/resident_runner.dart'; ...@@ -32,6 +32,7 @@ import 'package:flutter_tools/src/resident_runner.dart';
import 'package:flutter_tools/src/run_hot.dart'; import 'package:flutter_tools/src/run_hot.dart';
import 'package:flutter_tools/src/runner/flutter_command.dart'; import 'package:flutter_tools/src/runner/flutter_command.dart';
import 'package:flutter_tools/src/vmservice.dart'; import 'package:flutter_tools/src/vmservice.dart';
import 'package:flutter_tools/src/web/compile.dart';
import 'package:test/fake.dart'; import 'package:test/fake.dart';
import 'package:unified_analytics/unified_analytics.dart' as analytics; import 'package:unified_analytics/unified_analytics.dart' as analytics;
import 'package:vm_service/vm_service.dart'; import 'package:vm_service/vm_service.dart';
...@@ -1086,6 +1087,47 @@ void main() { ...@@ -1086,6 +1087,47 @@ void main() {
}); });
}); });
group('dart-defines and web-renderer options', () {
late List<String> dartDefines;
setUp(() {
dartDefines = <String>[];
});
test('auto web-renderer with no dart-defines', () {
dartDefines = FlutterCommand.updateDartDefines(dartDefines, WebRendererMode.auto);
expect(dartDefines, <String>['FLUTTER_WEB_AUTO_DETECT=true']);
});
test('canvaskit web-renderer with no dart-defines', () {
dartDefines = FlutterCommand.updateDartDefines(dartDefines, WebRendererMode.canvaskit);
expect(dartDefines, <String>['FLUTTER_WEB_AUTO_DETECT=false','FLUTTER_WEB_USE_SKIA=true']);
});
test('html web-renderer with no dart-defines', () {
dartDefines = FlutterCommand.updateDartDefines(dartDefines, WebRendererMode.html);
expect(dartDefines, <String>['FLUTTER_WEB_AUTO_DETECT=false','FLUTTER_WEB_USE_SKIA=false']);
});
test('auto web-renderer with existing dart-defines', () {
dartDefines = <String>['FLUTTER_WEB_USE_SKIA=false'];
dartDefines = FlutterCommand.updateDartDefines(dartDefines, WebRendererMode.auto);
expect(dartDefines, <String>['FLUTTER_WEB_AUTO_DETECT=true']);
});
test('canvaskit web-renderer with no dart-defines', () {
dartDefines = <String>['FLUTTER_WEB_USE_SKIA=false'];
dartDefines = FlutterCommand.updateDartDefines(dartDefines, WebRendererMode.canvaskit);
expect(dartDefines, <String>['FLUTTER_WEB_AUTO_DETECT=false','FLUTTER_WEB_USE_SKIA=true']);
});
test('html web-renderer with no dart-defines', () {
dartDefines = <String>['FLUTTER_WEB_USE_SKIA=true'];
dartDefines = FlutterCommand.updateDartDefines(dartDefines, WebRendererMode.html);
expect(dartDefines, <String>['FLUTTER_WEB_AUTO_DETECT=false','FLUTTER_WEB_USE_SKIA=false']);
});
});
group('terminal', () { group('terminal', () {
late FakeAnsiTerminal fakeTerminal; late FakeAnsiTerminal fakeTerminal;
......
...@@ -23,7 +23,6 @@ import 'package:flutter_tools/src/test/test_device.dart'; ...@@ -23,7 +23,6 @@ import 'package:flutter_tools/src/test/test_device.dart';
import 'package:flutter_tools/src/test/test_time_recorder.dart'; import 'package:flutter_tools/src/test/test_time_recorder.dart';
import 'package:flutter_tools/src/test/test_wrapper.dart'; import 'package:flutter_tools/src/test/test_wrapper.dart';
import 'package:flutter_tools/src/test/watcher.dart'; import 'package:flutter_tools/src/test/watcher.dart';
import 'package:flutter_tools/src/web/compile.dart';
import 'package:stream_channel/stream_channel.dart'; import 'package:stream_channel/stream_channel.dart';
import 'package:vm_service/vm_service.dart'; import 'package:vm_service/vm_service.dart';
...@@ -1059,24 +1058,6 @@ dev_dependencies: ...@@ -1059,24 +1058,6 @@ dev_dependencies:
FileSystem: () => fs, FileSystem: () => fs,
ProcessManager: () => FakeProcessManager.any(), ProcessManager: () => FakeProcessManager.any(),
}); });
testUsingContext('Passes web renderer into debugging options', () async {
final FakeFlutterTestRunner testRunner = FakeFlutterTestRunner(0);
final TestCommand testCommand = TestCommand(testRunner: testRunner);
final CommandRunner<void> commandRunner = createTestCommandRunner(testCommand);
await commandRunner.run(const <String>[
'test',
'--no-pub',
'--platform=chrome',
'--web-renderer=canvaskit',
]);
expect(testRunner.lastDebuggingOptionsValue.webRenderer, WebRendererMode.canvaskit);
}, overrides: <Type, Generator>{
FileSystem: () => fs,
ProcessManager: () => FakeProcessManager.any(),
});
}); });
} }
......
...@@ -21,10 +21,10 @@ import '../../src/fake_process_manager.dart'; ...@@ -21,10 +21,10 @@ import '../../src/fake_process_manager.dart';
void main() { void main() {
late FileSystem fileSystem; late FileSystem fileSystem;
late Environment environment; late Environment environment;
late TestTarget fooTarget; late Target fooTarget;
late TestTarget barTarget; late Target barTarget;
late TestTarget fizzTarget; late Target fizzTarget;
late TestTarget sharedTarget; late Target sharedTarget;
late int fooInvocations; late int fooInvocations;
late int barInvocations; late int barInvocations;
late int shared; late int shared;
...@@ -138,23 +138,6 @@ void main() { ...@@ -138,23 +138,6 @@ void main() {
json.decode(stampFile.readAsStringSync())); json.decode(stampFile.readAsStringSync()));
expect(stampContents, containsPair('inputs', <Object>['/foo.dart'])); expect(stampContents, containsPair('inputs', <Object>['/foo.dart']));
expect(stampContents!.containsKey('buildKey'), false);
});
testWithoutContext('Saves a stamp file with inputs, outputs and build key', () async {
fooTarget.buildKey = 'fooBuildKey';
final BuildSystem buildSystem = setUpBuildSystem(fileSystem);
await buildSystem.build(fooTarget, environment);
final File stampFile = fileSystem.file(
'${environment.buildDir.path}/foo.stamp');
expect(stampFile, exists);
final Map<String, Object?>? stampContents = castStringKeyedMap(
json.decode(stampFile.readAsStringSync()));
expect(stampContents, containsPair('inputs', <Object>['/foo.dart']));
expect(stampContents, containsPair('buildKey', 'fooBuildKey'));
}); });
testWithoutContext('Creates a BuildResult with inputs and outputs', () async { testWithoutContext('Creates a BuildResult with inputs and outputs', () async {
...@@ -185,19 +168,6 @@ void main() { ...@@ -185,19 +168,6 @@ void main() {
expect(fooInvocations, 2); expect(fooInvocations, 2);
}); });
testWithoutContext('Re-invoke build if build key is modified', () async {
final BuildSystem buildSystem = setUpBuildSystem(fileSystem);
fooTarget.buildKey = 'old';
await buildSystem.build(fooTarget, environment);
fooTarget.buildKey = 'new';
await buildSystem.build(fooTarget, environment);
expect(fooInvocations, 2);
});
testWithoutContext('does not re-invoke build if input timestamp changes', () async { testWithoutContext('does not re-invoke build if input timestamp changes', () async {
final BuildSystem buildSystem = setUpBuildSystem(fileSystem); final BuildSystem buildSystem = setUpBuildSystem(fileSystem);
await buildSystem.build(fooTarget, environment); await buildSystem.build(fooTarget, environment);
...@@ -753,7 +723,4 @@ class TestTarget extends Target { ...@@ -753,7 +723,4 @@ class TestTarget extends Target {
@override @override
List<Source> outputs = <Source>[]; List<Source> outputs = <Source>[];
@override
String? buildKey;
} }
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter_tools/src/build_system/targets/web.dart';
import 'package:flutter_tools/src/web/compile.dart';
import 'package:test/test.dart';
void main() {
group('dart-defines and web-renderer options', () {
late List<String> dartDefines;
setUp(() {
dartDefines = <String>[];
});
test('auto web-renderer with no dart-defines', () {
dartDefines = updateDartDefines(dartDefines, WebRendererMode.auto);
expect(dartDefines, <String>['FLUTTER_WEB_AUTO_DETECT=true']);
});
test('canvaskit web-renderer with no dart-defines', () {
dartDefines = updateDartDefines(dartDefines, WebRendererMode.canvaskit);
expect(dartDefines, <String>['FLUTTER_WEB_AUTO_DETECT=false','FLUTTER_WEB_USE_SKIA=true']);
});
test('html web-renderer with no dart-defines', () {
dartDefines = updateDartDefines(dartDefines, WebRendererMode.html);
expect(dartDefines, <String>['FLUTTER_WEB_AUTO_DETECT=false','FLUTTER_WEB_USE_SKIA=false']);
});
test('auto web-renderer with existing dart-defines', () {
dartDefines = <String>['FLUTTER_WEB_USE_SKIA=false'];
dartDefines = updateDartDefines(dartDefines, WebRendererMode.auto);
expect(dartDefines, <String>['FLUTTER_WEB_AUTO_DETECT=true']);
});
test('canvaskit web-renderer with no dart-defines', () {
dartDefines = <String>['FLUTTER_WEB_USE_SKIA=false'];
dartDefines = updateDartDefines(dartDefines, WebRendererMode.canvaskit);
expect(dartDefines, <String>['FLUTTER_WEB_AUTO_DETECT=false','FLUTTER_WEB_USE_SKIA=true']);
});
test('html web-renderer with no dart-defines', () {
dartDefines = <String>['FLUTTER_WEB_USE_SKIA=true'];
dartDefines = updateDartDefines(dartDefines, WebRendererMode.html);
expect(dartDefines, <String>['FLUTTER_WEB_AUTO_DETECT=false','FLUTTER_WEB_USE_SKIA=false']);
});
});
}
...@@ -43,11 +43,16 @@ void main() { ...@@ -43,11 +43,16 @@ void main() {
testUsingContext('WebBuilder sets environment on success', () async { testUsingContext('WebBuilder sets environment on success', () async {
final TestBuildSystem buildSystem = final TestBuildSystem buildSystem =
TestBuildSystem.all(BuildResult(success: true), (Target target, Environment environment) { TestBuildSystem.all(BuildResult(success: true), (Target target, Environment environment) {
expect(target, isA<WebServiceWorker>()); final WebServiceWorker webServiceWorker = target as WebServiceWorker;
expect(webServiceWorker.isWasm, isTrue, reason: 'should be wasm');
expect(webServiceWorker.webRenderer, WebRendererMode.auto);
expect(environment.defines, <String, String>{ expect(environment.defines, <String, String>{
'TargetFile': 'target', 'TargetFile': 'target',
'HasWebPlugins': 'false', 'HasWebPlugins': 'false',
'ServiceWorkerStrategy': ServiceWorkerStrategy.offlineFirst.cliName, 'ServiceWorkerStrategy': ServiceWorkerStrategy.offlineFirst.cliName,
'WasmOmitTypeChecks': 'false',
'RunWasmOpt': 'none',
'BuildMode': 'debug', 'BuildMode': 'debug',
'DartObfuscation': 'false', 'DartObfuscation': 'false',
'TrackWidgetCreation': 'true', 'TrackWidgetCreation': 'true',
...@@ -72,16 +77,10 @@ void main() { ...@@ -72,16 +77,10 @@ void main() {
'target', 'target',
BuildInfo.debug, BuildInfo.debug,
ServiceWorkerStrategy.offlineFirst, ServiceWorkerStrategy.offlineFirst,
compilerConfigs: <WebCompilerConfig>[ compilerConfig: const WasmCompilerConfig(
const WasmCompilerConfig( omitTypeChecks: false,
wasmOpt: WasmOptLevel.none, wasmOpt: WasmOptLevel.none,
renderer: WebRendererMode.skwasm, ),
),
const JsCompilerConfig.run(
nativeNullAssertions: true,
renderer: WebRendererMode.canvaskit,
),
],
); );
expect(logger.statusText, contains('Compiling target for the Web...')); expect(logger.statusText, contains('Compiling target for the Web...'));
...@@ -103,7 +102,7 @@ void main() { ...@@ -103,7 +102,7 @@ void main() {
label: 'web-compile', label: 'web-compile',
parameters: CustomDimensions( parameters: CustomDimensions(
buildEventSettings: buildEventSettings:
'RunWasmOpt: none; WasmOmitTypeChecks: false; web-renderer: skwasm,canvaskit; web-target: wasm,js;', 'RunWasmOpt: none; WasmOmitTypeChecks: false; wasm-compile: true; web-renderer: auto;',
), ),
), ),
], ],
...@@ -116,7 +115,7 @@ void main() { ...@@ -116,7 +115,7 @@ void main() {
Event.flutterBuildInfo( Event.flutterBuildInfo(
label: 'web-compile', label: 'web-compile',
buildType: 'web', buildType: 'web',
settings: 'RunWasmOpt: none; WasmOmitTypeChecks: false; web-renderer: skwasm,canvaskit; web-target: wasm,js;', settings: 'RunWasmOpt: none; WasmOmitTypeChecks: false; wasm-compile: true; web-renderer: auto;',
), ),
]), ]),
); );
...@@ -124,12 +123,12 @@ void main() { ...@@ -124,12 +123,12 @@ void main() {
// Sends timing event. // Sends timing event.
final TestTimingEvent timingEvent = testUsage.timings.single; final TestTimingEvent timingEvent = testUsage.timings.single;
expect(timingEvent.category, 'build'); expect(timingEvent.category, 'build');
expect(timingEvent.variableName, 'dual-compile'); expect(timingEvent.variableName, 'dart2wasm');
expect( expect(
analyticsTimingEventExists( analyticsTimingEventExists(
sentEvents: fakeAnalytics.sentEvents, sentEvents: fakeAnalytics.sentEvents,
workflow: 'build', workflow: 'build',
variableName: 'dual-compile', variableName: 'dart2wasm',
), ),
true, true,
); );
...@@ -162,9 +161,7 @@ void main() { ...@@ -162,9 +161,7 @@ void main() {
'target', 'target',
BuildInfo.debug, BuildInfo.debug,
ServiceWorkerStrategy.offlineFirst, ServiceWorkerStrategy.offlineFirst,
compilerConfigs: <WebCompilerConfig>[ compilerConfig: const JsCompilerConfig.run(nativeNullAssertions: true),
const JsCompilerConfig.run(nativeNullAssertions: true, renderer: WebRendererMode.auto),
]
), ),
throwsToolExit(message: 'Failed to compile application for the Web.')); throwsToolExit(message: 'Failed to compile application for the Web.'));
......
...@@ -66,7 +66,6 @@ void main() { ...@@ -66,7 +66,6 @@ void main() {
<String, String>{}, <String, String>{},
<String, String>{}, <String, String>{},
NullSafetyMode.unsound, NullSafetyMode.unsound,
webRenderer: WebRendererMode.canvaskit,
); );
releaseAssetServer = ReleaseAssetServer( releaseAssetServer = ReleaseAssetServer(
globals.fs.file('main.dart').uri, globals.fs.file('main.dart').uri,
...@@ -292,7 +291,6 @@ void main() { ...@@ -292,7 +291,6 @@ void main() {
<String, String>{}, <String, String>{},
<String, String>{}, <String, String>{},
NullSafetyMode.unsound, NullSafetyMode.unsound,
webRenderer: WebRendererMode.canvaskit,
); );
expect(webAssetServer.basePath, 'foo/bar'); expect(webAssetServer.basePath, 'foo/bar');
...@@ -312,7 +310,6 @@ void main() { ...@@ -312,7 +310,6 @@ void main() {
<String, String>{}, <String, String>{},
<String, String>{}, <String, String>{},
NullSafetyMode.unsound, NullSafetyMode.unsound,
webRenderer: WebRendererMode.canvaskit,
); );
// Defaults to "/" when there's no base element. // Defaults to "/" when there's no base element.
...@@ -334,7 +331,6 @@ void main() { ...@@ -334,7 +331,6 @@ void main() {
<String, String>{}, <String, String>{},
<String, String>{}, <String, String>{},
NullSafetyMode.unsound, NullSafetyMode.unsound,
webRenderer: WebRendererMode.canvaskit,
), ),
throwsToolExit(), throwsToolExit(),
); );
...@@ -355,7 +351,6 @@ void main() { ...@@ -355,7 +351,6 @@ void main() {
<String, String>{}, <String, String>{},
<String, String>{}, <String, String>{},
NullSafetyMode.unsound, NullSafetyMode.unsound,
webRenderer: WebRendererMode.canvaskit,
), ),
throwsToolExit(), throwsToolExit(),
); );
...@@ -689,7 +684,6 @@ void main() { ...@@ -689,7 +684,6 @@ void main() {
extraHeaders: const <String, String>{}, extraHeaders: const <String, String>{},
chromiumLauncher: null, chromiumLauncher: null,
nullSafetyMode: NullSafetyMode.unsound, nullSafetyMode: NullSafetyMode.unsound,
webRenderer: WebRendererMode.html,
); );
webDevFS.requireJS.createSync(recursive: true); webDevFS.requireJS.createSync(recursive: true);
webDevFS.flutterJs.createSync(recursive: true); webDevFS.flutterJs.createSync(recursive: true);
...@@ -751,6 +745,13 @@ void main() { ...@@ -751,6 +745,13 @@ void main() {
// New SDK should be visible.. // New SDK should be visible..
expect(await webDevFS.webAssetServer.dartSourceContents('dart_sdk.js'), 'BELLOW'); expect(await webDevFS.webAssetServer.dartSourceContents('dart_sdk.js'), 'BELLOW');
// Toggle CanvasKit
expect(webDevFS.webAssetServer.webRenderer, WebRendererMode.html);
webDevFS.webAssetServer.webRenderer = WebRendererMode.canvaskit;
expect(await webDevFS.webAssetServer.dartSourceContents('dart_sdk.js'), 'OL');
expect(await webDevFS.webAssetServer.dartSourceContents('dart_sdk.js.map'), 'CHUM');
// Generated entrypoint. // Generated entrypoint.
expect(await webDevFS.webAssetServer.dartSourceContents('web_entrypoint.dart'), expect(await webDevFS.webAssetServer.dartSourceContents('web_entrypoint.dart'),
contains('GENERATED')); contains('GENERATED'));
...@@ -799,7 +800,6 @@ void main() { ...@@ -799,7 +800,6 @@ void main() {
extraHeaders: const <String, String>{}, extraHeaders: const <String, String>{},
chromiumLauncher: null, chromiumLauncher: null,
nullSafetyMode: NullSafetyMode.sound, nullSafetyMode: NullSafetyMode.sound,
webRenderer: WebRendererMode.html,
); );
webDevFS.requireJS.createSync(recursive: true); webDevFS.requireJS.createSync(recursive: true);
webDevFS.flutterJs.createSync(recursive: true); webDevFS.flutterJs.createSync(recursive: true);
...@@ -861,6 +861,11 @@ void main() { ...@@ -861,6 +861,11 @@ void main() {
// New SDK should be visible.. // New SDK should be visible..
expect(await webDevFS.webAssetServer.dartSourceContents('dart_sdk.js'), 'BELLOW'); expect(await webDevFS.webAssetServer.dartSourceContents('dart_sdk.js'), 'BELLOW');
// Toggle CanvasKit
webDevFS.webAssetServer.webRenderer = WebRendererMode.canvaskit;
expect(await webDevFS.webAssetServer.dartSourceContents('dart_sdk.js'), 'OL');
expect(await webDevFS.webAssetServer.dartSourceContents('dart_sdk.js.map'), 'CHUM');
// Generated entrypoint. // Generated entrypoint.
expect(await webDevFS.webAssetServer.dartSourceContents('web_entrypoint.dart'), expect(await webDevFS.webAssetServer.dartSourceContents('web_entrypoint.dart'),
contains('GENERATED')); contains('GENERATED'));
...@@ -908,7 +913,6 @@ void main() { ...@@ -908,7 +913,6 @@ void main() {
extraHeaders: const <String, String>{}, extraHeaders: const <String, String>{},
chromiumLauncher: null, chromiumLauncher: null,
nullSafetyMode: NullSafetyMode.sound, nullSafetyMode: NullSafetyMode.sound,
webRenderer: WebRendererMode.canvaskit,
); );
webDevFS.requireJS.createSync(recursive: true); webDevFS.requireJS.createSync(recursive: true);
webDevFS.stackTraceMapper.createSync(recursive: true); webDevFS.stackTraceMapper.createSync(recursive: true);
...@@ -970,7 +974,6 @@ void main() { ...@@ -970,7 +974,6 @@ void main() {
nullAssertions: true, nullAssertions: true,
nativeNullAssertions: true, nativeNullAssertions: true,
nullSafetyMode: NullSafetyMode.sound, nullSafetyMode: NullSafetyMode.sound,
webRenderer: WebRendererMode.canvaskit,
); );
webDevFS.requireJS.createSync(recursive: true); webDevFS.requireJS.createSync(recursive: true);
webDevFS.stackTraceMapper.createSync(recursive: true); webDevFS.stackTraceMapper.createSync(recursive: true);
...@@ -1016,7 +1019,6 @@ void main() { ...@@ -1016,7 +1019,6 @@ void main() {
extraHeaders: const <String, String>{}, extraHeaders: const <String, String>{},
chromiumLauncher: null, chromiumLauncher: null,
nullSafetyMode: NullSafetyMode.sound, nullSafetyMode: NullSafetyMode.sound,
webRenderer: WebRendererMode.canvaskit,
); );
webDevFS.requireJS.createSync(recursive: true); webDevFS.requireJS.createSync(recursive: true);
webDevFS.stackTraceMapper.createSync(recursive: true); webDevFS.stackTraceMapper.createSync(recursive: true);
...@@ -1063,7 +1065,6 @@ void main() { ...@@ -1063,7 +1065,6 @@ void main() {
extraHeaders: const <String, String>{}, extraHeaders: const <String, String>{},
chromiumLauncher: null, chromiumLauncher: null,
nullSafetyMode: NullSafetyMode.sound, nullSafetyMode: NullSafetyMode.sound,
webRenderer: WebRendererMode.auto,
); );
webDevFS.requireJS.createSync(recursive: true); webDevFS.requireJS.createSync(recursive: true);
webDevFS.stackTraceMapper.createSync(recursive: true); webDevFS.stackTraceMapper.createSync(recursive: true);
...@@ -1111,7 +1112,6 @@ void main() { ...@@ -1111,7 +1112,6 @@ void main() {
extraHeaders: const <String, String>{}, extraHeaders: const <String, String>{},
chromiumLauncher: null, chromiumLauncher: null,
nullSafetyMode: NullSafetyMode.unsound, nullSafetyMode: NullSafetyMode.unsound,
webRenderer: WebRendererMode.canvaskit,
); );
webDevFS.requireJS.createSync(recursive: true); webDevFS.requireJS.createSync(recursive: true);
webDevFS.stackTraceMapper.createSync(recursive: true); webDevFS.stackTraceMapper.createSync(recursive: true);
...@@ -1148,9 +1148,7 @@ void main() { ...@@ -1148,9 +1148,7 @@ void main() {
null, null,
const <String, String>{}, const <String, String>{},
NullSafetyMode.unsound, NullSafetyMode.unsound,
webRenderer: WebRendererMode.canvaskit, testMode: true);
testMode: true
);
expect(webAssetServer.defaultResponseHeaders['x-frame-options'], null); expect(webAssetServer.defaultResponseHeaders['x-frame-options'], null);
await webAssetServer.dispose(); await webAssetServer.dispose();
...@@ -1182,9 +1180,7 @@ void main() { ...@@ -1182,9 +1180,7 @@ void main() {
extraHeaderKey: extraHeaderValue, extraHeaderKey: extraHeaderValue,
}, },
NullSafetyMode.unsound, NullSafetyMode.unsound,
webRenderer: WebRendererMode.canvaskit, testMode: true);
testMode: true
);
expect(webAssetServer.defaultResponseHeaders[extraHeaderKey], <String>[extraHeaderValue]); expect(webAssetServer.defaultResponseHeaders[extraHeaderKey], <String>[extraHeaderValue]);
...@@ -1219,7 +1215,6 @@ void main() { ...@@ -1219,7 +1215,6 @@ void main() {
<String, String>{}, <String, String>{},
<String, String>{}, <String, String>{},
NullSafetyMode.sound, NullSafetyMode.sound,
webRenderer: WebRendererMode.canvaskit,
); );
expect(await webAssetServer.metadataContents('foo/main_module.ddc_merged_metadata'), null); expect(await webAssetServer.metadataContents('foo/main_module.ddc_merged_metadata'), null);
...@@ -1262,7 +1257,6 @@ void main() { ...@@ -1262,7 +1257,6 @@ void main() {
extraHeaders: const <String, String>{}, extraHeaders: const <String, String>{},
chromiumLauncher: null, chromiumLauncher: null,
nullSafetyMode: NullSafetyMode.unsound, nullSafetyMode: NullSafetyMode.unsound,
webRenderer: WebRendererMode.canvaskit,
); );
webDevFS.requireJS.createSync(recursive: true); webDevFS.requireJS.createSync(recursive: true);
webDevFS.stackTraceMapper.createSync(recursive: true); webDevFS.stackTraceMapper.createSync(recursive: true);
......
...@@ -51,7 +51,7 @@ void main() { ...@@ -51,7 +51,7 @@ void main() {
final Directory appBuildDir = fileSystem.directory(fileSystem.path.join( final Directory appBuildDir = fileSystem.directory(fileSystem.path.join(
exampleAppDir.path, exampleAppDir.path,
'build', 'build',
'web', 'web_wasm',
)); ));
for (final String filename in const <String>[ for (final String filename in const <String>[
'flutter.js', 'flutter.js',
......
...@@ -19,7 +19,6 @@ void main() async { ...@@ -19,7 +19,6 @@ void main() async {
await _testProject(HotReloadProject(indexHtml: indexHtmlFlutterJsCallback), name: 'flutter.js (callback)'); await _testProject(HotReloadProject(indexHtml: indexHtmlFlutterJsCallback), name: 'flutter.js (callback)');
await _testProject(HotReloadProject(indexHtml: indexHtmlFlutterJsPromisesFull), name: 'flutter.js (promises)'); await _testProject(HotReloadProject(indexHtml: indexHtmlFlutterJsPromisesFull), name: 'flutter.js (promises)');
await _testProject(HotReloadProject(indexHtml: indexHtmlFlutterJsPromisesShort), name: 'flutter.js (promises, short)'); await _testProject(HotReloadProject(indexHtml: indexHtmlFlutterJsPromisesShort), name: 'flutter.js (promises, short)');
await _testProject(HotReloadProject(indexHtml: indexHtmlFlutterJsLoad), name: 'flutter.js (load)');
await _testProject(HotReloadProject(indexHtml: indexHtmlNoFlutterJs), name: 'No flutter.js'); await _testProject(HotReloadProject(indexHtml: indexHtmlNoFlutterJs), name: 'No flutter.js');
} }
......
...@@ -56,27 +56,6 @@ String indexHtmlFlutterJsPromisesFull = _generateFlutterJsIndexHtml(''' ...@@ -56,27 +56,6 @@ String indexHtmlFlutterJsPromisesFull = _generateFlutterJsIndexHtml('''
}); });
'''); ''');
/// index_with_flutterjs.html
String indexHtmlFlutterJsLoad = _generateFlutterJsIndexHtml('''
window.addEventListener('load', function(ev) {
_flutter.buildConfig = {
builds: [
{
"compileTarget": "dartdevc",
"renderer": "html",
"mainJsPath": "main.dart.js",
}
]
};
// Download main.dart.js
_flutter.loader.load({
serviceWorkerSettings: {
serviceWorkerVersion: serviceWorkerVersion,
},
});
});
''');
/// index_without_flutterjs.html /// index_without_flutterjs.html
String indexHtmlNoFlutterJs = ''' String indexHtmlNoFlutterJs = '''
<!DOCTYPE HTML> <!DOCTYPE HTML>
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment