web.dart 23.2 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5 6
import 'dart:math';

7
import 'package:crypto/crypto.dart';
8
import 'package:package_config/package_config.dart';
9

10 11 12 13
import '../../artifacts.dart';
import '../../base/file_system.dart';
import '../../base/io.dart';
import '../../build_info.dart';
14
import '../../cache.dart';
15
import '../../convert.dart';
16
import '../../dart/language_version.dart';
17
import '../../dart/package_map.dart';
18
import '../../flutter_plugins.dart';
19
import '../../globals.dart' as globals;
20
import '../../project.dart';
21
import '../../web/compile.dart';
22 23 24
import '../../web/file_generators/flutter_js.dart' as flutter_js;
import '../../web/file_generators/flutter_service_worker_js.dart';
import '../../web/file_generators/main_dart.dart' as main_dart;
25
import '../../web/file_generators/wasm_bootstrap.dart' as wasm_bootstrap;
26
import '../build_system.dart';
27
import '../depfile.dart';
28
import '../exceptions.dart';
29
import 'assets.dart';
30
import 'localizations.dart';
31
import 'shader_compiler.dart';
32 33 34 35 36 37 38 39 40

/// Whether the application has web plugins.
const String kHasWebPlugins = 'HasWebPlugins';

/// An override for the dart2js build mode.
///
/// Valid values are O1 (lowest, profile default) to O4 (highest, release default).
const String kDart2jsOptimization = 'Dart2jsOptimization';

41 42 43 44 45 46
/// If `--dump-info` should be passed to dart2js.
const String kDart2jsDumpInfo = 'Dart2jsDumpInfo';

// If `--no-frequency-based-minification` should be based to dart2js
const String kDart2jsNoFrequencyBasedMinification = 'Dart2jsNoFrequencyBasedMinification';

47 48 49
/// Whether to disable dynamic generation code to satisfy csp policies.
const String kCspMode = 'cspMode';

50 51 52 53 54 55
/// Base href to set in index.html in flutter build command
const String kBaseHref = 'baseHref';

/// Placeholder for base href
const String kBaseHrefPlaceholder = r'$FLUTTER_BASE_HREF';

56
/// The caching strategy to use for service worker generation.
57
const String kServiceWorkerStrategy = 'ServiceWorkerStrategy';
58

59 60 61
/// Whether the dart2js build should output source maps.
const String kSourceMapsEnabled = 'SourceMaps';

62 63 64
/// Whether the dart2js native null assertions are enabled.
const String kNativeNullAssertions = 'NativeNullAssertions';

65 66 67 68
const String kOfflineFirst = 'offline-first';
const String kNoneWorker = 'none';

/// Convert a [value] into a [ServiceWorkerStrategy].
69
ServiceWorkerStrategy _serviceWorkerStrategyFromString(String? value) {
70 71 72 73 74 75 76 77 78
  switch (value) {
    case kNoneWorker:
      return ServiceWorkerStrategy.none;
    // offline-first is the default value for any invalid requests.
    default:
      return ServiceWorkerStrategy.offlineFirst;
  }
}

79
/// Generates an entry point for a web target.
Dan Field's avatar
Dan Field committed
80
// Keep this in sync with build_runner/resident_web_runner.dart
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
class WebEntrypointTarget extends Target {
  const WebEntrypointTarget();

  @override
  String get name => 'web_entrypoint';

  @override
  List<Target> get dependencies => const <Target>[];

  @override
  List<Source> get inputs => const <Source>[
    Source.pattern('{FLUTTER_ROOT}/packages/flutter_tools/lib/src/build_system/targets/web.dart'),
  ];

  @override
  List<Source> get outputs => const <Source>[
    Source.pattern('{BUILD_DIR}/main.dart'),
  ];

  @override
  Future<void> build(Environment environment) async {
102
    final String? targetFile = environment.defines[kTargetFile];
103
    final Uri importUri = environment.fileSystem.file(targetFile).absolute.uri;
104
    // TODO(zanderso): support configuration of this file.
105
    const String packageFile = '.packages';
106
    final PackageConfig packageConfig = await loadPackageConfigWithLogging(
107
      environment.fileSystem.file(packageFile),
108
      logger: environment.logger,
109
    );
110
    final FlutterProject flutterProject = FlutterProject.current();
111
    final LanguageVersion languageVersion = determineLanguageVersion(
112 113
      environment.fileSystem.file(targetFile),
      packageConfig[flutterProject.manifest.appName],
114
      Cache.flutterRoot!,
115
    );
116

117
    // Use the PackageConfig to find the correct package-scheme import path
118 119 120 121 122 123
    // for the user application. If the application has a mix of package-scheme
    // and relative imports for a library, then importing the entrypoint as a
    // file-scheme will cause said library to be recognized as two distinct
    // libraries. This can cause surprising behavior as types from that library
    // will be considered distinct from each other.
    // By construction, this will only be null if the .packages file does not
124 125
    // have an entry for the user's application or if the main file is
    // outside of the lib/ directory.
126
    final String importedEntrypoint = packageConfig.toPackageUri(importUri)?.toString()
127
      ?? importUri.toString();
128

129 130 131 132
    await injectBuildTimePluginFiles(flutterProject, webPlatform: true, destination: environment.buildDir);
    // The below works because `injectBuildTimePluginFiles` is configured to write
    // the web_plugin_registrant.dart file alongside the generated main.dart
    const String generatedImport = 'web_plugin_registrant.dart';
133

134 135 136 137
    final String contents = main_dart.generateMainDartFile(importedEntrypoint,
      languageVersion: languageVersion,
      pluginRegistrantEntrypoint: generatedImport,
    );
138 139

    environment.buildDir.childFile('main.dart')
140
      .writeAsStringSync(contents);
141 142 143
  }
}

144
/// Compiles a web entry point with dart2js.
145 146
abstract class Dart2WebTarget extends Target {
  const Dart2WebTarget(this.webRenderer);
147 148

  final WebRendererMode webRenderer;
149
  Source get compilerSnapshot;
150 151 152

  @override
  List<Target> get dependencies => const <Target>[
153 154
    WebEntrypointTarget(),
    GenerateLocalizationsTarget(),
155 156 157
  ];

  @override
158 159 160 161 162 163
  List<Source> get inputs => <Source>[
    const Source.hostArtifact(HostArtifact.flutterWebSdk),
    compilerSnapshot,
    const Source.artifact(Artifact.engineDartBinary),
    const Source.pattern('{BUILD_DIR}/main.dart'),
    const Source.pattern('{PROJECT_DIR}/.dart_tool/package_config_subset'),
164 165 166
  ];

  @override
167 168
  List<Source> get outputs => const <Source>[];

169 170 171 172 173 174 175 176 177
  String _collectOutput(ProcessResult result) {
    final String stdout = result.stdout is List<int>
        ? utf8.decode(result.stdout as List<int>)
        : result.stdout as String;
    final String stderr = result.stderr is List<int>
        ? utf8.decode(result.stderr as List<int>)
        : result.stderr as String;
    return stdout + stderr;
  }
178 179 180 181 182 183 184 185 186 187 188 189 190 191 192
}

class Dart2JSTarget extends Dart2WebTarget {
  Dart2JSTarget(super.webRenderer);

  @override
  String get name => 'dart2js';

  @override
  Source get compilerSnapshot => const Source.artifact(Artifact.dart2jsSnapshot);

  @override
  List<String> get depfiles => const <String>[
    'dart2js.d',
  ];
193

194 195
  @override
  Future<void> build(Environment environment) async {
196 197 198 199 200
    final String? buildModeEnvironment = environment.defines[kBuildMode];
    if (buildModeEnvironment == null) {
      throw MissingDefineException(kBuildMode, name);
    }
    final BuildMode buildMode = getBuildModeForName(buildModeEnvironment);
201
    final bool sourceMapsEnabled = environment.defines[kSourceMapsEnabled] == 'true';
202
    final bool nativeNullAssertions = environment.defines[kNativeNullAssertions] == 'true';
203
    final Artifacts artifacts = globals.artifacts!;
204
    final String platformBinariesPath = getWebPlatformBinariesDirectory(artifacts, webRenderer).path;
205
    final List<String> sharedCommandOptions = <String>[
206
      artifacts.getArtifactPath(Artifact.engineDartBinary, platform: TargetPlatform.web_javascript),
207
      '--disable-dart-dev',
208 209
      artifacts.getArtifactPath(Artifact.dart2jsSnapshot, platform: TargetPlatform.web_javascript),
      '--platform-binaries=$platformBinariesPath',
210
      ...decodeCommaSeparated(environment.defines, kExtraFrontEndOptions),
211 212
      if (nativeNullAssertions)
        '--native-null-assertions',
213 214 215 216
      if (buildMode == BuildMode.profile)
        '-Ddart.vm.profile=true'
      else
        '-Ddart.vm.product=true',
217
      for (final String dartDefine in decodeDartDefines(environment.defines, kDartDefines))
218
        '-D$dartDefine',
219 220
      if (!sourceMapsEnabled)
        '--no-source-maps',
221 222
    ];

223
    final List<String> compilationArgs = <String>[
224 225 226
      ...sharedCommandOptions,
      '-o',
      environment.buildDir.childFile('app.dill').path,
227
      '--packages=.dart_tool/package_config.json',
228
      '--cfe-only',
229
      environment.buildDir.childFile('main.dart').path, // dartfile
230 231 232 233 234 235
    ];
    globals.printTrace('compiling dart code to kernel with command "${compilationArgs.join(' ')}"');

    // Run the dart2js compilation in two stages, so that icon tree shaking can
    // parse the kernel file for web builds.
    final ProcessResult kernelResult = await globals.processManager.run(compilationArgs);
236
    if (kernelResult.exitCode != 0) {
237
      throw Exception(_collectOutput(kernelResult));
238
    }
239

240
    final String? dart2jsOptimization = environment.defines[kDart2jsOptimization];
241 242
    final bool dumpInfo = environment.defines[kDart2jsDumpInfo] == 'true';
    final bool noFrequencyBasedMinification = environment.defines[kDart2jsNoFrequencyBasedMinification] == 'true';
243 244 245
    final File outputJSFile = environment.buildDir.childFile('main.dart.js');
    final bool csp = environment.defines[kCspMode] == 'true';

246
    final ProcessResult javaScriptResult = await environment.processManager.run(<String>[
247 248 249
      ...sharedCommandOptions,
      if (dart2jsOptimization != null) '-$dart2jsOptimization' else '-O4',
      if (buildMode == BuildMode.profile) '--no-minify',
250 251
      if (dumpInfo) '--dump-info',
      if (noFrequencyBasedMinification) '--no-frequency-based-minification',
252
      if (csp) '--csp',
253
      '-o',
254 255
      outputJSFile.path,
      environment.buildDir.childFile('app.dill').path, // dartfile
256
    ]);
257
    if (javaScriptResult.exitCode != 0) {
258
      throw Exception(_collectOutput(javaScriptResult));
259
    }
260
    final File dart2jsDeps = environment.buildDir
261
      .childFile('app.dill.deps');
262
    if (!dart2jsDeps.existsSync()) {
263
      globals.printWarning('Warning: dart2js did not produced expected deps list at '
264 265 266
        '${dart2jsDeps.path}');
      return;
    }
267 268 269 270 271
    final DepfileService depfileService = DepfileService(
      fileSystem: globals.fs,
      logger: globals.logger,
    );
    final Depfile depfile = depfileService.parseDart2js(
272
      environment.buildDir.childFile('app.dill.deps'),
273
      outputJSFile,
274
    );
275 276 277 278
    depfileService.writeToFile(
      depfile,
      environment.buildDir.childFile('dart2js.d'),
    );
279 280 281
  }
}

282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336
class Dart2WasmTarget extends Dart2WebTarget {
  Dart2WasmTarget(super.webRenderer);

  @override
  Future<void> build(Environment environment) async {
    final String? buildModeEnvironment = environment.defines[kBuildMode];
    if (buildModeEnvironment == null) {
      throw MissingDefineException(kBuildMode, name);
    }
    final BuildMode buildMode = getBuildModeForName(buildModeEnvironment);
    final Artifacts artifacts = globals.artifacts!;
    final File outputWasmFile = environment.buildDir.childFile('main.dart.wasm');
    final String dartSdkPath = artifacts.getArtifactPath(Artifact.engineDartSdkPath, platform: TargetPlatform.web_javascript);
    final String dartSdkRoot = environment.fileSystem.directory(dartSdkPath).parent.path;

    final List<String> compilationArgs = <String>[
      artifacts.getArtifactPath(Artifact.engineDartAotRuntime, platform: TargetPlatform.web_javascript),
      '--disable-dart-dev',
      artifacts.getArtifactPath(Artifact.dart2wasmSnapshot, platform: TargetPlatform.web_javascript),
      if (buildMode == BuildMode.profile)
        '-Ddart.vm.profile=true'
      else
        '-Ddart.vm.product=true',
      ...decodeCommaSeparated(environment.defines, kExtraFrontEndOptions),
      for (final String dartDefine in decodeDartDefines(environment.defines, kDartDefines))
        '-D$dartDefine',
      '--packages=.dart_tool/package_config.json',
      '--dart-sdk=$dartSdkPath',
      '--multi-root-scheme',
      'org-dartlang-sdk',
      '--multi-root',
      artifacts.getHostArtifact(HostArtifact.flutterWebSdk).path,
      '--multi-root',
      dartSdkRoot,
      '--libraries-spec',
      artifacts.getHostArtifact(HostArtifact.flutterWebLibrariesJson).path,

      environment.buildDir.childFile('main.dart').path, // dartfile
      outputWasmFile.path,
    ];
    final ProcessResult compileResult = await globals.processManager.run(compilationArgs);
    if (compileResult.exitCode != 0) {
      throw Exception(_collectOutput(compileResult));
    }
  }

  @override
  Source get compilerSnapshot => const Source.artifact(Artifact.dart2wasmSnapshot);

  @override
  String get name => 'dart2wasm';

  @override
  List<Source> get outputs => const <Source>[
    Source.pattern('{OUTPUT_DIR}/main.dart.wasm'),
337
    Source.pattern('{OUTPUT_DIR}/main.dart.mjs'),
338 339 340 341 342 343 344 345
  ];

  // TODO(jacksongardner): override `depfiles` once dart2wasm begins producing
  // them: https://github.com/dart-lang/sdk/issues/50747
}

/// Unpacks the dart2js or dart2wasm compilation and resources to a given
/// output directory.
346
class WebReleaseBundle extends Target {
347
  const WebReleaseBundle(this.webRenderer, this.isWasm);
348 349

  final WebRendererMode webRenderer;
350 351
  final bool isWasm;

352 353 354
  String get outputFileNameNoSuffix => 'main.dart';
  String get outputFileName => '$outputFileNameNoSuffix${isWasm ? '.wasm' : '.js'}';
  String get wasmJSRuntimeFileName => '$outputFileNameNoSuffix.mjs';
355 356 357 358 359

  @override
  String get name => 'web_release_bundle';

  @override
360
  List<Target> get dependencies => <Target>[
361
    if (isWasm) Dart2WasmTarget(webRenderer) else Dart2JSTarget(webRenderer),
362 363 364
  ];

  @override
365 366 367
  List<Source> get inputs => <Source>[
    Source.pattern('{BUILD_DIR}/$outputFileName'),
    const Source.pattern('{PROJECT_DIR}/pubspec.yaml'),
368
    if (isWasm) Source.pattern('{BUILD_DIR}/$wasmJSRuntimeFileName'),
369 370 371
  ];

  @override
372 373
  List<Source> get outputs => <Source>[
    Source.pattern('{OUTPUT_DIR}/$outputFileName'),
374
    if (isWasm) Source.pattern('{OUTPUT_DIR}/$wasmJSRuntimeFileName'),
375 376 377 378 379
  ];

  @override
  List<String> get depfiles => const <String>[
    'dart2js.d',
380 381
    'flutter_assets.d',
    'web_resources.d',
382 383
  ];

384 385 386 387 388
  bool shouldCopy(String name) =>
      // Do not copy the deps file.
      (name.contains(outputFileName) && !name.endsWith('.deps')) ||
      (isWasm && name == wasmJSRuntimeFileName);

389 390
  @override
  Future<void> build(Environment environment) async {
391
    for (final File outputFile in environment.buildDir.listSync(recursive: true).whereType<File>()) {
392
      final String basename = globals.fs.path.basename(outputFile.path);
393 394 395 396
      if (shouldCopy(basename)) {
        outputFile.copySync(
          environment.outputDir.childFile(globals.fs.path.basename(outputFile.path)).path
        );
397 398
      }
    }
399

400 401 402 403 404 405
    if (isWasm) {
      // TODO(jacksongardner): Enable icon tree shaking once dart2wasm can do a two-phase compile.
      // https://github.com/flutter/flutter/issues/117248
      environment.defines[kIconTreeShakerFlag] = 'false';
    }

406
    createVersionFile(environment, environment.defines);
407 408
    final Directory outputDirectory = environment.outputDir.childDirectory('assets');
    outputDirectory.createSync(recursive: true);
409 410 411 412
    final Depfile depfile = await copyAssets(
      environment,
      environment.outputDir.childDirectory('assets'),
      targetPlatform: TargetPlatform.web_javascript,
413
      shaderTarget: ShaderTarget.sksl,
414
    );
415 416 417 418 419 420 421 422
    final DepfileService depfileService = DepfileService(
      fileSystem: globals.fs,
      logger: globals.logger,
    );
    depfileService.writeToFile(
      depfile,
      environment.buildDir.childFile('flutter_assets.d'),
    );
423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440

    final Directory webResources = environment.projectDir
      .childDirectory('web');
    final List<File> inputResourceFiles = webResources
      .listSync(recursive: true)
      .whereType<File>()
      .toList();

    // Copy other resource files out of web/ directory.
    final List<File> outputResourcesFiles = <File>[];
    for (final File inputFile in inputResourceFiles) {
      final File outputFile = globals.fs.file(globals.fs.path.join(
        environment.outputDir.path,
        globals.fs.path.relative(inputFile.path, from: webResources.path)));
      if (!outputFile.parent.existsSync()) {
        outputFile.parent.createSync(recursive: true);
      }
      outputResourcesFiles.add(outputFile);
441 442 443
      // insert a random hash into the requests for service_worker.js. This is not a content hash,
      // because it would need to be the hash for the entire bundle and not just the resource
      // in question.
444 445
      if (environment.fileSystem.path.basename(inputFile.path) == 'index.html') {
        final String randomHash = Random().nextInt(4294967296).toString();
446
        String resultString = inputFile.readAsStringSync()
447 448 449 450 451 452
          .replaceFirst(
            'var serviceWorkerVersion = null',
            "var serviceWorkerVersion = '$randomHash'",
          )
          // This is for legacy index.html that still use the old service
          // worker loading mechanism.
453 454 455 456
          .replaceFirst(
            "navigator.serviceWorker.register('flutter_service_worker.js')",
            "navigator.serviceWorker.register('flutter_service_worker.js?v=$randomHash')",
          );
457 458
        final String? baseHref = environment.defines[kBaseHref];
        if (resultString.contains(kBaseHrefPlaceholder) && baseHref == null) {
459
          resultString = resultString.replaceAll(kBaseHrefPlaceholder, '/');
460 461
        } else if (resultString.contains(kBaseHrefPlaceholder) && baseHref != null) {
          resultString = resultString.replaceAll(kBaseHrefPlaceholder, baseHref);
462
        }
463 464 465 466
        outputFile.writeAsStringSync(resultString);
        continue;
      }
      inputFile.copySync(outputFile.path);
467 468
    }
    final Depfile resourceFile = Depfile(inputResourceFiles, outputResourcesFiles);
469 470 471 472
    depfileService.writeToFile(
      resourceFile,
      environment.buildDir.childFile('web_resources.d'),
    );
473
  }
474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492

  /// Create version.json file that contains data about version for package_info
  void createVersionFile(Environment environment, Map<String, String> defines) {
    final Map<String, dynamic> versionInfo =
        jsonDecode(FlutterProject.current().getVersionInfo())
            as Map<String, dynamic>;

    if (defines.containsKey(kBuildNumber)) {
      versionInfo['build_number'] = defines[kBuildNumber];
    }

    if (defines.containsKey(kBuildName)) {
      versionInfo['version'] = defines[kBuildName];
    }

    environment.outputDir
        .childFile('version.json')
        .writeAsStringSync(jsonEncode(versionInfo));
  }
493
}
494

495 496 497 498 499 500
/// Static assets provided by the Flutter SDK that do not change, such as
/// CanvasKit.
///
/// These assets can be cached forever and are only invalidated when the
/// Flutter SDK is upgraded to a new version.
class WebBuiltInAssets extends Target {
501
  const WebBuiltInAssets(this.fileSystem, this.cache, this.isWasm);
502 503

  final FileSystem fileSystem;
504
  final Cache cache;
505
  final bool isWasm;
506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523

  @override
  String get name => 'web_static_assets';

  @override
  List<Target> get dependencies => const <Target>[];

  @override
  List<String> get depfiles => const <String>[];

  @override
  List<Source> get inputs => const <Source>[];

  @override
  List<Source> get outputs => const <Source>[];

  @override
  Future<void> build(Environment environment) async {
524 525 526 527 528 529 530 531 532
    // TODO(yjbanov): https://github.com/flutter/flutter/issues/52588
    //
    // Update this when we start building CanvasKit from sources. In the
    // meantime, get the Web SDK directory from cache rather than through
    // Artifacts. The latter is sensitive to `--local-engine`, which changes
    // the directory to point to ENGINE/src/out. However, CanvasKit is not yet
    // built as part of the engine, but fetched from CIPD, and so it won't be
    // found in ENGINE/src/out.
    final Directory flutterWebSdk = cache.getWebSdkDirectory();
533 534 535 536 537 538
    final Directory canvasKitDirectory = flutterWebSdk.childDirectory('canvaskit');
    for (final File file in canvasKitDirectory.listSync(recursive: true).whereType<File>()) {
      final String relativePath = fileSystem.path.relative(file.path, from: canvasKitDirectory.path);
      final String targetPath = fileSystem.path.join(environment.outputDir.path, 'canvaskit', relativePath);
      file.copySync(targetPath);
    }
539

540 541 542 543 544
    if (isWasm) {
      final File bootstrapFile = environment.outputDir.childFile('main.dart.js');
      bootstrapFile.writeAsStringSync(wasm_bootstrap.generateWasmBootstrapFile());
    }

545 546 547
    // Write the flutter.js file
    final File flutterJsFile = environment.outputDir.childFile('flutter.js');
    flutterJsFile.writeAsStringSync(flutter_js.generateFlutterJsFile());
548 549 550
  }
}

551 552
/// Generate a service worker for a web target.
class WebServiceWorker extends Target {
553
  const WebServiceWorker(this.fileSystem, this.cache, this.webRenderer, this.isWasm);
554 555

  final FileSystem fileSystem;
556
  final Cache cache;
557
  final WebRendererMode webRenderer;
558
  final bool isWasm;
559 560 561 562 563

  @override
  String get name => 'web_service_worker';

  @override
564
  List<Target> get dependencies => <Target>[
565 566 567
    if (isWasm) Dart2WasmTarget(webRenderer) else Dart2JSTarget(webRenderer),
    WebReleaseBundle(webRenderer, isWasm),
    WebBuiltInAssets(fileSystem, cache, isWasm),
568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588
  ];

  @override
  List<String> get depfiles => const <String>[
    'service_worker.d',
  ];

  @override
  List<Source> get inputs => const <Source>[];

  @override
  List<Source> get outputs => const <Source>[];

  @override
  Future<void> build(Environment environment) async {
    final List<File> contents = environment.outputDir
      .listSync(recursive: true)
      .whereType<File>()
      .where((File file) => !file.path.endsWith('flutter_service_worker.js')
        && !globals.fs.path.basename(file.path).startsWith('.'))
      .toList();
589 590 591 592

    final Map<String, String> urlToHash = <String, String>{};
    for (final File file in contents) {
      // Do not force caching of source maps.
593 594
      if (file.path.endsWith('main.dart.js.map') ||
        file.path.endsWith('.part.js.map')) {
595 596 597 598 599 600 601 602 603
        continue;
      }
      final String url = globals.fs.path.toUri(
        globals.fs.path.relative(
          file.path,
          from: environment.outputDir.path),
        ).toString();
      final String hash = md5.convert(await file.readAsBytes()).toString();
      urlToHash[url] = hash;
604 605 606 607
      // Add an additional entry for the base URL.
      if (globals.fs.path.basename(url) == 'index.html') {
        urlToHash['/'] = hash;
      }
608 609
    }

610 611 612
    final File serviceWorkerFile = environment.outputDir
      .childFile('flutter_service_worker.js');
    final Depfile depfile = Depfile(contents, <File>[serviceWorkerFile]);
613
    final ServiceWorkerStrategy serviceWorkerStrategy = _serviceWorkerStrategyFromString(
614 615 616 617 618 619 620 621 622 623 624 625 626 627
      environment.defines[kServiceWorkerStrategy],
    );
    final String serviceWorker = generateServiceWorker(
      urlToHash,
      <String>[
        'main.dart.js',
        'index.html',
        if (urlToHash.containsKey('assets/AssetManifest.json'))
          'assets/AssetManifest.json',
        if (urlToHash.containsKey('assets/FontManifest.json'))
          'assets/FontManifest.json',
      ],
      serviceWorkerStrategy: serviceWorkerStrategy,
    );
628 629
    serviceWorkerFile
      .writeAsStringSync(serviceWorker);
630 631 632 633 634 635 636 637
    final DepfileService depfileService = DepfileService(
      fileSystem: globals.fs,
      logger: globals.logger,
    );
    depfileService.writeToFile(
      depfile,
      environment.buildDir.childFile('service_worker.d'),
    );
638 639
  }
}